I'm currently using a Pepper Robot to take photos that I use to detect object from coco_classes with a yolov3 algorithm (https://github.com/qqwweee/keras-yolo3) located on my Windows 10 computer. I made an app that can be used on Pepper Tablet using responsive (html, bootstrap, php, ...), to select the object you want to recognize. I'm struggling to pass the class name value from php to a python file called yolo_video.py, it's unlucky because I really want the robot to point out the recognized object, so I need to interact with this Python file.
One important thing to know is that I use Anaconda to call the script and have GPU acceleration.
I tried every single command to pass a value from PHP to Python, sometimes it works, but the script do not complete is mission when it's the case (It's really strange because called from a command prompt it's working fine). With no input, the code works fine even when called from php.
I try to use exec() command because it returns an array-like value witch I can use to take back the last printed element of the python script (witch is angle information that need to take the robot to point the object).
here is yolo_detect.php :
<?php
$classe = $_GET ["choice"];
exec("C:/Anaconda/Scripts/activate yolo && cd C:/wamp64/www/app/projetba3/ && python yolo_video.py --image $who", $value);
echo "valeur envoye ".$class;
var_dump ($value)
?>
You can see that i try to call the yolo_video.py after activating my yolo environment with the parameter --image (Because i do the recognition on one image taken by the robot). I wonder if that argument can cause problems ?
Yolo_video.py :
import sys
import argparse
from yolo import YOLO, detect_video
from PIL import Image
def detect_img(yolo):
while True:
img = "C:\wamp64\www\App\projetba3\camImage.png"
try:
image = Image.open(img)
except:
print('Open Error! Try again!')
continue
else:
r_image, angle = yolo.detect_image(image,str(classe)) #img passe dans le réseau de neurone
print(angle)
#r_image.show()
r_image.save("C:\wamp64\www\App\projetba3\camerapepper.png")
break;
yolo.close_session()
FLAGS = None
if __name__ == '__main__':
classe = sys.argv[1]
print(sys.argv[1])
# class YOLO defines the default value, so suppress any default here
parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
'''
Command line options
'''
parser.add_argument(
'--model', type=str,
help='path to model weight file, default ' + YOLO.get_defaults("model_path")
)
parser.add_argument(
'--anchors', type=str,
help='path to anchor definitions, default ' + YOLO.get_defaults("anchors_path")
)
parser.add_argument(
'--classes', type=str,
help='path to class definitions, default ' + YOLO.get_defaults("classes_path")
)
parser.add_argument(
'--gpu_num', type=int,
help='Number of GPU to use, default ' + str(YOLO.get_defaults("gpu_num"))
)
parser.add_argument(
'--image', default=True, action="store_true",
help='Image detection mode, will ignore all positional arguments'
)
'''
Command line positional arguments -- for video detection mode
'''
parser.add_argument(
"--input", nargs='?', type=str,required=False,default='./path2your_video',
help = "Video input path"
)
parser.add_argument(
"--output", nargs='?', type=str, default="",
help = "[Optional] Video output path"
)
FLAGS = parser.parse_args()
if FLAGS.image:
"""
Image detection mode, disregard any remaining command line arguments
"""
print("Image detection mode")
if "input" in FLAGS:
print(" Ignoring remaining command line arguments: " + FLAGS.input + "," + FLAGS.output)
detect_img(YOLO(**vars(FLAGS)))
elif "input" in FLAGS:
detect_video(YOLO(**vars(FLAGS)), FLAGS.input, FLAGS.output)
else:
print("Must specify at least video_input_path. See usage with --help.")
You can see that i use the simple sys.argv[1] to put the value in classe variable. This value is transmitted to another python file yolo.py inside the function yolo.detect_image(image,str(classe)). I added in the function the calculation for the robot position that i need to have. Here is the function :
def detect_image(self, image, classe):
start = timer()
if self.model_image_size != (None, None):
assert self.model_image_size[0]%32 == 0, 'Multiples of 32 required'
assert self.model_image_size[1]%32 == 0, 'Multiples of 32 required'
boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))
else:
new_image_size = (image.width - (image.width % 32),
image.height - (image.height % 32))
boxed_image = letterbox_image(image, new_image_size)
image_data = np.array(boxed_image, dtype='float32')
print(image_data.shape)
image_data /= 255.
image_data = np.expand_dims(image_data, 0) # Add batch dimension.
out_boxes, out_scores, out_classes = self.sess.run(
[self.boxes, self.scores, self.classes],
feed_dict={
self.yolo_model.input: image_data,
self.input_image_shape: [image.size[1], image.size[0]],
K.learning_phase(): 0
})
print('Found {} boxes for {}'.format(len(out_boxes), 'img'))
font = ImageFont.truetype(font='font/FiraMono-Medium.otf',
size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))
thickness = (image.size[0] + image.size[1]) // 300
angle = (0,0)
for i, c in reversed(list(enumerate(out_classes))):
predicted_class = self.class_names[c]
box = out_boxes[i]
score = out_scores[i]
label = '{} {:.2f}'.format(predicted_class, score)
draw = ImageDraw.Draw(image)
label_size = draw.textsize(label, font)
top, left, bottom, right = box
top = max(0, np.floor(top + 0.5).astype('int32'))
left = max(0, np.floor(left + 0.5).astype('int32'))
bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))
right = min(image.size[0], np.floor(right + 0.5).astype('int32'))
print(label, (left, top), (right, bottom))
if str(predicted_class)== classe :
ite =+ 1
if ite == 1 :
centresofa = (left+(right-left)/2,top+(bottom-top)/2)
print (centresofa)
anglehor = 55.2*(centresofa[0]/640)
print (anglehor)
if anglehor > 27.2 :
anglehor = anglehor - 27.2
if anglehor < 27.2 :
anglehor = -(27.2 - anglehor)
else :
anglehor = 0
anglever = 44.3*(centresofa[1]/480)
print(anglever)
if anglever < 22.15 :
anglever = 22.15-anglever
if anglever > 22.15 :
anglever = -(anglever-22.15)
else :
anglever = 0
print ("angle horizontal "+str(anglehor)+"angle vertical "+str(anglever))
angle = (anglehor,anglever)
if top - label_size[1] >= 0:
text_origin = np.array([left, top - label_size[1]])
else:
text_origin = np.array([left, top + 1])
# My kingdom for a good redistributable image drawing library.
for i in range(thickness):
draw.rectangle(
[left + i, top + i, right - i, bottom - i],
outline=self.colors[c])
draw.rectangle(
[tuple(text_origin), tuple(text_origin + label_size)],
fill=self.colors[c])
draw.text(text_origin, label, fill=(0, 0, 0), font=font)
del draw
end = timer()
print(end - start)
return image, angle
I should take the values back in the last element of var_dump($values), instead, it just shows me print(sys.argv[1]) value and nothing else (sign that the script stops just after it started). A more strange fact is that his value is "--image" (the argument of my function). How can i solve this big mess ?
How is this exec() function really working with input arguments ???
Python
python yolo_video.py --image $who
sys.argv[0] = yolo_video.py
sys.argv[1] = --image
sys.argv[2] = $who (classname)
I believe you are passing argv[1] "--image" as the class name, when you should be passing argv[2]
https://www.pythonforbeginners.com/argv/more-fun-with-sys-argv
Also, you are trying to use classe as a global variable within detect_img(). This is not a good way to do this and you would have to add a global keyword to make it work.
Change detect_img(yolo) to detect_img(yolo, classe) and pass the actual classe variable to the function via sys.argv[2]
Line 83: detect_img(YOLO(**vars(FLAGS)), sys.argv[2])
PHP
echo "valeur envoye ".$class;
should be
echo "valeur envoye ".$classe;
Related
I am running a Python script from a PHP file. For a very a simple example, it works perfectly. Here is the Python script:
#!/usr/bin/env python
def test():
x = 2 + 1
print x + 4
return x
print test()
And PHP script:
<?php
$command = escapeshellcmd('/usr/bin/python2.7 /home/super/PycharmProjects/img_plus_text/helloworld.py');
$output = shell_exec($command);
echo $output;
echo "Finishing....!";
?>
Unfortunately, for more complicated script, It does not work. Here is the Python script
#!/usr/bin/env python
import numpy as np
import os
import random
import caffe
import cv2
from sklearn.externals import joblib
import create_dataset_final_mlp
import text_2_bow
def create_class_mapping():
with open("text_processing/encoded-classes.txt") as class_file:
lines = class_file.readlines()
dictionary = {}
for item in lines:
item = item.split(" ")
dictionary[item[0]] = item[1].replace("\n", "").replace("#", "")
return dictionary
def get_top5(probability_list):
result = []
probabilities = []
for i in range(0, 5):
top = probability_list.index(max(probability_list))
probabilities.insert(i, probability_list[top])
probability_list[top] = -1
result.insert(i, top)
return result, probabilities
def select_random_file(base_dir):
# Select random category
file_chosen = random.choice(os.listdir(base_dir))
# Select random file in that category
file_chosen = random.choice(os.listdir(base_dir + "/" + file_chosen))
return file_chosen
def get_top5_class_name(mapping, top5_list):
class_name_list = []
for i in range(0, 5):
index = top5_list[i]
class_name = mapping[str(index)]
class_name_list.insert(i, class_name)
return class_name_list
def main(image_to_classify):
dataset_path = "/images-test1"
image_file_chosen = create_dataset_final_mlp.find(image_to_classify, dataset_path)
if image_file_chosen is None:
image_file_chosen = select_random_file("%s" % dataset_path)
identifier = image_file_chosen.split(".")[0]
print "Identifier: " + identifier
dictionary = text_2_bow.create_dictionary("text_processing/dictionary-1000-words.csv")
# load CNN model from disk
classifier = create_dataset_final_mlp.load_model_from_disk("test/deploy.prototxt",
"test/snapshot_iter_1020.caffemodel", '256,256',
"test/converted_mean.npy")
# load the final MLP to classify patterns
print "loading model from disk..."
mlp = joblib.load("trained_model_9097_5000_3000_iter_100.model")
with open("export-ferramenta.csv") as export_file:
for line in export_file:
if identifier in line:
pattern = line
print "Pattern: " + pattern
break
# Show selected image
full_img_path = create_dataset_final_mlp.find(image_file_chosen, dataset_path)
# img = cv2.imread(full_img_path, cv2.IMREAD_COLOR)
# cv2.imshow("Image selected", img)
# cv2.waitKey(0)
# get the CNN features
inputs = [caffe.io.load_image(full_img_path)]
# the second parameter is used to switch for prediction from center crop alone instead of averaging predictions across crops (default).
classifier.predict(inputs, False)
features = classifier.blobs['fc6'].data[0]
extracted_cnn_features = create_dataset_final_mlp.get_cnn_features_as_vector(features)
extracted_cnn_features = extracted_cnn_features[:-1]
extracted_cnn_features = extracted_cnn_features.split(",")
# transform the text using text_2_bow functions
pattern = pattern.split(",")
text_pattern = pattern[1] + pattern[2]
matrix = text_2_bow.get_matrix(text_pattern, dictionary)
reshaped_matrix = np.reshape(matrix, 5000).tolist()
full_features_vector = extracted_cnn_features + reshaped_matrix
full_features_vector = np.asarray(full_features_vector, np.float64)
# use the MLP to classify
prediction = mlp.predict_proba([full_features_vector])
tolist = prediction[0].tolist()
mapping = create_class_mapping()
top5, probabilities = get_top5(tolist)
top_class_name = get_top5_class_name(mapping, top5)
print "Top 5 classes: ", top_class_name
print "Top 5 probs ", probabilities
return top_class_name, probabilities
if __name__ == "__main__":
main("")
PHP Script
<?php
echo exec('sudo /home/super/bin/caffe-nv/python /home/super/PycharmProjects/img_plus_text/demo_website.py 2>&1');
?>
ERROR
sh: 1: /home/super/bin/caffe-nv/python: Permission denied
I have read majority of the questions on the issue however I am stuck here. Please point out the mistake. Thank you.
The problem was with environment variables, I made a shell script as shown below
export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/:$LD_LIBRARY_PATH
export PYTHONPATH=$PYTHONPATH:/home/super/bin/caffe-nv/python/
python /demo_website2.py $1
Then I run the shell script from PHP using exec
exec("/opt/lampp/htdocs/test/run.sh ". $param, $output);
In a previous Using R, how to reference variable variables (or variables variable) a la PHP[post]
I asked a question about something in R analagous to PHP $$ function:
Using R stats, I want to access a variable variable scenario similar to PHP double-dollar-sign technique: http://php.net/manual/en/language.variables.variable.php
Specifically, I am looking for a function in R that is equivalent to $$ in PHP.
The get( response works for strings (characters).
lapply is a way to loop over lists
Or I can loop over and get the values ...
for(name in names(vars))
{
val = vars[[name]];
I still haven't had the $$ function in R answered, although the lapply solved what I needed in the moment.
`$$` <- function
that allows any variable type to be evaluated. That is still the question.
UPDATES
> mlist = list('four'="score", 'seven'="years");
> str = 'mlist$four'
> mlist
$four
[1] "score"
$seven
[1] "years"
> str
[1] "mlist$four"
> get(str)
Error in get(str) : object 'mlist$four' not found
> mlist$four
[1] "score"
Or how about attributes for an object such as mobj#index
UPDATES #2
So let's put specific context on the need. I was hacking the texreg package to build a custom latex output of 24 models of regression for a research paper. I am using plm fixed effects, and the default output of texreg uses dcolumns to center, which I don't like (I prefer r#{}l, so I wanted to write my own template. The purpose for me, to code this, is for me to write extensible code that I can use again and again. I can rebuild my 24 tables across 4 pages in seconds, so if the data change, or if I want to tweak the function, I immediately have a nice answer. The power of abstraction.
As I hacked this, I wanted to get more than the number of observations, but also the number of groups, which can be any user defined index. In my case it is "country" (wait for it, hence, the need for variable variables).
If I do a lookup of the structure, what I want is right there: model$model#index$country which would be nice to simply call as $$('model$model#index$country'); where I can easily build the string using paste. Nope, this is my workaround.
getIndexCount = function(model,key="country")
{
myA = attr(summary(model)$model,"index");
for(i in 1:length(colnames(myA)))
{
if(colnames(myA)[i] == key) {idx = i; break;}
}
if(!is.na(idx))
{
length(unique(myA[,idx]));
} else {
FALSE;
}
}
UPDATES #3
Using R, on the command line, I can type in a string and it gets evaluated. Why can't that internal function be directly accessed, and the element captured that then gets printed to the screen?
There is no equivalent function in R. get() works for all types, not just strings.
Here is what I came up with, after chatting with the R-bug group, and getting some ideas from them. KUDOS!
`$$` <- function(str)
{
E = unlist( strsplit(as.character(str),"[#]") );
k = length(E);
if(k==1)
{
eval(parse(text=str));
} else {
# k = 2
nstr = paste("attributes(",E[1],")",sep="");
nstr = paste(nstr,'$',E[2],sep="");
if(k>2) {
for(i in 3:k)
{
nstr = paste("attributes(",nstr,")",sep="");
nstr = paste(nstr,'$',E[i],sep="");
}
}
`$$`(nstr);
}
}
Below are some example use cases, where I can directly access what the str(obj) is providing... Extending the utility of the '$' operator by also allowing '#' for attributes.
model = list("four" = "score", "seven"="years");
str = 'model$four';
result = `$$`(str);
print(result);
matrix = matrix(rnorm(1000), ncol=25);
str='matrix[1:5,8:10]';
result = `$$`(str);
print(result);
## Annette Dobson (1990) "An Introduction to Generalized Linear Models".
## Page 9: Plant Weight Data.
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14);
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69);
group <- gl(2, 10, 20, labels = c("Ctl","Trt"));
weight <- c(ctl, trt);
lm.D9 <- lm(weight ~ group);
lm.D90 <- lm(weight ~ group - 1); # omitting intercept
myA = anova(lm.D9); myA; str(myA);
str = 'myA#heading';
result = `$$`(str);
print(result);
myS = summary(lm.D90); myS; str(myS);
str = 'myS$terms#factors';
result = `$$`(str);
print(result);
str = 'myS$terms#factors#dimnames';
result = `$$`(str);
print(result);
str = 'myS$terms#dataClasses#names';
result = `$$`(str);
print(result);
After realizing the back-tick can be a bit tedious, I chose to update the function, calling it access
access <- function(str)
{
E = unlist( strsplit(as.character(str),"[#]") );
k = length(E);
if(k==1)
{
eval(parse(text=str));
} else {
# k = 2
nstr = paste("attributes(",E[1],")",sep="");
nstr = paste(nstr,'$',E[2],sep="");
if(k>2) {
for(i in 3:k)
{
nstr = paste("attributes(",nstr,")",sep="");
nstr = paste(nstr,'$',E[i],sep="");
}
}
access(nstr);
}
}
I am new to python. I have created a gui based app to insert values into database.
I have created a Rest api to handle db operations. How can i append the api URL with json created in python.
app.py
from Tkinter import *
import tkMessageBox
import json
import requests
from urllib import urlopen
top = Tk()
L1 = Label(top, text="Title")
L1.pack( side = TOP)
E1 = Entry(top, bd =5)
E1.pack(side = TOP)
L2 = Label(top, text="Author")
L2.pack( side = TOP)
E2 = Entry(top, bd =5)
E2.pack(side = TOP)
L3 = Label(top, text="Body")
L3.pack( side = TOP)
E3 = Entry(top, bd =5)
E3.pack(side = TOP)
input = E2.get();
def callfunc():
data = {"author": E2.get(),
"body" : E3.get(),
"title" : E1.get()}
data_json = json.dumps(data)
# r = requests.get('http://localhost/spritle/api.php?action=get_uses')
#url = "http://localhost/spritle/api.php?action=insert_list&data_json="
#
url = urlopen("http://localhost/spritle/api.php?action=insert_list&data_json="%data_json).read()
tkMessageBox.showinfo("Result",data_json)
SubmitButton = Button(text="Submit", fg="White", bg="#0094FF",
font=("Grobold", 10), command = callfunc)
SubmitButton.pack()
top.mainloop()
Error:
TypeError: not all arguments converted during string formatting
i AM GETTING error while appending url with data_json ?
There is an error on string formating:
Swap this:
"http://localhost/spritle/api.php?action=insert_list&data_json="%data_json
by this:
"http://localhost/spritle/api.php?action=insert_list&data_json=" + data_json
or:
"http://localhost/spritle/api.php?action=insert_list&data_json={}".format(data_json)
The following statements are equivalents:
"Python with " + "PHP"
"Python with %s" % "PHP"
"Python with {}".format("PHP")
"Python with {lang}".format(lang="PHP")
Also, I don't think sending JSON data like this via URL is a good idea. You should encode the data at least.
You are trying to use % operator to format the string, and you need to put the %s placeholder into the string:
"http://localhost/spritle/api.php?action=insert_list&data_json=%s" % data_json
Or use other methods suggested in another answer.
Regarding the data transfer - you definitely need to use POST request and not GET.
Check this, using urllib2 and this, using requests.
My PHP code:
function start($height, $width) {
# do stuff
return $image;
}
Here my Python code:
import subprocess
def php(script_path):
p = subprocess.Popen(['php', script_path], stdout=subprocess.PIPE)
result = p.communicate()[0]
return result
page_html = "test entry"
output = php("file.php")
print page_html + output
imageUrl = start(h,w)
In Python I want to use that PHP start function. I don't know how to access start function from Python. Can anyone help me on this?
This is how I do it. It works like a charm.
# shell execute PHP
def php(code):
# open process
p = Popen(['php'], stdout=PIPE, stdin=PIPE, stderr=STDOUT, close_fds=True)
# read output
o = p.communicate(code)[0]
# kill process
try:
os.kill(p.pid, signal.SIGTERM)
except:
pass
# return
return o
To execute a particular file do this:
width = 100
height = 100
code = """<?php
include('/path/to/file.php');
echo start(""" + width + """, """ + height + """);
?>
"""
res = php(code)
Note that for Python3 you need res = php(code.encode()), see the answer below
Small update to previous response:
For python3 code string should be encoded to bytes-like object
php(code.encode())
I'm trying to plot binomial curves using R scripts which are executed by PHP loops. The scripts are taking a very long time to run and I want to improve the algorithm to run faster.
The input values are:
$xmax = 360;
$p = 0.975;
$prvn = 1;
$b = 1.7;
$c = 0.995;
The PHP function called for each loop is:
function cg_graphs_get_binomial($xmax, $p, $prvn = 1, $b = 1.7, $c = 0.99){
$Alert = array();
/*run the Rscript file located in the module root*/
$Rgennloc = "/home/rcstest/www/".drupal_get_path('module', 'cg_graphs')."/Rbinomgenn.R"; //Rscript file location
$Rbinomloc = "/home/rcstest/www/".drupal_get_path('module', 'cg_graphs')."/Rbinomnew.R"; //Rscript file location
for($i = 0; $i <= $xmax; $i++){
exec("Rscript --slave ".$Rgennloc." ".$prvn." ".$i." ".$b, $n);
$ne = explode('[1]', $n[$i]);
$prvn = $ne[1];
exec("Rscript --slave ".$Rbinomloc." ".$prvn." ".$p." ".$c, $alert);
$at = explode('[1]', $alert[$i]);
$Alert[] = trim($at[1]);
}
return $Alert; //return the data array
The first R script called ($Rgennloc) generates the n value, based on the n value of the previous loop, or 1 if it is the first loop. This increments as follows (etc):
1
6
16
32
53
80
The first r script looks like this and runs in relatively short amount of time:
#!/usr/bin/Rscript
#grab args as passed into via CLI
args <- commandArgs(trailingOnly = TRUE)
#R script to generate n value
#implimentation of excel ROUNDDOWN function
ROUNDDOWN <- function(.number, .num_digits){
return(as.integer(.number*10^.num_digits)/(10^.num_digits))
}
#generate n
n <- function(.prvn, .xaxis, .B){
return(.prvn + ROUNDDOWN(.xaxis * exp(1)^.B, 0))
}
#wrapper function
n(as.integer(args[1]), as.integer(args[2]), as.double(args[3]))
When the second script is called, it runs quickly for about the first 20 calls (where n gets to around 1000 and xaxis is 20) but then it starts to slow down.
The second script:
#!/usr/bin/Rscript
# replace '/usr/bin' with actual R executable
args <- commandArgs(trailingOnly = TRUE)
#Critbinom - R implimentation of the excel function
CRITBINOM <- function(.trials, .probability_s, .alpha){
i <- 0
while(sum(dbinom(0:i, .trials, .probability_s)) < .alpha){
i <- i + 1
}
return(i)
}
# Binomdist - R implimentation of the excel function
BINOMDIST <- function(.number_s, .trials, .probability_s, .cumulative){
if(.cumulative){
return(sum(dbinom(0:.number_s, .trials, .probability_s)))
}else{
return(choose(.trials,.number_s)*.probability_s^.number_s*(1-.probability_s)^(.trials-.number_s))
}
}
# Iserror - R version of this, no need for all excel functionality.
ISERROR <- function(.value){
return(is.infinite(.value))
}
# Generate the alert
generate_Alert <- function(.n, .probability_s, .alpha){
critB <- CRITBINOM(.n, .probability_s, .alpha)
adj <- critB-(BINOMDIST(critB, .n, .probability_s,TRUE)-.alpha)/(BINOMDIST(critB, .n, .probability_s,TRUE)-BINOMDIST(critB-1, .n, .probability_s,TRUE))
if(ISERROR(100 * adj / .n)){
return(0)
}else{
adj_value <- (adj / .n)
return(adj_value)
}
}
# Generate the alert for current xaxis position
generate_data <- function(.n, .probability_s, .alpha){
Alert <- generate_Alert(.n, .probability_s, .alpha)
return(Alert)
}
# Call wrapper function generate_data(n, p, alpha)
generate_data(as.integer(args[1]), as.double(args[2]), as.double(args[3]))
The xaxis value may get as high as 360, but the script starts slowing down before xaxis gets to 30. By the time xaxis is at 100 it takes some 30 seconds to complete each loop, it just gets worse from there.
What is the best way of optimizing this? I think its only using 1 core at the moment. I have 2 available but I'm not sure how much difference the second core will make in the long run.
I am using the latest version of R.
Expanding my comment a bit, so this question gets an answer:
A while loop in R is a very unsual construct (I see it only once or twice a year in serious code). It's often an indicator that the code does not follow the spirit of R, but was written by someone with experience from other language (e.g., from the C familiy). while loops are very expensive performance-wise in R and if really needed should be better written in C.
Fortunately, the CRITBINOM function is just a naive re-implementation of qbinom (quantile function of the binomial distribution), which can be used instead. The only difference is in how multiple success probabilities are handled (qbinom is fully vectorized).
I believe a full reimplementation in R (avoiding explicit loops) could get this down to seconds or less, but I don't know PHP.