LovnishVerma commited on
Commit
062aef3
·
verified ·
1 Parent(s): 866dbff

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -0
app.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import tensorflow as tf
3
+ import numpy as np
4
+ import json
5
+ from PIL import Image
6
+
7
+ # 1. Load Model and Labels
8
+ model = tf.keras.models.load_model('devanagari_model.keras')
9
+
10
+ with open('labels.json', 'r') as f:
11
+ labels = json.load(f)
12
+
13
+ # 2. Preprocessing Function
14
+ def process_image(image):
15
+ # Convert to grayscale (L)
16
+ image = image.convert('L')
17
+ # Resize to 32x32 (dataset size)
18
+ image = image.resize((32, 32))
19
+ # Convert to array
20
+ img_array = np.array(image)
21
+ # Normalize to 0-1
22
+ img_array = img_array / 255.0
23
+ # Add batch dimension (1, 32, 32, 1)
24
+ img_array = np.expand_dims(img_array, axis=0)
25
+ img_array = np.expand_dims(img_array, axis=-1)
26
+ return img_array
27
+
28
+ # 3. Prediction Function
29
+ def predict_character(image):
30
+ if image is None:
31
+ return "Please upload an image."
32
+
33
+ processed_img = process_image(image)
34
+ predictions = model.predict(processed_img)
35
+
36
+ # Get top prediction
37
+ predicted_class_index = np.argmax(predictions)
38
+ predicted_label = labels[str(predicted_class_index)]
39
+ confidence = float(np.max(predictions))
40
+
41
+ return {predicted_label: confidence}
42
+
43
+ # 4. Gradio Interface
44
+ iface = gr.Interface(
45
+ fn=predict_character,
46
+ inputs=gr.Image(type="pil", label="Upload Character Image"),
47
+ outputs=gr.Label(num_top_classes=3),
48
+ title="Devanagari Character Recognition (Lightweight)",
49
+ description="Upload a handwritten Hindi/Devanagari character. This model is optimized for low-resource environments."
50
+ )
51
+
52
+ iface.launch()