Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import requests
|
3 |
+
import os
|
4 |
+
|
5 |
+
# Streamlit Page Configuration
|
6 |
+
st.set_page_config(page_title="Currency Converter", page_icon="💱", layout="centered")
|
7 |
+
|
8 |
+
# Title & Description
|
9 |
+
st.title("💱 Currency Converter")
|
10 |
+
st.write("Convert currencies in real-time using the latest exchange rates.")
|
11 |
+
|
12 |
+
# Get API Key Securely
|
13 |
+
API_KEY = os.getenv("API_KEY") # Fetch from Hugging Face Secrets
|
14 |
+
|
15 |
+
# Base API URL
|
16 |
+
BASE_URL = "https://api.apilayer.com/exchangerates_data/latest"
|
17 |
+
|
18 |
+
# Fetch List of Available Currencies
|
19 |
+
@st.cache_data # Cache to avoid multiple API calls
|
20 |
+
def get_currencies():
|
21 |
+
url = f"{BASE_URL}?apikey={API_KEY}"
|
22 |
+
response = requests.get(url).json()
|
23 |
+
|
24 |
+
if "rates" in response:
|
25 |
+
return sorted(response["rates"].keys()) # Sorted list of currencies
|
26 |
+
else:
|
27 |
+
st.error("⚠️ Unable to fetch currency list. Check API key.")
|
28 |
+
return []
|
29 |
+
|
30 |
+
# Load Currency Options
|
31 |
+
currencies = get_currencies()
|
32 |
+
|
33 |
+
# User Inputs
|
34 |
+
amount = st.number_input("Enter Amount:", min_value=0.01, step=0.01)
|
35 |
+
from_currency = st.selectbox("From Currency", currencies, index=currencies.index("USD"))
|
36 |
+
to_currency = st.selectbox("To Currency", currencies, index=currencies.index("INR"))
|
37 |
+
|
38 |
+
# Conversion Function
|
39 |
+
def convert_currency(amount, from_currency, to_currency):
|
40 |
+
url = f"{BASE_URL}?base={from_currency}&apikey={API_KEY}"
|
41 |
+
response = requests.get(url).json()
|
42 |
+
|
43 |
+
if "rates" in response and to_currency in response["rates"]:
|
44 |
+
converted_amount = amount * response["rates"][to_currency]
|
45 |
+
return f"{amount} {from_currency} = {converted_amount:.2f} {to_currency}"
|
46 |
+
else:
|
47 |
+
return "⚠️ Error: Unable to fetch exchange rates."
|
48 |
+
|
49 |
+
# Convert Button
|
50 |
+
if st.button("Convert"):
|
51 |
+
if from_currency == to_currency:
|
52 |
+
st.warning("Please select different currencies! 🚀")
|
53 |
+
else:
|
54 |
+
result = convert_currency(amount, from_currency, to_currency)
|
55 |
+
st.success(f"**{result}**") # Bold Black Output
|