barunsaha commited on
Commit
8a486f9
1 Parent(s): ec53f85

Store download file name in session and display the button again on app reload

Browse files
Files changed (1) hide show
  1. chat_app.py +70 -32
chat_app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import logging
2
  import pathlib
3
  import random
@@ -15,7 +16,9 @@ from langchain_core.runnables.history import RunnableWithMessageHistory
15
  from global_config import GlobalConfig
16
  from helpers import llm_helper, pptx_helper
17
 
 
18
  APP_TEXT = json5.loads(open(GlobalConfig.APP_STRINGS_FILE, 'r', encoding='utf-8').read())
 
19
  # langchain.debug = True
20
  # langchain.verbose = True
21
 
@@ -82,7 +85,6 @@ def set_up_chat_ui():
82
  template = in_file.read()
83
 
84
  prompt = ChatPromptTemplate.from_template(template)
85
-
86
  chain = prompt | llm
87
 
88
  chain_with_history = RunnableWithMessageHistory(
@@ -103,6 +105,11 @@ def set_up_chat_ui():
103
  # st.chat_message(msg.type).markdown(msg.content)
104
  st.chat_message(msg.type).code(msg.content, language='json')
105
 
 
 
 
 
 
106
  progress_bar.progress(100, text='Done!')
107
  progress_bar.empty()
108
 
@@ -123,28 +130,9 @@ def set_up_chat_ui():
123
  # The content has been generated as JSON
124
  # There maybe trailing ``` at the end of the response -- remove them
125
  # To be careful: ``` may be part of the content as well when code is generated
126
- str_len = len(response)
127
- response_cleaned = response
128
-
129
  progress_bar_pptx.progress(50, 'Analyzing response...')
130
 
131
- try:
132
- idx = response.rindex('```')
133
- logger.debug('str_len: %d, idx of ```: %d', str_len, idx)
134
-
135
- if idx + 3 == str_len:
136
- # The response ends with ``` -- most likely the end of JSON response string
137
- response_cleaned = response[:idx]
138
- elif idx + 3 < str_len:
139
- # Looks like there are some more content beyond the last ```
140
- # In the best case, it would be some additional plain-text response from the LLM
141
- # and is unlikely to contain } or ] that are present in JSON
142
- if '}' not in response[idx + 3:]: # the remainder of the text
143
- response_cleaned = response[:idx]
144
- except ValueError:
145
- # No ``` found
146
- pass
147
-
148
  # Now create the PPT file
149
  progress_bar_pptx.progress(75, 'Creating the slide deck...give it a moment')
150
  generate_slide_deck(response_cleaned)
@@ -159,28 +147,78 @@ def generate_slide_deck(json_str: str) -> List:
159
  :return: A list of all slide headers and the title.
160
  """
161
 
162
- # # Get a unique name for the file to save -- use the session ID
163
- # ctx = st_sr.get_script_run_ctx()
164
- # session_id = ctx.session_id
165
- # timestamp = time.time()
166
- # output_file_name = f'{session_id}_{timestamp}.pptx'
167
-
168
- temp = tempfile.NamedTemporaryFile(delete=False, suffix='.pptx')
169
- path = pathlib.Path(temp.name)
170
 
171
- logger.info('Creating PPTX file...')
172
  all_headers = pptx_helper.generate_powerpoint_presentation(
173
  json_str,
174
  slides_template=pptx_template,
175
  output_file_path=path
176
  )
177
 
178
- with open(path, 'rb') as f:
179
- st.download_button('Download PPTX file ⇩', f, file_name='Presentation.pptx')
180
 
181
  return all_headers
182
 
183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  def main():
185
  """
186
  Trigger application run.
 
1
+ import datetime
2
  import logging
3
  import pathlib
4
  import random
 
16
  from global_config import GlobalConfig
17
  from helpers import llm_helper, pptx_helper
18
 
19
+
20
  APP_TEXT = json5.loads(open(GlobalConfig.APP_STRINGS_FILE, 'r', encoding='utf-8').read())
21
+ DOWNLOAD_FILE_KEY = 'download_file_name'
22
  # langchain.debug = True
23
  # langchain.verbose = True
24
 
 
85
  template = in_file.read()
86
 
87
  prompt = ChatPromptTemplate.from_template(template)
 
88
  chain = prompt | llm
89
 
90
  chain_with_history = RunnableWithMessageHistory(
 
105
  # st.chat_message(msg.type).markdown(msg.content)
106
  st.chat_message(msg.type).code(msg.content, language='json')
107
 
108
+ # The download button disappears on clicking (anywhere) because of app reload
109
+ # So, display it again
110
+ if DOWNLOAD_FILE_KEY in st.session_state:
111
+ _display_download_button(st.session_state[DOWNLOAD_FILE_KEY])
112
+
113
  progress_bar.progress(100, text='Done!')
114
  progress_bar.empty()
115
 
 
130
  # The content has been generated as JSON
131
  # There maybe trailing ``` at the end of the response -- remove them
132
  # To be careful: ``` may be part of the content as well when code is generated
133
+ response_cleaned = _clean_json(response)
 
 
134
  progress_bar_pptx.progress(50, 'Analyzing response...')
135
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  # Now create the PPT file
137
  progress_bar_pptx.progress(75, 'Creating the slide deck...give it a moment')
138
  generate_slide_deck(response_cleaned)
 
147
  :return: A list of all slide headers and the title.
148
  """
149
 
150
+ if DOWNLOAD_FILE_KEY in st.session_state:
151
+ path = pathlib.Path(st.session_state[DOWNLOAD_FILE_KEY])
152
+ logger.debug('DOWNLOAD_FILE_KEY found in session')
153
+ else:
154
+ temp = tempfile.NamedTemporaryFile(delete=False, suffix='.pptx')
155
+ path = pathlib.Path(temp.name)
156
+ st.session_state[DOWNLOAD_FILE_KEY] = str(path)
157
+ logger.debug('DOWNLOAD_FILE_KEY not found in session')
158
 
159
+ logger.debug('Creating PPTX file: %s...', st.session_state[DOWNLOAD_FILE_KEY])
160
  all_headers = pptx_helper.generate_powerpoint_presentation(
161
  json_str,
162
  slides_template=pptx_template,
163
  output_file_path=path
164
  )
165
 
166
+ _display_download_button(path)
 
167
 
168
  return all_headers
169
 
170
 
171
+ def _clean_json(json_str: str) -> str:
172
+ """
173
+ Attempt to clean a JSON response string from the LLM by removing the trailing ```
174
+ and any text beyond that. May not be always accurate.
175
+
176
+ :param json_str: The input string in JSON format.
177
+ :return: The "cleaned" JSON string.
178
+ """
179
+
180
+ str_len = len(json_str)
181
+ response_cleaned = json_str
182
+
183
+ try:
184
+ idx = json_str.rindex('```')
185
+ logger.debug(
186
+ 'Fixing JSON response: str_len: %d, idx of ```: %d',
187
+ str_len, idx
188
+ )
189
+
190
+ if idx + 3 == str_len:
191
+ # The response ends with ``` -- most likely the end of JSON response string
192
+ response_cleaned = json_str[:idx]
193
+ elif idx + 3 < str_len:
194
+ # Looks like there are some more content beyond the last ```
195
+ # In the best case, it would be some additional plain-text response from the LLM
196
+ # and is unlikely to contain } or ] that are present in JSON
197
+ if '}' not in json_str[idx + 3:]: # the remainder of the text
198
+ response_cleaned = json_str[:idx]
199
+ except ValueError:
200
+ # No ``` found
201
+ pass
202
+
203
+ return response_cleaned
204
+
205
+
206
+ def _display_download_button(file_path: pathlib.Path):
207
+ """
208
+ Display a download button to download a slide deck.
209
+
210
+ :param file_path: The path of the .pptx file.
211
+ """
212
+
213
+ with open(file_path, 'rb') as download_file:
214
+ st.download_button(
215
+ 'Download PPTX file ⬇️',
216
+ data=download_file,
217
+ file_name='Presentation.pptx',
218
+ key=datetime.datetime.now()
219
+ )
220
+
221
+
222
  def main():
223
  """
224
  Trigger application run.