ayman-ejaz-dev commited on
Commit
2150e6a
·
verified ·
1 Parent(s): 7c53f3f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -0
app.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from flask import Flask, request, jsonify
3
+ from transformers import AutoModelForImageClassification
4
+ from PIL import Image
5
+ import torch
6
+ import torchvision.transforms as transforms
7
+
8
+ app = Flask(__name__)
9
+
10
+ # Load model safely (disable safetensors conversion)
11
+ model_name = "SanketJadhav/PlantDiseaseClassifier-Resnet50"
12
+ try:
13
+ model = AutoModelForImageClassification.from_pretrained(
14
+ model_name,
15
+ use_safetensors=False
16
+ )
17
+ print(f"✅ Model '{model_name}' loaded successfully")
18
+ except Exception as e:
19
+ print(f"❌ Error loading model: {e}")
20
+ model = None
21
+
22
+ # Manual preprocessing
23
+ transform = transforms.Compose([
24
+ transforms.Resize((224, 224)),
25
+ transforms.ToTensor(),
26
+ transforms.Normalize(mean=[0.485, 0.456, 0.406],
27
+ std=[0.229, 0.224, 0.225])
28
+ ])
29
+
30
+ @app.route("/predict", methods=["POST"])
31
+ def predict():
32
+ if model is None:
33
+ return jsonify({"error": "Model not loaded"}), 500
34
+
35
+ if "image" not in request.files:
36
+ return jsonify({"error": "No image file provided"}), 400
37
+
38
+ try:
39
+ file = request.files["image"]
40
+ image = Image.open(file.stream).convert("RGB")
41
+
42
+ inputs = transform(image).unsqueeze(0)
43
+
44
+ with torch.no_grad():
45
+ outputs = model(inputs)
46
+ logits = outputs.logits
47
+ predicted_class = logits.argmax(-1).item()
48
+
49
+ label = model.config.id2label[predicted_class]
50
+ return jsonify({"prediction": label})
51
+
52
+ except Exception as e:
53
+ return jsonify({"error": str(e)}), 500
54
+
55
+ if __name__ == "__main__":
56
+ # Hugging Face hamesha port 7860 use karta hai
57
+ app.run(host="0.0.0.0", port=7860)
58
+