File size: 2,554 Bytes
3a32888
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import gradio as gr
from huggingface_hub import hf_hub_download
from llama_cpp import Llama
import spaces  # <--- ĐIỀU KIỆN 1: Import thư viện này
import os

# 1. Cấu hình Model
REPO_ID = "mradermacher/Floppa-12B-Gemma3-Uncensored-i1-GGUF"
FILENAME = "Floppa-12B-Gemma3-Uncensored.i1-IQ1_S.gguf" # Nhớ thay tên file đúng

# 2. Tải model về (Bước này chỉ tải file, không tốn GPU nên để ngoài OK)
print(f"Đang tải {FILENAME}...")
try:
    model_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME)
except Exception as e:
    # Fallback nếu tên file sai, bạn nên check lại trên HF
    print(f"Lỗi tải file: {e}")
    model_path = ""

# Biến toàn cục để lưu model
llm = None

# Hàm load model an toàn
def load_model_if_needed():
    global llm
    if llm is None:
        print("Đang load model vào GPU...")
        # n_gpu_layers=-1 để đẩy hết vào GPU
        llm = Llama(
            model_path=model_path,
            n_gpu_layers=-1, 
            n_ctx=4096,
            verbose=False
        )
    return llm

# 3. Hàm xử lý dịch thuật (CÓ GPU)
@spaces.GPU  # <--- ĐIỀU KIỆN 2: Decorator bắt buộc để kích hoạt ZeroGPU
def translate_text(text, target_lang, temperature, max_tokens):
    # Load model NGAY TRONG KHI ĐANG CÓ GPU
    # Vì ZeroGPU có thể di chuyển session, nên đảm bảo model nằm đúng chỗ
    current_llm = load_model_if_needed()
    
    prompt = f"""<start_of_turn>user
Translate the following text into {target_lang} accurately without explanation.

Text:
{text}<end_of_turn>
<start_of_turn>model
Translation:"""

    output = current_llm(
        prompt,
        max_tokens=max_tokens,
        temperature=temperature,
        stop=["<end_of_turn>", "Text:"], 
        echo=False
    )
    
    return output['choices'][0]['text'].strip()

# 4. Giao diện Gradio (Giữ nguyên)
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown(f"# 🤖 Floppa Translator (ZeroGPU Enabled)")
    
    with gr.Row():
        with gr.Column():
            input_text = gr.Textbox(label="Văn bản nguồn", lines=5)
            target_lang = gr.Dropdown(["Vietnamese", "English", "Japanese"], value="Vietnamese", label="Dịch sang")
            btn = gr.Button("Dịch", variant="primary")
        with gr.Column():
            output_text = gr.Textbox(label="Kết quả", lines=5)

    btn.click(translate_text, inputs=[input_text, target_lang], outputs=output_text)

if __name__ == "__main__":
    demo.launch()