Serg4451D commited on
Commit
e83b61c
·
verified ·
1 Parent(s): 20f2452

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -0
app.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from gradio_client import Client, handle_file
4
+ from openai import OpenAI
5
+
6
+ # --- Конфиг ---
7
+ NV_API_KEY = os.environ.get("NV_API_KEY")
8
+ if not NV_API_KEY:
9
+ raise ValueError("В Secrets Hugging Face Spaces нужно задать NV_API_KEY")
10
+
11
+ # Модель Florence-2
12
+ florence = Client("gokaygokay/Florence-2")
13
+
14
+ # Модель NVIDIA GPT-OSS-120B
15
+ llm = OpenAI(
16
+ base_url="https://integrate.api.nvidia.com/v1",
17
+ api_key=NV_API_KEY
18
+ )
19
+
20
+ # --- Функции ---
21
+ def get_caption(image_path):
22
+ """Делаем подробную подпись через Florence-2."""
23
+ try:
24
+ result = florence.predict(
25
+ image=handle_file(image_path),
26
+ task_prompt="More Detailed Caption",
27
+ text_input=None,
28
+ model_id="microsoft/Florence-2-large",
29
+ api_name="/process_image"
30
+ )
31
+ return result if isinstance(result, str) else str(result)
32
+ except Exception as e:
33
+ return f"[Ошибка при генерации подписи: {e}]"
34
+
35
+ def chat_with_image(image_path, user_message, history):
36
+ """Отправляем в LLM запрос с учетом подписи от Florence-2."""
37
+ if not image_path:
38
+ return history + [[user_message, "Пожалуйста, загрузите изображение."]]
39
+
40
+ caption = get_caption(image_path)
41
+
42
+ system_prompt = (
43
+ "Ты — 'multimodal gpt-oss 120b', умный ассистент, который видит изображение.\n"
44
+ f"Подробная подпись к картинке:\n{caption}\n"
45
+ "Используй её, чтобы отвечать на вопросы пользователя."
46
+ )
47
+
48
+ history = history or []
49
+ history.append([user_message, ""])
50
+
51
+ # Стриминг ответа
52
+ response_text = ""
53
+ for chunk in llm.chat.completions.create(
54
+ model="openai/gpt-oss-120b",
55
+ messages=[
56
+ {"role": "system", "content": system_prompt},
57
+ {"role": "user", "content": user_message}
58
+ ],
59
+ temperature=0.8,
60
+ top_p=1,
61
+ max_tokens=1024,
62
+ stream=True
63
+ ):
64
+ delta = chunk.choices[0].delta
65
+ if delta.content:
66
+ response_text += delta.content
67
+ history[-1][1] = response_text
68
+ yield history
69
+
70
+ # --- UI ---
71
+ example_images = [
72
+ ["https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png"],
73
+ ["https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png"],
74
+ ["https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cheetah.jpg"],
75
+ ["https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/flowers.png"],
76
+ ]
77
+
78
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
79
+ gr.Markdown(
80
+ "<h1 style='text-align:center'>🖼️ multimodal gpt-oss 120b</h1>"
81
+ "<p style='text-align:center'>Загружайте изображение или выберите из галереи — модель увидит его и ответит на вопросы.</p>"
82
+ )
83
+
84
+ with gr.Row():
85
+ with gr.Column(scale=4):
86
+ image_input = gr.Image(type="filepath", label="Загрузите или выберите картинку")
87
+ gallery = gr.Gallery(
88
+ value=example_images,
89
+ label="Примеры",
90
+ columns=4,
91
+ height="auto",
92
+ preview=True
93
+ )
94
+ user_input = gr.Textbox(label="Ваш вопрос", placeholder="Например: Что изображено на фото?")
95
+ send_btn = gr.Button("Отправить")
96
+
97
+ with gr.Column(scale=6):
98
+ chatbot = gr.Chatbot(label="Чат", height=500)
99
+ clear_btn = gr.Button("Очистить чат")
100
+
101
+ # Логика выбора картинки из галереи
102
+ def select_example(example):
103
+ return example[0]
104
+
105
+ gallery.select(select_example, inputs=[gallery], outputs=[image_input])
106
+
107
+ send_btn.click(
108
+ chat_with_image,
109
+ inputs=[image_input, user_input, chatbot],
110
+ outputs=[chatbot]
111
+ )
112
+
113
+ clear_btn.click(lambda: None, None, chatbot)
114
+
115
+ # Запуск
116
+ if __name__ == "__main__":
117
+ demo.launch()
118
+