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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -11
app.py CHANGED
@@ -13,16 +13,26 @@ def get_blocks_from_docx():
13
  return ["Файл .docx не найден!"]
14
  doc = Document(docx_list[0])
15
  blocks = []
16
- # Абзацы
17
  for p in doc.paragraphs:
18
  txt = p.text.strip()
19
- if txt and not (len(txt) <= 3 and txt.isdigit()):
 
 
 
 
 
 
 
 
 
 
20
  blocks.append(txt)
21
- # Таблицы
22
  for table in doc.tables:
23
  for row in table.rows:
24
  row_text = " | ".join(cell.text.strip() for cell in row.cells if cell.text.strip())
25
- if row_text:
 
26
  blocks.append(row_text)
27
  seen = set()
28
  uniq_blocks = []
@@ -53,14 +63,18 @@ def ask_chatbot(question):
53
  return "Пожалуйста, введите вопрос."
54
  if len(blocks) < 2:
55
  return "Ошибка: база знаний пуста или слишком мала. Проверьте .docx."
56
- # Берём ТРИ лучших блока для большего контекста (больше данных для генерации)
57
  user_vec = vectorizer.transform([question])
58
- sims = cosine_similarity(user_vec, matrix)[0]
 
59
  top_idxs = sims.argsort()[-3:][::-1]
60
- context = " ".join([blocks[i] for i in top_idxs if sims[i] > 0.08])
 
 
 
 
61
  answer = rut5_answer(question, context)
62
- # Проверяем: выдаём только развёрнутые (2 предложения и более) или повторяем часть исходника как расширение
63
- if len(answer.split('.')) < 2:
64
  answer += "\n\n" + context
65
  return answer
66
 
@@ -87,8 +101,10 @@ with gr.Blocks() as demo:
87
  ask_btn.click(ask_chatbot, question, answer)
88
  question.submit(ask_chatbot, question, answer)
89
  gr.Markdown("#### Примеры вопросов:")
90
- for ex in EXAMPLES:
91
- gr.Markdown(f"- {ex}")
 
 
92
  gr.Markdown("""
93
  ---
94
 
 
13
  return ["Файл .docx не найден!"]
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())
22
+ and not (
23
+ len(txt) < 35
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()
38
  uniq_blocks = []
 
63
  return "Пожалуйста, введите вопрос."
64
  if len(blocks) < 2:
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
80
 
 
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("""
109
  ---
110