QAway-to commited on
Commit
c8cd73e
·
1 Parent(s): b7e18a3

New version v1.8

Browse files
Files changed (1) hide show
  1. app.py +89 -100
app.py CHANGED
@@ -1,103 +1,92 @@
1
  import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
3
-
4
- # === 1️⃣ Модель MBTI ===
5
- MODEL_ID = "f3nsmart/MBTIclassifier"
6
- tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
7
- model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID)
8
- analyzer = pipeline("text-classification", model=model, tokenizer=tokenizer, return_all_scores=True)
9
-
10
- # === 2️⃣ Интервьюер (Phi-3-mini) ===
11
- q_gen = pipeline(
12
- "text-generation",
13
- model="microsoft/Phi-3-mini-4k-instruct",
14
- temperature=0.6,
15
- top_p=0.9,
16
- max_new_tokens=80
17
  )
18
-
19
- # === 3️⃣ Интервью ===
20
- def mbti_interview(user_input, history):
21
- """Проводит один шаг диалога"""
22
- if history is None:
23
- history = []
24
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  if not user_input.strip():
26
- return history, "⚠️ Введите ответ.", "Please describe yourself.", f"{len(history)}/30"
27
-
28
- # --- Анализ MBTI ---
29
- results = analyzer(user_input)[0]
30
- results = sorted(results, key=lambda x: x["score"], reverse=True)
31
- result_text = "\n".join([f"{r['label']} {r['score']:.3f}" for r in results[:3]])
32
-
33
- # --- История ---
34
- last_q = history[-1][0] if history else "Initial question"
35
- history.append((last_q, user_input))
36
- progress = f"{len(history)}/30"
37
-
38
- # --- Составляем контекст последних 5 пар ---
39
- convo = "\n".join([f"Q: {q}\nA: {a}" for q, a in history[-5:]])
40
-
41
- # --- Список уже заданных вопросов ---
42
- prev_qs = [q for q, _ in history]
43
-
44
- # --- Новый запрос ---
45
- prompt = (
46
- "You are an HR interviewer performing an MBTI personality assessment. "
47
- "You have already asked these questions:\n"
48
- + "\n".join(f"- {q}" for q in prev_qs[-10:]) + "\n\n"
49
- "Based on the candidate’s latest answer, generate ONE new question that:\n"
50
- "• Is unique and not identical to previous ones.\n"
51
- "• Is short (under 20 words).\n"
52
- "• Is polite and natural.\n"
53
- "• Helps understand the person’s motivation or preferences.\n\n"
54
- f"Recent dialogue:\n{convo}\n\nNext question:"
55
- )
56
-
57
- try:
58
- raw = q_gen(prompt)[0]["generated_text"]
59
- # --- очистка ---
60
- raw = raw.replace("\n", " ").strip()
61
- next_q = raw.split("?")[0]
62
- next_q = next_q.split("Next question:")[-1].strip().capitalize() + "?"
63
-
64
- # --- фильтр повторов ---
65
- if any(next_q.lower() == q.lower() for q in prev_qs):
66
- next_q = "What do you value most when collaborating with others?"
67
-
68
- if len(next_q.split()) < 4 or len(next_q) > 140:
69
- next_q = "What motivates you the most when you start something new?"
70
-
71
- except Exception as e:
72
- next_q = f"(⚠️ Ошибка генерации вопроса: {e})"
73
-
74
- return history, result_text, next_q, progress
75
-
76
-
77
- # === 4️⃣ Интерфейс Gradio ===
78
- with gr.Blocks(css="""
79
- .gradio-container {max-width: 1600px !important; margin: auto;}
80
- #inp, #out, #question {width: 90% !important; margin: auto; font-size: 16px;}
81
- #progress {text-align: center; font-weight: bold; color: #4CAF50; font-size: 18px;}
82
- textarea {height: 100px !important;}
83
- """) as demo:
84
- gr.Markdown("## 🧠 Adaptive MBTI Classifier\n### Context-aware interviewer with memory and unique questions.")
85
-
86
- state = gr.State([])
87
-
88
- question = gr.Textbox(
89
- label="Вопрос",
90
- value="Let's start: How do you usually spend your free time?",
91
- interactive=False,
92
- elem_id="question"
93
- )
94
- inp = gr.Textbox(label="Ваш ответ", placeholder="Type your answer here...", elem_id="inp")
95
- out = gr.Textbox(label="Результат анализа", elem_id="out")
96
- progress = gr.Markdown("**0/30**", elem_id="progress")
97
-
98
- btn = gr.Button("Ответить")
99
- btn.click(fn=mbti_interview,
100
- inputs=[inp, state],
101
- outputs=[state, out, question, progress])
102
-
103
- demo.launch()
 
