Search This Blog

Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Thursday, June 8, 2023

Why python django uploaded images not showing in angular UI profile or any screen ?

Option 1: 

    Note:  keep your images under media/ <folder> for upload and view 


Option 2: 

if you want to change the default media folder under your project root, 

then please go to settings.py 

MEDIA=<custom path> 

MEDIA_URL=<path after above media settings>


Now

http://<url:port>/media/customfolder/image.jpg



Tuesday, June 6, 2023

Ubuntu Port Firewall uwf - not via iptables

 step 1: apt install ufw

step 2: ufw enable

step 3:   sudo nano /etc/default/ufw

          #enable ipv6=yes

step 4: Added default deny of incoming and allow outgoing

   sudo ufw default deny incoming

   sudo ufw default allow outgoing


#. to see the list   

sudo ufw app list


step 5: #. Allow open ssh for all your login and other operations

sudo ufw allow OpenSSH

   sudo ufw allow ssh

   sudo ufw allow 22

   sudo ufw show added

   sudo ufw enable


step 6: #. Allow default web ports and custom ports

   sudo ufw allow http

   sudo ufw allow https

   sudo ufw allow 8099

   sudo ufw allow 88


 

#. To see the port list

   sudo ufw status verbose


#. To deny the ports

   sudo ufw deny <port>


Thank You

https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-with-ufw-on-ubuntu-18-04



Wednesday, May 31, 2023

Ms Sql server problem with linux python django app/settings.py

 From Database {section}


'driver': 'SQL Server Native Client 11.0',


To         

    'driver': 'ODBC Driver 17 for SQL Server'



Linux Ubuntu - See Running process with port number and details for that service

To see the pid details of running process

step 1.

lsof -i TCP:<port number>


lsof -i TCP:99


step 2

ps -ef | grep <pid>

ps -ef | grep 39100


step 3

kill -9 <pid>

Wednesday, March 29, 2023

ModuleNotFoundError: no module named 'gaze_tracking', but installed python 3.x

 #Gaze_tracking

1. Install with below command, 

pip install gaze_tracking

2. find site-packages path with below command

> python -m site


3. extract gaze_tracking.zip and copy into site-packages

        > download the zip and extract into site-packages folder

    > git clone https://github.com/Arsenal-iT/gaze_tracking.git



Tuesday, March 21, 2023

Install Python Specific version upgrade or downgrade and Also Virtual Environment with the specific Python Version

1. install python 3.7 and 3.7 virtual env 

**********************************

sudo add-apt-repository ppa:deadsnakes/ppa

sudo apt update

sudo apt install python3.7

sudo apt install python3.7-venv



2. create environment
*******************
#goto your project root folder

python3.7 -m venv env3.7

source env3.7/bin/activate

now check version, all same
************************
python3 --version
python --version
python3.7 --version
pip --version
pip3 --version


3. upgrade pip
*************
python3.7 -m pip install --upgrade pip

Tuesday, September 7, 2021

Eclipse - Python Import Libraries or Error issues fixes

 step 1) Removing the interpreter, auto configuring it again

step 2) Window - Preferences - PyDev - Interpreters - Python Interpreter Go to the Forced builtins tab Click on New... Type the name of the module (tensorflow in my case) and click OK

step 3) Right click in the project explorer on whichever module is giving errors. Go to PyDev->Code analysis.

Tuesday, August 31, 2021

Python - ImportError: cannot import name 'signature' from 'sklearn.utils.fixes'

 Please install funcsigs directly using

pip install funcsigs

and use from funcsigs import signature instead.


#ex:

#from sklearn.utils.fixes import signature

from funcsigs import signature



-- enjoy

Wednesday, June 30, 2021

How to Host Flask Applications on Namecheap cPanel

Very good. 


1. Follow the link, 

 https://dev.to/lordghostx/how-to-host-flask-applications-on-namecheap-cpanel-299b


2. In Execute Python Script 

-m pip install --upgrade pip

-m pip install -r requirements.txt






Restart the server for app.py changes.


Python - Image to Pdf

1. Install img2pdf

> pip/pip3 install img2pdf

2. img2pdfown.py


# importing necessary libraries

import img2pdf

from PIL import Image

import os

  

# CLI  img2pdf *jpg -o output_all_pngs.pdf

'''

img_path = "image1.jpg";

pdf_path = "output.pdf";

image = Image.open(img_path);

pdf_bytes = img2pdf.convert(image.filename);

file = open(pdf_path, "wb");

file.write(pdf_bytes);

image.close();

file.close();

'''


# convert all files ending in .jpg inside a directory

dirname = "dump/images/"

imgs = []

#dpix = dpiy = 300;

#layout_fun = img2pdf.get_fixed_dpi_layout_fun((dpix, dpiy))

for fname in os.listdir(dirname):

    if not fname.endswith(".jpg"):

        continue

    path = os.path.join(dirname, fname)

    if os.path.isdir(path):

        continue

    imgs.append(path)

    print ("\n" + path);

