emeses commited on
Commit
eb0dbf7
·
1 Parent(s): 0f922f9

Update space

Browse files
Files changed (1) hide show
  1. app.py +26 -63
app.py CHANGED
@@ -4,32 +4,20 @@ import requests
4
  from bs4 import BeautifulSoup
5
  import pandas as pd
6
 
7
- """
8
- 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
9
- """
10
  client = InferenceClient("meta-llama/Llama-3.2-3B-Instruct")
11
 
 
 
12
 
13
- def respond(
14
- message,
15
- history: list[tuple[str, str]],
16
- system_message,
17
- max_tokens,
18
- temperature,
19
- top_p,
20
- ):
21
  messages = [{"role": "system", "content": system_message}]
22
-
23
  for val in history:
24
  if val[0]:
25
  messages.append({"role": "user", "content": val[0]})
26
  if val[1]:
27
  messages.append({"role": "assistant", "content": val[1]})
28
-
29
  messages.append({"role": "user", "content": message})
30
-
31
  response = ""
32
-
33
  for message in client.chat_completion(
34
  messages,
35
  max_tokens=max_tokens,
@@ -38,7 +26,6 @@ def respond(
38
  top_p=top_p,
39
  ):
40
  token = message.choices[0].delta.content
41
-
42
  response += token
43
  yield response
44
 
@@ -48,31 +35,26 @@ def extract_table(url):
48
  try:
49
  response = requests.get(url)
50
  response.raise_for_status()
51
- soup = BeautifulSoup(response.text, 'html.parser')
52
- table = soup.find('table')
53
  if not table:
54
  return "<p>No table found on page</p>"
55
-
56
  # Extract data
57
  data = []
58
- rows = table.find_all('tr')
59
- for i, row in enumerate(rows[1:]):
60
- cells = row.find_all('td')
61
  if len(cells) >= 2:
62
- data.append({
63
- 'Index': i,
64
- 'Date': cells[0].text.strip()[:10],
65
- 'Topic': cells[1].text.strip(),
66
- })
67
-
68
- # Generate HTML table with buttons
69
  html_rows = ""
70
  for row in data:
71
  html_rows += f"""
72
  <tr>
73
  <td>{row['Date']}</td>
74
  <td>{row['Topic']}</td>
75
- <td><button onclick="handlePrepare({row['Index']})">Prepare</button></td>
76
  </tr>
77
  """
78
  html_table = f"""
@@ -80,7 +62,6 @@ def extract_table(url):
80
  <tr>
81
  <th>Date</th>
82
  <th>Topic</th>
83
- <th>Action</th>
84
  </tr>
85
  {html_rows}
86
  </table>
@@ -90,33 +71,24 @@ def extract_table(url):
90
  return f"<p>Error: {str(e)}</p>"
91
 
92
 
93
-
94
- def display_table(url):
95
- return extract_table(url)
96
-
97
  def handle_prepare(index):
98
  topic = data[index]["Topic"]
99
  return f"Prepare a 10-minute reading on what I should know before the class for the topic: {topic}"
100
 
101
- """
102
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
103
- """
104
  with gr.Blocks() as demo:
105
  with gr.Row():
106
  with gr.Column(scale=1):
107
  url_input = gr.Textbox(
108
  value="https://id2223kth.github.io/schedule/",
109
- label="Table URL"
110
  )
111
  table_output = gr.HTML(label="Extracted Table")
112
  extract_btn = gr.Button("Extract Table")
113
-
114
- extract_btn.click(
115
- fn=display_table,
116
- inputs=[url_input],
117
- outputs=[table_output]
118
- )
119
-
120
  with gr.Column(scale=2):
121
  chatbot = gr.ChatInterface(
122
  respond,
@@ -124,33 +96,24 @@ with gr.Blocks() as demo:
124
  gr.Textbox(value="Student class preparation companion.", label="System message"),
125
  ],
126
  )
127
-
128
- # Dynamically generate buttons for "Prepare" actions
129
- prepare_buttons = gr.Column(visible=False)
130
 
131
- def create_prepare_buttons():
132
- # Create individual buttons for each topic
 
 
133
  components = []
134
  for i, row in enumerate(data):
135
  btn = gr.Button(f"Prepare: {row['Topic']}")
136
  btn.click(
137
  fn=handle_prepare,
138
- inputs=[gr.State(i)], # Pass the index of the row
139
- outputs=[],
140
- ).then(
141
- fn=lambda message: ([message],), # Feed to chatbot
142
- inputs=[],
143
  outputs=[chatbot],
144
  )
145
  components.append(btn)
146
  return components
147
 
148
- extract_btn.click(
149
- fn=create_prepare_buttons,
150
- inputs=[],
151
- outputs=[prepare_buttons],
152
- )
153
-
154
 
155
  if __name__ == "__main__":
156
- demo.launch()
 
4
  from bs4 import BeautifulSoup
5
  import pandas as pd
6
 
 
 
 
7
  client = InferenceClient("meta-llama/Llama-3.2-3B-Instruct")
8
 
9
+ # Global data store for the table
10
+ data = []
11
 
12
+ def respond(message, history, system_message, max_tokens, temperature, top_p):
 
 
 
 
 
 
 
13
  messages = [{"role": "system", "content": system_message}]
 
14
  for val in history:
15
  if val[0]:
16
  messages.append({"role": "user", "content": val[0]})
17
  if val[1]:
18
  messages.append({"role": "assistant", "content": val[1]})
 
19
  messages.append({"role": "user", "content": message})
 
20
  response = ""
 
21
  for message in client.chat_completion(
22
  messages,
23
  max_tokens=max_tokens,
 
26
  top_p=top_p,
27
  ):
28
  token = message.choices[0].delta.content
 
29
  response += token
30
  yield response
31
 
 
35
  try:
36
  response = requests.get(url)
37
  response.raise_for_status()
38
+ soup = BeautifulSoup(response.text, "html.parser")
39
+ table = soup.find("table")
40
  if not table:
41
  return "<p>No table found on page</p>"
42
+
43
  # Extract data
44
  data = []
45
+ rows = table.find_all("tr")
46
+ for i, row in enumerate(rows[1:]): # Skip header
47
+ cells = row.find_all("td")
48
  if len(cells) >= 2:
49
+ data.append({"Index": i, "Date": cells[0].text.strip()[:10], "Topic": cells[1].text.strip()})
50
+
51
+ # Generate HTML table without buttons
 
 
 
 
52
  html_rows = ""
53
  for row in data:
54
  html_rows += f"""
55
  <tr>
56
  <td>{row['Date']}</td>
57
  <td>{row['Topic']}</td>
 
58
  </tr>
59
  """
60
  html_table = f"""
 
62
  <tr>
63
  <th>Date</th>
64
  <th>Topic</th>
 
65
  </tr>
66
  {html_rows}
67
  </table>
 
71
  return f"<p>Error: {str(e)}</p>"
72
 
73
 
 
 
 
 
74
  def handle_prepare(index):
75
  topic = data[index]["Topic"]
76
  return f"Prepare a 10-minute reading on what I should know before the class for the topic: {topic}"
77
 
78
+
79
+ # Gradio App
 
80
  with gr.Blocks() as demo:
81
  with gr.Row():
82
  with gr.Column(scale=1):
83
  url_input = gr.Textbox(
84
  value="https://id2223kth.github.io/schedule/",
85
+ label="Table URL",
86
  )
87
  table_output = gr.HTML(label="Extracted Table")
88
  extract_btn = gr.Button("Extract Table")
89
+
90
+ extract_btn.click(fn=extract_table, inputs=[url_input], outputs=[table_output])
91
+
 
 
 
 
92
  with gr.Column(scale=2):
93
  chatbot = gr.ChatInterface(
94
  respond,
 
96
  gr.Textbox(value="Student class preparation companion.", label="System message"),
97
  ],
98
  )
 
 
 
99
 
100
+ # Container for dynamically generated buttons
101
+ buttons_container = gr.Column(visible=True)
102
+
103
+ def create_buttons():
104
  components = []
105
  for i, row in enumerate(data):
106
  btn = gr.Button(f"Prepare: {row['Topic']}")
107
  btn.click(
108
  fn=handle_prepare,
109
+ inputs=[gr.State(i)],
 
 
 
 
110
  outputs=[chatbot],
111
  )
112
  components.append(btn)
113
  return components
114
 
115
+ # Create buttons when table is extracted
116
+ extract_btn.click(fn=create_buttons, inputs=[], outputs=[buttons_container])
 
 
 
 
117
 
118
  if __name__ == "__main__":
119
+ demo.launch()