Spaces:
Runtime error
Runtime error
Заміна кнопки завантаження на збереження результатів
Browse files- Gradio_UI.py +40 -66
- reports/report_20250215_133244.md +49 -0
- saved_reports/research_report_20250215_140148.md +33 -0
Gradio_UI.py
CHANGED
|
@@ -2,14 +2,13 @@ import gradio as gr
|
|
| 2 |
import logging
|
| 3 |
from pathlib import Path
|
| 4 |
from typing import Tuple, List
|
|
|
|
| 5 |
|
| 6 |
logger = logging.getLogger(__name__)
|
| 7 |
|
| 8 |
class GradioUI:
|
| 9 |
-
def __init__(self, agent
|
| 10 |
self.agent = agent
|
| 11 |
-
self.file_upload_folder = Path(file_upload_folder)
|
| 12 |
-
self.file_upload_folder.mkdir(exist_ok=True)
|
| 13 |
|
| 14 |
def build_interface(self):
|
| 15 |
with gr.Blocks(theme=gr.themes.Soft()) as interface:
|
|
@@ -40,17 +39,6 @@ class GradioUI:
|
|
| 40 |
show_copy_button=True
|
| 41 |
)
|
| 42 |
|
| 43 |
-
with gr.Row(visible=False) as file_upload_row:
|
| 44 |
-
upload_file = gr.File(
|
| 45 |
-
label="Upload File",
|
| 46 |
-
file_types=[".csv", ".xlsx", ".txt", ".pdf", ".doc", ".docx"]
|
| 47 |
-
)
|
| 48 |
-
upload_status = gr.Textbox(
|
| 49 |
-
label="Upload Status",
|
| 50 |
-
interactive=False,
|
| 51 |
-
visible=False
|
| 52 |
-
)
|
| 53 |
-
|
| 54 |
with gr.Row():
|
| 55 |
text_input = gr.Textbox(
|
| 56 |
label="Введіть ваш запит",
|
|
@@ -61,11 +49,16 @@ class GradioUI:
|
|
| 61 |
with gr.Row():
|
| 62 |
submit_btn = gr.Button("Надіслати", variant="primary")
|
| 63 |
clear_btn = gr.Button("Очистити")
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
# Зберігання стану
|
| 67 |
state = gr.State([])
|
| 68 |
-
file_history = gr.State([])
|
| 69 |
current_model = gr.State(self.agent.model_initializer.config['default_model'])
|
| 70 |
|
| 71 |
def change_model(choice):
|
|
@@ -79,85 +72,66 @@ class GradioUI:
|
|
| 79 |
outputs=[current_model]
|
| 80 |
)
|
| 81 |
|
| 82 |
-
def
|
| 83 |
-
return not visible
|
| 84 |
-
|
| 85 |
-
toggle_upload_btn.click(
|
| 86 |
-
fn=toggle_upload,
|
| 87 |
-
inputs=[file_upload_row],
|
| 88 |
-
outputs=[file_upload_row]
|
| 89 |
-
)
|
| 90 |
-
|
| 91 |
-
def process_upload(file, history):
|
| 92 |
-
if file:
|
| 93 |
-
try:
|
| 94 |
-
file_path = self.file_upload_folder / file.name
|
| 95 |
-
with open(file_path, 'wb') as f:
|
| 96 |
-
f.write(file.read())
|
| 97 |
-
history.append(str(file_path))
|
| 98 |
-
return gr.update(value=f"Файл завантажено: {file.name}"), history
|
| 99 |
-
except Exception as e:
|
| 100 |
-
logger.error(f"Помилка завантаження: {e}")
|
| 101 |
-
return gr.update(value=f"Помилка завантаження: {str(e)}"), history
|
| 102 |
-
return gr.update(value="Файл не вибрано"), history
|
| 103 |
-
|
| 104 |
-
upload_file.change(
|
| 105 |
-
fn=process_upload,
|
| 106 |
-
inputs=[upload_file, file_history],
|
| 107 |
-
outputs=[upload_status, file_history]
|
| 108 |
-
)
|
| 109 |
-
|
| 110 |
-
def user_message(message, chat_history, files):
|
| 111 |
-
if files:
|
| 112 |
-
message += f"\nДоступні файли для аналізу: {', '.join(files)}"
|
| 113 |
chat_history.append((message, None))
|
| 114 |
return "", chat_history, "Початок обробки запиту...\n"
|
| 115 |
|
| 116 |
-
def bot_response(chat_history,
|
| 117 |
try:
|
| 118 |
-
# Оновлюємо лог кроків
|
| 119 |
steps = []
|
| 120 |
def step_callback(step_info):
|
| 121 |
steps.append(f"Step {len(steps)+1}: {step_info}")
|
| 122 |
return "\n".join(steps)
|
| 123 |
|
| 124 |
-
# Додаємо callback до агента
|
| 125 |
self.agent.step_callback = step_callback
|
| 126 |
-
|
| 127 |
-
# Обробляємо запит
|
| 128 |
-
response = self.agent.process_query(
|
| 129 |
-
chat_history[-1][0],
|
| 130 |
-
available_files=files if files else None
|
| 131 |
-
)
|
| 132 |
-
|
| 133 |
-
# Оновлюємо історію чату
|
| 134 |
chat_history[-1] = (chat_history[-1][0], response)
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
| 138 |
except Exception as e:
|
| 139 |
logger.error(f"Помилка відповіді: {e}")
|
| 140 |
error_msg = f"Помилка: {str(e)}"
|
| 141 |
chat_history[-1] = (chat_history[-1][0], error_msg)
|
| 142 |
-
return chat_history, steps_text + f"\nПомилка: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
submit_btn.click(
|
| 145 |
user_message,
|
| 146 |
-
[text_input, state
|
| 147 |
[text_input, chatbot, steps_log]
|
| 148 |
).then(
|
| 149 |
bot_response,
|
| 150 |
-
[chatbot,
|
| 151 |
-
[chatbot, steps_log]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
)
|
| 153 |
|
| 154 |
def clear_chat():
|
| 155 |
-
return [],
|
| 156 |
|
| 157 |
clear_btn.click(
|
| 158 |
clear_chat,
|
| 159 |
None,
|
| 160 |
-
[chatbot,
|
| 161 |
queue=False
|
| 162 |
)
|
| 163 |
|
|
|
|
| 2 |
import logging
|
| 3 |
from pathlib import Path
|
| 4 |
from typing import Tuple, List
|
| 5 |
+
from datetime import datetime
|
| 6 |
|
| 7 |
logger = logging.getLogger(__name__)
|
| 8 |
|
| 9 |
class GradioUI:
|
| 10 |
+
def __init__(self, agent):
|
| 11 |
self.agent = agent
|
|
|
|
|
|
|
| 12 |
|
| 13 |
def build_interface(self):
|
| 14 |
with gr.Blocks(theme=gr.themes.Soft()) as interface:
|
|
|
|
| 39 |
show_copy_button=True
|
| 40 |
)
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
with gr.Row():
|
| 43 |
text_input = gr.Textbox(
|
| 44 |
label="Введіть ваш запит",
|
|
|
|
| 49 |
with gr.Row():
|
| 50 |
submit_btn = gr.Button("Надіслати", variant="primary")
|
| 51 |
clear_btn = gr.Button("Очистити")
|
| 52 |
+
save_btn = gr.Button("Зберегти")
|
| 53 |
+
|
| 54 |
+
# Прихований компонент для зберігання тексту відповіді
|
| 55 |
+
response_text = gr.Textbox(visible=False)
|
| 56 |
+
|
| 57 |
+
# Компонент для файлу з автоматичним завантаженням
|
| 58 |
+
file_output = gr.File(interactive=False)
|
| 59 |
|
| 60 |
# Зберігання стану
|
| 61 |
state = gr.State([])
|
|
|
|
| 62 |
current_model = gr.State(self.agent.model_initializer.config['default_model'])
|
| 63 |
|
| 64 |
def change_model(choice):
|
|
|
|
| 72 |
outputs=[current_model]
|
| 73 |
)
|
| 74 |
|
| 75 |
+
def user_message(message, chat_history):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
chat_history.append((message, None))
|
| 77 |
return "", chat_history, "Початок обробки запиту...\n"
|
| 78 |
|
| 79 |
+
def bot_response(chat_history, steps_text):
|
| 80 |
try:
|
|
|
|
| 81 |
steps = []
|
| 82 |
def step_callback(step_info):
|
| 83 |
steps.append(f"Step {len(steps)+1}: {step_info}")
|
| 84 |
return "\n".join(steps)
|
| 85 |
|
|
|
|
| 86 |
self.agent.step_callback = step_callback
|
| 87 |
+
response = self.agent.process_query(chat_history[-1][0])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
chat_history[-1] = (chat_history[-1][0], response)
|
| 89 |
|
| 90 |
+
return (
|
| 91 |
+
chat_history,
|
| 92 |
+
"\n".join(steps) + "\n\nОбробку завершено.",
|
| 93 |
+
response
|
| 94 |
+
)
|
| 95 |
except Exception as e:
|
| 96 |
logger.error(f"Помилка відповіді: {e}")
|
| 97 |
error_msg = f"Помилка: {str(e)}"
|
| 98 |
chat_history[-1] = (chat_history[-1][0], error_msg)
|
| 99 |
+
return chat_history, steps_text + f"\nПомилка: {str(e)}", ""
|
| 100 |
+
|
| 101 |
+
def save_response(response):
|
| 102 |
+
if response:
|
| 103 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 104 |
+
filename = f"research_report_{timestamp}.md"
|
| 105 |
+
file_path = Path("saved_reports") / filename
|
| 106 |
+
file_path.parent.mkdir(exist_ok=True)
|
| 107 |
+
with open(file_path, "w", encoding="utf-8") as f:
|
| 108 |
+
f.write(str(response))
|
| 109 |
+
return str(file_path)
|
| 110 |
+
return None
|
| 111 |
|
| 112 |
submit_btn.click(
|
| 113 |
user_message,
|
| 114 |
+
[text_input, state],
|
| 115 |
[text_input, chatbot, steps_log]
|
| 116 |
).then(
|
| 117 |
bot_response,
|
| 118 |
+
[chatbot, steps_log],
|
| 119 |
+
[chatbot, steps_log, response_text]
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
save_btn.click(
|
| 123 |
+
save_response,
|
| 124 |
+
inputs=[response_text],
|
| 125 |
+
outputs=[file_output]
|
| 126 |
)
|
| 127 |
|
| 128 |
def clear_chat():
|
| 129 |
+
return [], "", "", None
|
| 130 |
|
| 131 |
clear_btn.click(
|
| 132 |
clear_chat,
|
| 133 |
None,
|
| 134 |
+
[chatbot, steps_log, response_text, file_output],
|
| 135 |
queue=False
|
| 136 |
)
|
| 137 |
|
reports/report_20250215_133244.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
**Report on the Application of LLMs in Healthcare**
|
| 2 |
+
|
| 3 |
+
**Introduction**
|
| 4 |
+
|
| 5 |
+
The integration of large language models (LLMs) in healthcare has garnered significant interest and advancements. LLMs are powerful AI models capable of processing and generating human-like text, which offers transformative potential for various aspects of healthcare.
|
| 6 |
+
|
| 7 |
+
**Current Applications**
|
| 8 |
+
|
| 9 |
+
Various applications of LLMs in healthcare include:
|
| 10 |
+
|
| 11 |
+
* **Medical Information Extraction:** LLMs can extract relevant information from medical records, such as symptoms, diagnoses, and treatments, reducing manual labor and improving data accuracy.
|
| 12 |
+
* **Clinical Decision Support:** By analyzing patient data, LLMs can assist healthcare professionals in making informed clinical decisions, suggesting diagnoses, and providing treatment recommendations.
|
| 13 |
+
* **Drug Discovery:** LLMs can analyze vast amounts of scientific literature and data to identify potential drug targets and design new molecules, accelerating drug development.
|
| 14 |
+
* **Personalized Medicine:** LLMs can tailor treatments to individual patients based on their genetic profile and medical history, enabling personalized healthcare interventions.
|
| 15 |
+
* **Patient Education:** LLMs can create patient-friendly educational materials, empowering patients with comprehensive information about their health conditions and treatment options.
|
| 16 |
+
|
| 17 |
+
**Benefits**
|
| 18 |
+
|
| 19 |
+
The application of LLMs in healthcare brings numerous benefits:
|
| 20 |
+
|
| 21 |
+
* **Improved Efficiency:** LLMs automate tasks, freeing up healthcare professionals to focus on patient care.
|
| 22 |
+
* **Enhanced Accuracy:** LLMs can process vast amounts of data and provide accurate and reliable information.
|
| 23 |
+
* **Personalized Care:** LLMs facilitate tailor-made treatments and enhance the patient-provider relationship.
|
| 24 |
+
* **Time Savings:** LLMs can expedite processes such as medical record review and clinical decision-making.
|
| 25 |
+
* **Expanded Access:** LLMs can provide essential healthcare information and support to underserved communities.
|
| 26 |
+
|
| 27 |
+
**Challenges**
|
| 28 |
+
|
| 29 |
+
Despite their potential, LLMs face certain challenges:
|
| 30 |
+
|
| 31 |
+
* **Data Privacy:** LLMs require access to vast amounts of sensitive patient data, raising data privacy and security concerns.
|
| 32 |
+
* **Bias:** LLMs trained on biased data may perpetuate biases, leading to unfair or inaccurate outcomes.
|
| 33 |
+
* **Interpretability:** The complex nature of LLMs may make it difficult to understand and explain their decision-making process.
|
| 34 |
+
* **Ethical Considerations:** The use of LLMs in healthcare raises ethical questions related to patient autonomy, informed consent, and accountability for decisions.
|
| 35 |
+
|
| 36 |
+
**Future Outlook**
|
| 37 |
+
|
| 38 |
+
The future of LLMs in healthcare is promising:
|
| 39 |
+
|
| 40 |
+
* **Continued Research:** Ongoing research will address challenges and expand the capabilities of LLMs.
|
| 41 |
+
* **Integration with Other Technologies:** LLMs will be integrated with other technologies, such as electronic health records, for seamless and interoperable healthcare systems.
|
| 42 |
+
* **Enhanced Patient Experience:** LLMs will empower patients with personalized care plans, improved access to information, and a more proactive role in their health management.
|
| 43 |
+
* **Improved Healthcare Outcomes:** LLMs will contribute to improved healthcare outcomes by providing timely, accurate, and personalized information and decision support.
|
| 44 |
+
|
| 45 |
+
**References**
|
| 46 |
+
|
| 47 |
+
* [Revolutionizing Healthcare: Exploring the Impact and Future of Large Language Models in Medicine](https://www.unite.ai/uk/революціонізуюча-охорона-здоров’я,-досліджуючи-вплив-і-майбутнє-великих-мовних-моделей-у-медицині/)
|
| 48 |
+
* [Best Llm Programs in Healthcare Medical Humanities](https://www.pravoznavstvo.com/llm/медична-етика)
|
| 49 |
+
* [Generative AI in Healthcare: Applications, Benefits, Challenges, and the Future](https://uk.shaip.com/blog/generative-ai-in-healthcare/)
|
saved_reports/research_report_20250215_140148.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
**Застосування великих мовних моделей (LLM) у фінансах**
|
| 2 |
+
|
| 3 |
+
**Вступ**
|
| 4 |
+
Штучний інтелект (ШІ) трансформує фінансову галузь, а великі мовні моделі (LLM) є на передовій цих інновацій. LLM - це потужні алгоритми, які навчаються на величезних обсягах текстових даних і можуть виконувати широкий спектр завдань, пов'язаних з мовою, включаючи створення, переклад, підсумовування та відповідей на запитання.
|
| 5 |
+
|
| 6 |
+
**Застосування LLM у фінансах**
|
| 7 |
+
|
| 8 |
+
LLM знаходять численні застосування у фінансовій сфері, зокрема:
|
| 9 |
+
|
| 10 |
+
* **Аналіз ринку:** LLM можна використовувати для аналізу великих обсягів фінансових даних, таких як новини, звіти компаній та економічні показники. Вони можуть виявляти закономірності, тенденції та аномалії, які можуть бути корисними для прийняття інвестиційних рішень.
|
| 11 |
+
* **Автоматизоване створення звітів:** LLM можуть автоматизувати створення фінансових звітів, заощаджуючи час і покращуючи точність. Вони можуть генерувати звіти з фінансової інформації, такої як фінансові звіти, аналізи ринку та звіти про стійкість.
|
| 12 |
+
* **Оцінювання кредитного ризику:** LLM можуть допомогти банкам і фінансовим установам оцінити кредитний ризик позичальників. Вони можуть аналізувати кредитну історію, фінансове становище та інші фактори, щоб визначити ймовірність дефолту.
|
| 13 |
+
* **Чат-боти для обслуговування клієнтів:** LLM можуть використовуватися для створення чат-ботів, які можуть надавати допомогу клієнтам у режимі реального часу. Вони можуть відповідати на запитання, вирішувати проблеми та направляти клієнтів до відповідних ресурсів.
|
| 14 |
+
* **Розробка інвестиційних стратегій:** LLM можуть допомогти фінансовим радникам розробляти інвестиційні стратегії для своїх клієнтів. Вони можуть аналізувати дані про ринок, інвестиційні цілі клієнтів і рівень толерантності до ризику та надавати персоналізовані рекомендації.
|
| 15 |
+
|
| 16 |
+
**Переваги використання LLM у фінансах**
|
| 17 |
+
|
| 18 |
+
Використання LLM у фінансах пропонує численні переваги, зокрема:
|
| 19 |
+
|
| 20 |
+
* **Покращена ефективність:** LLM можуть автоматизувати багато завдань, які традиційно виконуються людьми, що призводить до підвищення ефективності.
|
| 21 |
+
* **Точність:** LLM є високоточними, оскільки вони навчаються на великих наборах даних і можуть обробляти складні дані.
|
| 22 |
+
* **Персоналізація:** LLM можуть бути налаштовані для задоволення потреб окремих фінансових установ і клієнтів.
|
| 23 |
+
* **Інновації:** LLM відкривають можливості для нових і інноваційних фінансових продуктів і послуг.
|
| 24 |
+
|
| 25 |
+
**Висновки**
|
| 26 |
+
|
| 27 |
+
LLM мають великий потенціал для трансформації фінансової галузі. Вони пропонують низку переваг, включаючи підвищену ефективність, точність, персоналізацію та інновації. Оскільки LLM продовжують розвиватися, можна очікувати, що вони відіграватимуть ще важливішу роль у майбутньому фінансів.
|
| 28 |
+
|
| 29 |
+
**Джерела**
|
| 30 |
+
|
| 31 |
+
* [Large Language Models (LLMs): An Introduction](https://research.aimultiple.com/natural-language-processing/large-language-models/)
|
| 32 |
+
* [How AI is Transforming the Financial Sector: 6 Key Trends](https://processer.media/ua/yak-shtuchnij-intelekt-zminiv-finansovij-sektor-6-golovnih-napryamkiv/)
|
| 33 |
+
* [LLM Applications in Banking and Finance: Key Use Cases](https://uk.shaip.com/blog/llm-in-banking-and-finance/)
|