Translator / app.py
sreejang's picture
Update app.py
ac67af9 verified
import os
import gradio as gr
from groq import Groq
# Get API key from environment (will be set in Hugging Face Space secrets)
api_key = os.environ.get("GROQ_API_KEY")
if not api_key:
raise ValueError("GROQ_API environment variable not set. Please add it to Space Secrets.")
client = Groq(api_key=api_key)
def translate_english_to_nepali(text):
if not text or not text.strip():
return "Please enter some English text to translate."
try:
response = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[
{
"role": "system",
"content": "You are a professional translator. Translate the given English text to Nepali (नेपाली) accurately. Provide only the translation without explanations, transliterations, or additional text."
},
{
"role": "user",
"content": text
}
],
temperature=0.1, # Lower temperature for more consistent translations
max_tokens=1024
)
translation = response.choices[0].message.content.strip()
return translation
except Exception as e:
return f"Error: {str(e)}"
# Custom CSS for better appearance
css = """
.container {max-width: 800px; margin: 0 auto;}
.input-text {font-size: 16px;}
.output-text {font-size: 18px; font-weight: 500;}
"""
with gr.Blocks(css=css, title="English to Nepali Translator") as demo:
gr.Markdown(
"""
# 🇬🇧 ➡️ 🇳🇵 English to Nepali Translator
Made for Kucchi Mucchi | High-speed AI Translation
"""
)
with gr.Row():
with gr.Column():
input_text = gr.Textbox(
label="English Text",
placeholder="Enter English text here...",
lines=6,
elem_classes="input-text"
)
translate_btn = gr.Button("🔄 Translate", variant="primary", size="lg")
clear_btn = gr.Button("Clear", size="sm")
with gr.Column():
output_text = gr.Textbox(
label="Nepali Translation (नेपाली अनुवाद)",
lines=6,
elem_classes="output-text",
interactive=False
)
gr.Markdown(
"""
### Tips:
- Enter natural English sentences for best results
- The model handles formal and informal Nepali contexts
- Supports long paragraphs (up to 1024 tokens)
"""
)
# Event handlers
translate_btn.click(
fn=translate_english_to_nepali,
inputs=input_text,
outputs=output_text
)
clear_btn.click(
fn=lambda: ("", ""),
inputs=None,
outputs=[input_text, output_text]
)
# Allow Enter key to submit
input_text.submit(
fn=translate_english_to_nepali,
inputs=input_text,
outputs=output_text
)
# Launch configuration
if __name__ == "__main__":
demo.launch()