How can i implement Python inside a PHP Code?

60 views Asked by At

I have created an ecommerce website that allows users to upload images. i want the uploaded images to be analyzed via the python code so that a keyword can be generated for the object in the image. The website is built using PHP, but i am having trouble integrating the Python code that analyzes the images into the PHP code & The PHP code runs on localhost 8080, while the Python code runs on port 127.0.0.1.5000.

To run the PHP code i have installed t=some packages and those are -

1. pip install flask

2. pip install numpy

3. pip install tensorflow

4. pip install keras

5. pip install pillow

Python code -

import os
from flask import Flask, render_template, request
import numpy as np
from tensorflow.keras.preprocessing.image import load_img, img_to_array
from keras.applications.resnet_v2 import preprocess_input as resnet152v2_preprocess_input
from keras.applications.resnet_v2 import ResNet152V2
from keras.applications.imagenet_utils import decode_predictions


model = ResNet152V2(weights='imagenet')


class_dict = {
    'notebook': 'laptop',
    'cellular_telephone': 'Smartphone',
    'hand-held_computer': 'Smartphone',
    'remote_control': 'Smartphone',
    'iPod': 'Smartphone',
    'microphone': 'Headphone',
    'espresso_maker': 'Headphone',
    'washer': 'Washing Machine',
    'analog_clock': 'Watch',
    'digital_watch': 'Watch',
    'reflex_camera': 'Camera',
    'vending_machine': 'Fridge',
    'pill_bottle': 'Water Bottle',
    'water_bottle': 'Water Bottle',
    'ashcan': 'Fridge'
    
}

app = Flask(__name__)


UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app.config['ALLOWED_EXTENSIONS'] = ALLOWED_EXTENSIONS


def allowed_file(filename):
    """Function to check if the file extension is allowed"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']


@app.route('/', methods=['GET', 'POST'])
def upload_file():
 
    if request.method == "POST":
        if 'file' not in request.files:
            return render_template('search_page.php', message='No file selected')
        file = request.files['file']

        if not allowed_file(file.filename):
            return render_template('search_page.php', message='File type not allowed')

        
        filename = file.filename
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

      
        img_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        img = load_img(img_path, target_size=(224, 224))

  
        img = img_to_array(img)
        img = np.expand_dims(img, axis=0)
        img = resnet152v2_preprocess_input(img)

   
        preds = model.predict(img)

       
        decoded_preds = decode_predictions(preds, top=1)[0]
        for pred in decoded_preds:
          
            pred = (pred[0], class_dict.get(pred[1], pred[1]), pred[2])
            message = 'Predicted: {} with probability {}'.format(pred[1], pred[2])

        
        return render_template('search_page.php', message=message, filename=filename)

    return render_template('search_page.php')


@app.route('/view/<filename>')
def view_image(filename):
    """Function to display an uploaded image"""
    return '<img src="/uploads/{}">'.format(filename)



if __name__ == '__main__':
    app.run(debug=True, port=8080)




Php Code - 


<?php

include 'components/connect.php';

session_start();

if(isset($_SESSION['user_id'])){
   $user_id = $_SESSION['user_id'];
}else{
   $user_id = '';
};



?>

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>search page</title>
   
  
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">

   
   <link rel="stylesheet" href="css/style.css">

</head>
<body>
   
<?php include 'components/user_header.php'; ?>


<section class="search-form">
   <form action="" method="post">
      <input type="text" name="search_box" placeholder="search here..." maxlength="100" class="box" required>
      <button type="submit" class="fas fa-search" name="search_btn"></button>
   </form>
</section>
<section class="search-form">
<form method="POST" enctype="multipart/form-data">

            <input type="file" name="file" id="file">
            <br><br>
            <button type="button" onclick="previewImage()">View</button>
            <br><br>
            <img src="" id="imgPreview" style="display:none;max-width:300px;max-height:300px;">
            <br><br>
            
        </form>
        <input type="submit" value="Upload">
   
     
        
        
   <script type="text/javascript">
      
            function previewImage() {
                var preview = document.getElementById("imgPreview");
                var file    = document.getElementById("file").files[0];
                var reader  = new FileReader();

                reader.onloadend = function () {
                    preview.src = reader.result;
                    preview.style.display = "block";
                }

                if (file) {
                    reader.readAsDataURL(file);
                } else {
                    preview.src = "";
                    preview.style.display = "none";
                }
            }
        </script>
</section>
</section>



<section class="products" style="padding-top: 0; min-height:100vh;">

   <div class="box-container">

   <?php
     if(isset($_POST['search_box']) OR isset($_POST['search_btn'])){
     $search_box = $_POST['search_box'];
     $select_products = $conn->prepare("SELECT * FROM `products` WHERE name LIKE '%{$search_box}%'"); 
     $select_products->execute();
     if($select_products->rowCount() > 0){
      while($fetch_product = $select_products->fetch(PDO::FETCH_ASSOC)){
   ?>
   <form action="" method="post" class="box">
      <input type="hidden" name="pid" value="<?= $fetch_product['id']; ?>">
      <input type="hidden" name="name" value="<?= $fetch_product['name']; ?>">
      <input type="hidden" name="price" value="<?= $fetch_product['price']; ?>">
      <input type="hidden" name="image" value="<?= $fetch_product['image_01']; ?>">
      
      <a href="quick_view.php?pid=<?= $fetch_product['id']; ?>" class="fas fa-eye"></a>
      <img src="uploaded_img/<?= $fetch_product['image_01']; ?>" alt="">
      <div class="name"><?= $fetch_product['name']; ?></div>
      <div class="flex">
         <div class="price"><span>Rs. </span><?= $fetch_product['price']; ?><span>/-</span></div>
         <input type="number" name="qty" class="qty" min="1" max="99" onkeypress="if(this.value.length == 2) return false;" value="1">
      </div>
      <input type="submit" value="add to cart" class="btn" name="add_to_cart">
   </form>
   <?php
         }
      }else{
         echo '<p class="empty">no products found!</p>';
      }
   }
   ?>

   </div>

</section>


<?php include 'components/footer.php'; ?>

<script src="js/script.js"></script>

</body>
</html>
1

There are 1 answers

0
Potato Science On

While it is possible to run Python inside PHP, doing so is not recommended due to potential security risks and performance issues. Instead, it's better to use a simple queueing system to communicate between the two languages, especially when dealing with user-uploaded files like images.

Assuming you have a database such as SQLite or PostgreSQL, you can create a table to store information about the images that need processing. This table could have the following columns:

id, imagePath, status, isProcessed, createdAt, updatedAt
1,/home/user/project/storage/img/sample.jpg,pending,false,2023-04-01,2023-04-01

Next, with your Python script you can run this every 5 minutes that checks for new entries in the table with a 'pending' status. This script can then perform the necessary image analysis using Python libraries. After processing the image, the script should update the table, setting the status to 'completed' or 'errored' depending on the outcome, and setting the isProcessed flag to 'true'.

Meanwhile, your PHP application can periodically check the table to see if the status of the image has been updated to 'completed'. If so, it can then retrieve the results of the image analysis and display them to the user or perform any further actions as needed. This requires you changing the workflow of your user as you need to show them like 'Your file has been uploaded and we will notify you once we have processed your image'

with this you can effectively integrate both Python and PHP in your application.