Spaces:
Configuration error

File size: 1,352 Bytes
5565e67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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()