i-timur commited on
Commit
29dbcf6
·
1 Parent(s): 49672d8
Files changed (2) hide show
  1. .gitignore +1 -0
  2. app.py +140 -53
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ .env
app.py CHANGED
@@ -1,70 +1,157 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
-
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
 
 
 
 
 
 
14
  """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
 
 
 
 
 
 
16
  """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
 
19
- messages = [{"role": "system", "content": system_message}]
 
20
 
21
- messages.extend(history)
 
 
 
 
 
 
22
 
23
- messages.append({"role": "user", "content": message})
 
 
 
24
 
25
- response = ""
 
26
 
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
 
39
- response += token
40
- yield response
41
 
 
 
 
 
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
  )
62
 
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  if __name__ == "__main__":
70
- demo.launch()
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import asyncio
3
+ from smolagents import CodeAgent, tool, InferenceClientModel
4
+ from bs4 import BeautifulSoup
5
+ import duckduckgo_search
6
+ import os
7
+
8
+ token = os.environ.get("HUGGINGFACE_TOKEN", "")
9
+
10
+ @tool
11
+ def web_search_duckduckgo(query: str) -> list:
12
+ """
13
+ Выполняет поиск через DuckDuckGo.
14
+
15
+ Args:
16
+ query (str): поисковый запрос.
17
+
18
+ Returns:
19
+ list: список найденных URL.
20
  """
21
+ results = duckduckgo_search.DDGS().text(query)
22
+ urls = [r["href"] for r in results]
23
+ return urls
24
+
25
+
26
+ @tool
27
+ def fetch_html(url: str) -> str:
28
  """
29
+ Загружает HTML по URL.
30
 
31
+ Args:
32
+ url (str): адрес страницы.
33
 
34
+ Returns:
35
+ str: HTML-текст страницы.
36
+ """
37
+ import requests
38
+ resp = requests.get(url, timeout=10)
39
+ resp.raise_for_status()
40
+ return resp.text
41
 
42
+ @tool
43
+ def extract_text_from_html(html: str) -> str:
44
+ """
45
+ Извлекает текст из HTML.
46
 
47
+ Args:
48
+ html (str): HTML-документ.
49
 
50
+ Returns:
51
+ str: текстовое содержимое документа.
52
+ """
53
+ from bs4 import BeautifulSoup
54
+ soup = BeautifulSoup(html, "html.parser")
55
+ return soup.get_text("\n")
 
 
 
 
 
56
 
 
 
57
 
58
+ @tool
59
+ def summarize_and_extract_architecture(text: str) -> str:
60
+ """
61
+ Анализирует текст статьи и извлекает архитектуру описанной системы.
62
 
63
+ Args:
64
+ text (str): Полный текст статьи или её фрагмент, в котором описана система.
65
+
66
+ Returns:
67
+ str: Структурированное текстовое описание архитектуры системы
68
+ (компоненты, связи, потоки данных, этапы обработки).
69
+ """
70
+ model = InferenceClientModel(model_id="Qwen/Qwen2.5-7B-Instruct")
71
+ prompt = f"""
72
+ Ты — эксперт по анализу научных статей.
73
+
74
+ Текст статьи:
75
+ {text}
76
+
77
+ Задача:
78
+ 1. Найди описание архитектуры системы.
79
+ 2. Сформулируй её в виде структурированной схемы:
80
+ - компоненты системы
81
+ - связи между компонентами
82
+ - потоки данных
83
+ - этапы обработки
84
+ 3. Если архитектура явно не выражена — попытайся реконструировать её.
85
  """
86
+ return model(prompt)
87
+
88
+ model = InferenceClientModel(model_id="Qwen/Qwen2.5-7B-Instruct", token = token)
89
+
90
+ agent = CodeAgent(
91
+ model=model,
92
+ tools=[web_search_duckduckgo, fetch_html, extract_text_from_html, summarize_and_extract_architecture],
93
+ add_base_tools=False,
 
 
 
 
 
 
 
 
 
94
  )
95
 
96
+ def process_article(article_title):
97
+ """
98
+ Функция для обработки запроса статьи.
99
+ Вызывает мультиагента для поиска и суммаризации.
100
+ """
101
+ try:
102
+ # Если ваш агент использует асинхронные вызовы
103
+ if hasattr(agent, 'run_async'):
104
+ # Создаем новую event loop для асинхронного вызова
105
+ loop = asyncio.new_event_loop()
106
+ asyncio.set_event_loop(loop)
107
+ result = loop.run_until_complete(agent.run_async(article_title))
108
+ loop.close()
109
+ else:
110
+ # Если агент синхронный
111
+ result = agent.run(article_title)
112
+
113
+ return result
114
+ except Exception as e:
115
+ return f"Произошла ошибка: {str(e)}"
116
 
117
+ # Альтернативный более простой интерфейс (если нужен минималистичный вариант)
118
+ def create_simple_interface():
119
+ """Простой интерфейс для быстрого тестирования"""
120
+
121
+ def simple_process(article_title):
122
+ if not article_title.strip():
123
+ return "Пожалуйста, введите название статьи."
124
+ return process_article(article_title)
125
+
126
+ interface = gr.Interface(
127
+ fn=simple_process,
128
+ inputs=gr.Textbox(
129
+ label="Название статьи",
130
+ placeholder="Например: 'Deep Learning in Computer Vision'",
131
+ lines=2
132
+ ),
133
+ outputs=gr.Textbox(
134
+ label="Результат",
135
+ lines=15,
136
+ placeholder="Результат появится здесь..."
137
+ ),
138
+ title="📄 Поиск и суммаризация статей",
139
+ description="Введите название статьи, и агент найдет ее и создаст краткое содержание.",
140
+ examples=[
141
+ ["Neural Networks and Deep Learning"],
142
+ ["Renewable Energy Technologies Review"],
143
+ ["COVID-19 Vaccines Development and Efficacy"]
144
+ ],
145
+ theme=gr.themes.Soft()
146
+ )
147
+
148
+ return interface
149
 
150
  if __name__ == "__main__":
151
+ demo = create_simple_interface()
152
+ demo.launch(
153
+ server_name="0.0.0.0",
154
+ server_port=7860,
155
+ share=False,
156
+ debug=True
157
+ )