lab2 / app.py
emeses's picture
Update space
a8a3ce3
raw
history blame
2.93 kB
import gradio as gr
from huggingface_hub import InferenceClient
import requests
from bs4 import BeautifulSoup
import pandas as pd
"""
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
"""
client = InferenceClient("meta-llama/Llama-3.2-3B-Instruct")
def respond(
message,
history: list[tuple[str, str]],
system_message,
max_tokens,
temperature,
top_p,
):
messages = [{"role": "system", "content": system_message}]
for val in history:
if val[0]:
messages.append({"role": "user", "content": val[0]})
if val[1]:
messages.append({"role": "assistant", "content": val[1]})
messages.append({"role": "user", "content": message})
response = ""
for message in client.chat_completion(
messages,
max_tokens=max_tokens,
stream=True,
temperature=temperature,
top_p=top_p,
):
token = message.choices[0].delta.content
response += token
yield response
def extract_table(url):
global data
try:
response = requests.get(url)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table')
if not table:
return "<p>No table found on page</p>"
data = []
rows = table.find_all('tr')
for i, row in enumerate(rows[1:]):
cells = row.find_all('td')
if len(cells) >= 2:
data.append({
'Date': cells[0].text.strip()[:10],
'Topic': cells[1].text.strip(),
})
df = pd.DataFrame(data)
return df.to_html(escape=False, index=False)
except Exception as e:
return f"<p>Error: {str(e)}</p>"
def display_table(url):
return extract_table(url)
"""
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
"""
with gr.Blocks() as demo:
with gr.Row():
with gr.Column(scale=1):
url_input = gr.Textbox(
value="https://id2223kth.github.io/schedule/",
label="Table URL"
)
table_output = gr.HTML(label="Extracted Table")
extract_btn = gr.Button("Extract Table")
extract_btn.click(
fn=display_table,
inputs=[url_input],
outputs=[table_output]
)
with gr.Column(scale=2):
chatbot = gr.ChatInterface(
respond,
additional_inputs=[
gr.Textbox(value="Student class preparation companion.", label="System message"),
],
)
if __name__ == "__main__":
demo.launch()