Tojichok commited on
Commit
40082c2
·
verified ·
1 Parent(s): 327edf5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -25
app.py CHANGED
@@ -5,46 +5,41 @@ from PIL import Image
5
  import torch
6
  from transformers import BlipProcessor, BlipForConditionalGeneration
7
 
8
- # 1) Устройство (CPU/GPU)
9
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10
- print("Using device:", device)
11
 
12
- # 2) Лёгкая BLIPмодель (~240 MiB)
13
  processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
14
  model = BlipForConditionalGeneration.from_pretrained(
15
  "Salesforce/blip-image-captioning-base"
16
  ).to(device)
17
 
18
- # 3) TMDb API key из Secrets
19
- TMDB_KEY = os.environ.get("TMDB_API_KEY", None)
20
  if not TMDB_KEY:
21
- raise ValueError("TMDB_API_KEY not found in Secrets")
22
-
23
  TMDB_SEARCH_URL = "https://api.themoviedb.org/3/search/movie"
24
 
25
  def caption_and_search(image: Image.Image):
26
- print(">>> got request, image size:", image.size)
27
- # Генерируем подпись
28
  inputs = processor(images=image, return_tensors="pt").to(device)
29
  with torch.no_grad():
30
  out_ids = model.generate(**inputs, max_new_tokens=30)
31
  caption = processor.decode(out_ids[0], skip_special_tokens=True).strip()
32
-
33
- # Ищем фильмы по полученной подписи
34
- params = {"api_key": TMDB_KEY, "query": caption}
35
- resp = requests.get(TMDB_SEARCH_URL, params=params, timeout=10)
36
  if resp.status_code != 200:
37
- return caption, [{"error": f"TMDb API returned {resp.status_code}"}]
38
-
39
  data = resp.json().get("results", [])[:3]
40
- results = [
41
- {"title": m.get("title", "Unknown"), "url": f"https://www.themoviedb.org/movie/{m['id']}"}
42
- for m in data
43
- ]
44
- print(">>> returning caption:", caption)
45
  return caption, results
46
 
47
- # 4) Gradio-интерфейс
48
  iface = gr.Interface(
49
  fn=caption_and_search,
50
  inputs=gr.Image(type="pil", label="Постер или кадр фильма"),
@@ -53,9 +48,9 @@ iface = gr.Interface(
53
  gr.JSON(label="Top‑3 Movies (title + URL)")
54
  ],
55
  title="Fast Movie Finder (BLIP‑Base + TMDb)",
56
- description="Генерирует подпись и ищет топ‑3 фильма по TMDb"
57
- )
58
 
59
  if __name__ == "__main__":
60
- # Без share=True внутри Spaces
61
- iface.launch()
 
5
  import torch
6
  from transformers import BlipProcessor, BlipForConditionalGeneration
7
 
8
+ # 1) Устройство
9
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10
+ print("🖥️ Using device:", device)
11
 
12
+ # 2) Лёгкая BLIP-модель (~240 MiB)
13
  processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
14
  model = BlipForConditionalGeneration.from_pretrained(
15
  "Salesforce/blip-image-captioning-base"
16
  ).to(device)
17
 
18
+ # 3) TMDb API key
19
+ TMDB_KEY = os.environ.get("TMDB_API_KEY")
20
  if not TMDB_KEY:
21
+ raise RuntimeError("TMDB_API_KEY is missing in your Secrets")
 
22
  TMDB_SEARCH_URL = "https://api.themoviedb.org/3/search/movie"
23
 
24
  def caption_and_search(image: Image.Image):
25
+ print("➡️ Received request, image size:", image.size)
26
+ # 4) caption
27
  inputs = processor(images=image, return_tensors="pt").to(device)
28
  with torch.no_grad():
29
  out_ids = model.generate(**inputs, max_new_tokens=30)
30
  caption = processor.decode(out_ids[0], skip_special_tokens=True).strip()
31
+ print("🔖 Caption:", caption)
32
+ # 5) TMDb search
33
+ resp = requests.get(TMDB_SEARCH_URL, params={"api_key": TMDB_KEY, "query": caption}, timeout=10)
 
34
  if resp.status_code != 200:
35
+ print("⚠️ TMDb returned", resp.status_code)
36
+ return caption, [{"error": f"TMDb {resp.status_code}"}]
37
  data = resp.json().get("results", [])[:3]
38
+ results = [{"title": m["title"], "url": f"https://www.themoviedb.org/movie/{m['id']}"} for m in data]
39
+ print(" Returning", len(results), "results")
 
 
 
40
  return caption, results
41
 
42
+ # 6) Интерфейс с очередью
43
  iface = gr.Interface(
44
  fn=caption_and_search,
45
  inputs=gr.Image(type="pil", label="Постер или кадр фильма"),
 
48
  gr.JSON(label="Top‑3 Movies (title + URL)")
49
  ],
50
  title="Fast Movie Finder (BLIP‑Base + TMDb)",
51
+ description="Генерирует подпись и ищет топ‑3 фильма в TMDb"
52
+ ).queue() # <— включает очередь обработки долгих запросов
53
 
54
  if __name__ == "__main__":
55
+ # debug=True позволит вывести стектрейсы ошибок в браузер
56
+ iface.launch(debug=True)