Spaces:
Runtime error

Remit_Finder_AI / app.py
GilbertKiwanuka
Add FinChat RemitFinder Space
a701e52
Raw History Blame Contribute Delete
3.62 kB
import os, re, asyncio
from dotenv import load_dotenv
from urllib.parse import urljoin
import openai
import pycountry
import gradio as gr
from playwright.async_api import async_playwright
from bs4 import BeautifulSoup
# 1) Load your API key
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
assert openai.api_key, "OPENAI_API_KEY must be set in Secrets"
# 2) Scraper function (RemitFinder via Playwright)
async def fetch_remitfinder(src_cc: str, dst_cc: str, amount: float):
def slugify(text: str) -> str:
return re.sub(r'[^a-z0-9]+','-', text.lower()).strip('-')
src = pycountry.countries.get(alpha_3=src_cc) or pycountry.countries.get(alpha_2=src_cc)
dst = pycountry.countries.get(alpha_3=dst_cc) or pycountry.countries.get(alpha_2=dst_cc)
path = slugify(f"best-exchange-rate-to-send-money-from-{src.name}-to-{dst.name}")
url = f"https://www.remitfinder.com/{path}/rr/{src.alpha_3}/{dst.alpha_3}"
async with async_playwright() as pw:
browser = await pw.chromium.launch()
page = await browser.new_page()
await page.goto(url, wait_until="networkidle")
await page.wait_for_selector("div.card.no-hover")
html = await page.content()
await browser.close()
soup = BeautifulSoup(html, "html.parser")
cards = soup.select("div.card.no-hover > div.card-body")[:3]
out = []
for c in cards:
link = c.select_one("a.text-link")
name = link.get_text(strip=True).replace("Read more about ","")
href = urljoin("https://www.remitfinder.com", link["href"])
delivered = c.select_one("div.amount-rate").get_text(strip=True)
limit = c.find(text=re.compile("Transfer Limit")).split(":",1)[-1].strip()
rate = c.select_one("div.rate-type span:last-child").get_text(strip=True)
out.append(dict(name=name, url=href, delivered=delivered, limit=limit, rate=rate))
return out
# 3) LLM + scraping orchestration
async def finchat_bot(user_input, history):
# merge history into one line
merged = " ".join(m[0] for m in history) + " " + user_input
m = re.search(r"(\d+\.?\d*)\s*([A-Za-z]{3})\s*from\s*([A-Za-z]{2,3})\s*to\s*([A-Za-z]{2,3})", merged, re.IGNORECASE)
if not m:
return "❓ Please tell me “100 USD from US to CA” (or similar).", history
amount, _, src_cc, dst_cc = float(m.group(1)), m.group(2), m.group(3).upper(), m.group(4).upper()
providers = await fetch_remitfinder(src_cc, dst_cc, amount)
# build Markdown
md = "\n\n".join(
f"### {p['name']}\n"
f"- **You receive:** {p['delivered']}\n"
f"- **Transfer limit:** {p['limit']}\n"
f"- **Rate:** {p['rate']}\n"
f"- **Link:** [Go to provider]({p['url']})"
for p in providers
)
prompt = f"""
You are FinTec Assistant. A user wants to send {amount} {src_cc} to {dst_cc}.
Here are live RemitFinder top-3 options:
{md}
Recommend them in order of **highest delivered amount first**, with exactly three blocks formatted as above.
"""
resp = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role":"system","content":prompt}],
temperature=0.2,
)
answer = resp.choices[0].message.content.strip()
history.append((user_input, answer))
return answer, history
# 4) Gradio UI
with gr.Blocks(title="FinChat RemitFinder") as demo:
chatbot = gr.Chatbot()
txt = gr.Textbox(placeholder="e.g. 100 EUR from DE to UG", show_label=False)
txt.submit(lambda msg, hist: asyncio.run(finchat_bot(msg, hist)), [txt, chatbot], [txt, chatbot])
demo.launch()