Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
3 |
+
from peft import PeftModel
|
4 |
+
import torch
|
5 |
+
|
6 |
+
# Login to Hugging Face Hub
|
7 |
+
access_token = os.environ.get("HUGGING_FACE_HUB_TOKEN")
|
8 |
+
login(token=access_token)
|
9 |
+
|
10 |
+
|
11 |
+
# Load model and tokenizer from the Hugging Face Hub
|
12 |
+
model_name = "kuyesu22/sunbird-ug-lang-v1.0"
|
13 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
|
14 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto")
|
15 |
+
model = PeftModel.from_pretrained(model, model_name)
|
16 |
+
|
17 |
+
# Ensure the model is in evaluation mode
|
18 |
+
model.eval()
|
19 |
+
|
20 |
+
# Define the translation function
|
21 |
+
def translate(text, source_lang="Runyankole", target_lang="English"):
|
22 |
+
prompt = f"Translate from {source_lang} to {target_lang}: {text}"
|
23 |
+
inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
|
24 |
+
|
25 |
+
with torch.no_grad():
|
26 |
+
outputs = model.generate(
|
27 |
+
inputs["input_ids"],
|
28 |
+
max_length=100,
|
29 |
+
num_beams=5,
|
30 |
+
early_stopping=True
|
31 |
+
)
|
32 |
+
|
33 |
+
translation = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
34 |
+
return translation
|
35 |
+
|
36 |
+
# Set up the Gradio interface
|
37 |
+
def runyankole_to_english(text):
|
38 |
+
return translate(text, source_lang="Runyankole", target_lang="English")
|
39 |
+
|
40 |
+
def english_to_runyankole(text):
|
41 |
+
return translate(text, source_lang="English", target_lang="Runyankole")
|
42 |
+
|
43 |
+
# Create Gradio inputs and interface
|
44 |
+
with gr.Blocks() as demo:
|
45 |
+
gr.Markdown("# Runyankole-English Translation Model")
|
46 |
+
|
47 |
+
with gr.Tab("Runyankole to English"):
|
48 |
+
runyankole_input = gr.Textbox(label="Enter Runyankole Text")
|
49 |
+
english_output = gr.Textbox(label="English Translation")
|
50 |
+
gr.Button("Translate").click(runyankole_to_english, inputs=runyankole_input, outputs=english_output)
|
51 |
+
|
52 |
+
with gr.Tab("English to Runyankole"):
|
53 |
+
english_input = gr.components.Textbox(label="Enter English Text")
|
54 |
+
runyankole_output = gr.components.Textbox(label="Runyankole Translation")
|
55 |
+
gr.Button("Translate").click(english_to_runyankole, inputs=english_input, outputs=runyankole_output)
|
56 |
+
|
57 |
+
# Launch the app
|
58 |
+
demo.launch()
|