I developed a script to extract entities from the given text and script is executing fine.
python code:
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize
with open('C:\\pythonScripts\\input.txt', 'r') as f:
sample = f.read()
import nltk
def list_tokens(sampletext):
nltk.internals.config_java("C:\\Program Files\\Java\\jdk1.8.0_131\\bin\\java.exe")
classifier='C:\\Users\\gsrilakshmi.INDIA\\Desktop\\stanford\\stanford-ner-2016-10-31\\classifiers\\english.all.3class.distsim.crf.ser.gz'
jar='C:\\Users\\gsrilakshmi.INDIA\\Desktop\\stanford\\stanford-ner-2016-10-31\\stanford-ner.jar'
st = StanfordNERTagger(classifier,jar,encoding='utf-8')
tokenized_text = word_tokenize(sampletext)
classified_text = st.tag(tokenized_text)
with open('C:\\pythonScripts\\output.txt', 'w') as fp:
fp.write('\n'.join('%s %s' % x for x in classified_text))
return classified_text
tokens = list_tokens(sample)
print(tokens)
While calling the python script from php,the output file is not generated.
php code:
$pyscript = 'C:\\Python\Python36-32\python C:\pythonScripts\sample1.py';
$python = 'C:\Python\Python36-32\python.exe';
$p=exec($pyscript,$fulloutput);
exec("python C:\\pythonScripts\\sample1.py > C:\\pythonScripts\\out.txt");
echo $p;
I got the output: '[Found C:\Program Files\Java\jdk1.8.0_131\bin\java.exe: C:\Program Files\Java\jdk1.8.0_131\bin\java.exe]'
Please help me in solving this issue.
Thanks,
Srilu
Related
i was trying to open and read a pdf from php using python. but after executing the php code in my browser, its not redirecting to python script.
i want my php code to execute the python script and return the output to
php
php code:
<?php
$command = escapeshellcmd("python filename.py");
$output = shell_exec($command);
echo $output;
?>
python code:
this code will read the pdf from the directory and extracts required data from the pdf and gives the corresponding result as an output to the php code which is printed on the browser
import PyPDF2
import re,time
import sys
start_time =time.time()
# open the pdf file
address="pv3.pdf"
object = PyPDF2.PdfFileReader(address)
#print('hello')
# get number of pages
NumPages = object.getNumPages()
l = list()
# extract text and do the search
for i in range(0, NumPages):
PageObj = object.getPage(i)
Text = PageObj.extractText()
l.append(Text)
#print(len(l))
#print(l[0])
d={}
count=0
for i in range(len(l)):
x = l[i].split('\n')
for j in range(len(x)):
if re.search('[0-9]{8}',x[j]) and (j!=len(x)-1 and re.search('-',x[j+1])==None):
#print(x[j],'in page',i+1,',line no',j+1)
count +=1
str = ''
temp =0
for m in range(j+1,len(x)):
if '~na' not in x[m]:
str+=x[m]
else:
temp = 1
break
if temp==0:
#print('hello')
y=l[i+1].split('\n')
for n in range(len(y)):
if '~' in y[n]:
break
str+=y[n]
# if d[x[j]]==None:
d[x[j]]=str
for x,y in d.items():
print(x,"::::",y,"...,")
print()
#print(l[i])
#print(d)
#print('No of matches are',count)
#print(l[0])
end_time = time.time()
#print('Total time taken :',end_time-start_time)
As the title says, I am running a python script from PHP using shell_exec, and this works when running it from a SSH session into my web server by running 'php ./python.php'. I get the expected output.
However when the page is loaded on a web browser, I simply get a blank web page with no PHP warnings or errors. Any help is appreciated.
python.php:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('memory_limit', '-1');
$command = escapeshellcmd("python3 ./test.py 2>&1");
$output = shell_exec($command);
echo $output;
?>
test.py:
#!/usr/bin/env python
import pandas as pd
import math
import csv
url = 'https://afltables.com/afl/stats/2018a.html'
dfs = pd.read_html(url)
dfs = dfs[1]
dfs.to_csv('hmm.csv', sep=',', encoding='utf-8');
dfs = dfs[dfs.TM == "NM"]
dfs = dfs[dfs.GM > 3]
url = 'https://afltables.com/afl/seas/2018.html'
lad = pd.read_html(url)
scores = []
for index, row in dfs.iterrows():
score = (math.sqrt(row['CP']) * 2 + (row['IF']) * 2 + (row['CL']) ** 2)
scores.append([row['Player'], score])
pos = 1
scores = sorted(scores, key=lambda x: x[1], reverse=True)
for item in scores:
print(str(pos) + ". " + item[0] + ": " + str(item[1]))
pos = pos + 1
Im quite new in web developing, could someone please point me in the right direction of help with the scripts to run a .py script on a web page. Below are the ones that i am using. Do i have to create a html file and a php file??
If so please help me. I have a internal server running on XAMPP with Apache and configured to run CGI, .py scripts.
Work flow:
Upload > button to run the below .py script > download
Upload script(php):
<?php
if(isset($_POST['UploadButton'])){ //check if form was submitted
$target_dir = '/opt/lampp/htdocs/pic-el/Dump/';
$target_file = $target_dir . basename($_FILES["filepath"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["filepath"]["tmp_name"], $target_file);
}
?>
Python script:
#!/usr/bin/env python
import CGIHTTPServer
CGIHTTPServer.test()
import os
import urllib
import cgi
import webcolors
import xlsxwriter
from PIL import Image
filename = "/home/Desktop/tess/test1"
imageNameArray = []
def downloadfile(urlData):
urllib.urlretrieve(urlData[0], urlData[1])
print " image downloaded: " + str(urlData[1])
return
# open file to read
with open("{0}.csv".format(filename), 'r') as csvfile:
# iterate on all lines
i = 0
for line in csvfile:
splitted_line = line.split(',')
# check if we have an image URL
if splitted_line[1] != '' and splitted_line[1] != "\n":
# urllib.urlretrieve(splitted_line[1], '/home/tf_files/images/{0}.jpg'.format (splitted_line[0]))
imageNameArray.append(
(splitted_line[1], '/home/Desktop/tess/images/{0}.jpg'.format(splitted_line[0])))
print "Image added to list for processing for {0}".format(splitted_line[0])
i += 1
else:
print "No result for {0}".format(splitted_line[0])
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from multiprocessing import Pool
processPool = Pool(5)
processPool.map(downloadfile, imageNameArray)
# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('output1.xlsx')
worksheet = workbook.add_worksheet()
# Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0
# search for files in 'images' dir
files_dir = os.getcwd() + '/images'
files = os.listdir(files_dir)
def closest_colour(requested_colour):
min_colours = {}
for key, name in webcolors.css3_hex_to_names.items():
r_c, g_c, b_c = webcolors.hex_to_rgb(key)
rd = (r_c - requested_colour[0]) ** 2
gd = (g_c - requested_colour[1]) ** 2
bd = (b_c - requested_colour[2]) ** 2
min_colours[(rd + gd + bd)] = name
return min_colours[min(min_colours.keys())]
def get_colour_name(requested_colour):
try:
closest_name = actual_name = webcolors.rgb_to_name(requested_colour)
except ValueError:
closest_name = closest_colour(requested_colour)
actual_name = None
return actual_name, closest_name
for f in files:
if f.lower().endswith(('.png', '.jpg', '.jpeg')):
image_path = files_dir + '/' + f
im = Image.open(image_path)
n, cl = max(im.getcolors(im.size[0] * im.size[1]))
requested_colour = cl
actual_name, closest_name = get_colour_name(requested_colour)
width = im.size
if width < (500, 500):
worksheet.write(row, 4, "False")
else:
worksheet.write(row, 4, "True")
print image_path
print cl
print width
print "Actual colour name:", actual_name, ", closest colour name:", closest_name
worksheet.write_string(row, 1, image_path)
worksheet.write(row, 3, closest_name)
row += 1
workbook.close()
you can't run .py on a web page, only u can run on the server since Python's a server side programming. But you can run python script from PHP (since u r using XAMPP.)
Example -
<?php
$output = exec('./filename.py');
?>
You don't need to create separate php and html files.
First, when the server goes back to apache2
sudo apt-get install libapache2-mod-wsgi
(It connects apache2 with wsgi.)
Second, you need to create a configuration file and
Move the configuration file to Document_Root.
ex> server.conf
WSGIScriptAlias /test /var/www/wsgi/main.py
MainOption | Address to be connected | Python file location
Third, restart apache2 service.
EXAMPLE_CODES
main.py
server.conf
I have a php code that is writing the user input on the webpage into a text file. I wish to pass the text file into my python script that looks like follows:
PHP Script (getfile.php)
<?php
function writetofile($file, $content, $writeType){
$fo = fopen($file, $writeType);
if($fo){
fwrite($fo,$content);
fclose($fo);
}
}
?>
Python Script (predict.py)
clf=joblib.load('model.pkl')
def run(command):
output = subprocess.check_output(command, shell=True)
return output
row = run('cat '+'/Users/minks/Documents/X-test.txt'+" | wc -l").split()[0]
print("Test row size:")
print(row)
matrix_tmp_test = np.zeros((int(row),col), dtype=np.int64)
print("Test matrix size:")
print(matrix_tmp_test.size)
What I am asking is, after writing to a file : $file in php, how can I then pass this file to replace:
row = run('cat '+'/Users/minks/Documents/X-test.txt'+" | wc -l").split()[0]
where the path gets replace by $file and the processing continues? Also, is it possible to pass $file directly to the python code via command line? I am little confused on how this entire passing and processing can be carried out.
Dow you want something like this?
PHP:
$path = "my.txt";
system("python predict.py $path");
Python:
row = run("cat %s | wc -l" % sys.argv[1]).split()[0]
I have a problem running another file from php. I want my php params to be the output of running a python file that calls another file itself.
Here is my php file:
<?php
if (isset($_POST['submit'])) {
$params = solve();
}
function solve() {
exec("python array.py", $output);
return $output;
}
?>
If array.py is simply:
if __name__ == "__main__":
print 1
print 2
print 3
print 4
I will get 1,2,3,4 for my output, but I as soon as I change array.py to the following file that calls os.system, I don't get anything. So the new array.py is:
import os
def main():
os.system("python test.py") #test.py creates tmp.txt with 4 lines w/ values 1,2,3,4
def output():
f = open("tmp.txt", "r")
myReturn = []
currentline = f.readline()
while currentline:
val = currentline[:-1] #Getting rid of '\n'
val = int(val)
myReturn = myReturn + [val]
currentline = f.readline()
f.close()
return myReturn
if __name__ == "__main__":
main()
o = output()
print o[0]
print o[1]
print o[2]
print o[3]
Also if I just run test.py, the output is the file tmp.txt:
1
2
3
4
So now, when I run my php file, the output tmp.txt is not even created in the directory and as a result I don't get any output from my php either.
I am not sure why this is happening because when I just run array.py myself, I get the desired output, and the tmp file is created.
EDIT:
I forgot to include: import os above.
Change exec to:
exec("python array.py 2>&1", $output)
Or check the web server or php error log. This will return the error output from the python script to your php script (not normally what you want in production).