arpitsharrrma commited on
Commit
4d7735c
·
verified ·
1 Parent(s): 8d64a2c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -112
app.py CHANGED
@@ -1,117 +1,33 @@
1
- from tensorflow.keras.models import load_model
2
- from tensorflow.keras.preprocessing.image import load_img, img_to_array
3
- import numpy as np
4
- from flask import Flask, request, render_template, jsonify
5
- from werkzeug.utils import secure_filename
6
- import os
7
  from huggingface_hub import hf_hub_download
8
- from tensorflow import keras
9
-
10
- # Initialize Flask app
11
- app = Flask(__name__)
12
 
13
  # Load model from Hugging Face Hub
14
  model_path = hf_hub_download(repo_id="arpitsharrrma/soilnet-model", filename="SoilNet.keras")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- SoilNet = keras.models.load_model(model_path)
17
-
18
- # Classes dictionary
19
- classes = {
20
- 0: "Alluvial Soil:-{ Rice, Wheat, Sugarcane, Maize, Cotton, Soyabean, Jute }",
21
- 1: "Black Soil:-{ Virginia, Wheat, Jowar, Millets, Linseed, Castor, Sunflower }",
22
- 2: "Clay Soil:-{ Rice, Lettuce, Chard, Broccoli, Cabbage, Snap Beans }",
23
- 3: "Red Soil:-{ Cotton, Wheat, Pulses, Millets, Oil Seeds, Potatoes }"
24
- }
25
-
26
- # API Key (set this securely in prod)
27
- API_KEY = "your-secret-api-key-1234"
28
-
29
- # Prediction function
30
- def model_predict(image_path, model):
31
- image = load_img(image_path, target_size=(224, 224))
32
- image = img_to_array(image) / 255.0
33
- image = np.expand_dims(image, axis=0)
34
-
35
- result = np.argmax(model.predict(image), axis=-1)[0]
36
- prediction = classes[result]
37
-
38
- if result == 0:
39
- return "Alluvial", "Alluvial.html"
40
- elif result == 1:
41
- return "Black", "Black.html"
42
- elif result == 2:
43
- return "Clay", "Clay.html"
44
- elif result == 3:
45
- return "Red", "Red.html"
46
-
47
- # Route: Home (form)
48
- @app.route('/', methods=['GET'])
49
- def index():
50
- return render_template('index.html')
51
-
52
- # Route: Form-based upload + result display
53
- @app.route('/predict', methods=['POST'])
54
- def predict():
55
- file = request.files.get('image')
56
- if not file or file.filename == '':
57
- return "No image uploaded", 400
58
-
59
- # Validate extension
60
- filename = secure_filename(file.filename)
61
- if not filename.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp', '.gif')):
62
- return "Unsupported file type", 400
63
-
64
- # Save image
65
- upload_folder = os.path.join(os.path.dirname(__file__), 'static', 'user_uploaded')
66
- os.makedirs(upload_folder, exist_ok=True)
67
- file_path = os.path.join(upload_folder, filename)
68
- file.save(file_path)
69
-
70
- # Check image is valid
71
- try:
72
- _ = load_img(file_path)
73
- except Exception as e:
74
- os.remove(file_path)
75
- return f"Invalid image file: {e}", 400
76
-
77
- pred, output_page = model_predict(file_path, SoilNet)
78
- user_image_path = os.path.join('static', 'user_uploaded', filename)
79
-
80
- return render_template(output_page, pred_output=pred, user_image=user_image_path)
81
-
82
- # Route: API endpoint with API key
83
- @app.route('/api/predict', methods=['POST'])
84
- def api_predict():
85
- key = request.headers.get('x-api-key')
86
- if key != API_KEY:
87
- return jsonify({"error": "Unauthorized"}), 401
88
-
89
- file = request.files.get('image')
90
- if not file or file.filename == '':
91
- return jsonify({"error": "No image uploaded"}), 400
92
-
93
- filename = secure_filename(file.filename)
94
- if not filename.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp', '.gif')):
95
- return jsonify({"error": "Unsupported file type"}), 400
96
-
97
- api_temp_folder = os.path.join(os.path.dirname(__file__), 'static', 'api_temp')
98
- os.makedirs(api_temp_folder, exist_ok=True)
99
- file_path = os.path.join(api_temp_folder, filename)
100
- file.save(file_path)
101
-
102
- try:
103
- _ = load_img(file_path)
104
- except Exception as e:
105
- os.remove(file_path)
106
- return jsonify({"error": f"Invalid image: {str(e)}"}), 400
107
-
108
- pred, _ = model_predict(file_path, SoilNet)
109
- os.remove(file_path)
110
-
111
- return jsonify({"soil_type": pred})
112
-
113
- # Start the app
114
- if __name__ == '__main__':
115
- app.run(debug=True)
116
-
117
- app.run(debug=True, threaded=False)
 
1
+ import gradio as gr
2
+ import tensorflow as tf
 
 
 
 
3
  from huggingface_hub import hf_hub_download
4
+ from PIL import Image
5
+ import numpy as np
 
 
6
 
7
  # Load model from Hugging Face Hub
8
  model_path = hf_hub_download(repo_id="arpitsharrrma/soilnet-model", filename="SoilNet.keras")
9
+ model = tf.keras.models.load_model(model_path)
10
+
11
+ # Define class labels (adjust if needed)
12
+ class_names = ['Alluvial Soil', 'Black Soil', 'Clay Soil', 'Red Soil', 'Sandy Soil']
13
+
14
+ def predict_soil(image):
15
+ image = image.resize((150, 150)) # Model input size
16
+ img_array = np.array(image) / 255.0
17
+ img_array = img_array.reshape(1, 150, 150, 3)
18
+ predictions = model.predict(img_array)
19
+ predicted_class = class_names[np.argmax(predictions)]
20
+ confidence = float(np.max(predictions)) * 100
21
+ return f"{predicted_class} ({confidence:.2f}% confidence)"
22
+
23
+ # Gradio Interface
24
+ interface = gr.Interface(
25
+ fn=predict_soil,
26
+ inputs=gr.Image(type="pil", label="Upload Soil Image"),
27
+ outputs=gr.Textbox(label="Predicted Soil Type"),
28
+ title="SoilNet - Soil Type Classifier",
29
+ description="Upload a soil image and the model will predict the soil type using deep learning."
30
+ )
31
+
32
+ interface.launch()
33