Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,36 +1,42 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import sys
|
| 3 |
-
from huggingface_hub import snapshot_download
|
| 4 |
import torch
|
| 5 |
-
from transformers import AutoFeatureExtractor, AutoModelForImageClassification, AutoConfig
|
| 6 |
from PIL import Image
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
#
|
| 9 |
model_path = snapshot_download("shahad-alh/arabichar-finetuned-v2")
|
| 10 |
-
|
| 11 |
-
# Step 2: Add to Python path
|
| 12 |
sys.path.append(model_path)
|
| 13 |
|
| 14 |
-
#
|
| 15 |
config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
|
| 16 |
model = AutoModelForImageClassification.from_pretrained(model_path, config=config, trust_remote_code=True)
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
def predict(
|
| 21 |
-
|
| 22 |
with torch.no_grad():
|
| 23 |
-
|
| 24 |
-
predicted =
|
| 25 |
-
label =
|
| 26 |
return label
|
| 27 |
|
| 28 |
-
#
|
| 29 |
gr.Interface(
|
| 30 |
fn=predict,
|
| 31 |
inputs=gr.Image(type="pil", label="Upload Arabic Letter"),
|
| 32 |
-
outputs=gr.Textbox(label="
|
| 33 |
title="Arabic Character Classifier",
|
| 34 |
-
|
| 35 |
-
|
| 36 |
).launch()
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
| 2 |
import torch
|
|
|
|
| 3 |
from PIL import Image
|
| 4 |
+
from torchvision import transforms
|
| 5 |
+
from transformers import AutoConfig, AutoModelForImageClassification
|
| 6 |
+
import sys
|
| 7 |
+
from huggingface_hub import snapshot_download
|
| 8 |
|
| 9 |
+
# β
Download and link custom model repo
|
| 10 |
model_path = snapshot_download("shahad-alh/arabichar-finetuned-v2")
|
|
|
|
|
|
|
| 11 |
sys.path.append(model_path)
|
| 12 |
|
| 13 |
+
# β
Load model with config
|
| 14 |
config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
|
| 15 |
model = AutoModelForImageClassification.from_pretrained(model_path, config=config, trust_remote_code=True)
|
| 16 |
+
model.eval()
|
| 17 |
+
|
| 18 |
+
# β
Manual preprocessing (Grayscale β Resize β Tensor)
|
| 19 |
+
transform = transforms.Compose([
|
| 20 |
+
transforms.Grayscale(num_output_channels=1),
|
| 21 |
+
transforms.Resize((32, 32)),
|
| 22 |
+
transforms.ToTensor()
|
| 23 |
+
])
|
| 24 |
|
| 25 |
+
# β
Prediction logic
|
| 26 |
+
def predict(image: Image.Image):
|
| 27 |
+
tensor = transform(image).unsqueeze(0) # Add batch dimension
|
| 28 |
with torch.no_grad():
|
| 29 |
+
logits = model(tensor).logits
|
| 30 |
+
predicted = torch.argmax(logits, dim=1).item()
|
| 31 |
+
label = config.id2label[str(predicted)]
|
| 32 |
return label
|
| 33 |
|
| 34 |
+
# β
Gradio app
|
| 35 |
gr.Interface(
|
| 36 |
fn=predict,
|
| 37 |
inputs=gr.Image(type="pil", label="Upload Arabic Letter"),
|
| 38 |
+
outputs=gr.Textbox(label="Predicted Letter"),
|
| 39 |
title="Arabic Character Classifier",
|
| 40 |
+
allow_api=True,
|
| 41 |
+
allow_flagging="never"
|
| 42 |
).launch()
|