# 只输出译文
import requests
import json
import re
# 定义 API 端点 URL
url = "http://localhost:11434/api/generate"
# 定义请求数据
data = {
"model": "gemma2:latest", # 使用 gemma2 模型
"prompt": "请翻译为中文:Antony Blinken Dragged US Diplomacy Into the 21st Century. Even He’s Surprised by the Results",
"format": "json", # 确保 API 支持这种格式
"stream": False
}
# 发送 POST 请求
response = requests.post(url, json=data)
# 检查响应状态码
if response.status_code == 200:
try:
# 尝试解析响应 JSON
result = response.json()
# 提取 'response' 键的内容
if 'response' in result and result['response']:
# 清理响应内容中的多余字符
cleaned_response = result['response'].strip().replace('\n', ' ').replace('\r', ' ')
try:
# 尝试将响应直接解析为 JSON
chat_response = json.loads(cleaned_response)
# 打印翻译结果
if isinstance(chat_response, dict):
# 如果结果是字典,取出所有的值(假设翻译文本是其中之一)
for value in chat_response.values():
print(value)
else:
# 如果结果不是字典,直接输出
print(chat_response)
except json.JSONDecodeError as e:
# JSON 解析失败时,使用正则表达式提取翻译文本
match = re.search(r'"(.*?)"', cleaned_response)
if match:
print(match.group(1))
else:
print("Failed to extract translation result.")
else:
print("No 'response' key found or it's empty.")
except json.JSONDecodeError as e:
print(f"Error decoding JSON response: {e}")
else:
print("Failed to generate response. Status code:", response.status_code)
print("Response:", response.text)