with open("dump/output.pdf", "wb") as f:

    #f.write(img2pdf.convert(imgs, layout_fun=layout_fun));

    f.write(img2pdf.convert(imgs));

  

'''    

imgs = ['dump/images/page_1.jpg', 'dump/images/page_2.jpg', 'dump/images/page_10.jpg']

with open("dump/output1.pdf", "wb") as f:

    f.write(img2pdf.convert(imgs))


# specify paper size (A4)

a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297))

layout_fun = img2pdf.get_layout_fun(a4inpt)

with open("name.pdf", "wb") as f:

    f.write(img2pdf.convert('test.jpg', layout_fun=layout_fun))


# use a fixed dpi of 300 instead of reading it from the image

dpix = dpiy = 300;

layout_fun = img2pdf.get_fixed_dpi_layout_fun((dpix, dpiy))

with open("name.pdf", "wb") as f:

    f.write(img2pdf.convert('test.jpg', layout_fun=layout_fun))


# create a PDF/A-1b compliant document by passing an ICC profile

with open("name.pdf", "wb") as f:

    f.write(img2pdf.convert('test.jpg', pdfa="/usr/share/color/icc/sRGB.icc"))    

'''

    


Friday, May 28, 2021

Eclipse - boto3 botocore.exceptions.ProfileNotFound: The config profile () could not be found

1.  If terminal is not opening, 

Go and update the eclipse from Help->MarketPlace.

2. See whether you installed boto3 and awscli from sudo or root and now you login as same user or different, 

   if different, then uninstall the above two plugin and install with the current user. 

    pip/pip3 install boto3

    pip/pip3 install awscli


3.type aws configure

            Enter Key, access scret, region

4. type vi ~/.aws/credentials

        [default]

            aws_access_key_id = xxx

            aws_secret_access_key = xx+xx

        [vijay]

            aws_access_key_id = x

            aws_secret_access_key = x+xx


5. your python program
   
          import csv
import datetime
import os
import smtplib, ssl
import boto3

botSession=boto3.session.Session(profile_name="vijay")
iam_mag_con=botSession.client(service_name="ec2",region_name='us-east-2')
resp = iam_mag_con.describe_regions()

....... 

Friday, August 7, 2020

Python AutoBot - ChatterBot Plugin

 >install python 3.8

> create your app folder

> pip or pip3 install  chatterbot
> pip or pip3 install   chatterbot-corpus

>Program mychat.py

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

# Create a new chat bot named ArsenaliT
chatbot = ChatBot('ArsenaliT')

trainer = ListTrainer(chatbot)

trainer.train([
    "Hi",
    "Hi, can I help you?",
    "Sure, I'd like to book a flight to Iceland.",
    "Your flight has been booked."
])

user = "hi";
print("User : ", user)
response = chatbot.get_response(user)
print("Bot : ", response)

user = "I'd like to book a flight ";
print("User : ", user)
response = chatbot.get_response(user)
print("Bot : ", response)


> OUTPUT

User :  hi
Bot :  Hope you are safe and good
User :  I'd like to book a flight
Bot :  Your flight has been booked.



ENJOY

Monday, June 8, 2020

Python Array of Array - Inner Array processing

#Program -1, To print array of array 
 
a = [[{'Key': 'key700', 'Value': 'val145'}, {'Key': 'key123', 'Value': 'val123'}]]

for i in range(len(a)):
    for j in range(len(a[i])):
        jsonData = a[i][j]
        #print(jsonData);
        for (k, v) in jsonData.items():
            print("Key: " + k)
            print("Value: " + str(v))

   


'''
output
********
Key: Key
Value: key700
Key: Value
Value: val145
Key: Key
Value: Key123
Key: Value
Value: val123

'''


#Program -2 , print only the key=userName

import json

a = [[{'Key': 'age', 'Value': '10'}, {'Key': 'userName', 'Value': 'vijay'}, {'Key': 'address', 'Value': '1, car st'}, {'Key': 'userName', 'Value': 'pranika'}]]

for i in range(len(a)):
    for j in range(len(a[i])):
        jsonData = a[i][j]
        data = json.loads(json.dumps(jsonData ) );
        if ( jsonData['Key'] == 'Name' ):
            print ( jsonData['Value'] )

           
       
   


'''
output
********
vijay
pranika
'''

 

Thursday, June 4, 2020

React or Localhsot CORS Error to Solve in Server Side Filters

package com.drvijayy2k2;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.product.sr.global.utils.Constants;

/**
 * The Class ContextFilters
 * ******* THIS CONTROLLER IS THE COMMON filter for the API context, this will receive all the request/response ********
 *
 * @author drvijay
 */

@Component
@Order ( 1 )
public class ContextFilters implements Filter, Constants
{


    /*
     * (non-Javadoc)
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    @Override
    public void init ( FilterConfig arg0 ) throws ServletException
    {
    }

    /*
     * (non-Javadoc)
     * @see javax.servlet.Filter#destroy()
     */
    @Override
    public void destroy ()
    {
    }

