Wplotnikow commited on
Commit
2b2154a
·
verified ·
1 Parent(s): f010eaa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -14
app.py CHANGED
@@ -1,30 +1,59 @@
1
  import gradio as gr
2
  import glob
3
  from docx import Document
4
- from sklearn.feature_extraction.text import TfidfVectorizer
5
- from sklearn.metrics.pairwise import cosine_similarity
6
 
7
- # ---- Распознаёт первый docx в папке (поддерживает любые методички) ----
8
- def extract_paragraphs():
9
  docx_list = glob.glob("*.docx")
10
  if not docx_list:
11
- return ["Файл .docx с материалами не найден!"]
12
  doc = Document(docx_list[0])
13
- return [p.text.strip() for p in doc.paragraphs if p.text.strip()]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- paragraphs = extract_paragraphs()
16
  vectorizer = TfidfVectorizer().fit(paragraphs)
17
  paragraph_matrix = vectorizer.transform(paragraphs)
18
 
19
  def search_faq(question):
20
  if not question.strip():
21
  return "Пожалуйста, введите вопрос."
 
 
22
  user_vec = vectorizer.transform([question])
23
- sims = cosine_similarity(user_vec, paragraph_matrix)
24
  idx = sims.argmax()
25
  score = sims[idx]
26
  if score < 0.12:
27
- return "Не найдено подходящего ответа. Попробуйте переформулировать вопрос, либо обратитесь к преподавателю."
28
  return paragraphs[idx]
29
 
30
  EXAMPLES = [
@@ -38,8 +67,9 @@ EXAMPLES = [
38
  with gr.Blocks() as demo:
39
  gr.Markdown(
40
  """
41
- # Чат-бот по ВКР на базе ваших материалов
42
- Задайте вопрос о правилах, требованиях и оформлении работы — найдите нужную информацию в своем методическом документе!
 
43
  """
44
  )
45
  question = gr.Textbox(label="Ваш вопрос", lines=2)
@@ -49,13 +79,13 @@ with gr.Blocks() as demo:
49
  question.submit(search_faq, question, answer)
50
  gr.Markdown("#### Примеры вопросов:")
51
  gr.Examples(EXAMPLES, inputs=question)
52
-
53
  gr.Markdown("""
54
  ---
55
- ### Контакты (заполните по своей кафедре/руководителю)
 
56
  Преподаватель: ___________________
57
  Email: ___________________________
58
- Кафедра/Программа: ____________________
59
  """)
60
 
61
  demo.launch()
 
1
  import gradio as gr
2
  import glob
3
  from docx import Document
 
 
4
 
5
+ def get_all_text_from_docx():
 
6
  docx_list = glob.glob("*.docx")
7
  if not docx_list:
8
+ return ["Файл .docx с методичкой не найден!"]
9
  doc = Document(docx_list[0])
10
+ blocks = []
11
+
12
+ # Извлекаем все нестандартные абзацы (пропускаем короткие технические, например '4')
13
+ for p in doc.paragraphs:
14
+ txt = p.text.strip()
15
+ if txt and not (len(txt) <= 3 and txt.isdigit()):
16
+ blocks.append(txt)
17
+
18
+ # Вытаскиваем ТЕКСТ из ТАБЛИЦ.
19
+ for table in doc.tables:
20
+ for row in table.rows:
21
+ # склеиваем все ячейки строки таблицы через " | "
22
+ row_text = " | ".join(cell.text.strip() for cell in row.cells if cell.text.strip())
23
+ if row_text: # отсекаем совсем пустые строки
24
+ blocks.append(row_text)
25
+
26
+ # дополнительно: удаляем дубли (могут встречаться в Word после копирования)
27
+ seen = set()
28
+ uniq_blocks = []
29
+ for b in blocks:
30
+ if b not in seen:
31
+ uniq_blocks.append(b)
32
+ seen.add(b)
33
+ return uniq_blocks
34
+
35
+ paragraphs = get_all_text_from_docx()
36
+
37
+ # Проверьте, сколько блоков реально читается!
38
+ print("Блоков для поиска:", len(paragraphs))
39
+
40
+ from sklearn.feature_extraction.text import TfidfVectorizer
41
+ from sklearn.metrics.pairwise import cosine_similarity
42
 
 
43
  vectorizer = TfidfVectorizer().fit(paragraphs)
44
  paragraph_matrix = vectorizer.transform(paragraphs)
45
 
46
  def search_faq(question):
47
  if not question.strip():
48
  return "Пожалуйста, введите вопрос."
49
+ if len(paragraphs) < 2:
50
+ return "Ошибка: база знаний пуста или слишком мала. Проверьте содержимое .docx или перезагрузите файл с материалами."
51
  user_vec = vectorizer.transform([question])
52
+ sims = cosine_similarity(user_vec, paragraph_matrix)[0]
53
  idx = sims.argmax()
54
  score = sims[idx]
55
  if score < 0.12:
56
+ return "Не найдено подходящего ответа. Попробуйте иначе сформулировать вопрос или обратитесь к преподавателю."
57
  return paragraphs[idx]
58
 
59
  EXAMPLES = [
 
67
  with gr.Blocks() as demo:
68
  gr.Markdown(
69
  """
70
+ # Чат-бот по ВКР на базе вашей методички
71
+
72
+ Задайте вопрос — бот ищет точный ответ в вашем документе, в том числе в таблицах!
73
  """
74
  )
75
  question = gr.Textbox(label="Ваш вопрос", lines=2)
 
79
  question.submit(search_faq, question, answer)
80
  gr.Markdown("#### Примеры вопросов:")
81
  gr.Examples(EXAMPLES, inputs=question)
 
82
  gr.Markdown("""
83
  ---
84
+
85
+ ### Контакты (заполните сами)
86
  Преподаватель: ___________________
87
  Email: ___________________________
88
+ Кафедра: _________________________
89
  """)
90
 
91
  demo.launch()