Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
|
| 2 |
import torch
|
| 3 |
import io
|
| 4 |
from fastapi import FastAPI, File, UploadFile
|
|
@@ -8,13 +8,14 @@ from PIL import Image
|
|
| 8 |
import uvicorn
|
| 9 |
|
| 10 |
# --- 1. إعداد التطبيق والموديلات ---
|
| 11 |
-
app = FastAPI(title="YOLO + GIT Large
|
| 12 |
|
| 13 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 14 |
MY_MODEL_PATH = 'best.pt'
|
| 15 |
|
| 16 |
print(f"🔄 جاري تحميل الموديلات على: {device}...")
|
| 17 |
|
|
|
|
| 18 |
try:
|
| 19 |
detection_model = YOLO(MY_MODEL_PATH)
|
| 20 |
print("✅ تم تحميل YOLO بنجاح")
|
|
@@ -22,14 +23,15 @@ except Exception as e:
|
|
| 22 |
print(f"⚠️ فشل تحميل الموديل الخاص، استخدام الافتراضي: {e}")
|
| 23 |
detection_model = YOLO("yolov8n.pt")
|
| 24 |
|
| 25 |
-
# تحميل
|
| 26 |
model_name = "microsoft/git-large"
|
| 27 |
processor = AutoProcessor.from_pretrained(model_name)
|
| 28 |
caption_model = AutoModelForCausalLM.from_pretrained(model_name).to(device)
|
|
|
|
| 29 |
|
| 30 |
@app.get("/")
|
| 31 |
def home():
|
| 32 |
-
return {"status": "Online", "mode": "Detailed
|
| 33 |
|
| 34 |
# --- 2. وظيفة المعالجة ---
|
| 35 |
|
|
@@ -38,6 +40,7 @@ async def analyze_image(file: UploadFile = File(...)):
|
|
| 38 |
data = await file.read()
|
| 39 |
original_image = Image.open(io.BytesIO(data)).convert("RGB")
|
| 40 |
|
|
|
|
| 41 |
results = detection_model(original_image, conf=0.25)
|
| 42 |
integrated_results = []
|
| 43 |
|
|
@@ -47,8 +50,8 @@ async def analyze_image(file: UploadFile = File(...)):
|
|
| 47 |
conf_score = float(box.conf[0])
|
| 48 |
coords = box.xyxy[0].tolist()
|
| 49 |
|
| 50 |
-
# قص العنصر مع
|
| 51 |
-
pad =
|
| 52 |
cropped_img = original_image.crop((
|
| 53 |
max(0, coords[0]-pad),
|
| 54 |
max(0, coords[1]-pad),
|
|
@@ -56,39 +59,49 @@ async def analyze_image(file: UploadFile = File(...)):
|
|
| 56 |
min(original_image.height, coords[3]+pad)
|
| 57 |
))
|
| 58 |
|
| 59 |
-
# --- ال
|
| 60 |
-
# ن
|
| 61 |
-
prompt = f"a photo of a {label},
|
|
|
|
| 62 |
inputs = processor(images=cropped_img, text=prompt, return_tensors="pt").to(device)
|
| 63 |
|
| 64 |
generated_ids = caption_model.generate(
|
| 65 |
pixel_values=inputs.pixel_values,
|
| 66 |
-
input_ids=inputs.input_ids,
|
| 67 |
-
|
| 68 |
num_beams=5,
|
| 69 |
-
repetition_penalty=1.
|
|
|
|
| 70 |
)
|
| 71 |
|
| 72 |
# فك التشفير
|
| 73 |
-
|
| 74 |
|
| 75 |
-
# تنظيف ال
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
integrated_results.append({
|
| 79 |
"object_id": i + 1,
|
| 80 |
"label": label,
|
| 81 |
"confidence": f"{conf_score:.2f}",
|
| 82 |
-
"visual_description":
|
| 83 |
})
|
| 84 |
|
|
|
|
| 85 |
if not integrated_results:
|
| 86 |
inputs = processor(images=original_image, return_tensors="pt").to(device)
|
| 87 |
-
generated_ids = caption_model.generate(pixel_values=inputs.pixel_values,
|
| 88 |
-
|
|
|
|
| 89 |
|
| 90 |
-
return {
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
-
# --- 3. تشغيل السيرفر
|
| 93 |
if __name__ == "__main__":
|
| 94 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
mport os
|
| 2 |
import torch
|
| 3 |
import io
|
| 4 |
from fastapi import FastAPI, File, UploadFile
|
|
|
|
| 8 |
import uvicorn
|
| 9 |
|
| 10 |
# --- 1. إعداد التطبيق والموديلات ---
|
| 11 |
+
app = FastAPI(title="YOLO + GIT Large Detailed API")
|
| 12 |
|
| 13 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 14 |
MY_MODEL_PATH = 'best.pt'
|
| 15 |
|
| 16 |
print(f"🔄 جاري تحميل الموديلات على: {device}...")
|
| 17 |
|
| 18 |
+
# تحميل YOLO
|
| 19 |
try:
|
| 20 |
detection_model = YOLO(MY_MODEL_PATH)
|
| 21 |
print("✅ تم تحميل YOLO بنجاح")
|
|
|
|
| 23 |
print(f"⚠️ فشل تحميل الموديل الخاص، استخدام الافتراضي: {e}")
|
| 24 |
detection_model = YOLO("yolov8n.pt")
|
| 25 |
|
| 26 |
+
# تحميل GIT-large
|
| 27 |
model_name = "microsoft/git-large"
|
| 28 |
processor = AutoProcessor.from_pretrained(model_name)
|
| 29 |
caption_model = AutoModelForCausalLM.from_pretrained(model_name).to(device)
|
| 30 |
+
print(f"✅ تم تحميل {model_name} بنجاح")
|
| 31 |
|
| 32 |
@app.get("/")
|
| 33 |
def home():
|
| 34 |
+
return {"status": "Online", "mode": "Detailed Color & Shape Description"}
|
| 35 |
|
| 36 |
# --- 2. وظيفة المعالجة ---
|
| 37 |
|
|
|
|
| 40 |
data = await file.read()
|
| 41 |
original_image = Image.open(io.BytesIO(data)).convert("RGB")
|
| 42 |
|
| 43 |
+
# الكشف عن الأجسام
|
| 44 |
results = detection_model(original_image, conf=0.25)
|
| 45 |
integrated_results = []
|
| 46 |
|
|
|
|
| 50 |
conf_score = float(box.conf[0])
|
| 51 |
coords = box.xyxy[0].tolist()
|
| 52 |
|
| 53 |
+
# قص العنصر مع هامش بسيط
|
| 54 |
+
pad = 5
|
| 55 |
cropped_img = original_image.crop((
|
| 56 |
max(0, coords[0]-pad),
|
| 57 |
max(0, coords[1]-pad),
|
|
|
|
| 59 |
min(original_image.height, coords[3]+pad)
|
| 60 |
))
|
| 61 |
|
| 62 |
+
# --- الحل الجديد: البرومبت بصيغة "إكمال الجملة" ---
|
| 63 |
+
# نبدأ الجملة للموديل بـ "The [object] is" ليقوم هو بوصف اللون والشكل
|
| 64 |
+
prompt = f"a photo of a {label}, the color and shape are"
|
| 65 |
+
|
| 66 |
inputs = processor(images=cropped_img, text=prompt, return_tensors="pt").to(device)
|
| 67 |
|
| 68 |
generated_ids = caption_model.generate(
|
| 69 |
pixel_values=inputs.pixel_values,
|
| 70 |
+
input_ids=inputs.input_ids,
|
| 71 |
+
max_new_tokens=40, # نطلب توليد كلمات جديدة فقط
|
| 72 |
num_beams=5,
|
| 73 |
+
repetition_penalty=1.5,
|
| 74 |
+
do_sample=False
|
| 75 |
)
|
| 76 |
|
| 77 |
# فك التشفير
|
| 78 |
+
full_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 79 |
|
| 80 |
+
# تنظيف النتيجة: إزالة البرومبت إذا ظهر في البداية
|
| 81 |
+
if full_text.startswith(prompt):
|
| 82 |
+
description_only = full_text[len(prompt):].strip()
|
| 83 |
+
else:
|
| 84 |
+
description_only = full_text.strip()
|
| 85 |
|
| 86 |
integrated_results.append({
|
| 87 |
"object_id": i + 1,
|
| 88 |
"label": label,
|
| 89 |
"confidence": f"{conf_score:.2f}",
|
| 90 |
+
"visual_description": f"The {label} is {description_only}"
|
| 91 |
})
|
| 92 |
|
| 93 |
+
# في حال عدم وجود نتائج
|
| 94 |
if not integrated_results:
|
| 95 |
inputs = processor(images=original_image, return_tensors="pt").to(device)
|
| 96 |
+
generated_ids = caption_model.generate(pixel_values=inputs.pixel_values, max_new_tokens=40)
|
| 97 |
+
desc = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 98 |
+
return {"message": "No specific objects detected", "general_description": desc}
|
| 99 |
|
| 100 |
+
return {
|
| 101 |
+
"detected_count": len(integrated_results),
|
| 102 |
+
"results": integrated_results
|
| 103 |
+
}
|
| 104 |
|
| 105 |
+
# --- 3. تشغيل السيرفر ---
|
| 106 |
if __name__ == "__main__":
|
| 107 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|