Spaces:
Build error
Build error
Store download file name in session and display the button again on app reload
Browse files12311 unmodified lines1516171819202160 unmodified lines8283848586878814 unmodified lines10310410510610710814 unmodified lines1231241251261271281291301311321331341351361371381391401411421431441451461471481491508 unmodified lines159160161162163164165166167168169170171172173174175176177178179180181182183184185186import loggingimport pathlibimport random11 unmodified linesfrom global_config import GlobalConfigfrom helpers import llm_helper, pptx_helperAPP_TEXT = json5.loads(open(GlobalConfig.APP_STRINGS_FILE, 'r', encoding='utf-8').read())# langchain.debug = True# langchain.verbose = True60 unmodified linestemplate = in_file.read()prompt = ChatPromptTemplate.from_template(template)chain = prompt | llmchain_with_history = RunnableWithMessageHistory(14 unmodified lines# st.chat_message(msg.type).markdown(msg.content)st.chat_message(msg.type).code(msg.content, language='json')progress_bar.progress(100, text='Done!')progress_bar.empty()14 unmodified lines# The content has been generated as JSON# There maybe trailing ``` at the end of the response -- remove them# To be careful: ``` may be part of the content as well when code is generatedstr_len = len(response)response_cleaned = responseprogress_bar_pptx.progress(50, 'Analyzing response...')try:idx = response.rindex('```')logger.debug('str_len: %d, idx of ```: %d', str_len, idx)if idx + 3 == str_len:# The response ends with ``` -- most likely the end of JSON response stringresponse_cleaned = response[:idx]elif idx + 3 < str_len:# Looks like there are some more content beyond the last ```# In the best case, it would be some additional plain-text response from the LLM# and is unlikely to contain } or ] that are present in JSONif '}' not in response[idx + 3:]: # the remainder of the textresponse_cleaned = response[:idx]except ValueError:# No ``` foundpass# Now create the PPT fileprogress_bar_pptx.progress(75, 'Creating the slide deck...give it a moment')generate_slide_deck(response_cleaned)8 unmodified lines:return: A list of all slide headers and the title."""# # Get a unique name for the file to save -- use the session ID# ctx = st_sr.get_script_run_ctx()# session_id = ctx.session_id# timestamp = time.time()# output_file_name = f'{session_id}_{timestamp}.pptx'temp = tempfile.NamedTemporaryFile(delete=False, suffix='.pptx')path = pathlib.Path(temp.name)logger.info('Creating PPTX file...')all_headers = pptx_helper.generate_powerpoint_presentation(json_str,slides_template=pptx_template,output_file_path=path)with open(path, 'rb') as f:st.download_button('Download PPTX file ⇩', f, file_name='Presentation.pptx')return all_headersdef main():"""Trigger application run.123411 unmodified lines16171819202122232460 unmodified lines85868788899014 unmodified lines10510610710810911011111211311411514 unmodified lines1301311321331341351361371388 unmodified lines147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224import datetimeimport loggingimport pathlibimport random11 unmodified linesfrom global_config import GlobalConfigfrom helpers import llm_helper, pptx_helperAPP_TEXT = json5.loads(open(GlobalConfig.APP_STRINGS_FILE, 'r', encoding='utf-8').read())DOWNLOAD_FILE_KEY = 'download_file_name'# langchain.debug = True# langchain.verbose = True60 unmodified linestemplate = in_file.read()prompt = ChatPromptTemplate.from_template(template)chain = prompt | llmchain_with_history = RunnableWithMessageHistory(14 unmodified lines# st.chat_message(msg.type).markdown(msg.content)st.chat_message(msg.type).code(msg.content, language='json')# The download button disappears on clicking (anywhere) because of app reload# So, display it againif DOWNLOAD_FILE_KEY in st.session_state:_display_download_button(st.session_state[DOWNLOAD_FILE_KEY])progress_bar.progress(100, text='Done!')progress_bar.empty()14 unmodified lines# The content has been generated as JSON# There maybe trailing ``` at the end of the response -- remove them# To be careful: ``` may be part of the content as well when code is generatedresponse_cleaned = _clean_json(response)progress_bar_pptx.progress(50, 'Analyzing response...')# Now create the PPT fileprogress_bar_pptx.progress(75, 'Creating the slide deck...give it a moment')generate_slide_deck(response_cleaned)8 unmodified lines:return: A list of all slide headers and the title."""if DOWNLOAD_FILE_KEY in st.session_state:path = pathlib.Path(st.session_state[DOWNLOAD_FILE_KEY])logger.debug('DOWNLOAD_FILE_KEY found in session')else:temp = tempfile.NamedTemporaryFile(delete=False, suffix='.pptx')path = pathlib.Path(temp.name)st.session_state[DOWNLOAD_FILE_KEY] = str(path)logger.debug('DOWNLOAD_FILE_KEY not found in session')logger.debug('Creating PPTX file: %s...', st.session_state[DOWNLOAD_FILE_KEY])all_headers = pptx_helper.generate_powerpoint_presentation(json_str,slides_template=pptx_template,output_file_path=path)_display_download_button(path)return all_headersdef _clean_json(json_str: str) -> str:"""Attempt to clean a JSON response string from the LLM by removing the trailing ```and any text beyond that. May not be always accurate.:param json_str: The input string in JSON format.:return: The "cleaned" JSON string."""str_len = len(json_str)response_cleaned = json_strtry:idx = json_str.rindex('```')logger.debug('Fixing JSON response: str_len: %d, idx of ```: %d',str_len, idx)if idx + 3 == str_len:# The response ends with ``` -- most likely the end of JSON response stringresponse_cleaned = json_str[:idx]elif idx + 3 < str_len:# Looks like there are some more content beyond the last ```# In the best case, it would be some additional plain-text response from the LLM# and is unlikely to contain } or ] that are present in JSONif '}' not in json_str[idx + 3:]: # the remainder of the textresponse_cleaned = json_str[:idx]except ValueError:# No ``` foundpassreturn response_cleaneddef _display_download_button(file_path: pathlib.Path):"""Display a download button to download a slide deck.:param file_path: The path of the .pptx file."""with open(file_path, 'rb') as download_file:st.download_button('Download PPTX file ⬇️',data=download_file,file_name='Presentation.pptx',key=datetime.datetime.now())def main():"""Trigger application run.
chat_app.py+70-32