1
  import gradio as gr
2
+ import concurrent.futures
3
+ import time
4
+ from transformers import (
5
+ AutoTokenizer,
6
+ AutoModelForSequenceClassification,
7
+ pipeline,
 
 
 
 
 
 
 
 
 
8
  )
9
+ # =========================================================
10
+ # 1. Настройка моделей
11
+ # =========================================================
12
+
13
+ # Твоя fine-tuned MBTI модель
14
+ MBTI_MODEL_ID = "f3nsmart/MBTIclassifier"
15
+
16
+ # Генератор вопросов — лёгкая LLM
17
+ LLM_MODEL_ID = "microsoft/Phi-3-mini-4k-instruct" # можно заменить на другую
18
+
19
+ # Загружаем классификатор
20
+ mbti_tokenizer = AutoTokenizer.from_pretrained(MBTI_MODEL_ID)
21
+ mbti_model = AutoModelForSequenceClassification.from_pretrained(MBTI_MODEL_ID)
22
+ analyzer = pipeline("text-classification", model=mbti_model, tokenizer=mbti_tokenizer, return_all_scores=True)
23
+
24
+ # Загружаем генератор вопросов
25
+ q_gen = pipeline("text-generation", model=LLM_MODEL_ID)
26
+
27
+ # =========================================================
28
+ # 2. Основная функция
29
+ # =========================================================
30
+ def classify_and_ask(user_input):
31
+ """
32
+ Параллельно выполняет:
33
+ - классификацию текста по MBTI,
34
+ - генерацию нового открытого вопроса.
35
+ """
36
  if not user_input.strip():
37
+ return "⚠️ Введите текст.", "⚠️ Вопрос не сформирован."
38
+
39
+ start_time = time.perf_counter()
40
+
41
+ # === Параллельная обработка ===
42
+ with concurrent.futures.ThreadPoolExecutor() as executor:
43
+ future_analysis = executor.submit(lambda: analyzer(user_input))
44
+ future_question = executor.submit(lambda: q_gen(
45
+ f"You are a friendly HR interviewer for an MBTI test. "
46
+ f"Generate ONE open-ended and meaningful question starting with 'How', 'Why', 'What', or 'When'. "
47
+ f"Do NOT repeat or refer to previous answers.\nUser said: {user_input}\n"
48
+ ))
49
+
50
+ analysis_result = future_analysis.result()
51
+ question_result = future_question.result()
52
+
53
+ elapsed = time.perf_counter() - start_time
54
+ print(f"⏱ Время обработки запроса: {elapsed:.2f} сек")
55
+
56
+ # === Обработка результатов анализа ===
57
+ results = sorted(analysis_result[0], key=lambda x: x["score"], reverse=True)
58
+ top = "\n".join([f"{r['label']} {r['score']:.3f}" for r in results[:3]])
59
+
60
+ # === Обработка сгенерированного вопроса ===
61
+ raw = question_result[0]["generated_text"].replace("\n", " ").strip()
62
+ question = raw.split("?")[0].split("Question:")[-1].strip().capitalize() + "?"
63
+
64
+ return top, question
65
+
66
+ # =========================================================
67
+ # 3. Интерфейс Gradio
68
+ # =========================================================
69
+ with gr.Blocks(title="MBTI Interactive Interview") as demo:
70
+ gr.Markdown("## 🧠 MBTI Personality Interviewer\n"
71
+ "Определи личностный тип и получи следующий вопрос от интервьюера.")
72
+
73
+ with gr.Row():
74
+ with gr.Column(scale=1):
75
+ inp = gr.Textbox(
76
+ label="Введите свой ответ",
77
+ placeholder="Например: I enjoy working with people and organizing events.",
78
+ lines=4
79
+ )
80
+ btn = gr.Button("Анализировать и задать новый вопрос")
81
+
82
+ with gr.Column(scale=1):
83
+ out_analysis = gr.Textbox(label="📊 Анализ MBTI", lines=6)
84
+ out_question = gr.Textbox(label="💬 Следующий вопрос от интервьюера", lines=3)
85
+
86
+ btn.click(fn=classify_and_ask, inputs=inp, outputs=[out_analysis, out_question])
87
+
88
+ # =========================================================
89
+ # 4. Запуск
90
+ # =========================================================
91
+ if __name__ == "__main__":
92
+ demo.launch()