Spaces:
Configuration error

Pink-Elsa22's picture
Create app.py
5d542ee verified
Raw History Blame Contribute Delete
1.35 kB
import gradio as gr
import openai
import os
# 读取 HuggingFace Secrets(你必须在 Settings → Variables 设置 OPENAI_API_KEY)
openai.api_key = os.getenv("OPENAI_API_KEY")
def translate_file(file):
if file is None:
return "请上传文件。"
try:
with open(file.name, "r", encoding="utf-8") as f:
content = f.read()
except:
return "文件读取失败,请确保是 UTF-8 文本文件(.txt 或 .md)。"
try:
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "你是专业中英翻译助手。"},
{"role": "user", "content": f"请将以下内容翻译为英文:\n\n{content}"}
]
)
translation = response.choices[0].message["content"]
return translation
except Exception as e:
return f"翻译失败:{str(e)}"
title = "文件上传翻译器"
description = "上传一个 .txt 或 .md 文件,我将为你翻译内容。(依赖 OPENAI_API_KEY)"
interface = gr.Interface(
fn=translate_file,
inputs=gr.File(label="上传文件(UTF-8 文本)"),
outputs=gr.Textbox(label="翻译结果", lines=20),
title=title,
description=description,
)
if __name__ == "__main__":
interface.launch()