Spaces:
Sleeping
Sleeping
File size: 1,916 Bytes
2d6d0bb 8e403db 2d6d0bb |
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 |
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() |