from fastapi import FastAPI, UploadFile, File, Form, HTTPException import tensorflow as tf from PIL import Image import io, base64, numpy as np import pandas as pd import re app = FastAPI(title="Sign ↔ Text API") # دالة تنظيف وتوحيد النص العربي def normalize_arabic(text): text = str(text).strip() text = re.sub("[إأآ]", "ا", text) text = re.sub("ة", "ه", text) return text # 1. تحميل ملف الإكسل وعمل القاموس word_to_id = {} try: file_name = "KARSL-100_Labels (1).xlsx" df = pd.read_excel(file_name) df.columns = [str(col).strip() for col in df.columns] if 'Sign-Arabic' in df.columns and 'SignID' in df.columns: for index, row in df.iterrows(): if pd.notna(row['Sign-Arabic']): key = normalize_arabic(row['Sign-Arabic']) word_to_id[key] = row['SignID'] print(f"✅ تم تحميل {len(word_to_id)} كلمة بنجاح") except Exception as e: print(f"❌ خطأ في الإكسل: {e}") # 2. تحميل الموديلات try: sign_to_text_model = tf.keras.models.load_model("best_model.h5", compile=False) text_to_sign_model = tf.keras.models.load_model("word_to_sign_model.h5", compile=False) print("✅ تم تحميل الموديلات بنجاح") except Exception as e: print(f"❌ خطأ في الموديلات: {e}") @app.post("/text-to-sign") async def text_to_sign(text: str = Form(...)): try: clean_text = normalize_arabic(text) label_id = word_to_id.get(clean_text) if label_id is None: raise ValueError(f"الكلمة '{text}' مش موجودة في الإكسل.") # --- الحل الجذري لمشكلة الـ Shape (100) --- # بنعمل مصفوفة فيها 100 صفر one_hot_input = np.zeros((1, 100), dtype=np.float32) # بننور الرقم بتاع الكلمة (مثلاً 72) بنخلي قيمته 1 # ملحوظة: لو الـ IDs في الإكسل بتبدأ من 1، بنطرح 1 عشان الـ index بيبدأ من 0 idx = int(label_id) - 1 if int(label_id) > 0 else 0 if idx < 100: one_hot_input[0, idx] = 1.0 else: raise ValueError(f"الـ ID رقم {label_id} أكبر من حجم الموديل (100)") # التوقع (دلوقتي الـ Shape بقا 100 ومظبوط) prediction = text_to_sign_model.predict(one_hot_input) # --------------------------------------- if isinstance(prediction, np.ndarray): img_data = prediction[0] if img_data.max() <= 1.0: img_data = (img_data * 255).astype("uint8") else: img_data = img_data.astype("uint8") if len(img_data.shape) == 3 and img_data.shape[-1] == 1: img_data = img_data.reshape(img_data.shape[0], img_data.shape[1]) img = Image.fromarray(img_data) else: img = prediction buf = io.BytesIO() img.save(buf, format="PNG") encoded = base64.b64encode(buf.getvalue()).decode("utf-8") return { "status": "success", "word": clean_text, "sign_id": int(label_id), "image_base64": encoded } except Exception as e: raise HTTPException(status_code=500, detail=f"خطأ في الموديل: {str(e)}") if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)