emeses commited on
Commit
0897fdf
·
1 Parent(s): f463dfd

Update space

Browse files
Files changed (1) hide show
  1. app.py +63 -41
app.py CHANGED
@@ -3,7 +3,6 @@ from huggingface_hub import InferenceClient
3
  import requests
4
  from bs4 import BeautifulSoup
5
  import pandas as pd
6
- import ast
7
 
8
  client = InferenceClient("meta-llama/Llama-3.2-3B-Instruct")
9
 
@@ -34,7 +33,6 @@ def respond(message, history, system_message):
34
 
35
  def extract_table(url):
36
  global data
37
- data = [] # Clear existing data
38
  try:
39
  response = requests.get(url)
40
  response.raise_for_status()
@@ -43,8 +41,10 @@ def extract_table(url):
43
  if not table:
44
  return "<p>No table found on page</p>"
45
 
 
 
46
  rows = table.find_all('tr')
47
- for row in rows[1:]: # Skip header row
48
  cells = row.find_all('td')
49
  if len(cells) >= 2:
50
  data.append({
@@ -52,33 +52,65 @@ def extract_table(url):
52
  'Topic': cells[1].text.strip(),
53
  })
54
 
55
- print(f"Extracted {len(data)} rows") # Debug print
56
- return create_table_html() # Your existing HTML creation code
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  except Exception as e:
58
- print(f"Error in extract_table: {e}")
59
  return f"<p>Error: {str(e)}</p>"
60
 
61
- def prepare_topic(selected_topic):
62
- print(f"Preparing topic: {selected_topic}") # Debug print
63
  try:
64
- # Handle potential list or string input
65
- if isinstance(selected_topic, list):
66
- # If it's a list, take the first item
67
- selected_topic = selected_topic[0] if selected_topic else ""
68
-
69
- # Find the index of the selected topic
70
- for index, row in enumerate(data):
71
- full_topic = f"{row['Topic']} ({row['Date']})"
72
- if full_topic == selected_topic:
73
- topic = row["Topic"]
74
- date = row["Date"]
75
- message = f"Please prepare a 10-minute reading guide for the topic '{topic}' scheduled for {date}"
76
- print(f"Generated preparation message: {message}") # Debug print
77
- return message
78
 
79
- print(f"Topic not found: {selected_topic}")
80
- return "Error: Topic not found"
81
-
 
 
 
 
 
 
 
 
 
 
82
  except Exception as e:
83
  print(f"Unexpected error in prepare_topic: {e}")
84
  return "Error: Could not prepare topic"
@@ -97,15 +129,6 @@ def generate_response(history, system_message):
97
  history[-1] = (history[-1][0], response)
98
  yield history
99
 
100
- def update_dropdown():
101
- try:
102
- choices = [f"{row['Topic']} ({row['Date']})" for row in data]
103
- print(f"Generated choices: {choices}") # Debug print
104
- return gr.Dropdown(choices=choices)
105
- except Exception as e:
106
- print(f"Error updating dropdown: {e}")
107
- return gr.Dropdown(choices=[])
108
-
109
  def clear_chat():
110
  return [], ""
111
 
@@ -124,8 +147,7 @@ with gr.Blocks() as demo:
124
  topic_dropdown = gr.Dropdown(
125
  label="Select Topic",
126
  choices=[],
127
- interactive=True,
128
- allow_custom_value=True
129
  )
130
  prepare_btn = gr.Button("Prepare Topic")
131
 
@@ -143,12 +165,12 @@ with gr.Blocks() as demo:
143
 
144
  # Event handlers
145
  extract_btn.click(
146
- fn=extract_table,
147
- inputs=[url_input],
148
- outputs=[table_output]
149
  ).success(
150
- fn=lambda: [f"{row['Topic']} ({row['Date']})" for row in data],
151
- outputs=[topic_dropdown]
152
  )
153
 
154
  # Prepare topic handler
 
3
  import requests
4
  from bs4 import BeautifulSoup
5
  import pandas as pd
 
6
 
7
  client = InferenceClient("meta-llama/Llama-3.2-3B-Instruct")
8
 
 
33
 
34
  def extract_table(url):
35
  global data
 
36
  try:
37
  response = requests.get(url)
38
  response.raise_for_status()
 
41
  if not table:
42
  return "<p>No table found on page</p>"
43
 
44
+ # Clear existing data
45
+ data = []
46
  rows = table.find_all('tr')
47
+ for i, row in enumerate(rows[1:]):
48
  cells = row.find_all('td')
49
  if len(cells) >= 2:
50
  data.append({
 
52
  'Topic': cells[1].text.strip(),
53
  })
54
 
55
+ # Create HTML table with prepare buttons
56
+ html = '''
57
+ <style>
58
+ .dataframe {
59
+ border-collapse: collapse;
60
+ width: 100%;
61
+ margin: 10px 0;
62
+ }
63
+ .dataframe th, .dataframe td {
64
+ border: 1px solid #ddd;
65
+ padding: 8px;
66
+ text-align: left;
67
+ }
68
+ .dataframe th {
69
+ background-color: #f6f8fa;
70
+ }
71
+ .dataframe tr:nth-child(even) {
72
+ background-color: #f9f9f9;
73
+ }
74
+ </style>
75
+ '''
76
+
77
+ html += '<table class="dataframe">'
78
+ html += '<thead><tr><th>Date</th><th>Topic</th></tr></thead>'
79
+ html += '<tbody>'
80
+
81
+ for row in data:
82
+ html += f'''
83
+ <tr>
84
+ <td>{row['Date']}</td>
85
+ <td>{row['Topic']}</td>
86
+ </tr>
87
+ '''
88
+ html += '</tbody></table>'
89
+ return html
90
+
91
  except Exception as e:
92
+ print(f"Error in extract_table: {e}") # Debug print
93
  return f"<p>Error: {str(e)}</p>"
94
 
95
+ def prepare_topic(index):
96
+ print(f"Preparing topic with index: {index}") # Debug print
97
  try:
98
+ # Convert index to integer
99
+ index = int(index)
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
+ # Check if index is valid
102
+ if 0 <= index < len(data):
103
+ topic = data[index]["Topic"]
104
+ date = data[index]["Date"]
105
+ message = f"Please prepare a 10-minute reading guide for the topic '{topic}' scheduled for {date}"
106
+ print(f"Generated preparation message: {message}") # Debug print
107
+ return message
108
+ else:
109
+ print(f"Invalid index: {index}. Total data length: {len(data)}")
110
+ return "Error: Invalid topic selection"
111
+ except ValueError:
112
+ print(f"Could not convert {index} to integer")
113
+ return "Error: Invalid topic selection"
114
  except Exception as e:
115
  print(f"Unexpected error in prepare_topic: {e}")
116
  return "Error: Could not prepare topic"
 
129
  history[-1] = (history[-1][0], response)
130
  yield history
131
 
 
 
 
 
 
 
 
 
 
132
  def clear_chat():
133
  return [], ""
134
 
 
147
  topic_dropdown = gr.Dropdown(
148
  label="Select Topic",
149
  choices=[],
150
+ interactive=True
 
151
  )
152
  prepare_btn = gr.Button("Prepare Topic")
153
 
 
165
 
166
  # Event handlers
167
  extract_btn.click(
168
+ fn=extract_table,
169
+ inputs=[url_input],
170
+ outputs=[table_output]
171
  ).success(
172
+ fn=lambda: [f"{row['Topic']} ({row['Date']})" for row in data],
173
+ outputs=[topic_dropdown]
174
  )
175
 
176
  # Prepare topic handler