File size: 3,005 Bytes
85d8ab6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import requests
import os
import gradio as gr

def fetch_exchange_rates():
    """
    Fetches the latest exchange rates from the ExchangeRate API.
    """
    API_KEY = os.getenv('EXCHANGE_RATE_API_KEY')  # Get API key from environment variable
    if not API_KEY:
        return None, "❌ API key is missing. Please set it in the environment variable 'EXCHANGE_RATE_API_KEY'."
    url = f"https://v6.exchangerate-api.com/v6/{API_KEY}/latest/USD"
    try:
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception for HTTP errors
        data = response.json()
    except requests.RequestException as e:
        return None, f"❌ Error fetching data from API: {e}"

    if data.get('result') != 'success':
        return None, "❌ Failed to fetch exchange rates. Check your API key or account limits."

    return data.get('conversion_rates'), None


def convert_currency(amount, input_currency, output_currency):
    """
    Converts the given amount from one currency to another using exchange rates.
    """
    exchange_rates, error = fetch_exchange_rates()

    if error:
        return error

    if input_currency not in exchange_rates or output_currency not in exchange_rates:
        return "❌ Invalid currency. Please ensure the currency codes are valid."

    # Perform the conversion
    input_rate = exchange_rates[input_currency]
    output_rate = exchange_rates[output_currency]
    converted_amount = amount * (output_rate / input_rate)
    rounded_amount = round(converted_amount, 2)

    return f"{amount} {input_currency} is equal to {rounded_amount} {output_currency}."


# Gradio Interface
def interface(amount, input_currency, output_currency):
    try:
        amount = float(amount)
        if amount <= 0:
            return "❌ Amount must be greater than 0."
    except ValueError:
        return "❌ Invalid input. Please enter a valid number."

    return convert_currency(amount, input_currency.upper(), output_currency.upper())


# Create Gradio app
with gr.Blocks() as app:
    gr.Markdown("## 🌍 Currency Converter using Live API")
    gr.Markdown(
        "Convert currencies using live exchange rates. Enter the amount, "
        "source currency (e.g., USD), and target currency (e.g., PKR)."
    )

    with gr.Row():
        amount_input = gr.Textbox(label="Amount", placeholder="Enter amount (e.g., 100)")
        input_currency_input = gr.Textbox(label="From Currency", placeholder="Enter source currency code (e.g., USD)")
        output_currency_input = gr.Textbox(label="To Currency", placeholder="Enter target currency code (e.g., PKR)")

    convert_button = gr.Button("Convert")
    result_output = gr.Textbox(label="Result", placeholder="Result will appear here", interactive=False)

    convert_button.click(
        interface,
        inputs=[amount_input, input_currency_input, output_currency_input],
        outputs=result_output,
    )

# Launch the Gradio app
if __name__ == "__main__":
    app.launch()