emeses commited on
Commit
d392c5f
·
1 Parent(s): 10fd571

Update space

Browse files
Files changed (1) hide show
  1. app.py +54 -150
app.py CHANGED
@@ -1,160 +1,64 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
- import pandas as pd
4
- import requests
5
- from bs4 import BeautifulSoup
6
 
7
- # Initialize HF client
8
- client = InferenceClient("meta-llama/Llama-2-7b-chat-hf")
 
 
9
 
10
- def respond(message, history, max_tokens=512, temperature=0.7, top_p=0.95):
11
- try:
12
- # Format messages including history
13
- messages = []
14
- for user_msg, assistant_msg in history:
15
- messages.append({"role": "user", "content": user_msg})
16
- messages.append({"role": "assistant", "content": assistant_msg})
17
- messages.append({"role": "user", "content": message})
18
-
19
- # Generate response
20
- response = ""
21
- for chunk in client.chat_completion(
22
- messages,
23
- max_tokens=max_tokens,
24
- temperature=temperature,
25
- top_p=top_p,
26
- stream=True,
27
- ):
28
- if hasattr(chunk.choices[0].delta, 'content'):
29
- token = chunk.choices[0].delta.content
30
- if token:
31
- response += token
32
- return response
33
-
34
- except Exception as e:
35
- return f"Error: {str(e)}"
36
 
37
- def extract_schedule(url):
38
- try:
39
- # Fetch and parse webpage
40
- response = requests.get(url)
41
- response.raise_for_status()
42
- soup = BeautifulSoup(response.text, 'html.parser')
43
-
44
- # Find table and extract data
45
- table = soup.find('table')
46
- if not table:
47
- return "<p>No table found on page</p>"
48
-
49
- schedule_data = []
50
- rows = table.find_all('tr')
51
- for row in rows[1:]:
52
- cells = row.find_all('td')
53
- if len(cells) >= 4:
54
- date = cells[0].text.strip()
55
- topic = cells[1].text.strip()
56
-
57
- if date and topic and not topic.startswith('See Canvas'):
58
- schedule_data.append({
59
- 'Date': date[:10],
60
- 'Topic': topic,
61
- 'Action': f"""
62
- <button
63
- onclick="triggerChatbotPreparation('{topic.replace("'", "")}')"
64
- class="prepare-btn">
65
- Prepare
66
- </button>
67
- """
68
- })
69
 
70
- df = pd.DataFrame(schedule_data)
71
-
72
- # Convert to HTML with styling and JavaScript
73
- html = f"""
74
- <style>
75
- table {{
76
- border-collapse: collapse;
77
- width: 100%;
78
- font-size: 12px;
79
- }}
80
- th, td {{
81
- border: 1px solid black;
82
- padding: 6px;
83
- text-align: left;
84
- font-family: Arial, sans-serif;
85
- }}
86
- .prepare-btn {{
87
- padding: 4px 8px;
88
- font-size: 11px;
89
- cursor: pointer;
90
- }}
91
- </style>
92
- <script>
93
- function triggerChatbotPreparation(topic) {{
94
- // Find all Gradio textareas
95
- const textareas = document.querySelectorAll('.gradio-container textarea');
96
-
97
- // Find the first textarea (assuming it's the input)
98
- const textbox = textareas[0];
99
-
100
- if (textbox) {{
101
- // Set the value
102
- const preparationMessage = `prepare 5 minutes reading important parts related to ${topic}`;
103
- textbox.value = preparationMessage;
104
-
105
- // Trigger input and change events
106
- const inputEvent = new Event('input', {{ bubbles: true }});
107
- const changeEvent = new Event('change', {{ bubbles: true }});
108
- textbox.dispatchEvent(inputEvent);
109
- textbox.dispatchEvent(changeEvent);
110
-
111
- // Find and click the send button
112
- const sendButtons = document.querySelectorAll('.gradio-container button');
113
- for (let button of sendButtons) {{
114
- if (button.getAttribute('aria-label') === 'Send') {{
115
- button.click();
116
- break;
117
- }}
118
- }}
119
- }}
120
- }}
121
- </script>
122
- {df.to_html(index=False, escape=False)}
123
- """
124
- return html
125
-
126
- except Exception as e:
127
- return f"<p>Error: {str(e)}</p>"
128
 
129
- def display_schedule(url):
130
- try:
131
- html_table = extract_schedule(url)
132
- return html_table # Already HTML string
133
- except Exception as e:
134
- return str(e)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
- with gr.Blocks() as demo:
137
- with gr.Row():
138
- # Left Column - Schedule
139
- with gr.Column(scale=1):
140
- url_input = gr.Textbox(
141
- value="https://id2223kth.github.io/schedule/",
142
- label="Schedule URL"
143
- )
144
- schedule_output = gr.HTML(label="Extracted Schedule")
145
- extract_btn = gr.Button("Extract Schedule")
146
-
147
- extract_btn.click(
148
- fn=display_schedule,
149
- inputs=[url_input],
150
- outputs=[schedule_output]
151
- )
152
-
153
- # Right Column - Chatbot
154
- with gr.Column(scale=2):
155
- chatbot = gr.ChatInterface(
156
- respond
157
- )
158
 
159
  if __name__ == "__main__":
160
- demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
 
 
3
 
4
+ """
5
+ 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
6
+ """
7
+ client = InferenceClient("meta-llama/Llama-3.2-3B-Instruct")
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ def respond(
11
+ message,
12
+ history: list[tuple[str, str]],
13
+ system_message,
14
+ max_tokens,
15
+ temperature,
16
+ top_p,
17
+ ):
18
+ messages = [{"role": "system", "content": system_message}]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ for val in history:
21
+ if val[0]:
22
+ messages.append({"role": "user", "content": val[0]})
23
+ if val[1]:
24
+ messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ messages.append({"role": "user", "content": message})
27
+
28
+ response = ""
29
+
30
+ for message in client.chat_completion(
31
+ messages,
32
+ max_tokens=max_tokens,
33
+ stream=True,
34
+ temperature=temperature,
35
+ top_p=top_p,
36
+ ):
37
+ token = message.choices[0].delta.content
38
+
39
+ response += token
40
+ yield response
41
+
42
+
43
+ """
44
+ For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
+ """
46
+ demo = gr.ChatInterface(
47
+ respond,
48
+ additional_inputs=[
49
+ gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
+ gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
+ gr.Slider(
53
+ minimum=0.1,
54
+ maximum=1.0,
55
+ value=0.95,
56
+ step=0.05,
57
+ label="Top-p (nucleus sampling)",
58
+ ),
59
+ ],
60
+ )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  if __name__ == "__main__":
64
+ demo.launch()