File size: 6,034 Bytes
442f51a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import streamlit as st
import os
import time
from google import genai
from google.genai.errors import APIError

# Using the requested model ID for the most advanced Flash preview model
MODEL_NAME = "gemini-2.5-flash-preview-09-2025"
MAX_RETRIES = 3

# Define supported languages for the dropdown
LANGUAGES = {
    "Spanish": "es",
    "French": "fr",
    "German": "de",
    "Japanese": "ja",
    "Chinese (Mandarin)": "zh",
    "Korean": "ko",
    "Portuguese": "pt",
    "Italian": "it",
    "Russian": "ru",
    "Hindi": "hi"
}

def get_gemini_client():
    """Initializes the Gemini client, retrieving API key from environment variables (for deployment)."""
    try:
        # Tries to get the key from environment variables (standard for Hugging Face/Streamlit Cloud)
        api_key = os.environ.get("GEMINI_API_KEY")
        if not api_key:
            # If not found in env, check Streamlit secrets (for Streamlit Cloud standard)
            api_key = st.secrets.get("GEMINI_API_KEY")
            
        if not api_key:
            st.error("GEMINI_API_KEY not found. Please set it as an environment variable or in `st.secrets`.")
            return None
            
        return genai.Client(api_key=api_key)
    except Exception as e:
        st.error(f"Error during client initialization: {e}")
        return None

@st.cache_data(show_spinner=False)
def translate_text(text: str, target_language_name: str) -> str:
    """
    Translates text using the Gemini API with exponential backoff.
    
    Args:
        text: The source text to translate.
        target_language_name: The target language name (e.g., "Spanish").
        
    Returns:
        The translated text or an error message.
    """
    client = get_gemini_client()
    if not client:
        return "Error: API key not configured."

    # Use a system instruction to make the model act as a professional translator
    system_instruction = (
        "You are a professional and highly accurate translation engine. "
        "Your task is to translate the user's provided text into the specified target language."
        "Only output the translated text, nothing else. Do not add any commentary, notes, or explanation."
    )

    prompt = f"Translate the following source text to {target_language_name}: \n\n{text}"

    for attempt in range(MAX_RETRIES):
        try:
            response = client.models.generate_content(
                model=MODEL_NAME,
                contents=prompt,
                config=dict(
                    system_instruction=system_instruction,
                    temperature=0.1,  # Low temperature for deterministic translation
                )
            )
            return response.text.strip()

        except APIError as e:
            if attempt < MAX_RETRIES - 1:
                wait_time = 2 ** attempt
                print(f"API Error on attempt {attempt + 1}: {e}. Retrying in {wait_time} seconds...")
                time.sleep(wait_time)
            else:
                st.exception(e)
                return "Translation failed after multiple retries due to a persistent API error."
        except Exception as e:
            st.exception(e)
            return "An unexpected error occurred during translation."

# --- Streamlit UI Configuration ---

st.set_page_config(
    page_title="Gemini AI Translator",
    layout="centered",
    initial_sidebar_state="expanded"
)

# Custom CSS for aesthetics (using a single file mandate)
st.markdown("""
    <style>
        .stButton>button {
            background-color: #4CAF50;
            color: white;
            font-weight: bold;
            border-radius: 12px;
            padding: 10px 24px;
            border: none;
            transition: 0.3s;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            width: 100%;
        }
        .stButton>button:hover {
            background-color: #45a049;
            box-shadow: 0 6px 10px rgba(0,0,0,0.2);
        }
        .stTextInput, .stTextArea, .stSelectbox, .main .block-container {
            border-radius: 12px;
        }
        .block-container {
            padding-top: 2rem;
            padding-bottom: 2rem;
        }
    </style>
""", unsafe_allow_html=True)

st.title("🗣️ Gemini Flash AI Translator")
st.markdown(f"**Model:** `{MODEL_NAME}` | **Latency:** Optimized for speed and quality.")

# Sidebar for instructions and setup information
with st.sidebar:
    st.header("App Deployment Info")
    st.info(f"""
        To deploy this app on Hugging Face Spaces or Streamlit Cloud, you MUST set your 
        **Google Gemini API Key** as a secret environment variable named `GEMINI_API_KEY`.
    """)
    st.markdown("---")
    st.header("How to Use")
    st.write("1. Enter your source text.")
    st.write("2. Select the target language.")
    st.write("3. Click 'Translate Text' to get the output.")


# Input and selection layout
col1, col2 = st.columns([3, 1])

with col1:
    source_text = st.text_area(
        "Source Text",
        placeholder="Enter text to be translated (e.g., 'Bonjour le monde, comment allez-vous?')",
        height=200
    )

with col2:
    # Use a dummy variable for target language code, but show the name in the UI
    target_language_name = st.selectbox(
        "Target Language",
        options=list(LANGUAGES.keys()),
        index=0 # Default to Spanish
    )

# Translation button
translate_button = st.button("✨ Translate Text")

# Translation logic
if translate_button:
    if not source_text:
        st.warning("Please enter some text to translate.")
    else:
        with st.spinner(f"Translating to {target_language_name}..."):
            # Call the translation function
            translated_text = translate_text(source_text, target_language_name)
        
        # Output section
        st.subheader(f"Result in {target_language_name}")
        st.text_area(
            label="Translated Text",
            value=translated_text,
            height=200,
            key="translated_output"
        )