lab2 / app.py
emeses's picture
Update space
38853b8
raw
history blame
5.3 kB
import gradio as gr
from huggingface_hub import InferenceClient
import pandas as pd
import requests
from bs4 import BeautifulSoup
# Initialize HF client
client = InferenceClient("meta-llama/Llama-2-7b-chat-hf")
def respond(message, history, max_tokens=512, temperature=0.7, top_p=0.95):
try:
# Format messages including history
messages = []
for user_msg, assistant_msg in history:
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": assistant_msg})
messages.append({"role": "user", "content": message})
# Generate response
response = ""
for chunk in client.chat_completion(
messages,
max_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
stream=True,
):
if hasattr(chunk.choices[0].delta, 'content'):
token = chunk.choices[0].delta.content
if token:
response += token
return response
except Exception as e:
return f"Error: {str(e)}"
def extract_schedule(url):
try:
# Fetch and parse webpage
response = requests.get(url)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# Find table and extract data
table = soup.find('table')
if not table:
return "<p>No table found on page</p>"
schedule_data = []
rows = table.find_all('tr')
for row in rows[1:]:
cells = row.find_all('td')
if len(cells) >= 4:
date = cells[0].text.strip()
topic = cells[1].text.strip()
if date and topic and not topic.startswith('See Canvas'):
schedule_data.append({
'Date': date[:10],
'Topic': topic,
'Action': f"""
<button
onclick="triggerChatbotPreparation('{topic.replace("'", "")}')"
class="prepare-btn">
Prepare
</button>
"""
})
df = pd.DataFrame(schedule_data)
# Convert to HTML with styling and JavaScript
html = f"""
<style>
table {{
border-collapse: collapse;
width: 100%;
font-size: 12px;
}}
th, td {{
border: 1px solid black;
padding: 6px;
text-align: left;
font-family: Arial, sans-serif;
}}
.prepare-btn {{
padding: 4px 8px;
font-size: 11px;
cursor: pointer;
}}
</style>
<script>
function triggerChatbotPreparation(topic) {{
// Find all Gradio textareas
const textareas = document.querySelectorAll('.gradio-container textarea');
// Find the first textarea (assuming it's the input)
const textbox = textareas[0];
if (textbox) {{
// Set the value
const preparationMessage = `prepare 5 minutes reading important parts related to ${topic}`;
textbox.value = preparationMessage;
// Trigger input and change events
const inputEvent = new Event('input', {{ bubbles: true }});
const changeEvent = new Event('change', {{ bubbles: true }});
textbox.dispatchEvent(inputEvent);
textbox.dispatchEvent(changeEvent);
// Find and click the send button
const sendButtons = document.querySelectorAll('.gradio-container button');
for (let button of sendButtons) {{
if (button.getAttribute('aria-label') === 'Send') {{
button.click();
break;
}}
}}
}}
}}
</script>
{df.to_html(index=False, escape=False)}
"""
return html
except Exception as e:
return f"<p>Error: {str(e)}</p>"
def display_schedule(url):
try:
html_table = extract_schedule(url)
return html_table # Already HTML string
except Exception as e:
return str(e)
with gr.Blocks() as demo:
with gr.Row():
# Left Column - Schedule
with gr.Column(scale=1):
url_input = gr.Textbox(
value="https://id2223kth.github.io/schedule/",
label="Schedule URL"
)
schedule_output = gr.HTML(label="Extracted Schedule")
extract_btn = gr.Button("Extract Schedule")
extract_btn.click(
fn=display_schedule,
inputs=[url_input],
outputs=[schedule_output]
)
# Right Column - Chatbot
with gr.Column(scale=2):
chatbot = gr.ChatInterface(
respond
)
if __name__ == "__main__":
demo.launch()