Linked Questions

Popular Questions

How can i implement Python inside a PHP Code?

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

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'

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

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['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')

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

if __name__ == '__main__':, port=8080)

Php Code - 


include 'components/connect.php';


   $user_id = $_SESSION['user_id'];
   $user_id = '';


<!DOCTYPE html>
<html lang="en">
   <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="">

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

<?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>
<section class="search-form">
<form method="POST" enctype="multipart/form-data">

            <input type="file" name="file" id="file">
            <button type="button" onclick="previewImage()">View</button>
            <img src="" id="imgPreview" style="display:none;max-width:300px;max-height:300px;">
        <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;
           = "block";

                if (file) {
                } else {
                    preview.src = "";
           = "none";

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

   <div class="box-container">

     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}%'"); 
     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">
      <input type="submit" value="add to cart" class="btn" name="add_to_cart">
         echo '<p class="empty">no products found!</p>';



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

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


Related Questions