Spaces:
Sleeping
Sleeping
Mohammad Zeeshan commited on
Update main.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import uvicornfrom fastapi import FastAPI, Dependsfrom pydantic import BaseModelfrom transformers import M2M100ForConditionalGeneration, M2M100Tokenizerimport torchimport torch.quantization# Initialize FastAPI appapp = FastAPI()# Global model cachemodel_cache = {"model": None, "tokenizer": None, "device": None}# Function to lazily load and quantize the modeldef get_model():if model_cache["model"] is None:print("Loading and quantizing model for the first time...")model_name = "facebook/m2m100_418M"model_cache["tokenizer"] = M2M100Tokenizer.from_pretrained(model_name)model = M2M100ForConditionalGeneration.from_pretrained(model_name)# Set devicedevice = torch.device("cpu") # CPU for AWS Free Tiermodel.to(device)model.eval() # Set to evaluation mode# πΉ Apply dynamic quantization (only works on CPU)model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8 # Reduces memory usage)# Cache the model and tokenizermodel_cache["model"] = modelmodel_cache["device"] = deviceprint("Model successfully loaded and quantized!")return model_cache["model"], model_cache["tokenizer"], model_cache["device"]# Request model for translationclass TranslationRequest(BaseModel):text: strsource_lang: strtarget_lang: str# Translation endpoint@app.post("/translate/")async def translate(request: TranslationRequest, model_data=Depends(get_model)):try:model, tokenizer, device = model_data# Tokenize the input texttokenizer.src_lang = request.source_langencoded_text = tokenizer(request.text, return_tensors="pt").to(device)# Generate translationwith torch.no_grad():generated_tokens = model.generate(**encoded_text,forced_bos_token_id=tokenizer.get_lang_id(request.target_lang),)# Decode the translationtranslated_text = tokenizer.decode(generated_tokens[0], skip_special_tokens=True)return {"translated_text": translated_text}except Exception as e:return {"error": str(e)}# Main entry point for developmentif __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)12345678910111213141516171819202122232425262728293031323334353637383940414243444546import uvicornfrom fastapi import FastAPIfrom pydantic import BaseModelfrom transformers import pipelineimport asyncio# Initialize FastAPIapp = FastAPI()# Load Hugging Face translation pipeline globallyprint("π Loading translation pipeline...")translator = pipeline("translation", model="facebook/m2m100_418M")print("β Model is ready!")# Request model for batch translationclass BatchTranslationRequest(BaseModel):texts: list[str]source_lang: strtarget_lang: str@app.post("/translate")async def translate(request: BatchTranslationRequest):try:# Prepare input batchbatch_inputs = [f"{text} ({request.source_lang})" for text in request.texts]# Run translation asynchronouslytranslated_texts = await asyncio.to_thread(translator, batch_inputs, src_lang=request.source_lang, tgt_lang=request.target_lang)# Extract translated text resultstranslated_results = [result['translation_text'] for result in translated_texts]return {"translated_texts": translated_results}except Exception as e:return {"error": str(e)}@app.get("/")async def root():return {"message": "π M2M100 Translation API is running!"}@app.get("/health")async def health_check():return {"status": "healthy"}
main.py+33-61