Spaces:
Runtime error
Runtime error
GilbertKiwanuka commited on
Commit ·
a701e52
1
Parent(s): 34e4a78
Add FinChat RemitFinder Space
Browse filesFiles changed (2)
- app.py+89-28
- requirements.txt+8-4
12345678910111213141516171819202122232425262728293031import gradio as grfrom transformers import AutoModelForCausalLM, AutoTokenizerimport torch# 1) Load modeltokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf")model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf",torch_dtype=torch.float16,device_map="auto")# 2) Chat functiondef chat(history, user_input):history = history or []history.append(("You", user_input))inputs = tokenizer([f"{u}: {m}" for u,m in history],return_tensors="pt", truncation=True, padding=True).to(model.device)out = model.generate(**inputs, max_new_tokens=128)reply = tokenizer.decode(out[0], skip_special_tokens=True)history.append(("Bot", reply))return history, ""# 3) Gradio UIwith gr.Blocks() as demo:chatbot = gr.Chatbot()userbox = gr.Textbox(placeholder="Type a message and press Enter")userbox.submit(chat, [chatbot, userbox], [chatbot, userbox])demo.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192import os, re, asynciofrom dotenv import load_dotenvfrom urllib.parse import urljoinimport openaiimport pycountryimport gradio as grfrom playwright.async_api import async_playwrightfrom bs4 import BeautifulSoup# 1) Load your API keyload_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 orchestrationasync def finchat_bot(user_input, history):# merge history into one linemerged = " ".join(m[0] for m in history) + " " + user_inputm = 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).", historyamount, _, 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 Markdownmd = "\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 UIwith 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()
1234gradiotransformerstorchbitsandbytes12345678fastapiuvicornopenaipython-dotenvplaywrightbeautifulsoup4pycountrygradio
app.py+89-28
requirements.txt+8-4