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(""" """, 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" )