File size: 38,877 Bytes
b7ff12a
2c18966
 
 
5aafae3
2c18966
5aafae3
2c18966
 
 
 
 
 
5aafae3
2c18966
5aafae3
2c18966
 
 
 
 
 
 
 
5aafae3
 
 
2c18966
5aafae3
01c9745
5aafae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c18966
b7ff12a
 
5aafae3
 
 
 
 
 
b7ff12a
5aafae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7ff12a
 
5aafae3
 
 
 
 
 
b7ff12a
5aafae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7ff12a
 
5aafae3
 
 
 
 
 
b7ff12a
5aafae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7ff12a
 
5aafae3
 
 
 
 
 
b7ff12a
5aafae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7ff12a
 
5aafae3
 
 
 
 
 
b7ff12a
5aafae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7ff12a
 
5aafae3
 
 
 
 
 
b7ff12a
5aafae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7ff12a
 
 
2c18966
 
 
24a5724
2c18966
 
 
 
5aafae3
 
 
 
 
 
2c18966
 
 
 
5aafae3
 
 
2c18966
 
5aafae3
 
24a5724
5aafae3
 
 
2c18966
 
 
24a5724
 
b7ff12a
 
5aafae3
 
 
 
 
 
 
 
 
 
b7ff12a
24a5724
 
2c18966
 
5aafae3
 
 
 
 
2c18966
24a5724
5aafae3
 
2c18966
5aafae3
 
 
 
 
 
2c18966
5aafae3
 
 
01c9745
5aafae3
 
 
2c18966
5aafae3
2c18966
 
 
24a5724
5aafae3
2c18966
5aafae3
 
b7ff12a
2c18966
 
 
 
 
 
 
 
 
 
5aafae3
2c18966
 
 
 
 
5aafae3
 
24a5724
5aafae3
01c9745
2c18966
01c9745
5aafae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c18966
 
 
 
 
5aafae3
2c18966
5aafae3
24a5724
5aafae3
2c18966
 
5aafae3
2c18966
 
5aafae3
2c18966
5aafae3
 
2c18966
 
 
5aafae3
 
 
01c9745
5aafae3
 
b7ff12a
5aafae3
 
2c18966
5aafae3
2c18966
 
b7ff12a
5aafae3
b7ff12a
5aafae3
 
 
 
 
 
 
 
 
 
2c18966
 
 
 
5aafae3
2c18966
 
b7ff12a
5aafae3
 
b7ff12a
5aafae3
 
24a5724
2c18966
 
5aafae3
 
 
 
 
 
 
 
 
 
2c18966
 
 
 
 
5aafae3
2c18966
 
b7ff12a
5aafae3
 
b7ff12a
5aafae3
 
 
 
 
2c18966
 
 
 
5aafae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24a5724
01c9745
 
 
 
5aafae3
01c9745
 
 
5aafae3
b7ff12a
5aafae3
24a5724
71e133a
 
01c9745
5aafae3
 
01c9745
5aafae3
01c9745
5aafae3
01c9745
5aafae3
01c9745
 
71e133a
 
5aafae3
 
 
24a5724
5aafae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24a5724
 
5aafae3
 
24a5724
5aafae3
 
 
24a5724
 
 
5aafae3
 
 
24a5724
5aafae3
 
 
 
 
24a5724
 
5aafae3
24a5724
 
 
 
 
5aafae3
24a5724
5aafae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788

import json
import os
import re
import tempfile
from statistics import mean
from typing import Any, Dict, List, Optional, Tuple

import requests
from fastapi import FastAPI, File, Form, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel

APP_VERSION = "5.0.0"

app = FastAPI(title="Japanese Role Interview API", version=APP_VERSION)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)

# -----------------------------
# Config
# -----------------------------
HF_TOKEN = os.getenv("HF_TOKEN", "").strip()
HF_ROUTER_URL = os.getenv("HF_ROUTER_URL", "https://router.huggingface.co/v1/chat/completions")
HF_INFERENCE_BASE = os.getenv("HF_INFERENCE_BASE", "https://router.huggingface.co/hf-inference/models")
ASR_MODEL = os.getenv("ASR_MODEL", "openai/whisper-large-v3")
CHAT_MODEL = os.getenv("CHAT_MODEL", "Qwen/Qwen2.5-7B-Instruct-1M")
USE_FASTER_WHISPER = os.getenv("USE_FASTER_WHISPER", "true").lower() in {"1", "true", "yes", "on"}
FASTER_WHISPER_MODEL = os.getenv("FASTER_WHISPER_MODEL", "small")
MAX_QUESTION_LIMIT = int(os.getenv("MAX_QUESTION_LIMIT", "20"))
ASR_TIMEOUT_SECONDS = int(os.getenv("ASR_TIMEOUT_SECONDS", "180"))
LLM_TIMEOUT_SECONDS = int(os.getenv("LLM_TIMEOUT_SECONDS", "90"))

_REPEAT_PROMPTS = [
    "ๅฃฐใŒๅฐใ•ใ„ใงใ™ใ€‚ใ‚‚ใ†ๅฐ‘ใ—ๅคงใใ„ๅฃฐใงใ€ใ‚‚ใ†ไธ€ๅบฆใŠ้ก˜ใ„ใ—ใพใ™ใ€‚",
    "ใพใ ้ŸณใŒใฏใฃใใ‚Š่žใ“ใˆใพใ›ใ‚“ใ€‚ใƒžใ‚คใ‚ฏใ‚’็ขบ่ชใ—ใฆใ€ใ‚‚ใ†ไธ€ๅบฆใŠ้ก˜ใ„ใ—ใพใ™ใ€‚",
    "้ŸณใŒใ†ใพใๅ…ฅใฃใฆใ„ใพใ›ใ‚“ใ€‚ใƒžใ‚คใ‚ฏใ‚’่ฟ‘ใฅใ‘ใฆใ€ใ‚‚ใ†ไธ€ๅบฆใŠ้ก˜ใ„ใ—ใพใ™ใ€‚",
]

_LOCAL_ASR_MODEL = None

