Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, Depends, HTTPException, Security | |
| from fastapi.security.api_key import APIKeyHeader | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| from transformers import pipeline | |
| import os | |
| # سحب الباسوورد من الإعدادات | |
| SECRET_API_KEY = os.environ.get("API_KEY") | |
| api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False) | |
| app = FastAPI(title="Dentor NLP API") | |
| # السماح للموقع بتبادل البيانات | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| def get_api_key(api_key_header: str = Security(api_key_header)): | |
| if api_key_header == SECRET_API_KEY: | |
| return api_key_header | |
| raise HTTPException(status_code=403, detail="Access Denied: Invalid API Key") | |
| # تحميل الموديلات (من الفولدرات اللي لسه رافعينها) | |
| print("Loading BioBART Summarizer...") | |
| summarizer = pipeline("summarization", model="./biobart", tokenizer="./biobart") | |
| print("Loading Helsinki Translator...") | |
| translator = pipeline("translation", model="./helsinki", tokenizer="./helsinki") | |
| print("All Models Loaded!") | |
| class TextRequest(BaseModel): | |
| text: str | |
| # مسار التلخيص | |
| async def summarize_text(request: TextRequest, api_key: str = Depends(get_api_key)): | |
| try: | |
| summary = summarizer(request.text, max_length=150, min_length=30, do_sample=False) | |
| return {"status": "success", "summary": summary[0]['summary_text']} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| # مسار الترجمة | |
| async def translate_text(request: TextRequest, api_key: str = Depends(get_api_key)): | |
| try: | |
| translation = translator(request.text) | |
| return {"status": "success", "translation": translation[0]['translation_text']} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) |