AlserFurma commited on
Commit
dccb835
·
verified ·
1 Parent(s): a0c5931

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -27
app.py CHANGED
@@ -9,6 +9,7 @@ import scipy.io.wavfile as wavfile
9
  import traceback
10
  import random
11
  import re
 
12
 
13
  # =========================
14
  # ПАРАМЕТРЫ
@@ -46,51 +47,47 @@ except Exception as e:
46
  # ГЕНЕРАЦИЯ ВОПРОСА
47
  # =========================
48
 
 
 
49
  def generate_quiz(text: str):
50
  prompt = (
51
- "Сгенерируй учебный вопрос по тексту и дай 1 правильный и 1 неправильный вариант ответа.\n"
52
- "СТРОГО ИСПОЛЬЗУЙ ФОРМАТ:\n"
53
- "QUESTION: ...\n"
54
- "CORRECT: ...\n"
55
- "WRONG: ...\n"
 
 
56
  f"TEXT: {text}"
57
  )
58
 
59
  try:
60
- out = qa_model(prompt, max_length=200)[0]["generated_text"]
61
  except Exception as e:
62
  raise RuntimeError(f"Ошибка генерации вопроса: {e}")
63
 
64
- text_out = out.replace("\r", "").strip()
65
-
66
- # --- Regular expressions ---
67
- q = re.search(r"QUESTION:\s*(.+)", text_out, re.IGNORECASE)
68
- c = re.search(r"CORRECT:\s*(.+)", text_out, re.IGNORECASE)
69
- w = re.search(r"WRONG:\s*(.+)", text_out, re.IGNORECASE)
70
-
71
- question = q.group(1).strip() if q else ""
72
- correct = c.group(1).strip() if c else ""
73
- wrong = w.group(1).strip() if w else ""
74
 
75
- # --- fallback ---
76
- if not (question and correct and wrong):
77
- lines = [l.strip() for l in text_out.split("\n") if l.strip()]
78
- for l in lines:
79
- if l.lower().startswith("question"):
80
- question = l.split(":", 1)[1].strip()
81
- elif l.lower().startswith("correct"):
82
- correct = l.split(":", 1)[1].strip()
83
- elif l.lower().startswith("wrong"):
84
- wrong = l.split(":", 1)[1].strip()
85
 
86
  if not (question and correct and wrong):
87
- raise ValueError(f"Модель вывела неправильный формат:\n{out}")
88
 
89
  options = [correct, wrong]
90
  random.shuffle(options)
 
91
  return question, options, correct
92
 
93
 
 
94
  # =========================
95
  # АУДИО НА КАЗАХСКОМ
96
  # =========================
 
9
  import traceback
10
  import random
11
  import re
12
+ import json
13
 
14
  # =========================
15
  # ПАРАМЕТРЫ
 
47
  # ГЕНЕРАЦИЯ ВОПРОСА
48
  # =========================
49
 
50
+
51
+
52
  def generate_quiz(text: str):
53
  prompt = (
54
+ "Сгенерируй один учебный вопрос по тексту. "
55
+ "Ответ верни строго в формате JSON БЕЗ лишнего текста, без комментариев, только JSON.\n"
56
+ "{\n"
57
+ " \"question\": \"...\",\n"
58
+ " \"correct\": \"...\",\n"
59
+ " \"wrong\": \"...\"\n"
60
+ "}\n"
61
  f"TEXT: {text}"
62
  )
63
 
64
  try:
65
+ out = qa_model(prompt, max_new_tokens=150)[0]["generated_text"].strip()
66
  except Exception as e:
67
  raise RuntimeError(f"Ошибка генерации вопроса: {e}")
68
 
69
+ # Иногда FLAN-T5 добавляет текст до/после JSON → пробуем вытащить JSON из строки
70
+ try:
71
+ json_str = out[out.index("{"): out.rindex("}") + 1]
72
+ data = json.loads(json_str)
73
+ except Exception:
74
+ raise ValueError(f"Модель вывела неправильный JSON:\n{out}")
 
 
 
 
75
 
76
+ # Проверяем данные
77
+ question = data.get("question", "").strip()
78
+ correct = data.get("correct", "").strip()
79
+ wrong = data.get("wrong", "").strip()
 
 
 
 
 
 
80
 
81
  if not (question and correct and wrong):
82
+ raise ValueError(f"Модель вернула некорректные поля:\n{data}")
83
 
84
  options = [correct, wrong]
85
  random.shuffle(options)
86
+
87
  return question, options, correct
88
 
89
 
90
+
91
  # =========================
92
  # АУДИО НА КАЗАХСКОМ
93
  # =========================