batch_summary.py

파일 다운로드

"""순차 또는 제한 병렬 상담 정리. 공급자 Batch API와 별도다.

파일 행은 완료 순서(case_id로 연결), 반환 목록은 입력 순서다.
완료·실패 행은 매번 flush한다. 자동 재시도·중단 후 재시작은 지원하지 않는다.
중단 시 이미 기록한 행은 남지만 실행 중인 스레드의 종료를 기다릴 수 있다.
flush는 디스크 영구 보장(fsync)이 아니다.
"""
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import json
import time
from summarize import organize
from usage import usage_scope, summarize_events


def run_batch(source, output, workers=1, organizer=organize):
    if type(workers) is not int or not 1 <= workers <= 4:
        raise ValueError('동시 작업은 1~4개입니다.')
    rows = [json.loads(line) for line in Path(source).read_text(encoding='utf-8').splitlines() if line.strip()]
    ids = [row['case_id'] for row in rows]
    if any(not isinstance(x, str) or not x.strip() for x in ids) or len(ids) != len(set(ids)):
        raise ValueError('case_id는 비어 있지 않은 고유 문자열입니다.')
    def one(row):
        start = time.perf_counter()
        with usage_scope('consultation_batch') as scope:
            record = {'case_id': row['case_id']}
            try:
                record.update(status='OK', result=organizer(row['conversation']))
            except Exception as error:
                record.update(status='ERROR', error_type=type(error).__name__)
            record.update(metrics=summarize_events(scope['events']),
                          request_id=scope['request_id'], elapsed_seconds=round(time.perf_counter()-start, 6))
            return record
    output = Path(output)
    output.parent.mkdir(parents=True, exist_ok=True)
    # 이전 결과는 덮어쓰지 않는다. 실패 행도 남기며 다음 행을 처리한다.
    with output.open('x', encoding='utf-8') as stream:
        records = [None] * len(rows)
        with ThreadPoolExecutor(max_workers=workers) as pool:
            futures = {pool.submit(one, row): index for index, row in enumerate(rows)}
            for future in as_completed(futures):
                record = future.result()
                stream.write(json.dumps(record, ensure_ascii=False) + '\n')
                stream.flush()
                records[futures[future]] = record
    return records


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('source', type=Path)
    parser.add_argument('output', type=Path)
    parser.add_argument('--workers', type=int, default=1)
    args = parser.parse_args()
    print(json.dumps(run_batch(args.source, args.output, args.workers), ensure_ascii=False, indent=2))