doulan7166
2017-01-05 08:31 阅读 57

来自PHP的Python脚本

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("
", "").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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dtwncxs3547 dtwncxs3547 2017-01-11 08:04

    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);
    
    点赞 评论 复制链接分享

相关推荐