92 lines
3.9 KiB
Python
92 lines
3.9 KiB
Python
import os
|
|
import json
|
|
from groq import Groq
|
|
|
|
# 1. API 키 설정 (직접 문자열로 넣거나 환경변수 사용)
|
|
# 발급받은 키를 "gsk_..." 부분에 넣으세요.
|
|
client = Groq(
|
|
api_key="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"
|
|
)
|
|
|
|
# 2. 테스트할 OCR 결과 데이터 (샘플)
|
|
SAMPLE_1 = [
|
|
{'text': '高密【拉毛布】', 'confidence': 0.8697245717048645},
|
|
{'text': '柔中带韧不易坏', 'confidence': 0.9874316453933716},
|
|
{'text': '安静无声助力深度睡眠', 'confidence': 0.9960897564888},
|
|
{'text': 'newpet家的', 'confidence': 0.9988763928413391},
|
|
{'text': '别人家的', 'confidence': 0.9997605085372925},
|
|
{'text': '密织拉毛布保暖还结实', 'confidence': 0.9967950582504272},
|
|
{'text': '劣质无纺布一拉就烂一洗就散', 'confidence': 0.9917935729026794},
|
|
]
|
|
|
|
# OCR 결과를 번역용 items 형태로 변환
|
|
items = []
|
|
for i, ocr_item in enumerate(SAMPLE_1, 1):
|
|
text = (ocr_item.get("text") or "").strip()
|
|
if text:
|
|
items.append({"id": i, "source": text})
|
|
|
|
items_json = json.dumps(items, ensure_ascii=False, indent=2)
|
|
|
|
print(f"--- [모델: llama-3.1-8b-instant] 테스트 시작 ---")
|
|
print(f"입력 항목 수: {len(items)}")
|
|
|
|
try:
|
|
completion = client.chat.completions.create(
|
|
# 스크린샷에 있던 그 모델입니다. (속도 매우 빠름)
|
|
model="llama-3.1-8b-instant",
|
|
messages=[
|
|
{
|
|
"role": "system",
|
|
"content": (
|
|
"당신은 중국어-한국어 전문 온라인 쇼핑마케팅 번역가입니다.\n\n"
|
|
"아래 JSON 배열의 각 항목에서 \"source\" 필드의 중국어 텍스트를 한국어로 번역해주세요.\n\n"
|
|
"번역 규칙:\n"
|
|
"1. 정확하고 자연스러운 한국어로 번역\n"
|
|
"2. 상품 문맥에 맞게 번역\n"
|
|
"3. 브랜드명, 고유명사는 그대로 유지\n"
|
|
"4. 숫자와 단위는 유지\n\n"
|
|
"반드시 입력된 순서와 개수를 지켜서 JSON 배열만 출력하세요. 다른 설명 없이 JSON 배열만 출력합니다."
|
|
)
|
|
},
|
|
{
|
|
"role": "user",
|
|
"content": f"입력:\n{items_json}\n\n출력 형식 (JSON 배열만 출력, 다른 텍스트 없이):\n[\n{{\"id\": 1, \"translation\": \"번역된 텍스트\"}},\n{{\"id\": 2, \"translation\": \"번역된 텍스트\"}}\n]"
|
|
}
|
|
],
|
|
temperature=0.5, # 창의성 조절
|
|
max_tokens=2048, # 출력 길이 제한 증가
|
|
)
|
|
|
|
# 결과 출력
|
|
response_content = completion.choices[0].message.content
|
|
print("\n--- 번역 결과 ---")
|
|
print(response_content)
|
|
|
|
# JSON 파싱 시도
|
|
try:
|
|
# JSON 코드 블록 제거 (```json ... ``` 형태)
|
|
if "```" in response_content:
|
|
lines = response_content.split("\n")
|
|
json_lines = []
|
|
in_json_block = False
|
|
for line in lines:
|
|
if line.strip().startswith("```"):
|
|
in_json_block = not in_json_block
|
|
continue
|
|
if in_json_block or (not in_json_block and line.strip()):
|
|
json_lines.append(line)
|
|
response_content = "\n".join(json_lines)
|
|
|
|
translated_items = json.loads(response_content.strip())
|
|
print(f"\n--- 파싱된 결과 ({len(translated_items)}개) ---")
|
|
for item in translated_items:
|
|
item_id = item.get("id", "N/A")
|
|
translation = item.get("translation", item.get("result", item.get("translated", "")))
|
|
print(f"ID {item_id}: {translation}")
|
|
except json.JSONDecodeError as e:
|
|
print(f"\nJSON 파싱 실패: {e}")
|
|
print("원본 응답을 확인하세요.")
|
|
|
|
except Exception as e:
|
|
print(f"에러 발생: {e}") |