Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,12 +10,11 @@ from transformers import T5ForConditionalGeneration, T5Tokenizer
|
|
| 10 |
def get_blocks_from_docx():
|
| 11 |
docx_list = glob.glob("*.docx")
|
| 12 |
if not docx_list:
|
| 13 |
-
return [
|
| 14 |
doc = Document(docx_list[0])
|
| 15 |
blocks = []
|
| 16 |
for p in doc.paragraphs:
|
| 17 |
txt = p.text.strip()
|
| 18 |
-
# Исключаем очень короткие и похожие на заголовки блоки
|
| 19 |
if (
|
| 20 |
txt
|
| 21 |
and not (len(txt) <= 3 and txt.isdigit())
|
|
@@ -27,7 +26,6 @@ def get_blocks_from_docx():
|
|
| 27 |
and len(txt.split()) > 3
|
| 28 |
):
|
| 29 |
blocks.append(txt)
|
| 30 |
-
# Таблицы
|
| 31 |
for table in doc.tables:
|
| 32 |
for row in table.rows:
|
| 33 |
row_text = " | ".join(cell.text.strip() for cell in row.cells if cell.text.strip())
|
|
@@ -42,6 +40,10 @@ def get_blocks_from_docx():
|
|
| 42 |
return uniq_blocks
|
| 43 |
|
| 44 |
blocks = get_blocks_from_docx()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
vectorizer = TfidfVectorizer().fit(blocks)
|
| 46 |
matrix = vectorizer.transform(blocks)
|
| 47 |
|
|
@@ -57,26 +59,30 @@ def rut5_answer(question, context):
|
|
| 57 |
output_ids = model.generate(
|
| 58 |
input_ids,
|
| 59 |
max_length=250, num_beams=4, min_length=40,
|
| 60 |
-
no_repeat_ngram_size=3,
|
| 61 |
-
do_sample=False
|
| 62 |
)
|
| 63 |
return tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
| 64 |
|
| 65 |
def ask_chatbot(question):
|
| 66 |
if not question.strip():
|
| 67 |
return "Пожалуйста, введите вопрос."
|
| 68 |
-
if
|
| 69 |
-
return "Ошибка: база знаний
|
| 70 |
user_vec = vectorizer.transform([question])
|
| 71 |
sims = cosine_similarity(user_vec, matrix)
|
| 72 |
n_blocks = min(3, len(blocks))
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
context = " ".join(context_blocks)
|
| 78 |
if not context:
|
| 79 |
-
return "Не найден релевантный фрагмент в документе. Попробуйте иначе сформулировать
|
| 80 |
answer = rut5_answer(question, context)
|
| 81 |
if len(answer.strip().split()) < 8 or len(answer.split('.')) < 2:
|
| 82 |
answer += "\n\n" + context
|
|
@@ -93,30 +99,22 @@ EXAMPLES = [
|
|
| 93 |
|
| 94 |
with gr.Blocks() as demo:
|
| 95 |
gr.Markdown(
|
| 96 |
-
""
|
| 97 |
-
# Русскоязычный FAQ-чат-бот на базе вашей методички и нейросетевой модели
|
| 98 |
-
|
| 99 |
-
Задайте вопрос — получите развернутый AI-ответ (бот анализирует ваш документ, подборка абзацев и генерация выполняются автоматически).
|
| 100 |
-
"""
|
| 101 |
)
|
| 102 |
question = gr.Textbox(label="Ваш вопрос", lines=2)
|
| 103 |
ask_btn = gr.Button("Получить ответ")
|
| 104 |
answer = gr.Markdown(label="Ответ", visible=True)
|
| 105 |
|
| 106 |
-
# Активация спиннера "Чат-бот думает..."
|
| 107 |
def with_spinner(q):
|
| 108 |
yield "Чат-бот думает..."
|
| 109 |
yield ask_chatbot(q)
|
| 110 |
|
| 111 |
ask_btn.click(with_spinner, question, answer)
|
| 112 |
question.submit(with_spinner, question, answer)
|
| 113 |
-
|
| 114 |
gr.Markdown("#### Примеры вопросов:")
|
| 115 |
gr.Examples(EXAMPLES, inputs=question)
|
| 116 |
-
|
| 117 |
gr.Markdown("""
|
| 118 |
---
|
| 119 |
-
|
| 120 |
### Контакты (укажите свои)
|
| 121 |
Преподаватель: ___________________
|
| 122 |
Email: ___________________________
|
|
@@ -124,3 +122,4 @@ with gr.Blocks() as demo:
|
|
| 124 |
""")
|
| 125 |
|
| 126 |
demo.launch()
|
|
|
|
|
|
| 10 |
def get_blocks_from_docx():
|
| 11 |
docx_list = glob.glob("*.docx")
|
| 12 |
if not docx_list:
|
| 13 |
+
return []
|
| 14 |
doc = Document(docx_list[0])
|
| 15 |
blocks = []
|
| 16 |
for p in doc.paragraphs:
|
| 17 |
txt = p.text.strip()
|
|
|
|
| 18 |
if (
|
| 19 |
txt
|
| 20 |
and not (len(txt) <= 3 and txt.isdigit())
|
|
|
|
| 26 |
and len(txt.split()) > 3
|
| 27 |
):
|
| 28 |
blocks.append(txt)
|
|
|
|
| 29 |
for table in doc.tables:
|
| 30 |
for row in table.rows:
|
| 31 |
row_text = " | ".join(cell.text.strip() for cell in row.cells if cell.text.strip())
|
|
|
|
| 40 |
return uniq_blocks
|
| 41 |
|
| 42 |
blocks = get_blocks_from_docx()
|
| 43 |
+
|
| 44 |
+
if len(blocks) < 1:
|
| 45 |
+
blocks = ["База знаний пуста: проверьте содержание и формат вашего .docx!"]
|
| 46 |
+
|
| 47 |
vectorizer = TfidfVectorizer().fit(blocks)
|
| 48 |
matrix = vectorizer.transform(blocks)
|
| 49 |
|
|
|
|
| 59 |
output_ids = model.generate(
|
| 60 |
input_ids,
|
| 61 |
max_length=250, num_beams=4, min_length=40,
|
| 62 |
+
no_repeat_ngram_size=3, do_sample=False
|
|
|
|
| 63 |
)
|
| 64 |
return tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
| 65 |
|
| 66 |
def ask_chatbot(question):
|
| 67 |
if not question.strip():
|
| 68 |
return "Пожалуйста, введите вопрос."
|
| 69 |
+
if not blocks or blocks == ["База знаний пуста: проверьте содержание и формат вашего .docx!"]:
|
| 70 |
+
return "Ошибка: база знаний пуста. Проверьте .docx и перезапустите Space."
|
| 71 |
user_vec = vectorizer.transform([question])
|
| 72 |
sims = cosine_similarity(user_vec, matrix)
|
| 73 |
n_blocks = min(3, len(blocks))
|
| 74 |
+
# Корректно работают даже при len(blocks) == 1
|
| 75 |
+
top_idxs = list(reversed(sims.argsort()[-n_blocks:]))
|
| 76 |
+
context_blocks = []
|
| 77 |
+
for idx in top_idxs:
|
| 78 |
+
try:
|
| 79 |
+
if sims[idx] > 0.08 and len(blocks[idx].split()) > 3 and len(blocks[idx]) > 35:
|
| 80 |
+
context_blocks.append(blocks[idx])
|
| 81 |
+
except IndexError:
|
| 82 |
+
continue
|
| 83 |
context = " ".join(context_blocks)
|
| 84 |
if not context:
|
| 85 |
+
return "Не найден релевантный фрагмент в документе. Попробуйте иначе сформулировать вопрос или добавьте больше содержательных абзацев в .docx."
|
| 86 |
answer = rut5_answer(question, context)
|
| 87 |
if len(answer.strip().split()) < 8 or len(answer.split('.')) < 2:
|
| 88 |
answer += "\n\n" + context
|
|
|
|
| 99 |
|
| 100 |
with gr.Blocks() as demo:
|
| 101 |
gr.Markdown(
|
| 102 |
+
"# Русскоязычный FAQ-чат-бот по методичке (AI+документ)\nЗадайте вопрос — получите развернутый ответ на основании вашего документа!"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
)
|
| 104 |
question = gr.Textbox(label="Ваш вопрос", lines=2)
|
| 105 |
ask_btn = gr.Button("Получить ответ")
|
| 106 |
answer = gr.Markdown(label="Ответ", visible=True)
|
| 107 |
|
|
|
|
| 108 |
def with_spinner(q):
|
| 109 |
yield "Чат-бот думает..."
|
| 110 |
yield ask_chatbot(q)
|
| 111 |
|
| 112 |
ask_btn.click(with_spinner, question, answer)
|
| 113 |
question.submit(with_spinner, question, answer)
|
|
|
|
| 114 |
gr.Markdown("#### Примеры вопросов:")
|
| 115 |
gr.Examples(EXAMPLES, inputs=question)
|
|
|
|
| 116 |
gr.Markdown("""
|
| 117 |
---
|
|
|
|
| 118 |
### Контакты (укажите свои)
|
| 119 |
Преподаватель: ___________________
|
| 120 |
Email: ___________________________
|
|
|
|
| 122 |
""")
|
| 123 |
|
| 124 |
demo.launch()
|
| 125 |
+
|