QAway-to commited on
Commit
bbd6808
·
1 Parent(s): f12b1ae

T5 models switcher. app.py v1.7

Browse files
Files changed (1) hide show
  1. app.py +44 -16
app.py CHANGED
@@ -5,7 +5,40 @@ from itertools import cycle
5
  from core.utils import generate_first_question
6
  from core.mbti_analyzer import analyze_mbti
7
  from core.interviewer import generate_question, session_state
 
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  # --------------------------------------------------------------
11
  # 🌀 Асинхронная анимация "Thinking..."
@@ -16,7 +49,6 @@ async def async_loader(update_fn, delay=0.15):
16
  update_fn(f"💭 Interviewer is thinking... {frame}")
17
  await asyncio.sleep(delay)
18
 
19
-
20
  # --------------------------------------------------------------
21
  # ⚙️ Основная логика
22
  # --------------------------------------------------------------
@@ -32,28 +64,28 @@ def analyze_and_ask(user_text, prev_count):
32
  n = 1
33
  counter = f"{n}/8"
34
 
35
- # 1️⃣ Мгновенная реакция — "анализ начинается"
36
  yield "⏳ Analyzing personality...", "💭 Interviewer is thinking... ⠋", counter
37
 
38
- # 2️⃣ Анализ MBTI
39
  mbti_gen = analyze_mbti(user_text)
40
  mbti_text = ""
41
  for chunk in mbti_gen:
42
  mbti_text = chunk
43
- yield mbti_text, "💭 Interviewer is thinking... ", counter
44
 
45
- # 3️⃣ Генерация вопроса
46
- question = generate_question(user_id=user_id, user_answer=user_text)
 
 
 
47
 
48
- # 4️⃣ Проверяем завершение сессии
49
  if question.startswith("✅ All"):
50
  yield f"{mbti_text}\n\nSession complete.", "🎯 All MBTI axes covered.", "8/8"
51
  return
52
 
53
- # 5️⃣ Финальный вывод
54
  yield mbti_text, question, counter
55
 
56
-
57
  # --------------------------------------------------------------
58
  # 🧱 Интерфейс Gradio
59
  # --------------------------------------------------------------
@@ -68,29 +100,25 @@ with gr.Blocks(theme=gr.themes.Soft(), title="MBTI Personality Interviewer") as
68
  inp = gr.Textbox(
69
  label="Ваш ответ",
70
  placeholder="Например: I enjoy working with people and organizing events.",
71
- lines=4
72
  )
73
  btn = gr.Button("Анализировать и задать новый вопрос", variant="primary")
74
-
75
  with gr.Column(scale=1):
76
  mbti_out = gr.Textbox(label="📊 Анализ MBTI", lines=4)
77
  interviewer_out = gr.Textbox(label="💬 Следующий вопрос", lines=3)
78
  progress = gr.Textbox(label="⏳ Прогресс", value="0/8")
79
 
80
- # Асинхронная обработка
81
  btn.click(
82
  analyze_and_ask,
83
  inputs=[inp, progress],
84
  outputs=[mbti_out, interviewer_out, progress],
85
- show_progress=True
86
  )
87
 
88
- # Стартовый вопрос при загрузке
89
  demo.load(
90
  lambda: ("", generate_first_question(), "0/8"),
91
  inputs=None,
92
- outputs=[mbti_out, interviewer_out, progress]
93
  )
94
 
95
- # Очеред�� нужна для стриминга, но без старого аргумента concurrency_count
96
  demo.queue(max_size=32).launch(server_name="0.0.0.0", server_port=7860)
 
5
  from core.utils import generate_first_question
6
  from core.mbti_analyzer import analyze_mbti
7
  from core.interviewer import generate_question, session_state
8
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
9
 
