Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,31 +1,49 @@
|
|
| 1 |
-
|
| 2 |
-
import
|
| 3 |
-
import pandas as pd
|
| 4 |
from transformers import MarianMTModel, MarianTokenizer
|
|
|
|
|
|
|
| 5 |
import logging
|
| 6 |
-
import os
|
| 7 |
|
| 8 |
# ---------------- LOGGING ----------------
|
| 9 |
-
logging.basicConfig(
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# ---------------- MODEL CLASS ----------------
|
| 13 |
class FrenchTitleGenerator:
|
| 14 |
-
def __init__(self, model_name=
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
def
|
| 22 |
try:
|
| 23 |
input_text = f"Generate title from: Year: {year} City: {city} Description: {original_title}"
|
| 24 |
-
inputs = self.tokenizer(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
with torch.no_grad():
|
| 27 |
outputs = self.model.generate(
|
| 28 |
-
inputs["input_ids"],
|
| 29 |
attention_mask=inputs["attention_mask"],
|
| 30 |
max_length=max_length,
|
| 31 |
temperature=temperature,
|
|
@@ -33,38 +51,55 @@ class FrenchTitleGenerator:
|
|
| 33 |
num_beams=3,
|
| 34 |
early_stopping=True
|
| 35 |
)
|
| 36 |
-
|
| 37 |
-
result = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 38 |
-
for phrase in ["Le titre de", "Année:", "Ville:", "Description:", "[YEAR]", "[CITY]", "[DESC]", "[TITLE]"]:
|
| 39 |
-
result = result.replace(phrase, "")
|
| 40 |
-
return " ".join(result.split()).strip()
|
| 41 |
-
|
| 42 |
except Exception as e:
|
| 43 |
-
logger.error(f"
|
| 44 |
-
return f"
|
| 45 |
|
| 46 |
-
# ----------------
|
| 47 |
-
|
| 48 |
|
| 49 |
-
# ----------------
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from pydantic import BaseModel
|
|
|
|
| 3 |
from transformers import MarianMTModel, MarianTokenizer
|
| 4 |
+
import torch
|
| 5 |
+
import time
|
| 6 |
import logging
|
|
|
|
| 7 |
|
| 8 |
# ---------------- LOGGING ----------------
|
| 9 |
+
logging.basicConfig(
|
| 10 |
+
level=logging.INFO,
|
| 11 |
+
format="%(asctime)s - %(levelname)s - %(message)s"
|
| 12 |
+
)
|
| 13 |
+
logger = logging.getLogger("FrenchTitleAPI")
|
| 14 |
+
|
| 15 |
+
# ---------------- FASTAPI APP ----------------
|
| 16 |
+
app = FastAPI(title="French Title Generator API")
|
| 17 |
|
| 18 |
# ---------------- MODEL CLASS ----------------
|
| 19 |
class FrenchTitleGenerator:
|
| 20 |
+
def __init__(self, model_name='Helsinki-NLP/opus-mt-en-fr'):
|
| 21 |
+
try:
|
| 22 |
+
logger.info("Loading tokenizer and model...")
|
| 23 |
+
self.tokenizer = MarianTokenizer.from_pretrained(model_name)
|
| 24 |
+
self.model = MarianMTModel.from_pretrained(model_name)
|
| 25 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 26 |
+
self.model.to(self.device)
|
| 27 |
+
self.model.eval()
|
| 28 |
+
logger.info(f"Model loaded on {self.device}")
|
| 29 |
+
except Exception as e:
|
| 30 |
+
logger.error(f"Model initialization failed: {e}")
|
| 31 |
+
raise
|
| 32 |
|
| 33 |
+
def generate_title(self, year: str, city: str, original_title: str, max_length: int = 50, temperature: float = 0.8):
|
| 34 |
try:
|
| 35 |
input_text = f"Generate title from: Year: {year} City: {city} Description: {original_title}"
|
| 36 |
+
inputs = self.tokenizer(
|
| 37 |
+
input_text,
|
| 38 |
+
return_tensors="pt",
|
| 39 |
+
max_length=128,
|
| 40 |
+
truncation=True,
|
| 41 |
+
padding=True
|
| 42 |
+
).to(self.device)
|
| 43 |
|
| 44 |
with torch.no_grad():
|
| 45 |
outputs = self.model.generate(
|
| 46 |
+
input_ids=inputs["input_ids"],
|
| 47 |
attention_mask=inputs["attention_mask"],
|
| 48 |
max_length=max_length,
|
| 49 |
temperature=temperature,
|
|
|
|
| 51 |
num_beams=3,
|
| 52 |
early_stopping=True
|
| 53 |
)
|
| 54 |
+
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
except Exception as e:
|
| 56 |
+
logger.error(f"Title generation failed: {e}")
|
| 57 |
+
return f"{original_title} - {city} {year}"
|
| 58 |
|
| 59 |
+
# ---------------- INITIALIZE MODEL ----------------
|
| 60 |
+
model = FrenchTitleGenerator()
|
| 61 |
|
| 62 |
+
# ---------------- REQUEST SCHEMA ----------------
|
| 63 |
+
class TitleRequest(BaseModel):
|
| 64 |
+
year: str
|
| 65 |
+
city: str
|
| 66 |
+
original_title: str
|
| 67 |
+
max_length: int = 50
|
| 68 |
+
temperature: float = 0.8
|
| 69 |
|
| 70 |
+
# ---------------- API ENDPOINTS ----------------
|
| 71 |
+
@app.get("/api/health")
|
| 72 |
+
def health_check():
|
| 73 |
+
return {
|
| 74 |
+
"status": "healthy",
|
| 75 |
+
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
|
| 76 |
+
"model_loaded": model is not None
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
@app.post("/api/generate")
|
| 80 |
+
def generate_title(req: TitleRequest):
|
| 81 |
+
try:
|
| 82 |
+
result = model.generate_title(
|
| 83 |
+
year=req.year,
|
| 84 |
+
city=req.city,
|
| 85 |
+
original_title=req.original_title,
|
| 86 |
+
max_length=req.max_length,
|
| 87 |
+
temperature=req.temperature
|
| 88 |
+
)
|
| 89 |
+
return {
|
| 90 |
+
"input": req.dict(),
|
| 91 |
+
"generated_title": result,
|
| 92 |
+
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
|
| 93 |
+
}
|
| 94 |
+
except Exception as e:
|
| 95 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 96 |
|
| 97 |
+
@app.get("/")
|
| 98 |
+
def root():
|
| 99 |
+
return {
|
| 100 |
+
"message": "French Title Generator API is running",
|
| 101 |
+
"endpoints": {
|
| 102 |
+
"/api/health": "Health check",
|
| 103 |
+
"/api/generate": "POST JSON to generate title"
|
| 104 |
+
}
|
| 105 |
+
}
|