Crop prediction #3

Closed
opened 2025-02-23 07:24:19 +05:30 by KaranSalvi · 1 comment
Collaborator

app.py

(models) karan@fedora:~/Downloads/Status200/models$ cat app.py 
# predict.py
from PIL import Image, UnidentifiedImageError
from transformers import ViTImageProcessor, ViTForImageClassification
import sys

# Check if the image path is provided
if len(sys.argv) < 2:
    print("Error: No image path provided. Please provide the path to the image as an argument.")
    exit()

# Load the image processor and model
model_name = 'vishnun0027/Crop_Disease_model_1'
image_processor = ViTImageProcessor.from_pretrained(model_name)
model = ViTForImageClassification.from_pretrained(
    model_name,
    ignore_mismatched_sizes=True
)

# Load image
image_path = sys.argv[1]  # Get the image path from command line arguments
try:
    image = Image.open(image_path)
    # Convert the image to RGB if it's not already
    if image.mode != 'RGB':
        image = image.convert('RGB')
except FileNotFoundError:
    print("Error: Image file not found.")
    exit()
except UnidentifiedImageError:
    print("Error: Unable to open image. Check the file type.")
    exit()
except Exception as e:
    print(f"An error occurred: {e}")
    exit()

# Preparing the image for the model
inputs = image_processor(images=image, return_tensors="pt")

# Make the prediction
outputs = model(**inputs)
logits = outputs.logits
predicted_class_idx = logits.argmax(-1).item()

# Print the predicted class
print(model.config.id2label[predicted_class_idx])


server.js:

// server.js
const express = require('express');
const { spawn } = require('child_process');
const path = require('path');

const app = express();
const PORT = 3000;

// Endpoint to run the Python script
app.get('/predict', (req, res) => {
    const imagePath = path.join(__dirname, 'leaf1.webp'); // Path to your image

    // Spawn a new Python process
    const pythonProcess = spawn('python', ['app.py', imagePath]);

    // Collect data from the script
    pythonProcess.stdout.on('data', (data) => {
        console.log(`Output: ${data}`);
        res.send(data.toString()); // Send the output back to the client
    });

    // Handle errors
    pythonProcess.stderr.on('data', (data) => {
        console.error(`Error: ${data}`);
        res.status(500).send(data.toString());
    });

    // When the process is done
    pythonProcess.on('close', (code) => {
        console.log(`Python process exited with code ${code}`);
    });
});

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

app.py ```python (models) karan@fedora:~/Downloads/Status200/models$ cat app.py # predict.py from PIL import Image, UnidentifiedImageError from transformers import ViTImageProcessor, ViTForImageClassification import sys # Check if the image path is provided if len(sys.argv) < 2: print("Error: No image path provided. Please provide the path to the image as an argument.") exit() # Load the image processor and model model_name = 'vishnun0027/Crop_Disease_model_1' image_processor = ViTImageProcessor.from_pretrained(model_name) model = ViTForImageClassification.from_pretrained( model_name, ignore_mismatched_sizes=True ) # Load image image_path = sys.argv[1] # Get the image path from command line arguments try: image = Image.open(image_path) # Convert the image to RGB if it's not already if image.mode != 'RGB': image = image.convert('RGB') except FileNotFoundError: print("Error: Image file not found.") exit() except UnidentifiedImageError: print("Error: Unable to open image. Check the file type.") exit() except Exception as e: print(f"An error occurred: {e}") exit() # Preparing the image for the model inputs = image_processor(images=image, return_tensors="pt") # Make the prediction outputs = model(**inputs) logits = outputs.logits predicted_class_idx = logits.argmax(-1).item() # Print the predicted class print(model.config.id2label[predicted_class_idx]) ``` --- server.js: ```js // server.js const express = require('express'); const { spawn } = require('child_process'); const path = require('path'); const app = express(); const PORT = 3000; // Endpoint to run the Python script app.get('/predict', (req, res) => { const imagePath = path.join(__dirname, 'leaf1.webp'); // Path to your image // Spawn a new Python process const pythonProcess = spawn('python', ['app.py', imagePath]); // Collect data from the script pythonProcess.stdout.on('data', (data) => { console.log(`Output: ${data}`); res.send(data.toString()); // Send the output back to the client }); // Handle errors pythonProcess.stderr.on('data', (data) => { console.error(`Error: ${data}`); res.status(500).send(data.toString()); }); // When the process is done pythonProcess.on('close', (code) => { console.log(`Python process exited with code ${code}`); }); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); ```
Owner

Merged these changes in training branch.

Merged these changes in training branch.
Sign in to join this conversation.
2 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: notkshitij/CropCompass#3