    /*
     * (non-Javadoc)
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    @Override
    public void doFilter ( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException
    {
        try
        {
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;

            res.setHeader ( "Access-Control-Allow-Origin", "*" );
            res.setHeader ( "Access-Control-Allow-Credentials", "true" );
            res.setHeader ( "Access-Control-Allow-Methods", "ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL" );
            res.setHeader ( "Access-Control-Max-Age", "3600" );
            res.setHeader ( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Key, Authorization" );


            if ( "OPTIONS".equalsIgnoreCase ( req.getMethod () ) )
            {
                res.setStatus ( HttpServletResponse.SC_OK );
            }
            else
            {
                chain.doFilter ( req, res );
            }

        }
        catch ( Exception e )
        {
            //error
        }
    }

}

Wednesday, June 3, 2020

Install Yarn Linux Ubuntu


curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -

echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

sudo apt install yarn

apt-get update

sudo apt install yarn

yarn --version

Wednesday, May 6, 2020

Google - Chuck File Download

This example is discussed in stack overflow, tkx #stackoverflow.

#answer: https://stackoverflow.com/a/39225039
 
 
PYTHON
import requests

def download_file_from_google_drive(id, destination):
    URL = "https://docs.google.com/uc?export=download"

    session = requests.Session()

    response = session.get(URL, params = { 'id' : id }, stream = True)
    token = get_confirm_token(response)

    if token:
        params = { 'id' : id, 'confirm' : token }
        response = session.get(URL, params = params, stream = True)

    save_response_content(response, destination)    

def get_confirm_token(response):
    for key, value in response.cookies.items():
        if key.startswith('download_warning'):
            return value

    return None

def save_response_content(response, destination):
    CHUNK_SIZE = 32768

    with open(destination, "wb") as f:
        for chunk in response.iter_content(CHUNK_SIZE):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
 
 
RUN
file_id = '0B1fGSuBXAh1IeEpzajRISkNHckU'
destination = '/home/myusername/work/myfile.ext'
download_file_from_google_drive(file_id, destination)
 
 
 

Tuesday, April 14, 2020

Python AWS S3 - Upload a File

import os
import boto3
from botocore.exceptions import NoCredentialsError

ACCESS_KEY = 'AK....'
AWS_ACCESS_SECRET_KEY = 'DZKtksHidEexxxxxxx'

def upload_to_aws(local_file, bucket, s3_file):
    s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY,
                      aws_secret_access_key=AWS_ACCESS_SECRET_KEY)

    try:
        s3.upload_file(local_file, bucket, s3_file)
        print("Upload Successful")
        return True
    except FileNotFoundError:
        print("The file was not found")
        return False
    except NoCredentialsError:
        print("Credentials not available")
        return False



file = open('test.png', 'r+')

key = file.name
bucket = 'dev-nw'

uploaded = upload_to_aws('test.png', bucket, key)
    


#download a file
s3 = boto3.client( 's3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=AWS_ACCESS_SECRET_KEY );   
s3.download_file( bucket, key, 'D:/airtel-download.png' );



Sunday, April 12, 2020

Python Flask AttributeError: 'Request' object has no attribute 'is_xhr'

#. Remove flask and install recent version

    pip uninstall flask
    pip intall flask


#. Else, go to your requirements.txt remove the verions of your plugins/libraries.
   ex: flask=0.12.0
          to
         flask


Re run the requriements.txt and make sure all it is now in updated version.
#before uninstall manually and run the below command.

pip install -r requirements.txt


Wednesday, February 26, 2020

Pytesseract Read a image and labeled or Rename as filename

pytesseract_image.py

import cv2
import os
import pytesseract
try:
    from PIL import Image
except ImportError:
    import Image

pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe'

#for x in range (1,1000): 
#    img_cv = cv2.imread(r'D:/Temp/Captcha/program/'+ str(x) + '.png')

folderpath = "D:/Temp/Captcha/program/"
for filename in os.listdir(folderpath):   
    img_cv = cv2.imread(r'D:/Temp/Captcha/program/'+ filename )
    # By default OpenCV stores images in BGR format and since pytesseract assumes RGB format,
    # we need to convert from BGR to RGB format/mode:
    img_rgb = cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB)
    imagetext = pytesseract.image_to_string(img_rgb)
    print (imagetext)
    # OR
    #img_rgb = Image.frombytes('RGB', img_cv.shape[:2], img_cv, 'raw', 'BGR', 0, 0)
    #imagetext = pytesseract.image_to_string(img_rgb)
    #print (imagetext)
    src =folderpath+ filename
    dst =folderpath+ imagetext + ".png"
    os.rename(src, dst)


NOTE:
save filenmae other than pytesseract.py - Note: to avoid pytesseract.image_to_string not found error

AttributeError: module 'pytesseract' has no attribute 'image_to_string'

may be your python file name itself "pytesseract,py"

kindly rename it to new name like pytes_ex.py.


--Enjoy

Hit Counter


View My Stats