Spaces:
Sleeping
Sleeping
| import os | |
| from dotenv import load_dotenv | |
| import gradio as gr | |
| from agents import Agent, Runner, AsyncOpenAI, OpenAIChatCompletionsModel | |
| from agents.run import RunConfig | |
| import asyncio | |
| # Load environment variables from .env file | |
| load_dotenv() | |
| # Retrieve the Gemini API key from environment variables | |
| gemini_api_key = os.getenv("GEMINI_API_KEY") | |
| # Check if the API key is present; if not, raise an error | |
| if not gemini_api_key: | |
| raise ValueError("GEMINI_API_KEY is not set. Please ensure it is defined in your .env file.") | |
| # Configure the AsyncOpenAI client for Gemini API | |
| external_client = AsyncOpenAI( | |
| api_key=gemini_api_key, | |
| base_url="https://generativelanguage.googleapis.com/v1beta/openai/", | |
| ) | |
| # Define the model | |
| model = OpenAIChatCompletionsModel( | |
| model="gemini-2.0-flash", | |
| openai_client=external_client | |
| ) | |
| # Configure the run settings | |
| config = RunConfig( | |
| model=model, | |
| model_provider=external_client, | |
| tracing_disabled=True | |
| ) | |
| # Define the translation function | |
| async def translate_urdu_to_english(urdu_text): | |
| agent = Agent( | |
| name="Translator", | |
| instructions="You are a Translator, always translate Urdu sentences into English Language.", | |
| model=model | |
| ) | |
| result = await Runner.run(agent, urdu_text, run_config=config) | |
| return result.final_output | |
| # Gradio interface function | |
| def gradio_translate(urdu_input): | |
| # Run the async translation function within Gradio | |
| return asyncio.run(translate_urdu_to_english(urdu_input)) | |
| # Create Gradio interface | |
| iface = gr.Interface( | |
| fn=gradio_translate, | |
| inputs=gr.Textbox(label="Urdu Input", placeholder="Enter Urdu sentence here..."), | |
| outputs=gr.Textbox(label="English Translation"), | |
| title="Urdu to English Translator", | |
| description="Enter an Urdu sentence to get its English translation using the Gemini API." | |
| ) | |
| # Launch the Gradio app | |
| if __name__ == "__main__": | |
| iface.launch() |