emeses commited on
Commit
216e873
·
1 Parent(s): f723138

Update space

Browse files
Files changed (1) hide show
  1. app.py +64 -56
app.py CHANGED
@@ -10,16 +10,16 @@ client = InferenceClient("meta-llama/Llama-3.2-3B-Instruct")
10
  data = []
11
 
12
  def respond(message, history, system_message):
13
- # Ensure history is a list of tuples with user and assistant messages
14
  messages = [{"role": "system", "content": system_message}]
15
  for val in history:
16
- messages.append({"role": "user", "content": val[0]})
17
- if len(val) > 1 and val[1]:
 
18
  messages.append({"role": "assistant", "content": val[1]})
19
-
20
  messages.append({"role": "user", "content": message})
21
 
22
- full_response = ""
23
  for message in client.chat_completion(
24
  messages,
25
  max_tokens=2048,
@@ -28,8 +28,8 @@ def respond(message, history, system_message):
28
  top_p=0.9,
29
  ):
30
  if message.choices[0].delta.content is not None:
31
- full_response += message.choices[0].delta.content
32
- yield full_response
33
 
34
  def extract_table(url):
35
  global data
@@ -65,6 +65,7 @@ def extract_table(url):
65
  <button onclick='
66
  document.getElementById("prepare-topic").value = "{i}";
67
  document.getElementById("prepare-topic").dispatchEvent(new Event("input"));
 
68
  '>
69
  Prepare
70
  </button>
@@ -76,30 +77,33 @@ def extract_table(url):
76
  except Exception as e:
77
  return f"<p>Error: {str(e)}</p>"
78
 
79
- def prepare_topic_action(topic_index, system_message):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  try:
81
- # Convert index to integer
82
- index = int(topic_index)
83
-
84
- # Validate index
85
  if 0 <= index < len(data):
86
- # Get the topic
87
  topic = data[index]["Topic"]
88
-
89
- # Prepare the message
90
- prepare_message = f"Prepare a 10-minute reading for the topic: {topic}"
91
-
92
- # Generate response directly
93
- full_response = ""
94
- for chunk in respond(prepare_message, [], system_message):
95
- full_response = chunk
96
-
97
- return prepare_message, full_response
98
- else:
99
- return "", ""
100
- except Exception as e:
101
- print(f"Error in prepare_topic_action: {e}")
102
- return "", ""
103
 
104
  # Gradio app
105
  with gr.Blocks() as demo:
@@ -112,12 +116,13 @@ with gr.Blocks() as demo:
112
  table_output = gr.HTML(label="Extracted Table")
113
  extract_btn = gr.Button("Extract Table")
114
 
115
- # Hidden component for prepare functionality
116
  prepare_topic = gr.Textbox(value="", visible=False, elem_id="prepare-topic")
 
117
 
118
  with gr.Column(scale=2):
119
  chatbot = gr.Chatbot()
120
- msg = gr.Textbox(label="Message", interactive=True)
121
  system_message = gr.Textbox(
122
  value="Student class preparation companion.",
123
  label="System message"
@@ -134,43 +139,46 @@ with gr.Blocks() as demo:
134
  outputs=[table_output]
135
  )
136
 
137
- # Prepare topic event handler
138
- prepare_topic.change(
139
- fn=prepare_topic_action,
140
- inputs=[prepare_topic, system_message],
141
- outputs=[msg, chatbot]
142
- )
143
-
144
  # Submit button handler
145
- submit_event = submit.click(
146
- fn=lambda message: ([(message, None)] if message else []),
147
- inputs=[msg],
148
- outputs=[chatbot],
149
- ).then(
150
- fn=lambda: "", # Clear input textbox
151
- outputs=[msg]
152
  ).then(
153
- fn=lambda history, system_msg: list(respond(history[-1][0], history[:-1], system_msg)) if history else [],
154
  inputs=[chatbot, system_message],
155
- outputs=[chatbot]
156
  )
157
 
158
- # Enable message submission via enter key
159
- msg.submit(
160
- fn=lambda message: ([(message, None)] if message else []),
161
- inputs=[msg],
162
- outputs=[chatbot],
 
 
163
  ).then(
164
- fn=lambda: "", # Clear input textbox
165
- outputs=[msg]
 
 
 
 
 
 
 
 
166
  ).then(
167
- fn=lambda history, system_msg: list(respond(history[-1][0], history[:-1], system_msg)) if history else [],
168
  inputs=[chatbot, system_message],
169
- outputs=[chatbot]
170
  )
