Wplotnikow commited on
Commit
b1b58ec
·
verified ·
1 Parent(s): 2b9cf4d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -14
app.py CHANGED
@@ -15,7 +15,7 @@ def get_blocks_from_docx():
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())
@@ -24,14 +24,13 @@ def get_blocks_from_docx():
24
  and txt == txt.upper()
25
  and txt.endswith(('.', ':', '?', '!')) is False
26
  )
27
- and len(txt.split()) > 3 # минимум 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())
34
- # Аналогично — игнорируем сверхкороткие строки/возможные заголовки из таблиц:
35
  if row_text and len(row_text) > 35 and len(row_text.split()) > 3:
36
  blocks.append(row_text)
37
  seen = set()
@@ -55,7 +54,12 @@ def rut5_answer(question, context):
55
  prompt = f"question: {question} context: {context}"
56
  input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
57
  with torch.no_grad():
58
- output_ids = model.generate(input_ids, max_length=250, num_beams=4, min_length=40, no_repeat_ngram_size=3)
 
 
 
 
 
59
  return tokenizer.decode(output_ids[0], skip_special_tokens=True)
60
 
61
  def ask_chatbot(question):
@@ -65,15 +69,15 @@ def ask_chatbot(question):
65
  return "Ошибка: база знаний пуста или слишком мала. Проверьте .docx."
66
  user_vec = vectorizer.transform([question])
67
  sims = cosine_similarity(user_vec, matrix)
68
- # ТОП-3 самых осмысленных блока
69
- top_idxs = sims.argsort()[-3:][::-1]
70
- # Используем только НЕКОРОТКИЕ блоки как контекст
71
  context_blocks = [
72
  blocks[i] for i in top_idxs if sims[i] > 0.08 and len(blocks[i].split()) > 3 and len(blocks[i]) > 35
73
  ]
74
  context = " ".join(context_blocks)
 
 
75
  answer = rut5_answer(question, context)
76
- # Подстраховка — если ответ ТОЛЬКО заголовок, просто версифицируем и дополняем контекстом:
77
  if len(answer.strip().split()) < 8 or len(answer.split('.')) < 2:
78
  answer += "\n\n" + context
79
  return answer
@@ -92,17 +96,22 @@ with gr.Blocks() as demo:
92
  """
93
  # Русскоязычный FAQ-чат-бот на базе вашей методички и нейросетевой модели
94
 
95
- Задайте вопрос — получите развернутый AI-ответ на русском языке на основании вашего документа!
96
  """
97
  )
98
  question = gr.Textbox(label="Ваш вопрос", lines=2)
99
  ask_btn = gr.Button("Получить ответ")
100
  answer = gr.Markdown(label="Ответ", visible=True)
101
- ask_btn.click(ask_chatbot, question, answer)
102
- question.submit(ask_chatbot, question, answer)
103
- gr.Markdown("#### Примеры вопросов:")
104
 
105
- # ВОЗВРАЩАЕМ КЛИКАБЕЛЬНЫЕ примеры
 
 
 
 
 
 
 
 
106
  gr.Examples(EXAMPLES, inputs=question)
107
 
108
  gr.Markdown("""
 
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())
 
24
  and txt == txt.upper()
25
  and txt.endswith(('.', ':', '?', '!')) is False
26
  )
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())
 
34
  if row_text and len(row_text) > 35 and len(row_text.split()) > 3:
35
  blocks.append(row_text)
36
  seen = set()
 
54
  prompt = f"question: {question} context: {context}"
55
  input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
56
  with torch.no_grad():
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):
 
69
  return "Ошибка: база знаний пуста или слишком мала. Проверьте .docx."
70
  user_vec = vectorizer.transform([question])
71
  sims = cosine_similarity(user_vec, matrix)
72
+ n_blocks = min(3, len(blocks))
73
+ top_idxs = sims.argsort()[-n_blocks:][::-1] if n_blocks > 0 else []
 
74
  context_blocks = [
75
  blocks[i] for i in top_idxs if sims[i] > 0.08 and len(blocks[i].split()) > 3 and len(blocks[i]) > 35
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
83
  return answer
 
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("""