import gradio as gr import requests def convert_currency(amount, from_currency, to_currency): try: amount = float(amount) if amount < 0: return "Please enter a positive amount." # Get latest exchange rates url = f"https://api.frankfurter.app/latest?amount={amount}&from={from_currency}&to={to_currency}" response = requests.get(url, timeout=10) if response.status_code != 200: return "Could not get the latest exchange rate." data = response.json() result = data["rates"][to_currency] return f"{amount:,.2f} {from_currency} = {result:,.2f} {to_currency}" except ValueError: return "Please enter a valid number." except Exception as e: return f"Error: {str(e)}" currencies = [ "USD", "EUR", "GBP", "PKR", "INR", "AED", "SAR", "CAD", "AUD", "JPY", "CNY", "CHF", "TRY", "SGD", "NZD" ] with gr.Blocks(title="Currency Converter") as app: gr.Markdown( """ # 💱 Currency Converter Convert currencies using the latest available exchange rates. """ ) amount = gr.Number( label="Amount", value=1, minimum=0 ) with gr.Row(): from_currency = gr.Dropdown( choices=currencies, value="USD", label="From" ) to_currency = gr.Dropdown( choices=currencies, value="PKR", label="To" ) convert_button = gr.Button( "Convert 💱", variant="primary" ) result = gr.Textbox( label="Result", interactive=False ) convert_button.click( fn=convert_currency, inputs=[amount, from_currency, to_currency], outputs=result ) app.launch()