171
 
172
  # Clear button handler
173
- clear.click(fn=lambda: [], outputs=[chatbot, msg])
174
 
175
  if __name__ == "__main__":
176
  demo.launch()
 
10
  data = []
11
 
12
  def respond(message, history, system_message):
 
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
+
20
  messages.append({"role": "user", "content": message})
21
 
22
+ response = ""
23
  for message in client.chat_completion(
24
  messages,
25
  max_tokens=2048,
 
28
  top_p=0.9,
29
  ):
30
  if message.choices[0].delta.content is not None:
31
+ response += message.choices[0].delta.content
32
+ yield response
33
 
34
  def extract_table(url):
35
  global data
 
65
  <button onclick='
66
  document.getElementById("prepare-topic").value = "{i}";
67
  document.getElementById("prepare-topic").dispatchEvent(new Event("input"));
68
+ document.getElementById("prepare-button").click();
69
  '>
70
  Prepare
71
  </button>
 
77
  except Exception as e:
78
  return f"<p>Error: {str(e)}</p>"
79
 
80
+ def add_text(history, text):
81
+ history = history + [(text, None)]
82
+ return history
83
+
84
+ def generate_response(history, system_message):
85
+ if not history:
86
+ return history
87
+
88
+ response = ""
89
+ for chunk in respond(history[-1][0], history[:-1], system_message):
90
+ response = chunk
91
+ history[-1] = (history[-1][0], response)
92
+ yield history
93
+
94
+ def handle_prepare(index, history):
95
  try:
96
+ index = int(index)
 
 
 
97
  if 0 <= index < len(data):
 
98
  topic = data[index]["Topic"]
99
+ date = data[index]["Date"]
100
+ message = f"Please prepare a 10-minute reading guide for the topic '{topic}' scheduled for {date}"
101
+ return history + [(message, None)]
102
+ except:
103
+ return history
104
+
105
+ def clear_chat():
106
+ return [], ""
 
 
 
 
 
 
 
107
 
108
  # Gradio app
109
  with gr.Blocks() as demo:
 
116
  table_output = gr.HTML(label="Extracted Table")
117
  extract_btn = gr.Button("Extract Table")
118
 
119
+ # Hidden components for prepare functionality
120
  prepare_topic = gr.Textbox(value="", visible=False, elem_id="prepare-topic")
121
+ prepare_button = gr.Button("Prepare", visible=False, elem_id="prepare-button")
122
 
123
  with gr.Column(scale=2):
124
  chatbot = gr.Chatbot()
125
+ msg = gr.Textbox(label="Message")
126
  system_message = gr.Textbox(
127
  value="Student class preparation companion.",
128
  label="System message"
 
139
  outputs=[table_output]
140
  )
141
 
 
 
 
 
 
 
 
142
  # Submit button handler
143
+ msg.submit(
144
+ fn=add_text,
145
+ inputs=[chatbot, msg],
146
+ outputs=chatbot
147
+ ).success(
148
+ fn=lambda: "",
149
+ outputs=msg
150
  ).then(
151
+ fn=generate_response,
152
  inputs=[chatbot, system_message],
153
+ outputs=chatbot
154
  )
155
 
156
+ submit.click(
157
+ fn=add_text,
158
+ inputs=[chatbot, msg],
159
+ outputs=chatbot
160
+ ).success(
161
+ fn=lambda: "",
162
+ outputs=msg
163
  ).then(
164
+ fn=generate_response,
165
+ inputs=[chatbot, system_message],
166
+ outputs=chatbot
167
+ )
168
+
169
+ # Prepare button handler
170
+ prepare_button.click(
171
+ fn=handle_prepare,
172
+ inputs=[prepare_topic, chatbot],
173
+ outputs=chatbot
174
  ).then(
175
+ fn=generate_response,
176
  inputs=[chatbot, system_message],
177
+ outputs=chatbot
178
  )
179
 
180
  # Clear button handler
181
+ clear.click(fn=clear_chat, outputs=[chatbot, msg])
182
 
183
  if __name__ == "__main__":
184
  demo.launch()