Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,16 +1,20 @@
|
|
| 1 |
from fastapi import FastAPI, Query
|
| 2 |
-
from transformers import
|
| 3 |
-
import requests
|
| 4 |
from PIL import Image
|
|
|
|
| 5 |
from io import BytesIO
|
|
|
|
| 6 |
|
| 7 |
-
# إنشاء
|
| 8 |
app = FastAPI(title="Image to Text API", description="تصنيف الصور باستخدام Hugging Face")
|
| 9 |
|
| 10 |
-
# تحميل النموذج
|
| 11 |
-
|
| 12 |
-
"
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
| 14 |
trust_remote_code=True
|
| 15 |
)
|
| 16 |
|
|
@@ -18,17 +22,27 @@ pipe = pipeline(
|
|
| 18 |
def root():
|
| 19 |
return {"message": "مرحبًا! أرسل رابط صورة إلى /classify"}
|
| 20 |
|
| 21 |
-
@app.
|
| 22 |
def classify_image(url: str = Query(..., description="رابط الصورة")):
|
| 23 |
try:
|
| 24 |
# تحميل الصورة من الرابط
|
| 25 |
response = requests.get(url)
|
| 26 |
image = Image.open(BytesIO(response.content))
|
| 27 |
|
| 28 |
-
#
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
# إرجاع النتيجة
|
| 32 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
except Exception as e:
|
| 34 |
return {"error": str(e)}
|
|
|
|
| 1 |
from fastapi import FastAPI, Query
|
| 2 |
+
from transformers import AutoModelForImageClassification, AutoFeatureExtractor
|
|
|
|
| 3 |
from PIL import Image
|
| 4 |
+
import requests
|
| 5 |
from io import BytesIO
|
| 6 |
+
import torch
|
| 7 |
|
| 8 |
+
# إنشاء التطبيق
|
| 9 |
app = FastAPI(title="Image to Text API", description="تصنيف الصور باستخدام Hugging Face")
|
| 10 |
|
| 11 |
+
# تحميل النموذج والمُعالج
|
| 12 |
+
model = AutoModelForImageClassification.from_pretrained(
|
| 13 |
+
"asyafalni/arabichar-v3",
|
| 14 |
+
trust_remote_code=True
|
| 15 |
+
)
|
| 16 |
+
extractor = AutoFeatureExtractor.from_pretrained(
|
| 17 |
+
"asyafalni/arabichar-v3",
|
| 18 |
trust_remote_code=True
|
| 19 |
)
|
| 20 |
|
|
|
|
| 22 |
def root():
|
| 23 |
return {"message": "مرحبًا! أرسل رابط صورة إلى /classify"}
|
| 24 |
|
| 25 |
+
@app.post("/classify")
|
| 26 |
def classify_image(url: str = Query(..., description="رابط الصورة")):
|
| 27 |
try:
|
| 28 |
# تحميل الصورة من الرابط
|
| 29 |
response = requests.get(url)
|
| 30 |
image = Image.open(BytesIO(response.content))
|
| 31 |
|
| 32 |
+
# تجهيز المدخلات
|
| 33 |
+
inputs = extractor(images=image, return_tensors="pt")
|
| 34 |
+
|
| 35 |
+
# تمريرها للنموذج
|
| 36 |
+
with torch.no_grad():
|
| 37 |
+
outputs = model(**inputs)
|
| 38 |
+
logits = outputs.logits
|
| 39 |
+
predicted_class = logits.argmax(-1).item()
|
| 40 |
|
| 41 |
# إرجاع النتيجة
|
| 42 |
+
return {
|
| 43 |
+
"url": url,
|
| 44 |
+
"predicted_class": model.config.id2label[predicted_class],
|
| 45 |
+
"scores": logits.softmax(-1).tolist()
|
| 46 |
+
}
|
| 47 |
except Exception as e:
|
| 48 |
return {"error": str(e)}
|