Spaces:
Sleeping
Sleeping
import gradio as gr | |
from freecurrencyapi import Client | |
# Initialize the FreeCurrencyAPI client | |
api_key = 'fca_live_TYFdDMZC9xmEEZPpTJCUdcJQIbdGwis1CHmmYF1d' # Replace with your actual API key | |
client = Client(api_key) | |
# Function to get current exchange rates | |
def convert_currency(amount, from_currency, to_currency, historical=False, date=None): | |
try: | |
if historical and date: | |
# Fetch historical data if needed | |
result = client.historical(date=date) | |
print(f"Historical data for {date}: {result}") # Debugging line to print the response | |
rates = result.get('data', {}).get(date, {}) | |
else: | |
# Get the latest rates | |
result = client.currencies(currencies=[from_currency, to_currency]) | |
print(f"Latest rates: {result}") # Debugging line to print the response | |
rates = result.get('data', {}).get('rates', {}) | |
# Check if rates for the given currencies are available | |
if from_currency in rates and to_currency in rates: | |
conversion_rate = rates[to_currency] / rates[from_currency] | |
converted_amount = float(amount) * conversion_rate | |
return f"{amount} {from_currency} = {converted_amount:.2f} {to_currency}" | |
else: | |
return f"Error: Data not available for {from_currency} or {to_currency}." | |
except Exception as e: | |
return f"Error: {str(e)}" | |
# Define the Gradio interface | |
def create_interface(): | |
with gr.Blocks() as interface: | |
with gr.Row(): | |
gr.Markdown("<h1 style='text-align: center;'>Currency Converter</h1>") | |
with gr.Row(): | |
amount = gr.Textbox(label="Amount", value="1", placeholder="Enter amount", elem_id="amount_input") | |
with gr.Row(): | |
from_currency = gr.Dropdown( | |
choices=["USD", "EUR", "GBP", "INR", "JPY", "CAD", "AUD", "CNY", "BRL", "ZAR"], | |
label="From Currency", value="USD", elem_id="from_currency_input" | |
) | |
to_currency = gr.Dropdown( | |
choices=["USD", "EUR", "GBP", "INR", "JPY", "CAD", "AUD", "CNY", "BRL", "ZAR"], | |
label="To Currency", value="EUR", elem_id="to_currency_input" | |
) | |
with gr.Row(): | |
historical_checkbox = gr.Checkbox(label="Get Historical Data", value=False) | |
historical_date = gr.Textbox(label="Select Date (YYYY-MM-DD)", visible=False) # Use Textbox for date | |
with gr.Row(): | |
convert_button = gr.Button("Convert") | |
with gr.Row(): | |
output = gr.Textbox(label="Converted Amount", interactive=False) | |
# Update the visibility of the date picker based on historical checkbox | |
historical_checkbox.change( | |
lambda checked: historical_date.update(visible=checked), inputs=[historical_checkbox], outputs=[historical_date] | |
) | |
# Function to trigger conversion with historical data if required | |
convert_button.click( | |
fn=convert_currency, | |
inputs=[amount, from_currency, to_currency, historical_checkbox, historical_date], | |
outputs=output | |
) | |
return interface | |
# Launch the interface | |
interface = create_interface() | |
interface.launch(share=True) | |