ROLE_BANK: Dict[str, Dict[str, Any]] = {
    "construction": {
        "english_name": "Construction",
        "japanese_name": "ๅปบ่จญ",
        "intro_jp": "ใ“ใ‚“ใซใกใฏใ€‚ๅปบ่จญใฎไป•ไบ‹ใฎ้ขๆŽฅ็ทด็ฟ’ใ‚’ๅง‹ใ‚ใพใ™ใ€‚ใ‚ˆใ‚ใ—ใใŠ้ก˜ใ„ใ—ใพใ™ใ€‚",
        "min_questions": 3,
        "max_questions": 20,
        "expected_keywords": ["ๅฎ‰ๅ…จ", "ใƒ˜ใƒซใƒกใƒƒใƒˆ", "็พๅ ด", "ๅทฅๅ…ท", "ไฝ“ๅŠ›", "ใƒใƒผใƒ ", "ใƒซใƒผใƒซ"],
        "questions": [
            {"id":"name","theme":"intro","stage":"screening","jp":"ใŠๅๅ‰ใ‚’ๆ•™ใˆใฆใใ ใ•ใ„ใ€‚","branch":"all"},
            {"id":"country","theme":"intro","stage":"screening","jp":"ใฉใ“ใฎๅ›ฝใ‹ใ‚‰ๆฅใพใ—ใŸใ‹ใ€‚","branch":"all"},
            {"id":"reason","theme":"motivation","stage":"screening","jp":"ๆ—ฅๆœฌใธ่กŒใใŸใ„็†็”ฑใฏไฝ•ใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"japanese","theme":"language","stage":"screening","jp":"ๆ—ฅๆœฌ่ชžใฏใฉใฎใใ‚‰ใ„ๅ‹‰ๅผทใ—ใพใ—ใŸใ‹ใ€‚","branch":"all"},
            {"id":"ready_check","theme":"intro","stage":"screening","jp":"้ขๆŽฅใฎๆบ–ๅ‚™ใฏใงใใฆใ„ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"experience_gate","theme":"experience","stage":"role","jp":"ๅปบ่จญใฎไป•ไบ‹ใ‚’ใ—ใŸใ“ใจใŒใ‚ใ‚Šใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"exp_yes_detail","theme":"experience","stage":"role","jp":"ใฉใ‚“ใชๅปบ่จญใฎไป•ไบ‹ใ‚’ใ—ใพใ—ใŸใ‹ใ€‚","branch":"yes_exp"},
            {"id":"exp_years","theme":"experience","stage":"role","jp":"ใใฎไป•ไบ‹ใฏไฝ•ๅนดใใ‚‰ใ„ใ—ใพใ—ใŸใ‹ใ€‚","branch":"yes_exp"},
            {"id":"exp_no_motivation","theme":"motivation","stage":"role","jp":"็ตŒ้จ“ใŒใชใใฆใ‚‚ใ€ๅปบ่จญใฎไป•ไบ‹ใ‚’ๅ‹‰ๅผทใ—ใฆใŒใ‚“ใฐใ‚Œใพใ™ใ‹ใ€‚","branch":"no_exp"},
            {"id":"physical","theme":"role_fit","stage":"role","jp":"ไฝ“ๅŠ›ใŒๅฟ…่ฆใชไป•ไบ‹ใงใ™ใŒใ€ๅคงไธˆๅคซใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"safety","theme":"safety","stage":"role","jp":"ๅฑใชใ„ๅ ดๆ‰€ใงๅƒใใจใใ€ไฝ•ใซๆฐ—ใ‚’ใคใ‘ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"teamwork","theme":"teamwork","stage":"role","jp":"ใƒใƒผใƒ ใงไป•ไบ‹ใ‚’ใ™ใ‚‹ใจใใ€ๅคงๅˆ‡ใชใ“ใจใฏไฝ•ใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"tools","theme":"role_fit","stage":"followup","jp":"ๅทฅๅ…ทใ‚’ไฝฟใ†ไป•ไบ‹ใซ่ˆˆๅ‘ณใฏใ‚ใ‚Šใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"morning","theme":"schedule","stage":"followup","jp":"ๆœๆ—ฉใ„ไป•ไบ‹ใ‚„ๅค–ใฎไป•ไบ‹ใฏใงใใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"report","theme":"teamwork","stage":"followup","jp":"ๅˆ†ใ‹ใ‚‰ใชใ„ใจใใ€ๅ…ˆ่ผฉใซใ™ใ็›ธ่ซ‡ใงใใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"mistake","theme":"reliability","stage":"followup","jp":"ไป•ไบ‹ใงใƒŸใ‚นใ‚’ใ—ใŸใ‚‰ใ€ใฉใ†ใ—ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"strength","theme":"personality","stage":"followup","jp":"ๅปบ่จญใฎไป•ไบ‹ใซๅ‘ใ„ใฆใ„ใ‚‹่‡ชๅˆ†ใฎ้•ทๆ‰€ใ‚’ไธ€ใค่ฉฑใ—ใฆใใ ใ•ใ„ใ€‚","branch":"all"},
            {"id":"closing","theme":"closing","stage":"closing","jp":"ๆœฌๆ—ฅใฎๅปบ่จญใฎ้ขๆŽฅ็ทด็ฟ’ใฏใ“ใ“ใพใงใงใ™ใ€‚ใ”ๅ‚ๅŠ ใ‚ใ‚ŠใŒใจใ†ใ”ใ–ใ„ใพใ—ใŸใ€‚","branch":"all"},
        ],
    },
    "restaurant_konbini": {
        "english_name": "Restaurant / Konbini",
        "japanese_name": "ๅค–้ฃŸใƒปใ‚ณใƒณใƒ“ใƒ‹",
        "intro_jp": "ใ“ใ‚“ใซใกใฏใ€‚ๅค–้ฃŸใƒปใ‚ณใƒณใƒ“ใƒ‹ใฎไป•ไบ‹ใฎ้ขๆŽฅ็ทด็ฟ’ใ‚’ๅง‹ใ‚ใพใ™ใ€‚ใ‚ˆใ‚ใ—ใใŠ้ก˜ใ„ใ—ใพใ™ใ€‚",
        "min_questions": 3,
        "max_questions": 20,
        "expected_keywords": ["ๆŽฅๅฎข", "ใƒฌใ‚ธ", "ใŠๅฎขๆง˜", "็ฌ‘้ก”", "ใฆใ„ใญใ„", "ๅ“ๅ‡บใ—", "ๆŽƒ้™ค"],
        "questions": [
            {"id":"name","theme":"intro","stage":"screening","jp":"ใŠๅๅ‰ใ‚’ๆ•™ใˆใฆใใ ใ•ใ„ใ€‚","branch":"all"},
            {"id":"country","theme":"intro","stage":"screening","jp":"ใฉใ“ใฎๅ›ฝใ‹ใ‚‰ๆฅใพใ—ใŸใ‹ใ€‚","branch":"all"},
            {"id":"reason","theme":"motivation","stage":"screening","jp":"ๆ—ฅๆœฌใธ่กŒใใŸใ„็†็”ฑใฏไฝ•ใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"japanese","theme":"language","stage":"screening","jp":"ๆ—ฅๆœฌ่ชžใฏใฉใฎใใ‚‰ใ„ๅ‹‰ๅผทใ—ใพใ—ใŸใ‹ใ€‚","branch":"all"},
            {"id":"ready_check","theme":"intro","stage":"screening","jp":"้ขๆŽฅใฎๆบ–ๅ‚™ใฏใงใใฆใ„ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"experience_gate","theme":"experience","stage":"role","jp":"ใƒฌใ‚นใƒˆใƒฉใƒณใ‚„ใ‚ณใƒณใƒ“ใƒ‹ใงๅƒใ„ใŸ็ตŒ้จ“ใฏใ‚ใ‚Šใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"exp_yes_detail","theme":"experience","stage":"role","jp":"ใฉใ‚“ใชไป•ไบ‹ใ‚’ใ—ใพใ—ใŸใ‹ใ€‚ใƒฌใ‚ธใ€ๆŽฅๅฎขใ€ๅ“ๅ‡บใ—ใชใฉใ‚’่ฉฑใ—ใฆใใ ใ•ใ„ใ€‚","branch":"yes_exp"},
            {"id":"exp_no_motivation","theme":"motivation","stage":"role","jp":"็ตŒ้จ“ใŒใชใใฆใ‚‚ใ€ๆŽฅๅฎขใ‚’ๅ‹‰ๅผทใ™ใ‚‹ๆฐ—ๆŒใกใฏใ‚ใ‚Šใพใ™ใ‹ใ€‚","branch":"no_exp"},
            {"id":"customer","theme":"service","stage":"role","jp":"ใŠๅฎขๆง˜ใซใฏใ€ใฉใ‚“ใช่ฉฑใ—ๆ–นใ‚’ใ—ใŸใ„ใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"busy","theme":"role_fit","stage":"role","jp":"ๅฟ™ใ—ใ„ๆ™‚้–“ใงใ‚‚่ฝใก็€ใ„ใฆๅƒใ‘ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"cleanliness","theme":"service","stage":"role","jp":"ใŠๅบ—ใฎๆธ…ๆฝ”ใ•ใฏๅคงๅˆ‡ใงใ™ใ‹ใ€‚ใชใœใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"shift","theme":"schedule","stage":"followup","jp":"็ซ‹ใกไป•ไบ‹ใ‚„ใ‚ทใƒ•ใƒˆๅ‹คๅ‹™ใฏๅคงไธˆๅคซใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"mistake","theme":"reliability","stage":"followup","jp":"ๆณจๆ–‡ใ‚„ใƒฌใ‚ธใง้–“้•ใˆใŸใ‚‰ใ€ใฉใ†ใ—ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"teamwork","theme":"teamwork","stage":"followup","jp":"ใปใ‹ใฎใ‚นใ‚ฟใƒƒใƒ•ใจๅ”ๅŠ›ใงใใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"strength","theme":"personality","stage":"followup","jp":"ใ“ใฎไป•ไบ‹ใซๅ‘ใ„ใฆใ„ใ‚‹่‡ชๅˆ†ใฎ้•ทๆ‰€ใ‚’ไธ€ใค่ฉฑใ—ใฆใใ ใ•ใ„ใ€‚","branch":"all"},
            {"id":"closing","theme":"closing","stage":"closing","jp":"ๆœฌๆ—ฅใฎๅค–้ฃŸใƒปใ‚ณใƒณใƒ“ใƒ‹ใฎ้ขๆŽฅ็ทด็ฟ’ใฏใ“ใ“ใพใงใงใ™ใ€‚ใ”ๅ‚ๅŠ ใ‚ใ‚ŠใŒใจใ†ใ”ใ–ใ„ใพใ—ใŸใ€‚","branch":"all"},
        ],
    },
    "nursing_care": {
        "english_name": "Nursing Care",
        "japanese_name": "ไป‹่ญท",
        "intro_jp": "ใ“ใ‚“ใซใกใฏใ€‚ไป‹่ญทใฎไป•ไบ‹ใฎ้ขๆŽฅ็ทด็ฟ’ใ‚’ๅง‹ใ‚ใพใ™ใ€‚ใ‚ˆใ‚ใ—ใใŠ้ก˜ใ„ใ—ใพใ™ใ€‚",
        "min_questions": 3,
        "max_questions": 20,
        "expected_keywords": ["ไป‹่ญท", "ใ‚„ใ•ใ—ใ„", "ๅˆฉ็”จ่€…", "ใŠๅนดๅฏ„ใ‚Š", "ๆธ…ๆฝ”", "ๆ‰‹ไผใ†", "่ฒฌไปป"],
        "questions": [
            {"id":"name","theme":"intro","stage":"screening","jp":"ใŠๅๅ‰ใ‚’ๆ•™ใˆใฆใใ ใ•ใ„ใ€‚","branch":"all"},
            {"id":"country","theme":"intro","stage":"screening","jp":"ใฉใ“ใฎๅ›ฝใ‹ใ‚‰ๆฅใพใ—ใŸใ‹ใ€‚","branch":"all"},
            {"id":"reason","theme":"motivation","stage":"screening","jp":"ๆ—ฅๆœฌใธ่กŒใใŸใ„็†็”ฑใฏไฝ•ใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"japanese","theme":"language","stage":"screening","jp":"ๆ—ฅๆœฌ่ชžใฏใฉใฎใใ‚‰ใ„ๅ‹‰ๅผทใ—ใพใ—ใŸใ‹ใ€‚","branch":"all"},
            {"id":"ready_check","theme":"intro","stage":"screening","jp":"้ขๆŽฅใฎๆบ–ๅ‚™ใฏใงใใฆใ„ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"experience_gate","theme":"experience","stage":"role","jp":"ไป‹่ญทใฎไป•ไบ‹ใ‚’ใ—ใŸใ“ใจใŒใ‚ใ‚Šใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"exp_yes_detail","theme":"experience","stage":"role","jp":"ใฉใ‚“ใชไป‹่ญทใฎไป•ไบ‹ใ‚’ใ—ใพใ—ใŸใ‹ใ€‚","branch":"yes_exp"},
            {"id":"exp_no_motivation","theme":"motivation","stage":"role","jp":"็ตŒ้จ“ใŒใชใใฆใ‚‚ใ€ไป‹่ญทใฎๅ‹‰ๅผทใ‚’ใ—ใฆใŒใ‚“ใฐใ‚Œใพใ™ใ‹ใ€‚","branch":"no_exp"},
            {"id":"kindness","theme":"service","stage":"role","jp":"ใŠๅนดๅฏ„ใ‚Šใ‚„ๅˆฉ็”จ่€…ใ•ใ‚“ใซใ€ใ‚„ใ•ใ—ใ่ฉฑใ›ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"cleanliness","theme":"safety","stage":"role","jp":"ไป‹่ญทใฎไป•ไบ‹ใงๆธ…ๆฝ”ใ•ใฏๅคงๅˆ‡ใงใ™ใ‹ใ€‚ใชใœใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"communication","theme":"service","stage":"role","jp":"ๅˆฉ็”จ่€…ใ•ใ‚“ใŒๅ›ฐใฃใฆใ„ใŸใ‚‰ใ€ใพใšไฝ•ใ‚’ใ—ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"hard_work","theme":"role_fit","stage":"followup","jp":"ๅคงๅค‰ใชไป•ไบ‹ใงใ‚‚ใ€่ฝใก็€ใ„ใฆ็ถšใ‘ใ‚‰ใ‚Œใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"teamwork","theme":"teamwork","stage":"followup","jp":"ใ‚นใ‚ฟใƒƒใƒ•ใจๅ”ๅŠ›ใงใใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"report","theme":"teamwork","stage":"followup","jp":"ๅ ฑๅ‘Šใƒป้€ฃ็ตกใƒป็›ธ่ซ‡ใฏใงใใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"strength","theme":"personality","stage":"followup","jp":"ไป‹่ญทใฎไป•ไบ‹ใซๅ‘ใ„ใฆใ„ใ‚‹่‡ชๅˆ†ใฎ้•ทๆ‰€ใ‚’ไธ€ใค่ฉฑใ—ใฆใใ ใ•ใ„ใ€‚","branch":"all"},
            {"id":"closing","theme":"closing","stage":"closing","jp":"ๆœฌๆ—ฅใฎไป‹่ญทใฎ้ขๆŽฅ็ทด็ฟ’ใฏใ“ใ“ใพใงใงใ™ใ€‚ใ”ๅ‚ๅŠ ใ‚ใ‚ŠใŒใจใ†ใ”ใ–ใ„ใพใ—ใŸใ€‚","branch":"all"},
        ],
    },
    "hotel_accommodation": {
        "english_name": "Hotel / Accommodation",
        "japanese_name": "ๅฎฟๆณŠ",
        "intro_jp": "ใ“ใ‚“ใซใกใฏใ€‚ๅฎฟๆณŠใƒปใƒ›ใƒ†ใƒซใฎไป•ไบ‹ใฎ้ขๆŽฅ็ทด็ฟ’ใ‚’ๅง‹ใ‚ใพใ™ใ€‚ใ‚ˆใ‚ใ—ใใŠ้ก˜ใ„ใ—ใพใ™ใ€‚",
        "min_questions": 3,
        "max_questions": 20,
        "expected_keywords": ["ใƒ›ใƒ†ใƒซ", "ใŠๅฎขๆง˜", "ใฆใ„ใญใ„", "็ฌ‘้ก”", "ๆŽƒ้™ค", "ใƒ•ใƒญใƒณใƒˆ", "ๆกˆๅ†…"],
        "questions": [
            {"id":"name","theme":"intro","stage":"screening","jp":"ใŠๅๅ‰ใ‚’ๆ•™ใˆใฆใใ ใ•ใ„ใ€‚","branch":"all"},
            {"id":"country","theme":"intro","stage":"screening","jp":"ใฉใ“ใฎๅ›ฝใ‹ใ‚‰ๆฅใพใ—ใŸใ‹ใ€‚","branch":"all"},
            {"id":"reason","theme":"motivation","stage":"screening","jp":"ๆ—ฅๆœฌใธ่กŒใใŸใ„็†็”ฑใฏไฝ•ใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"japanese","theme":"language","stage":"screening","jp":"ๆ—ฅๆœฌ่ชžใฏใฉใฎใใ‚‰ใ„ๅ‹‰ๅผทใ—ใพใ—ใŸใ‹ใ€‚","branch":"all"},
            {"id":"ready_check","theme":"intro","stage":"screening","jp":"้ขๆŽฅใฎๆบ–ๅ‚™ใฏใงใใฆใ„ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"experience_gate","theme":"experience","stage":"role","jp":"ใƒ›ใƒ†ใƒซใ‚„ๅฎฟๆณŠใฎไป•ไบ‹ใ‚’ใ—ใŸใ“ใจใŒใ‚ใ‚Šใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"exp_yes_detail","theme":"experience","stage":"role","jp":"ใฉใ‚“ใชไป•ไบ‹ใ‚’ใ—ใพใ—ใŸใ‹ใ€‚ใƒ•ใƒญใƒณใƒˆใ€ๆŽƒ้™คใ€ใƒ™ใƒƒใƒ‰ใƒกใ‚คใ‚ฏใชใฉใ‚’่ฉฑใ—ใฆใใ ใ•ใ„ใ€‚","branch":"yes_exp"},
            {"id":"exp_no_motivation","theme":"motivation","stage":"role","jp":"็ตŒ้จ“ใŒใชใใฆใ‚‚ใ€ใƒ›ใƒ†ใƒซใฎไป•ไบ‹ใ‚’ๅ‹‰ๅผทใ—ใฆใŒใ‚“ใฐใ‚Œใพใ™ใ‹ใ€‚","branch":"no_exp"},
            {"id":"customer","theme":"service","stage":"role","jp":"ใŠๅฎขๆง˜ใซ่ฉฑใ™ใจใใ€ใฉใ‚“ใชใ“ใจใ‚’ๅคงๅˆ‡ใซใ—ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"cleanliness","theme":"service","stage":"role","jp":"้ƒจๅฑ‹ใฎๆŽƒ้™คใ‚„ๆ•ด็†ๆ•ด้ “ใฏๅฅฝใใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"busy","theme":"role_fit","stage":"role","jp":"ๅฟ™ใ—ใ„ๆ™‚้–“ใงใ‚‚่ฝใก็€ใ„ใฆๅƒใ‘ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"teamwork","theme":"teamwork","stage":"followup","jp":"ใ‚นใ‚ฟใƒƒใƒ•ใจๅ”ๅŠ›ใ—ใฆๅƒใใ“ใจใฏใงใใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"shift","theme":"schedule","stage":"followup","jp":"ๅคœใ‚„ๆœใฎใ‚ทใƒ•ใƒˆใฏๅคงไธˆๅคซใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"strength","theme":"personality","stage":"followup","jp":"ใƒ›ใƒ†ใƒซใฎไป•ไบ‹ใซๅ‘ใ„ใฆใ„ใ‚‹่‡ชๅˆ†ใฎ้•ทๆ‰€ใ‚’ไธ€ใค่ฉฑใ—ใฆใใ ใ•ใ„ใ€‚","branch":"all"},
            {"id":"closing","theme":"closing","stage":"closing","jp":"ๆœฌๆ—ฅใฎๅฎฟๆณŠใฎ้ขๆŽฅ็ทด็ฟ’ใฏใ“ใ“ใพใงใงใ™ใ€‚ใ”ๅ‚ๅŠ ใ‚ใ‚ŠใŒใจใ†ใ”ใ–ใ„ใพใ—ใŸใ€‚","branch":"all"},
        ],
    },
    "agriculture": {
        "english_name": "Agriculture",
        "japanese_name": "่พฒๆฅญ",
        "intro_jp": "ใ“ใ‚“ใซใกใฏใ€‚่พฒๆฅญใฎไป•ไบ‹ใฎ้ขๆŽฅ็ทด็ฟ’ใ‚’ๅง‹ใ‚ใพใ™ใ€‚ใ‚ˆใ‚ใ—ใใŠ้ก˜ใ„ใ—ใพใ™ใ€‚",
        "min_questions": 3,
        "max_questions": 20,
        "expected_keywords": ["่พฒๆฅญ", "็•‘", "ไฝ“ๅŠ›", "ๆœ", "ๅŽ็ฉซ", "ๅค–", "ๆ™‚้–“"],
        "questions": [
            {"id":"name","theme":"intro","stage":"screening","jp":"ใŠๅๅ‰ใ‚’ๆ•™ใˆใฆใใ ใ•ใ„ใ€‚","branch":"all"},
            {"id":"country","theme":"intro","stage":"screening","jp":"ใฉใ“ใฎๅ›ฝใ‹ใ‚‰ๆฅใพใ—ใŸใ‹ใ€‚","branch":"all"},
            {"id":"reason","theme":"motivation","stage":"screening","jp":"ๆ—ฅๆœฌใธ่กŒใใŸใ„็†็”ฑใฏไฝ•ใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"japanese","theme":"language","stage":"screening","jp":"ๆ—ฅๆœฌ่ชžใฏใฉใฎใใ‚‰ใ„ๅ‹‰ๅผทใ—ใพใ—ใŸใ‹ใ€‚","branch":"all"},
            {"id":"ready_check","theme":"intro","stage":"screening","jp":"้ขๆŽฅใฎๆบ–ๅ‚™ใฏใงใใฆใ„ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"experience_gate","theme":"experience","stage":"role","jp":"่พฒๆฅญใฎไป•ไบ‹ใ‚’ใ—ใŸใ“ใจใŒใ‚ใ‚Šใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"exp_yes_detail","theme":"experience","stage":"role","jp":"ใฉใ‚“ใช่พฒๆฅญใฎไป•ไบ‹ใ‚’ใ—ใพใ—ใŸใ‹ใ€‚","branch":"yes_exp"},
            {"id":"exp_no_motivation","theme":"motivation","stage":"role","jp":"็ตŒ้จ“ใŒใชใใฆใ‚‚ใ€่พฒๆฅญใ‚’ๅ‹‰ๅผทใ—ใฆใŒใ‚“ใฐใ‚Œใพใ™ใ‹ใ€‚","branch":"no_exp"},
            {"id":"outside_work","theme":"role_fit","stage":"role","jp":"ๅค–ใง้•ทใ„ๆ™‚้–“ๅƒใใ“ใจใฏๅคงไธˆๅคซใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"early_morning","theme":"schedule","stage":"role","jp":"ๆœๆ—ฉใ„ไป•ไบ‹ใงใ‚‚ๆ™‚้–“ใ‚’ๅฎˆใ‚Œใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"physical","theme":"role_fit","stage":"role","jp":"ไฝ“ๅŠ›ใซ่‡ชไฟกใฏใ‚ใ‚Šใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"weather","theme":"role_fit","stage":"followup","jp":"ๆš‘ใ„ๆ—ฅใ‚„ๅฏ’ใ„ๆ—ฅใงใ‚‚ใ€ใพใ˜ใ‚ใซๅƒใ‘ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"teamwork","theme":"teamwork","stage":"followup","jp":"ใปใ‹ใฎไบบใจไธ€็ท’ใซๅƒใ‘ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"strength","theme":"personality","stage":"followup","jp":"่พฒๆฅญใฎไป•ไบ‹ใซๅ‘ใ„ใฆใ„ใ‚‹่‡ชๅˆ†ใฎ้•ทๆ‰€ใ‚’ไธ€ใค่ฉฑใ—ใฆใใ ใ•ใ„ใ€‚","branch":"all"},
            {"id":"closing","theme":"closing","stage":"closing","jp":"ๆœฌๆ—ฅใฎ่พฒๆฅญใฎ้ขๆŽฅ็ทด็ฟ’ใฏใ“ใ“ใพใงใงใ™ใ€‚ใ”ๅ‚ๅŠ ใ‚ใ‚ŠใŒใจใ†ใ”ใ–ใ„ใพใ—ใŸใ€‚","branch":"all"},
        ],
    },
    "manufacturing": {
        "english_name": "Manufacturing",
        "japanese_name": "่ฃฝ้€ ๆฅญ",
        "intro_jp": "ใ“ใ‚“ใซใกใฏใ€‚่ฃฝ้€ ๆฅญใฎไป•ไบ‹ใฎ้ขๆŽฅ็ทด็ฟ’ใ‚’ๅง‹ใ‚ใพใ™ใ€‚ใ‚ˆใ‚ใ—ใใŠ้ก˜ใ„ใ—ใพใ™ใ€‚",
        "min_questions": 3,
        "max_questions": 20,
        "expected_keywords": ["ๅทฅๅ ด", "ๅฎ‰ๅ…จ", "ๆญฃ็ขบ", "็ขบ่ช", "ๆ™‚้–“", "ใƒซใƒผใƒซ", "้›†ไธญ"],
        "questions": [
            {"id":"name","theme":"intro","stage":"screening","jp":"ใŠๅๅ‰ใ‚’ๆ•™ใˆใฆใใ ใ•ใ„ใ€‚","branch":"all"},
            {"id":"country","theme":"intro","stage":"screening","jp":"ใฉใ“ใฎๅ›ฝใ‹ใ‚‰ๆฅใพใ—ใŸใ‹ใ€‚","branch":"all"},
            {"id":"reason","theme":"motivation","stage":"screening","jp":"ๆ—ฅๆœฌใธ่กŒใใŸใ„็†็”ฑใฏไฝ•ใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"japanese","theme":"language","stage":"screening","jp":"ๆ—ฅๆœฌ่ชžใฏใฉใฎใใ‚‰ใ„ๅ‹‰ๅผทใ—ใพใ—ใŸใ‹ใ€‚","branch":"all"},
            {"id":"ready_check","theme":"intro","stage":"screening","jp":"้ขๆŽฅใฎๆบ–ๅ‚™ใฏใงใใฆใ„ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"experience_gate","theme":"experience","stage":"role","jp":"ๅทฅๅ ดใ‚„่ฃฝ้€ ใฎไป•ไบ‹ใ‚’ใ—ใŸใ“ใจใŒใ‚ใ‚Šใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"exp_yes_detail","theme":"experience","stage":"role","jp":"ใฉใ‚“ใช่ฃฝ้€ ใฎไป•ไบ‹ใ‚’ใ—ใพใ—ใŸใ‹ใ€‚","branch":"yes_exp"},
            {"id":"exp_no_motivation","theme":"motivation","stage":"role","jp":"็ตŒ้จ“ใŒใชใใฆใ‚‚ใ€่ฃฝ้€ ใฎไป•ไบ‹ใ‚’ๅ‹‰ๅผทใ—ใฆใŒใ‚“ใฐใ‚Œใพใ™ใ‹ใ€‚","branch":"no_exp"},
            {"id":"accuracy","theme":"role_fit","stage":"role","jp":"ใƒŸใ‚นใ‚’ๅฐ‘ใชใใ™ใ‚‹ใŸใ‚ใซใ€ไฝ•ใ‚’ๅคงๅˆ‡ใซใ—ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"safety","theme":"safety","stage":"role","jp":"ๆฉŸๆขฐใ‚’ไฝฟใ†ใจใใ€ๅฎ‰ๅ…จใฎใŸใ‚ใซไฝ•ใ‚’ใ—ใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"time","theme":"schedule","stage":"role","jp":"ๆ™‚้–“ใ‚’ๅฎˆใฃใฆใ€ๅŒใ˜ไฝœๆฅญใ‚’็ถšใ‘ใ‚‹ใ“ใจใฏใงใใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"quality","theme":"reliability","stage":"followup","jp":"ๅ“่ณชใ‚’ๅฎˆใ‚‹ใ“ใจใฏๅคงๅˆ‡ใงใ™ใ‹ใ€‚ใชใœใงใ™ใ‹ใ€‚","branch":"all"},
            {"id":"teamwork","theme":"teamwork","stage":"followup","jp":"ใƒใƒผใƒ ใงๅ”ๅŠ›ใงใใพใ™ใ‹ใ€‚","branch":"all"},
            {"id":"strength","theme":"personality","stage":"followup","jp":"่ฃฝ้€ ๆฅญใฎไป•ไบ‹ใซๅ‘ใ„ใฆใ„ใ‚‹่‡ชๅˆ†ใฎ้•ทๆ‰€ใ‚’ไธ€ใค่ฉฑใ—ใฆใใ ใ•ใ„ใ€‚","branch":"all"},
            {"id":"closing","theme":"closing","stage":"closing","jp":"ๆœฌๆ—ฅใฎ่ฃฝ้€ ๆฅญใฎ้ขๆŽฅ็ทด็ฟ’ใฏใ“ใ“ใพใงใงใ™ใ€‚ใ”ๅ‚ๅŠ ใ‚ใ‚ŠใŒใจใ†ใ”ใ–ใ„ใพใ—ใŸใ€‚","branch":"all"},
        ],
    },
}


class StartRequest(BaseModel):
    session_uuid: str
    job_role: str = "construction"


@app.get("/")
def root() -> Dict[str, Any]:
    return {
        "ok": True,
        "service": "jp-role-interview",
        "version": APP_VERSION,
        "routes": ["/health", "/roles", "/start", "/answer"],
    }


@app.get("/health")
def health() -> Dict[str, Any]:
    asr_backend = "hf_api"
    if USE_FASTER_WHISPER:
        asr_backend = "faster_whisper_then_hf_api"
    return {
        "ok": True,
        "service": "jp-role-interview",
        "version": APP_VERSION,
        "hf_token_set": bool(HF_TOKEN),
        "asr_backend": asr_backend,
        "chat_model": CHAT_MODEL,
        "role_count": len(ROLE_BANK),
    }


@app.get("/roles")
def roles() -> Dict[str, Any]:
    return {
        "ok": True,
        "roles": [
            {
                "key": key,
                "english_name": cfg["english_name"],
                "japanese_name": cfg["japanese_name"],
                "min_questions": cfg["min_questions"],
                "max_questions": cfg["max_questions"],
            }
            for key, cfg in ROLE_BANK.items()
        ],
    }


@app.post("/start")
def start_interview(payload: StartRequest) -> Dict[str, Any]:
    role_key = normalize_role_key(payload.job_role)
    role_cfg = ROLE_BANK[role_key]
    first_q = get_question(role_cfg, "name")
    opening = f"{role_cfg['intro_jp']} {first_q['jp']}"

    memory = {
        "job_role": role_key,
        "job_role_en": role_cfg["english_name"],
        "job_role_jp": role_cfg["japanese_name"],
        "candidate_name": None,
        "country_name": None,
        "age": None,
        "reason_for_japan": None,
        "occupation": None,
        "japanese_level": None,
        "experience_state": "unknown",
        "answers_so_far": [],
        "asked_question_ids": [first_q["id"]],
        "asked_themes": [first_q["theme"]],
        "low_score_streak": 0,
        "no_sound_count": 0,
        "min_questions": role_cfg["min_questions"],
        "max_questions": min(role_cfg["max_questions"], MAX_QUESTION_LIMIT),
        "auto_question_mode": True,
    }

    return {
        "ok": True,
        "session_uuid": payload.session_uuid,
        "job_role": role_key,
        "job_role_label": f"{role_cfg['english_name']} / {role_cfg['japanese_name']}",
        "question_no": 1,
        "question_id": first_q["id"],
        "question_jp": first_q["jp"],
        "speech_text_jp": opening,
        "memory": memory,
        "is_finished": False,
        "speak_now": True,
    }


@app.post("/answer")
async def answer_interview(
    session_uuid: str = Form(...),
    question_no: int = Form(...),
    question_id: str = Form(...),
    question_jp: str = Form(...),
    memory_json: str = Form("{}"),
    audio: UploadFile = File(...),
) -> Dict[str, Any]:
    memory = safe_json_loads(memory_json)
    role_key = normalize_role_key(memory.get("job_role"))
    role_cfg = ROLE_BANK[role_key]

    transcript, asr_backend, asr_error = await transcribe_upload(audio)

    if not transcript.strip():
        memory["no_sound_count"] = int(memory.get("no_sound_count", 0)) + 1
        name = memory.get("candidate_name")
        spoken = build_repeat_prompt(name, memory["no_sound_count"])
        should_finish = memory["no_sound_count"] >= 2 and question_no >= role_cfg["min_questions"]
        if should_finish:
            result = build_final_result(role_cfg, memory, force_fail=True, summary_jp="้ŸณๅฃฐใŒ่žใ“ใˆใชใ„ใŸใ‚ใ€้ขๆŽฅใ‚’็ต‚ไบ†ใ—ใพใ—ใŸใ€‚")
            return {
                "ok": True,
                "is_finished": True,
                "session_uuid": session_uuid,
                "job_role": role_key,
                "transcript_jp": "",
                "answer_score": 0,
                "feedback_jp": spoken,
                "speech_text_jp": spoken,
                "memory": memory,
                "asr_backend": asr_backend,
                "asr_error": asr_error,
                "result": result,
            }
        return {
            "ok": True,
            "is_finished": False,
            "needs_repeat": True,
            "session_uuid": session_uuid,
            "job_role": role_key,
            "question_no": question_no,
            "question_id": question_id,
            "question_jp": question_jp,
            "speech_text_jp": spoken,
            "transcript_jp": "",
            "answer_score": 0,
            "feedback_jp": spoken,
            "memory": memory,
            "next_question_no": question_no,
            "next_question_id": question_id,
            "next_question_jp": question_jp,
            "asr_backend": asr_backend,
            "asr_error": asr_error,
            "speak_now": True,
        }

    memory["no_sound_count"] = 0
    profile_update = maybe_extract_basic_profile(memory, transcript, question_id)
    memory = merge_memory(memory, profile_update)

    score = score_answer(role_cfg, question_id, transcript)
    feedback = build_feedback(score)

    answers = list(memory.get("answers_so_far", []))
    answers.append({
        "question_no": question_no,
        "question_id": question_id,
        "question_jp": question_jp,
        "answer_text_jp": transcript,
        "answer_score": score,
        "feedback_jp": feedback,
    })
    memory["answers_so_far"] = answers

    if score <= 3:
        memory["low_score_streak"] = int(memory.get("low_score_streak", 0)) + 1
    else:
        memory["low_score_streak"] = 0

    should_finish = decide_finish(role_cfg, memory, question_no, score)
    if should_finish:
        result = build_final_result(role_cfg, memory)
        return {
            "ok": True,
            "is_finished": True,
            "session_uuid": session_uuid,
            "job_role": role_key,
            "question_no": question_no,
            "transcript_jp": transcript,
            "answer_score": score,
            "feedback_jp": feedback,
            "speech_text_jp": result["closing_message_jp"],
            "memory": memory,
            "asr_backend": asr_backend,
            "asr_error": asr_error,
            "result": result,
        }

    next_q = select_next_question(role_cfg, memory)
    next_no = question_no + 1
    if next_q["id"] not in memory["asked_question_ids"]:
        memory["asked_question_ids"].append(next_q["id"])
    if next_q["theme"] not in memory["asked_themes"]:
        memory["asked_themes"].append(next_q["theme"])

    spoken_next = next_q["jp"]
    if next_q["id"] == "ready_check" and memory.get("candidate_name"):
        spoken_next = f"{memory['candidate_name']}ใ•ใ‚“ใ€ใ‚ใ‚ŠใŒใจใ†ใ”ใ–ใ„ใพใ™ใ€‚{next_q['jp']}"

    return {
        "ok": True,
        "is_finished": False,
        "session_uuid": session_uuid,
        "job_role": role_key,
        "question_no": question_no,
        "transcript_jp": transcript,
        "answer_score": score,
        "feedback_jp": feedback,
        "speech_text_jp": spoken_next,
        "memory": memory,
        "asr_backend": asr_backend,
        "asr_error": asr_error,
        "next_question_no": next_no,
        "next_question_id": next_q["id"],
        "next_question_jp": next_q["jp"],
        "speak_now": True,
    }


def normalize_role_key(value: Any) -> str:
    key = str(value or "construction").strip().lower()
    aliases = {
        "restaurant": "restaurant_konbini",
        "konbini": "restaurant_konbini",
        "nursing": "nursing_care",
        "care": "nursing_care",
        "hotel": "hotel_accommodation",
        "accommodation": "hotel_accommodation",
    }
    key = aliases.get(key, key)
    return key if key in ROLE_BANK else "construction"


def get_question(role_cfg: Dict[str, Any], qid: str) -> Dict[str, Any]:
    for q in role_cfg["questions"]:
        if q["id"] == qid:
            return q
    return role_cfg["questions"][0]


def build_repeat_prompt(name: Optional[str], count: int) -> str:
    idx = max(0, min(count - 1, len(_REPEAT_PROMPTS) - 1))
    base = _REPEAT_PROMPTS[idx]
    if name:
        return f"{name}ใ•ใ‚“ใ€{base}"
    return base


async def transcribe_upload(audio: UploadFile) -> Tuple[str, str, Optional[str]]:
    content = await audio.read()
    filename = audio.filename or "answer.webm"

    if USE_FASTER_WHISPER:
        try:
            text = transcribe_with_faster_whisper(content, filename)
            return normalize_text(text), "faster_whisper", None
        except Exception as exc:
            if HF_TOKEN:
                try:
                    text = transcribe_with_hf_api(content, filename)
                    return normalize_text(text), "hf_api_fallback", str(exc)
                except Exception as exc2:
                    return "", "hf_api_fallback_failed", f"{exc} | {exc2}"
            return "", "faster_whisper_failed", str(exc)

    if HF_TOKEN:
        try:
            text = transcribe_with_hf_api(content, filename)
            return normalize_text(text), "hf_api", None
        except Exception as exc:
            return "", "hf_api_failed", str(exc)

    return "", "no_asr_backend", "Neither faster-whisper nor HF API is available."


def transcribe_with_faster_whisper(content: bytes, filename: str) -> str:
    global _LOCAL_ASR_MODEL
    from faster_whisper import WhisperModel  # lazy import

    suffix = os.path.splitext(filename)[1] or ".webm"
    with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
        tmp.write(content)
        temp_path = tmp.name

    try:
        if _LOCAL_ASR_MODEL is None:
            _LOCAL_ASR_MODEL = WhisperModel(FASTER_WHISPER_MODEL, device="cpu", compute_type="int8")
        segments, _info = _LOCAL_ASR_MODEL.transcribe(temp_path, language="ja", vad_filter=True)
        return " ".join(seg.text.strip() for seg in segments).strip()
    finally:
        try:
            os.remove(temp_path)
        except OSError:
            pass


def transcribe_with_hf_api(content: bytes, filename: str) -> str:
    url = f"{HF_INFERENCE_BASE}/{ASR_MODEL}"
    headers = {
        "Authorization": f"Bearer {HF_TOKEN}",
        "Content-Type": guess_mime_type(filename),
    }
    response = requests.post(url, headers=headers, data=content, timeout=ASR_TIMEOUT_SECONDS)
    response.raise_for_status()
    data = response.json()
    if isinstance(data, dict):
        return str(data.get("text") or data.get("generated_text") or "")
    if isinstance(data, list) and data and isinstance(data[0], dict):
        return str(data[0].get("text") or "")
    return ""


def guess_mime_type(filename: str) -> str:
    lower = (filename or "").lower()
    if lower.endswith(".wav"):
        return "audio/wav"
    if lower.endswith(".mp3"):
        return "audio/mpeg"
    if lower.endswith(".m4a"):
        return "audio/mp4"
    if lower.endswith(".ogg"):
        return "audio/ogg"
    return "audio/webm"


def maybe_extract_basic_profile(memory: Dict[str, Any], transcript: str, question_id: str) -> Dict[str, Any]:
    text = normalize_text(transcript)
    update: Dict[str, Any] = {}

    if question_id == "name" and not memory.get("candidate_name"):
        name = extract_name(text)
        if name:
            update["candidate_name"] = name

    if question_id == "country" and not memory.get("country_name"):
        country = extract_country(text)
        if country:
            update["country_name"] = country

    if question_id == "reason" and not memory.get("reason_for_japan") and len(text) >= 4:
        update["reason_for_japan"] = text[:120]

    if question_id == "japanese" and not memory.get("japanese_level") and len(text) >= 4:
        update["japanese_level"] = text[:120]

    if question_id == "experience_gate":
        update["experience_state"] = detect_experience_state(text, memory.get("experience_state", "unknown"))

    age = extract_age(text)
    if age and not memory.get("age"):
        update["age"] = age

    return update


def detect_experience_state(text: str, current: str) -> str:
    yes_markers = ["ใ‚ใ‚Šใพใ™", "ใ—ใพใ—ใŸ", "็ตŒ้จ“ใŒใ‚ใ‚Šใพใ™", "ๅƒใ„ใŸใ“ใจใŒใ‚ใ‚Šใพใ™"]
    no_markers = ["ใ‚ใ‚Šใพใ›ใ‚“", "ใชใ„ใงใ™", "็ตŒ้จ“ใŒใ‚ใ‚Šใพใ›ใ‚“", "ใ—ใŸใ“ใจใŒใ‚ใ‚Šใพใ›ใ‚“"]
    if any(m in text for m in yes_markers):
        return "yes"
    if any(m in text for m in no_markers):
        return "no"
    return current if current in {"yes", "no"} else "unknown"


def select_next_question(role_cfg: Dict[str, Any], memory: Dict[str, Any]) -> Dict[str, Any]:
    asked_ids = set(memory.get("asked_question_ids", []))
    experience_state = memory.get("experience_state", "unknown")
    answers = memory.get("answers_so_far", [])
    avg = mean([a.get("answer_score", 0) for a in answers]) if answers else 0

    # fixed screening order
    for qid in ["country", "reason", "japanese", "ready_check", "experience_gate"]:
        q = get_question(role_cfg, qid)
        if q["id"] not in asked_ids:
            return q

    # branch by experience
    branch_order = []
    if experience_state == "yes":
        branch_order = ["exp_yes_detail", "exp_years"]
    elif experience_state == "no":
        branch_order = ["exp_no_motivation"]

    for qid in branch_order:
        q = get_question(role_cfg, qid)
        if q["id"] not in asked_ids:
            return q

    # weaker user gets simpler role questions first
    if avg < 4.5:
        simple_ids = ["physical", "busy", "kindness", "cleanliness", "outside_work", "time", "customer", "safety", "teamwork"]
        for qid in simple_ids:
            try:
                q = get_question(role_cfg, qid)
                if q["id"] not in asked_ids:
                    return q
            except Exception:
                pass

    # normal role/followup path
    for q in role_cfg["questions"]:
        if q["id"] in asked_ids:
            continue
        if q["stage"] == "closing":
            continue
        if q["branch"] == "yes_exp" and experience_state != "yes":
            continue
        if q["branch"] == "no_exp" and experience_state != "no":
            continue
        return q

    return get_question(role_cfg, "closing")


def score_answer(role_cfg: Dict[str, Any], question_id: str, transcript: str) -> int:
    text = normalize_text(transcript)
    if not text:
        return 0
    score = 3
    if len(text) >= 4:
        score += 1
    if len(text) >= 10:
        score += 1
    if len(text) >= 20:
        score += 1
    if "ใงใ™" in text or "ใพใ™" in text:
        score += 1
    role_hits = sum(1 for kw in role_cfg["expected_keywords"] if kw in text)
    score += min(2, role_hits)
    if question_id == "name" and extract_name(text):
        score += 1
    if question_id == "country" and extract_country(text):
        score += 1
    if question_id == "experience_gate" and detect_experience_state(text, "unknown") != "unknown":
        score += 1
    return max(0, min(score, 10))


def build_feedback(score: int) -> str:
    if score >= 8:
        return "ใจใฆใ‚‚่‰ฏใ„ใงใ™ใ€‚่‡ช็„ถใซ็ญ”ใˆใ‚‰ใ‚Œใฆใ„ใพใ™ใ€‚"
    if score >= 6:
        return "่‰ฏใ„ใงใ™ใ€‚ใ‚‚ใ†ๅฐ‘ใ—้•ทใใ€ใฆใ„ใญใ„ใซ่ฉฑใ™ใจใ‚‚ใฃใจ่‰ฏใใชใ‚Šใพใ™ใ€‚"
    if score >= 4:
        return "ๆ„ๅ‘ณใฏไผใ‚ใ‚Šใพใ™ใŒใ€็Ÿญใ„ใงใ™ใ€‚ๅฎŒๅ…จใชๆ–‡ใง็ญ”ใˆใฆใฟใพใ—ใ‚‡ใ†ใ€‚"
    return "็Ÿญใ™ใŽใ‚‹ใ‹ใ€ๅ†…ๅฎนใŒๅˆ†ใ‹ใ‚Šใซใใ„ใงใ™ใ€‚ใ‚‚ใ†ๅฐ‘ใ—่ฉณใ—ใ่ฉฑใ—ใฆใใ ใ•ใ„ใ€‚"


def decide_finish(role_cfg: Dict[str, Any], memory: Dict[str, Any], question_no: int, score: int) -> bool:
    answers = memory.get("answers_so_far", [])
    avg = mean([a.get("answer_score", 0) for a in answers]) if answers else 0
    min_q = int(memory.get("min_questions", role_cfg["min_questions"]))
    max_q = int(memory.get("max_questions", role_cfg["max_questions"]))

    if question_no >= max_q:
        return True
    if question_no >= min_q and memory.get("low_score_streak", 0) >= 2:
        return True
    if question_no >= min_q and len(answers) >= 3 and avg < 3.5:
        return True
    if question_no >= 10 and avg >= 6:
        # good candidate can continue; otherwise finish around middle
        return False
    if question_no >= 8 and avg < 5.5:
        return True
    return False


def build_final_result(role_cfg: Dict[str, Any], memory: Dict[str, Any], force_fail: bool = False, summary_jp: str = "") -> Dict[str, Any]:
    answers = list(memory.get("answers_so_far", []))
    scores = [int(a.get("answer_score", 0)) for a in answers] or [0]
    avg = mean(scores)
    overall_score = max(0, min(100, int(round(avg * 10))))
    if force_fail:
        overall_score = min(overall_score, 39)
    pass_fail = "PASS" if overall_score >= 60 and not force_fail else "FAIL"

    strengths: List[str] = []
    weaknesses: List[str] = []
    tips: List[str] = []

    if memory.get("candidate_name"):
        strengths.append("Self introduction was understood.")
    else:
        weaknesses.append("Name was not clearly understood.")

    if memory.get("experience_state") == "yes":
        strengths.append("Role experience was communicated.")
    elif memory.get("experience_state") == "no":
        weaknesses.append("No direct role experience was explained clearly.")

    if overall_score >= 70:
        strengths.append("Answers were mostly clear and relevant.")
    else:
        weaknesses.append("Several answers were too short or unclear.")

    tips.extend([
        "Use one or two extra sentences in each answer.",
        "Use polite endings like ใงใ™ and ใพใ™.",
        "Speak a little louder and more clearly.",
    ])

    closing = get_question(role_cfg, "closing")["jp"]
    return {
        "candidate_name": memory.get("candidate_name"),
        "country_name": memory.get("country_name"),
        "age": memory.get("age"),
        "job_role": memory.get("job_role"),
        "job_role_en": role_cfg["english_name"],
        "job_role_jp": role_cfg["japanese_name"],
        "summary_jp": summary_jp or f"{role_cfg['japanese_name']}ใฎ้ขๆŽฅ็ทด็ฟ’ใŒๅฎŒไบ†ใ—ใพใ—ใŸใ€‚",
        "closing_message_jp": closing,
        "total_questions": len(answers),
        "overall_score": overall_score,
        "scores": {
            "fluency": clamp_int(round(avg), 1, 10),
            "grammar": clamp_int(round(avg - 1), 1, 10),
            "confidence": clamp_int(round(avg), 1, 10),
            "relevance": clamp_int(round(avg + 1), 1, 10),
            "role_fit": clamp_int(round(avg), 1, 10),
        },
        "pass_fail": pass_fail,
        "strengths": strengths[:4],
        "weaknesses": weaknesses[:4],
        "tips": tips[:5],
        "answers": answers,
    }


def merge_memory(memory: Dict[str, Any], update: Dict[str, Any]) -> Dict[str, Any]:
    merged = dict(memory or {})
    for k, v in (update or {}).items():
        if v not in (None, "", [], {}):
            merged[k] = v
    return merged


def normalize_text(text: str) -> str:
    return re.sub(r"\s+", " ", (text or "")).strip()


def safe_json_loads(value: str) -> Dict[str, Any]:
    try:
        obj = json.loads(value or "{}")
        return obj if isinstance(obj, dict) else {}
    except Exception:
        return {}


def extract_name(text: str) -> Optional[str]:
    value = text.replace("็งใฏ", "").replace("ใ‚ใŸใ—ใฏ", "").replace("ใผใใฏ", "")
    value = value.replace("ใงใ™", "").replace("ใจ็”ณใ—ใพใ™", "").replace("ใจใ„ใ„ใพใ™", "").strip(" ใ€‚")
    if not value or len(value) > 30:
        return None
    return value


def extract_country(text: str) -> Optional[str]:
    known = ["ใƒใƒ‘ใƒผใƒซ", "ๆ—ฅๆœฌ", "ใ‚คใƒณใƒ‰", "ใƒใƒณใ‚ฐใƒฉใƒ‡ใ‚ทใƒฅ", "ใ‚นใƒชใƒฉใƒณใ‚ซ", "ใƒ™ใƒˆใƒŠใƒ ", "ไธญๅ›ฝ", "ใƒŸใƒฃใƒณใƒžใƒผ", "ใƒ•ใ‚ฃใƒชใƒ”ใƒณ", "ใ‚คใƒณใƒ‰ใƒใ‚ทใ‚ข"]
    for k in known:
        if k in text:
            return k
    m = re.search(r"(.+?)ใ‹ใ‚‰ๆฅใพใ—ใŸ", text)
    if m:
        return m.group(1).strip(" ใ€‚")
    return None


def extract_age(text: str) -> Optional[int]:
    m = re.search(r"(\d{1,2})", text)
    return int(m.group(1)) if m else None


def clamp_int(value: Any, low: int, high: int) -> int:
    try:
        return max(low, min(high, int(round(float(value)))))
    except Exception:
        return low