sufya12 commited on
Commit
841a7fd
·
verified ·
1 Parent(s): de0fab8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -45
app.py CHANGED
@@ -1,31 +1,49 @@
1
- import gradio as gr
2
- import torch
3
- import pandas as pd
4
  from transformers import MarianMTModel, MarianTokenizer
 
 
5
  import logging
6
- import os
7
 
8
  # ---------------- LOGGING ----------------
9
- logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
10
- logger = logging.getLogger("FrenchTitleApp")
 
 
 
 
 
 
11
 
12
  # ---------------- MODEL CLASS ----------------
13
  class FrenchTitleGenerator:
14
- def __init__(self, model_name="Helsinki-NLP/opus-mt-en-fr"):
15
- logger.info(f"Loading model: {model_name}")
16
- self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
17
- self.tokenizer = MarianTokenizer.from_pretrained(model_name)
18
- self.model = MarianMTModel.from_pretrained(model_name).to(self.device)
19
- logger.info("Model loaded successfully")
 
 
 
 
 
 
20
 
21
- def generate(self, year, city, original_title, max_length=50, temperature=0.8):
22
  try:
23
  input_text = f"Generate title from: Year: {year} City: {city} Description: {original_title}"
24
- inputs = self.tokenizer(input_text, return_tensors="pt", padding=True, truncation=True).to(self.device)
 
 
 
 
 
 
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"Error during generation: {e}")
44
- return f"Error: {e}"
45
 
46
- # ---------------- INIT MODEL ----------------
47
- generator = FrenchTitleGenerator()
48
 
49
- # ---------------- GRADIO APP ----------------
50
- def generate_title(year, city, original_title, temperature=0.8, max_length=50):
51
- return generator.generate(year, city, original_title, max_length=max_length, temperature=temperature)
 
 
 
 
52
 
53
- iface = gr.Interface(
54
- fn=generate_title,
55
- inputs=[
56
- gr.Textbox(label="Year", placeholder="e.g. 2025"),
57
- gr.Textbox(label="City", placeholder="e.g. Paris"),
58
- gr.Textbox(label="Original Title", placeholder="e.g. Jazz Festival in the City Park"),
59
- gr.Slider(0.1, 1.5, value=0.8, step=0.1, label="Temperature"),
60
- gr.Slider(10, 100, value=50, step=5, label="Max Length")
61
- ],
62
- outputs=gr.Textbox(label="Generated French Title"),
63
- title="🇫🇷 French Title Generator",
64
- description="Generate a French event title based on year, city, and description using a translation model.",
65
- theme="soft"
66
- )
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
- if __name__ == "__main__":
69
- iface.launch()
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
+ }