| import os | |
| import zipfile | |
| import gdown | |
| import torch | |
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel | |
| from transformers import AutoTokenizer, MT5ForConditionalGeneration | |
| import uvicorn | |
| from fastapi.middleware.cors import CORSMiddleware | |
| ZIP_PATH = "./model.zip" | |
| MODEL_PATH = "./saved_openie_model" | |
| def download_and_extract_model(): | |
| if not os.path.exists(MODEL_PATH) or not os.listdir(MODEL_PATH): | |
| print("جاري تحميل النموذج من Google Drive...") | |
| url = f"https://drive.google.com/uc?id=1MZHAeCaQAyyfi6b2Dh3V_JCdTe8fTVmP" | |
| gdown.download(url, ZIP_PATH, quiet=False) | |
| print("جاري فك ضغط النموذج...") | |
| with zipfile.ZipFile(ZIP_PATH, 'r') as zip_ref: | |
| zip_ref.extractall(".") | |
| if os.path.exists(ZIP_PATH): | |
| os.remove(ZIP_PATH) | |
| print(" تم تجهيز النموذج محلياً بنجاح!") | |
| else: | |
| print(" النموذج موجود مسبقاً، تخطي مرحلة التحميل.") | |
| download_and_extract_model() | |
| app = FastAPI(title="mT5 Relation Extraction API", version="1.0") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| device = torch.device("cpu") | |
| print(" جاري تحميل النموذج والمُرمّز في الذاكرة...") | |
| try: | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH) | |
| model = MT5ForConditionalGeneration.from_pretrained(MODEL_PATH) | |
| model.to(device) | |
| model.eval() # وضع الاستنتاج | |
| print("تم تحميل النموذج بنجاح! الخادم جاهز لاستقبال الطلبات.") | |
| except Exception as e: | |
| print(f" حدث خطأ أثناء تحميل النموذج: {e}") | |
| class RelationRequest(BaseModel): | |
| text: str | |
| async def extract_relation_api(request: RelationRequest): | |
| try: | |
| prompt = "استخراج العلاقة: " + request.text | |
| inputs = tokenizer( | |
| prompt, | |
| return_tensors="pt", | |
| max_length=64, | |
| padding="max_length", | |
| truncation=True | |
| ) | |
| with torch.no_grad(): | |
| outputs = model.generate( | |
| input_ids=inputs["input_ids"].to(device), | |
| attention_mask=inputs["attention_mask"].to(device), | |
| max_new_tokens=15, | |
| num_beams=3, | |
| early_stopping=True | |
| ) | |
| predicted_relation = tokenizer.decode(outputs[0], skip_special_tokens=True).strip() | |
| return {"relation": predicted_relation} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=7860) |