File size: 6,332 Bytes
1d029eb e128db1 a8a3ce3 91ab614 a8a3ce3 5ff825c a8a3ce3 f7a1b1d a8a3ce3 216e873 a8a3ce3 216e873 a8a3ce3 f7a1b1d a19992d a8a3ce3 f7a1b1d a8a3ce3 f7a1b1d a8a3ce3 13d2f6c a19992d 91ab614 a8a3ce3 e128db1 176deb5 e128db1 a8a3ce3 5ff825c a8a3ce3 176deb5 a8a3ce3 176deb5 a8a3ce3 176deb5 5ff825c d15bfd4 5ff825c e128db1 857e527 4967af8 216e873 a19992d 216e873 a19992d 1e2a25a d15bfd4 5df5853 d15bfd4 cbae7ec d15bfd4 ef1ee2b 5df5853 ef1ee2b d15bfd4 ef1ee2b d15bfd4 a19992d 216e873 f329e38 1e2a25a e128db1 176deb5 a8a3ce3 176deb5 a8a3ce3 1e2cf67 216e873 a19992d a8a3ce3 5ff825c 64f77f5 216e873 1e2a25a e128db1 1e2a25a 5ff825c a19992d 5df5853 a19992d 877da7e 1e2a25a 216e873 a19992d 216e873 a19992d f723138 216e873 f723138 a19992d f723138 216e873 a19992d 216e873 a19992d d6ea91d 216e873 a19992d 216e873 1e2a25a 216e873 1e2cf67 1d029eb 1e2cf67 |
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 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
import gradio as gr
from huggingface_hub import InferenceClient
import requests
from bs4 import BeautifulSoup
import pandas as pd
client = InferenceClient("meta-llama/Llama-3.2-3B-Instruct")
# Global data store for the table
data = []
def respond(message, history, system_message):
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=2048,
stream=True,
temperature=0.7,
top_p=0.9,
):
if message.choices[0].delta.content is not None:
response += message.choices[0].delta.content
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>"
# Clear existing data
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(),
})
# Create HTML table with prepare buttons
html = '<table class="dataframe">'
html += '<thead><tr><th>Date</th><th>Topic</th><th>Action</th></tr></thead>'
html += '<tbody>'
for i, row in enumerate(data):
html += f'''
<tr>
<td>{row['Date']}</td>
<td>{row['Topic']}</td>
<td>
<button onclick='
(function() {{
const indexInput = document.getElementById("prepare-index");
indexInput.value = {i};
const event = new Event("input", {{ bubbles: true }});
indexInput.dispatchEvent(event);
document.getElementById("prepare-trigger").click();
}})();
'>
Prepare
</button>
</td>
</tr>
'''
html += '</tbody></table>'
return html
except Exception as e:
return f"<p>Error: {str(e)}</p>"
def add_text(history, text):
history = history + [(text, None)]
return history
def generate_response(history, system_message):
if not history:
return history
response = ""
for chunk in respond(history[-1][0], history[:-1], system_message):
response = chunk
history[-1] = (history[-1][0], response)
yield history
def prepare_topic_message(index):
try:
print(f"Received index: '{index}'") # Debug print
# Convert index to integer, handling both string and numeric inputs
try:
idx = int(float(index))
except (ValueError, TypeError):
print(f"Invalid index value: {index}")
return ""
if 0 <= idx < len(data):
topic = data[idx]["Topic"]
date = data[idx]["Date"]
message = f"Please prepare a 10-minute reading guide for the topic '{topic}' scheduled for {date}"
print(f"Generated message: {message}") # Debug print
return message
else:
print(f"Index {idx} out of range")
return ""
except Exception as e:
print(f"Error in prepare_topic_message: {e}")
return ""
def clear_chat():
return [], ""
# Gradio app
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")
# Hidden components for prepare functionality
prepare_index = gr.Textbox(value="", visible=False, elem_id="prepare-index")
prepare_trigger = gr.Button("Prepare", visible=False, elem_id="prepare-trigger")
with gr.Column(scale=2):
chatbot = gr.Chatbot()
msg = gr.Textbox(label="Message")
system_message = gr.Textbox(
value="Student class preparation companion.",
label="System message"
)
with gr.Row():
submit = gr.Button("Submit")
clear = gr.Button("Clear")
# Event handlers
extract_btn.click(
fn=extract_table,
inputs=[url_input],
outputs=[table_output]
)
# Prepare trigger handler
prepare_trigger.click(
fn=prepare_topic_message,
inputs=[prepare_index],
outputs=[msg],
queue=False # Add this
).success( # Change .then to .success
fn=add_text,
inputs=[chatbot, msg],
outputs=[chatbot]
).then(
fn=generate_response,
inputs=[chatbot, system_message],
outputs=[chatbot]
)
# Submit button handler
msg.submit(
fn=add_text,
inputs=[chatbot, msg],
outputs=[chatbot]
).success(
fn=lambda: "",
outputs=[msg]
).then(
fn=generate_response,
inputs=[chatbot, system_message],
outputs=[chatbot]
)
submit.click(
fn=add_text,
inputs=[chatbot, msg],
outputs=[chatbot]
).success(
fn=lambda: "",
outputs=[msg]
).then(
fn=generate_response,
inputs=[chatbot, system_message],
outputs=[chatbot]
)
# Clear button handler
clear.click(fn=clear_chat, outputs=[chatbot, msg])
if __name__ == "__main__":
demo.launch() |