10
+ # --------------------------------------------------------------
11
+ # ⚙️ Проверка и автоматический fallback T5 модели
12
+ # --------------------------------------------------------------
13
+ def load_qg_model():
14
+ """
15
+ Пытаемся загрузить лёгкую T5-модель для генерации вопросов.
16
+ Если первая не доступна, переключаемся на запасную.
17
+ """
18
+ MODEL_CANDIDATES = [
19
+ "mrm8488/t5-small-finetuned-question-generation-ap", # быстрая, но часто недоступна
20
+ "iarfmoose/t5-base-question-generator", # качественная, чуть медленнее
21
+ "google/flan-t5-small" # fallback — всегда доступна
22
+ ]
23
+ for name in MODEL_CANDIDATES:
24
+ try:
25
+ tok = AutoTokenizer.from_pretrained(name)
26
+ mdl = AutoModelForSeq2SeqLM.from_pretrained(name)
27
+ print(f"✅ Loaded interviewer model: {name}")
28
+ return pipeline(
29
+ "text2text-generation",
30
+ model=mdl,
31
+ tokenizer=tok,
32
+ max_new_tokens=40,
33
+ num_beams=4,
34
+ no_repeat_ngram_size=4,
35
+ )
36
+ except Exception as e:
37
+ print(f"⚠️ Failed to load {name}: {e}")
38
+ raise RuntimeError("❌ No available T5 model for question generation.")
39
+
40
+ # глобальный экземпляр пайплайна
41
+ QG_PIPE = load_qg_model()
42
 
43
  # --------------------------------------------------------------
44
  # 🌀 Асинхронная анимация "Thinking..."
 
49
  update_fn(f"💭 Interviewer is thinking... {frame}")
50
  await asyncio.sleep(delay)
51
 
 
52
  # --------------------------------------------------------------
53
  # ⚙️ Основная логика
54
  # --------------------------------------------------------------
 
64
  n = 1
65
  counter = f"{n}/8"
66
 
67
+ # мгновенный отклик
68
  yield "⏳ Analyzing personality...", "💭 Interviewer is thinking... ⠋", counter
69
 
70
+ # анализ MBTI (стриминг)
71
  mbti_gen = analyze_mbti(user_text)
72
  mbti_text = ""
73
  for chunk in mbti_gen:
74
  mbti_text = chunk
75
+ yield mbti_text, "💭 Interviewer is thinking... ", counter
76
 
77
+ # генерация вопроса
78
+ try:
79
+ question = generate_question(user_id=user_id, user_answer=user_text, qg_pipe=QG_PIPE)
80
+ except Exception as e:
81
+ question = f"⚠️ Question generator error: {e}"
82
 
 
83
  if question.startswith("✅ All"):
84
  yield f"{mbti_text}\n\nSession complete.", "🎯 All MBTI axes covered.", "8/8"
85
  return
86
 
 
87
  yield mbti_text, question, counter
88
 
 
89
  # --------------------------------------------------------------
90
  # 🧱 Интерфейс Gradio
91
  # --------------------------------------------------------------
 
100
  inp = gr.Textbox(
101
  label="Ваш ответ",
102
  placeholder="Например: I enjoy working with people and organizing events.",
103
+ lines=4,
104
  )
105
  btn = gr.Button("Анализировать и задать новый вопрос", variant="primary")
 
106
  with gr.Column(scale=1):
107
  mbti_out = gr.Textbox(label="📊 Анализ MBTI", lines=4)
108
  interviewer_out = gr.Textbox(label="💬 Следующий вопрос", lines=3)
109
  progress = gr.Textbox(label="⏳ Прогресс", value="0/8")
110
 
 
111
  btn.click(
112
  analyze_and_ask,
113
  inputs=[inp, progress],
114
  outputs=[mbti_out, interviewer_out, progress],
115
+ show_progress=True,
116
  )
117
 
 
118
  demo.load(
119
  lambda: ("", generate_first_question(), "0/8"),
120
  inputs=None,
121
+ outputs=[mbti_out, interviewer_out, progress],
122
  )
123
 
 
124
  demo.queue(max_size=32).launch(server_name="0.0.0.0", server_port=7860)