Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,46 +5,41 @@ from PIL import Image
|
|
| 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
|
| 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
|
| 22 |
-
|
| 23 |
TMDB_SEARCH_URL = "https://api.themoviedb.org/3/search/movie"
|
| 24 |
|
| 25 |
def caption_and_search(image: Image.Image):
|
| 26 |
-
print("
|
| 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 |
-
|
| 35 |
-
resp = requests.get(TMDB_SEARCH_URL, params=params, timeout=10)
|
| 36 |
if resp.status_code != 200:
|
| 37 |
-
|
| 38 |
-
|
| 39 |
data = resp.json().get("results", [])[:3]
|
| 40 |
-
results = [
|
| 41 |
-
|
| 42 |
-
for m in data
|
| 43 |
-
]
|
| 44 |
-
print(">>> returning caption:", caption)
|
| 45 |
return caption, results
|
| 46 |
|
| 47 |
-
#
|
| 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 фильма
|
| 57 |
-
)
|
| 58 |
|
| 59 |
if __name__ == "__main__":
|
| 60 |
-
#
|
| 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)
|