# -*- coding: utf-8 -*-
# dzw_qa_amplify.py — QA 증폭기 [CEO 지시 2026-07-06]
#   대량생성된 QA(gen_*.qa.json)를 "머리 좋은" 로컬 모델(deepseek-r1:14b)에게 주고
#   ①같은 답으로 통하는 바꿔말하기(현장 말투) ②그 답에서 파생되는 후속 질문을 증폭 생성.
#   답은 원본 그대로(출처 보존) — 질문만 늘린다. 출력: amp_<원본>.qa.json
import os, re, json, urllib.request, glob

OUT   = r'E:\VLA시스템\_QA뱅크'
MODEL = 'deepseek-r1:14b'
PER   = 4   # 문항당 증폭 수

def amplify(q, a):
    prompt = ('용접 공장 작업자들이 아래 [답]을 얻으려고 실제로 던질 법한 질문을 %d개 만들어라. '
              '조건: 원래 질문("%s")과 다른 표현·다른 각도(반말/급한 말투/문제상황 서술 포함), '
              '그러나 반드시 [답]만으로 완전히 답변 가능한 질문일 것. 한 줄에 하나, "Q: "로 시작.\n\n[답] %s'
              ) % (PER, q, a)
    body = json.dumps({'model': MODEL, 'prompt': prompt, 'stream': False,
                       'options': {'temperature': 0.6, 'num_predict': 500}}).encode()
    r = urllib.request.urlopen(urllib.request.Request(
        'http://localhost:11434/api/generate', data=body,
        headers={'Content-Type': 'application/json'}), timeout=600)
    txt = json.loads(r.read()).get('response', '')
    txt = re.sub(r'<think>.*?</think>', '', txt, flags=re.S)   # r1 사고과정 제거
    out = []
    for line in txt.splitlines():
        line = line.strip().lstrip('*-0123456789. ')
        if line.startswith('Q:'):
            nq = line[2:].strip().strip('"')
            if 5 < len(nq) < 120 and nq != q: out.append(nq)
    return out[:PER]

def main():
    total = 0
    for fp in sorted(glob.glob(os.path.join(OUT, 'gen_*.qa.json')) + glob.glob(os.path.join(OUT, '!_전문가질문은행.qa.json'))):
        op = os.path.join(OUT, 'amp_' + os.path.basename(fp)[4:] if os.path.basename(fp).startswith('gen_') else os.path.join(OUT, 'amp_' + os.path.basename(fp)))
        op = os.path.join(OUT, 'amp_' + os.path.basename(fp).replace('gen_', ''))
        if os.path.exists(op): continue
        d = json.load(open(fp, encoding='utf-8'))
        amp = []
        for it in d.get('qa', []):
            try:
                for nq in amplify(it['q'], it['a']):
                    amp.append({'q': nq, 'a': it['a']})
            except Exception as e:
                print('  [증폭실패]', str(e)[:80]); continue
        if amp:
            json.dump({'src': d.get('src', ''), 'qa': amp}, open(op, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
            total += len(amp)
            print('[증폭] %s → +%d문항 (누적 %d)' % (os.path.basename(fp), len(amp), total), flush=True)
    print('증폭 완료: +%d문항' % total)

if __name__ == '__main__':
    main()
