Spaces:
Sleeping
Sleeping
File size: 2,116 Bytes
cf2a9d0 a7b2d2c 445477c 76c5f80 cf2a9d0 76c5f80 cf2a9d0 76c5f80 cf2a9d0 a7b2d2c 76c5f80 a7b2d2c cf2a9d0 a7b2d2c cf2a9d0 a7b2d2c cf2a9d0 76c5f80 cf2a9d0 445477c cf2a9d0 76c5f80 a7b2d2c 76c5f80 cf2a9d0 76c5f80 445477c 76c5f80 a7b2d2c 445477c cf2a9d0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
from fastapi import FastAPI, Query
from transformers import AutoModelForImageClassification, AutoImageProcessor
from PIL import Image, UnidentifiedImageError
import requests
from io import BytesIO
import torch
# إنشاء التطبيق
app = FastAPI(title="Image to Text API", description="تصنيف الصور باستخدام Hugging Face")
# تحميل النموذج
model = AutoModelForImageClassification.from_pretrained(
"asyafalni/arabichar-v3",
trust_remote_code=True
)
# استخدام معالج صور جاهز
processor = AutoImageProcessor.from_pretrained(
"google/vit-base-patch16-224-in21k"
)
# نقطة نهاية الجذر
@app.get("/")
def root():
return {
"message": "مرحبًا بك في Image-to-Text API!",
"usage": "أرسل رابط صورة إلى /classify عبر POST"
}
@app.post("/classify")
def classify_image(url: str = Query(..., description="رابط الصورة")):
try:
# تحميل الصورة مع timeout ومع التحقق
response = requests.get(url, timeout=10, stream=True)
response.raise_for_status() # رفع استثناء لو كان الرابط غير صالح
# قراءة الصورة
try:
image = Image.open(BytesIO(response.content)).convert("RGB")
except UnidentifiedImageError:
return {"error": "الرابط لا يحتوي على صورة صالحة"}
# تجهيز المدخلات
inputs = processor(images=image, return_tensors="pt")
# تمريرها للنموذج
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
predicted_class = logits.argmax(-1).item()
return {
"url": url,
"predicted_class": model.config.id2label.get(predicted_class, "Unknown"),
"scores": logits.softmax(-1).tolist()
}
except requests.exceptions.RequestException as e:
return {"error": f"تعذر الوصول إلى الرابط: {e}"}
except Exception as e:
return {"error": str(e)} |