Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,7 +4,6 @@ import pymorphy3
|
|
| 4 |
import re
|
| 5 |
import gradio as gr
|
| 6 |
|
| 7 |
-
|
| 8 |
# Инициализация pymorphy3 (лемматизатор)
|
| 9 |
morph = pymorphy3.MorphAnalyzer()
|
| 10 |
|
|
@@ -31,62 +30,36 @@ personalization_keywords = {
|
|
| 31 |
"Стадия бизнеса Эксперт": ["максимизация", "высокий", "лимит", "снижение", "ставка", "комиссия", "выгода", "оптимизация"]
|
| 32 |
}
|
| 33 |
|
| 34 |
-
# Функция для классификации одного текста преимущества
|
| 35 |
-
def classify_advantage(text, keywords_dict):
|
| 36 |
-
"""
|
| 37 |
-
Возвращает список кортежей вида:
|
| 38 |
-
[
|
| 39 |
-
(category, { 'count': int, 'matched_lemmas': set([...]) }),
|
| 40 |
-
...
|
| 41 |
-
]
|
| 42 |
-
отсортированных по убыванию count.
|
| 43 |
-
"""
|
| 44 |
-
lemmas = tokenize_and_lemmatize(text)
|
| 45 |
-
category_matches = {}
|
| 46 |
-
|
| 47 |
-
# Проходим по всем категориям и считаем число совпадений лемм
|
| 48 |
-
for category, keywords in keywords_dict.items():
|
| 49 |
-
matches = set(lemmas) & set(keywords) # Пересечение множеств
|
| 50 |
-
if matches:
|
| 51 |
-
category_matches[category] = {
|
| 52 |
-
'count': len(matches),
|
| 53 |
-
'matched_lemmas': matches
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
# Сортируем категории по количеству совпадений (по убыванию)
|
| 57 |
-
sorted_matches = sorted(
|
| 58 |
-
category_matches.items(),
|
| 59 |
-
key=lambda x: x[1]['count'],
|
| 60 |
-
reverse=True
|
| 61 |
-
)
|
| 62 |
-
return sorted_matches
|
| 63 |
-
|
| 64 |
# Глобальная переменная для хранения DataFrame
|
| 65 |
df = None
|
| 66 |
|
| 67 |
def load_excel(file):
|
| 68 |
-
"""
|
| 69 |
-
Функция для загрузки Excel-файла.
|
| 70 |
-
Возвращает список уникальных продуктов и сообщение о статусе загрузки.
|
| 71 |
-
"""
|
| 72 |
global df
|
| 73 |
if file is None:
|
| 74 |
return [], "Файл не загружен. Загрузите Excel-файл."
|
| 75 |
try:
|
| 76 |
-
# Читаем Excel в DataFrame
|
| 77 |
df = pd.read_excel(file.name, usecols=["Продукт", "Преимущество"])
|
| 78 |
unique_products = df["Продукт"].unique().tolist()
|
| 79 |
return unique_products, "Файл успешно загружен!"
|
| 80 |
except Exception as e:
|
| 81 |
return [], f"Ошибка при чтении файла: {str(e)}"
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
def analyze(product):
|
| 85 |
-
"""
|
| 86 |
-
Функция, вызываемая при выборе продукта в выпадающем списке.
|
| 87 |
-
Анализирует все преимущества, соответствующие данному продукту,
|
| 88 |
-
и возвращает подробный отчёт и визуализацию графа.
|
| 89 |
-
"""
|
| 90 |
global df
|
| 91 |
if df is None:
|
| 92 |
return "Сначала загрузите файл.", None
|
|
@@ -94,24 +67,22 @@ def analyze(product):
|
|
| 94 |
if not product:
|
| 95 |
return "Пожалуйста, выберите продукт.", None
|
| 96 |
|
| 97 |
-
# Фильтруем DataFrame по выбранному продукту
|
| 98 |
product_advantages = df[df["Продукт"] == product]["Преимущество"]
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
| 101 |
graph_html = create_category_graph(product, product_advantages, personalization_keywords)
|
| 102 |
-
|
| 103 |
-
# Собираем результаты
|
| 104 |
results = []
|
| 105 |
for advantage in product_advantages:
|
| 106 |
matches = classify_advantage(advantage, personalization_keywords)
|
| 107 |
-
# Формируем текстовый отчёт по каждому преимуществу
|
| 108 |
advantage_text = f"**Преимущество**: {advantage}\n\n"
|
| 109 |
advantage_text += f"**Леммы**: {tokenize_and_lemmatize(advantage)}\n\n"
|
| 110 |
advantage_text += "**Совпадающие категории:**\n"
|
| 111 |
-
|
| 112 |
if matches:
|
| 113 |
for category, data in matches:
|
| 114 |
-
# Выводим и количество совпадений, и сами совпавшие леммы
|
| 115 |
matched_lemmas_str = ", ".join(sorted(data['matched_lemmas']))
|
| 116 |
advantage_text += f"- {category}: {data['count']} совпадений (леммы: {matched_lemmas_str})\n"
|
| 117 |
else:
|
|
@@ -119,83 +90,68 @@ def analyze(product):
|
|
| 119 |
advantage_text += "\n---\n"
|
| 120 |
results.append(advantage_text)
|
| 121 |
|
| 122 |
-
if not results:
|
| 123 |
-
return "Для выбранного продукта не найдено преимуществ.", None
|
| 124 |
-
|
| 125 |
return "\n".join(results), graph_html
|
| 126 |
-
|
| 127 |
-
|
| 128 |
def create_category_graph(product, advantages, personalization_keywords):
|
| 129 |
-
"""
|
| 130 |
-
|
| 131 |
-
Возвращает HTML-код для отображения графа в iframe.
|
| 132 |
-
"""
|
| 133 |
-
net = Network(notebook=False, height="500px", width="100%", directed=True, cdn_resources='in_line') # Используем встроенные ресурсы
|
| 134 |
-
|
| 135 |
-
# Добавляем узел для продукта
|
| 136 |
net.add_node(product, label=product, color="lightblue", size=30)
|
| 137 |
-
|
| 138 |
-
# Проходим по всем преимуществам продукта
|
| 139 |
for advantage in advantages:
|
| 140 |
-
# Добавляем узел для преимущества
|
| 141 |
net.add_node(advantage, label=advantage, color="orange", size=20)
|
| 142 |
-
net.add_edge(product, advantage)
|
| 143 |
-
|
| 144 |
-
# Анализируем преимущество и добавляем связи с категориями
|
| 145 |
matches = classify_advantage(advantage, personalization_keywords)
|
| 146 |
for category, data in matches:
|
| 147 |
net.add_node(category, label=category, color="green", size=15)
|
| 148 |
-
net.add_edge(advantage, category)
|
| 149 |
-
|
| 150 |
-
# Генерируем HTML-код для графа
|
| 151 |
html = net.generate_html(notebook=False)
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
# Возвращаем iframe с HTML-кодом графа
|
| 157 |
-
return f"""
|
| 158 |
<iframe
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
</iframe>
|
| 164 |
"""
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
with gr.Blocks() as demo:
|
| 167 |
gr.Markdown("## Классификация преимуществ по признакам персонализации")
|
| 168 |
gr.Markdown("**Шаг 1:** Загрузите Excel-файл с двумя столбцами: 'Продукт' и 'Преимущество'.")
|
| 169 |
-
|
| 170 |
file_input = gr.File(label="Загрузите Excel-файл", file_types=[".xlsx"])
|
| 171 |
load_button = gr.Button("Загрузить файл")
|
| 172 |
load_status = gr.Markdown("")
|
| 173 |
-
|
| 174 |
-
gr.Markdown("**Шаг 2:** Выберите продукт из
|
| 175 |
product_dropdown = gr.Dropdown(choices=[], label="Продукты", value=None)
|
| 176 |
analyze_button = gr.Button("Анализировать")
|
| 177 |
-
|
| 178 |
output_text = gr.Markdown("")
|
| 179 |
output_graph = gr.HTML(label="Визуализация графа")
|
| 180 |
-
|
| 181 |
-
# Логика при нажатии "Загрузить файл"
|
| 182 |
def on_file_upload(file):
|
| 183 |
unique_products, status_message = load_excel(file)
|
| 184 |
return gr.update(choices=unique_products), status_message
|
| 185 |
-
|
| 186 |
load_button.click(
|
| 187 |
fn=on_file_upload,
|
| 188 |
inputs=file_input,
|
| 189 |
outputs=[product_dropdown, load_status]
|
| 190 |
)
|
| 191 |
|
| 192 |
-
# Логика при нажатии "Анализировать"
|
| 193 |
analyze_button.click(
|
| 194 |
fn=analyze,
|
| 195 |
inputs=product_dropdown,
|
| 196 |
outputs=[output_text, output_graph]
|
| 197 |
)
|
| 198 |
|
| 199 |
-
# Запускаем демо
|
| 200 |
if __name__ == "__main__":
|
| 201 |
-
demo.launch(debug=True)
|
|
|
|
| 4 |
import re
|
| 5 |
import gradio as gr
|
| 6 |
|
|
|
|
| 7 |
# Инициализация pymorphy3 (лемматизатор)
|
| 8 |
morph = pymorphy3.MorphAnalyzer()
|
| 9 |
|
|
|
|
| 30 |
"Стадия бизнеса Эксперт": ["максимизация", "высокий", "лимит", "снижение", "ставка", "комиссия", "выгода", "оптимизация"]
|
| 31 |
}
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
# Глобальная переменная для хранения DataFrame
|
| 34 |
df = None
|
| 35 |
|
| 36 |
def load_excel(file):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
global df
|
| 38 |
if file is None:
|
| 39 |
return [], "Файл не загружен. Загрузите Excel-файл."
|
| 40 |
try:
|
|
|
|
| 41 |
df = pd.read_excel(file.name, usecols=["Продукт", "Преимущество"])
|
| 42 |
unique_products = df["Продукт"].unique().tolist()
|
| 43 |
return unique_products, "Файл успешно загружен!"
|
| 44 |
except Exception as e:
|
| 45 |
return [], f"Ошибка при чтении файла: {str(e)}"
|
| 46 |
|
| 47 |
+
def classify_advantage(text, keywords_dict):
|
| 48 |
+
lemmas = tokenize_and_lemmatize(text)
|
| 49 |
+
category_matches = {}
|
| 50 |
+
|
| 51 |
+
for category, keywords in keywords_dict.items():
|
| 52 |
+
matches = set(lemmas) & set(keywords)
|
| 53 |
+
if matches:
|
| 54 |
+
category_matches[category] = {
|
| 55 |
+
'count': len(matches),
|
| 56 |
+
'matched_lemmas': matches
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
sorted_matches = sorted(category_matches.items(), key=lambda x: x[1]['count'], reverse=True)
|
| 60 |
+
return sorted_matches
|
| 61 |
|
| 62 |
def analyze(product):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
global df
|
| 64 |
if df is None:
|
| 65 |
return "Сначала загрузите файл.", None
|
|
|
|
| 67 |
if not product:
|
| 68 |
return "Пожалуйста, выберите продукт.", None
|
| 69 |
|
|
|
|
| 70 |
product_advantages = df[df["Продукт"] == product]["Преимущество"]
|
| 71 |
+
|
| 72 |
+
if product_advantages.empty:
|
| 73 |
+
return "Для выбранного продукта не найдено преимуществ.", None
|
| 74 |
+
|
| 75 |
graph_html = create_category_graph(product, product_advantages, personalization_keywords)
|
| 76 |
+
|
|
|
|
| 77 |
results = []
|
| 78 |
for advantage in product_advantages:
|
| 79 |
matches = classify_advantage(advantage, personalization_keywords)
|
|
|
|
| 80 |
advantage_text = f"**Преимущество**: {advantage}\n\n"
|
| 81 |
advantage_text += f"**Леммы**: {tokenize_and_lemmatize(advantage)}\n\n"
|
| 82 |
advantage_text += "**Совпадающие категории:**\n"
|
| 83 |
+
|
| 84 |
if matches:
|
| 85 |
for category, data in matches:
|
|
|
|
| 86 |
matched_lemmas_str = ", ".join(sorted(data['matched_lemmas']))
|
| 87 |
advantage_text += f"- {category}: {data['count']} совпадений (леммы: {matched_lemmas_str})\n"
|
| 88 |
else:
|
|
|
|
| 90 |
advantage_text += "\n---\n"
|
| 91 |
results.append(advantage_text)
|
| 92 |
|
|
|
|
|
|
|
|
|
|
| 93 |
return "\n".join(results), graph_html
|
| 94 |
+
|
|
|
|
| 95 |
def create_category_graph(product, advantages, personalization_keywords):
|
| 96 |
+
net = Network(height="500px", width="100%", directed=True, cdn_resources='in_line')
|
| 97 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
net.add_node(product, label=product, color="lightblue", size=30)
|
| 99 |
+
|
|
|
|
| 100 |
for advantage in advantages:
|
|
|
|
| 101 |
net.add_node(advantage, label=advantage, color="orange", size=20)
|
| 102 |
+
net.add_edge(product, advantage)
|
| 103 |
+
|
|
|
|
| 104 |
matches = classify_advantage(advantage, personalization_keywords)
|
| 105 |
for category, data in matches:
|
| 106 |
net.add_node(category, label=category, color="green", size=15)
|
| 107 |
+
net.add_edge(advantage, category)
|
| 108 |
+
|
|
|
|
| 109 |
html = net.generate_html(notebook=False)
|
| 110 |
+
html_escaped = html.replace('"', '"').replace("'", "'")
|
| 111 |
+
|
| 112 |
+
iframe_html = f"""
|
|
|
|
|
|
|
|
|
|
| 113 |
<iframe
|
| 114 |
+
width="100%"
|
| 115 |
+
height="600"
|
| 116 |
+
frameborder="0"
|
| 117 |
+
srcdoc="{html_escaped}">
|
| 118 |
</iframe>
|
| 119 |
"""
|
| 120 |
+
|
| 121 |
+
print("Generated HTML:", iframe_html[:500]) # Выводим первые 500 символов для отладки
|
| 122 |
+
|
| 123 |
+
return iframe_html
|
| 124 |
+
|
| 125 |
with gr.Blocks() as demo:
|
| 126 |
gr.Markdown("## Классификация преимуществ по признакам персонализации")
|
| 127 |
gr.Markdown("**Шаг 1:** Загрузите Excel-файл с двумя столбцами: 'Продукт' и 'Преимущество'.")
|
| 128 |
+
|
| 129 |
file_input = gr.File(label="Загрузите Excel-файл", file_types=[".xlsx"])
|
| 130 |
load_button = gr.Button("Загрузить файл")
|
| 131 |
load_status = gr.Markdown("")
|
| 132 |
+
|
| 133 |
+
gr.Markdown("**Шаг 2:** Выберите продукт из списка.")
|
| 134 |
product_dropdown = gr.Dropdown(choices=[], label="Продукты", value=None)
|
| 135 |
analyze_button = gr.Button("Анализировать")
|
| 136 |
+
|
| 137 |
output_text = gr.Markdown("")
|
| 138 |
output_graph = gr.HTML(label="Визуализация графа")
|
| 139 |
+
|
|
|
|
| 140 |
def on_file_upload(file):
|
| 141 |
unique_products, status_message = load_excel(file)
|
| 142 |
return gr.update(choices=unique_products), status_message
|
| 143 |
+
|
| 144 |
load_button.click(
|
| 145 |
fn=on_file_upload,
|
| 146 |
inputs=file_input,
|
| 147 |
outputs=[product_dropdown, load_status]
|
| 148 |
)
|
| 149 |
|
|
|
|
| 150 |
analyze_button.click(
|
| 151 |
fn=analyze,
|
| 152 |
inputs=product_dropdown,
|
| 153 |
outputs=[output_text, output_graph]
|
| 154 |
)
|
| 155 |
|
|
|
|
| 156 |
if __name__ == "__main__":
|
| 157 |
+
demo.launch(debug=True)
|