File size: 3,667 Bytes
911e6ac | 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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | import gradio as gr
import requests
import re
from datetime import datetime
import pytz
# -------- METAL PRICE --------
METALS = {
"gold": "XAU",
"silver": "XAG",
"palladium": "XPD",
"copper": "HG",
"platinum": "XPT"
}
OUNCE_TO_GRAM = 31.1035
def get_metal_price(query):
query = query.lower()
metal = next((m for m in METALS if m in query), None)
if not metal:
return None
match = re.search(r"(\d+)\s*gram", query)
grams = int(match.group(1)) if match else 1
symbol = METALS[metal]
try:
price_data = requests.get(f"https://api.gold-api.com/price/{symbol}").json()
usd_to_inr = requests.get("https://api.frankfurter.app/latest?from=USD&to=INR").json()["rates"]["INR"]
per_gram_usd = price_data["price"] / OUNCE_TO_GRAM
per_gram_inr = per_gram_usd * usd_to_inr
total = per_gram_inr * grams
return f"{metal.capitalize()} 💰\n₹{per_gram_inr:.2f}/g | {grams}g = ₹{total:.2f}"
except:
return "Error fetching metal price"
# -------- WEATHER --------
def get_weather(query):
match = re.search(r"in ([a-zA-Z ]+)", query)
if not match:
return None
city = match.group(1)
try:
geo = requests.get(f"https://geocoding-api.open-meteo.com/v1/search?name={city}").json()
if "results" not in geo:
return "City not found"
lat = geo["results"][0]["latitude"]
lon = geo["results"][0]["longitude"]
weather = requests.get(
f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t_weather=true"
).json()["current_weather"]
return f"{city} 🌦️\nTemp: {weather['temperature']}°C\nWind: {weather['windspeed']} km/h"
except:
return "Error fetching weather"
# -------- TIME --------
def get_time(query):
match = re.search(r"in ([a-zA-Z ]+)", query)
if not match:
return None
city = match.group(1)
try:
geo = requests.get(f"https://geocoding-api.open-meteo.com/v1/search?name={city}").json()
tz = geo["results"][0]["timezone"]
now = datetime.now(pytz.timezone(tz))
return f"{city} 🕒\n{now.strftime('%Y-%m-%d %H:%M:%S')}"
except:
return "Error fetching time"
# -------- CRYPTO --------
def get_crypto(query):
name = query.split()[-1].lower()
try:
data = requests.get(
f"https://api.coingecko.com/api/v3/simple/price?ids={name}&vs_currencies=inr"
).json()
if name not in data:
return None
return f"{name.capitalize()} 🪙 ₹{data[name]['inr']}"
except:
return "Error fetching crypto"
# -------- JOKE --------
def get_joke(query):
if "joke" not in query.lower():
return None
try:
data = requests.get("https://official-joke-api.appspot.com/random_joke").json()
return f"{data['setup']} 😂 {data['punchline']}"
except:
return "Error fetching joke"
# -------- MAIN ROUTER --------
def chatbot(query):
query = query.lower()
# Multi-step support
responses = []
for func in [get_metal_price, get_weather, get_time, get_crypto, get_joke]:
result = func(query)
if result:
responses.append(result)
if not responses:
return "Sorry, I couldn't understand. Try asking about gold, weather, time, crypto, or jokes."
return "\n\n".join(responses)
# -------- UI --------
gr.Interface(
fn=chatbot,
inputs="text",
outputs="text",
title="🔥 Multi-API AI Bot",
description="Ask about gold price, weather, time, crypto, or jokes!"
).launch() |