QAway-to commited on
Commit
89b8ce4
·
1 Parent(s): 29f110f

New version v1.2

Browse files
Files changed (1) hide show
  1. app.py +32 -20
app.py CHANGED
@@ -1,58 +1,70 @@
1
  import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
3
 
 
4
  MODEL_ID = "f3nsmart/MBTIclassifier"
5
-
6
- # === Модель классификации ===
7
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
8
  model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID)
9
  pipe = pipeline("text-classification", model=model, tokenizer=tokenizer, return_all_scores=True)
10
 
11
- # === Вспомогательная генеративная модель ===
12
  q_gen = pipeline(
13
  "text-generation",
14
- model="gpt2",
15
- temperature=0.8, # делает речь живее
16
- top_p=0.95, # ядровая выборка
17
  max_new_tokens=40
18
  )
19
 
 
20
  session = {"answers": [], "count": 0}
21
 
22
  def mbti_interview(user_input):
23
  if not user_input.strip():
24
- return "⚠️ Введите ответ.", "Please describe your thoughts briefly.", "0/30"
25
 
26
- # --- Анализ текста --- !
27
  results = pipe(user_input)[0]
28
  results = sorted(results, key=lambda x: x["score"], reverse=True)
29
  result_text = "\n".join([f"{r['label']} → {r['score']:.3f}" for r in results[:3]])
30
 
31
- # --- Сохраняем ответ ---
32
  session["answers"].append(user_input)
33
  session["count"] += 1
34
  progress = f"{session['count']}/30"
35
 
36
  # --- Генерация нового вопроса ---
37
- context = " | ".join(session["answers"][-3:])
38
- prompt = f"You are a personality test interviewer. Based on these responses ({context}), ask the next short MBTI-style question."
39
 
40
  raw_q = q_gen(prompt)[0]["generated_text"]
41
- next_q = raw_q.split(":")[-1].strip()
 
42
 
43
- # Чистим случайные обрывы
44
- if len(next_q.split()) < 4 or not next_q.endswith("?"):
45
- next_q += "?"
46
 
47
  return result_text, next_q, progress
48
 
49
- # === UI ===
50
  with gr.Blocks(css="""
51
- .gradio-container {max-width: 850px !important; margin: auto;}
52
- #inp, #out, #question {width: 100% !important;}
53
- #progress {text-align: center; font-weight: bold; color: #4CAF50;}
 
 
 
 
 
 
 
 
 
 
 
54
  """) as demo:
55
- gr.Markdown("## 🧠 Adaptive MBTI Classifier\nAnswer interactively — the model will ask questions dynamically.")
56
 
57
  question = gr.Textbox(label="Вопрос", value="Let's start: How do you usually spend your free time?", interactive=False, elem_id="question")
58
  inp = gr.Textbox(label="Ваш ответ", placeholder="Type your answer here...", elem_id="inp")
 
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
  pipe = pipeline("text-classification", model=model, tokenizer=tokenizer, return_all_scores=True)
9
 
10
+ # === 2. Генератор вопросов (диалоговая модель) ===
11
  q_gen = pipeline(
12
  "text-generation",
13
+ model="microsoft/DialoGPT-medium",
14
+ temperature=0.7,
15
+ top_p=0.9,
16
  max_new_tokens=40
17
  )
18
 
19
+ # === 3. Состояние сессии ===
20
  session = {"answers": [], "count": 0}
21
 
22
  def mbti_interview(user_input):
23
  if not user_input.strip():
24
+ return "⚠️ Введите ответ.", "Please share something about yourself.", "0/30"
25
 
26
+ # --- Анализ личности ---
27
  results = pipe(user_input)[0]
28
  results = sorted(results, key=lambda x: x["score"], reverse=True)
29
  result_text = "\n".join([f"{r['label']} → {r['score']:.3f}" for r in results[:3]])
30
 
31
+ # --- Обновляем историю ---
32
  session["answers"].append(user_input)
33
  session["count"] += 1
34
  progress = f"{session['count']}/30"
35
 
36
  # --- Генерация нового вопроса ---
37
+ context = " ".join(session["answers"][-3:])
38
+ prompt = f"As an MBTI interviewer, ask a meaningful personality question based on this: {context}. Ask only one question."
39
 
40
  raw_q = q_gen(prompt)[0]["generated_text"]
41
+ next_q = raw_q.split("?")[0] + "?"
42
+ next_q = next_q.strip().capitalize()
43
 
44
+ # фильтруем совсем бред
45
+ if len(next_q.split()) < 4:
46
+ next_q = "Can you tell me more about how you make important decisions?"
47
 
48
  return result_text, next_q, progress
49
 
50
+ # === 4. Интерфейс Gradio ===
51
  with gr.Blocks(css="""
52
+ .gradio-container {max-width: 1600px !important; margin: auto;}
53
+ #inp, #out, #question {
54
+ width: 90% !important;
55
+ margin-left: auto !important;
56
+ margin-right: auto !important;
57
+ font-size: 16px !important;
58
+ }
59
+ #progress {
60
+ text-align: center;
61
+ font-weight: bold;
62
+ color: #4CAF50;
63
+ font-size: 18px;
64
+ }
65
+ textarea {height: 100px !important;}
66
  """) as demo:
67
+ gr.Markdown("## 🧠 Adaptive MBTI Classifier\nDynamic MBTI Interview with Context-Aware Questions.")
68
 
69
  question = gr.Textbox(label="Вопрос", value="Let's start: How do you usually spend your free time?", interactive=False, elem_id="question")
70
  inp = gr.Textbox(label="Ваш ответ", placeholder="Type your answer here...", elem_id="inp")