Spaces:
Build error
Build error
Create PPTX file and allow to download
Browse files123454 unmodified lines101112131415161771 unmodified lines899091929394955 unmodified lines101102103104105106107108109110111import loggingimport randomimport json5import streamlit as st4 unmodified linesfrom langchain_core.runnables.history import RunnableWithMessageHistoryfrom global_config import GlobalConfigfrom helpers import llm_helperAPP_TEXT = json5.loads(open(GlobalConfig.APP_STRINGS_FILE, 'r', encoding='utf-8').read())# langchain.debug = True71 unmodified lines)for msg in history.messages:st.chat_message(msg.type).markdown(msg.content)progress_bar.progress(100, text='Done!')progress_bar.empty()5 unmodified lineslogger.debug('User input: %s', prompt)st.chat_message('user').write(prompt)# As usual, new messages are added to StreamlitChatMessageHistory when the Chain is calledconfig = {'configurable': {'session_id': 'any'}}response = chain_with_history.invoke({'question': prompt}, config)st.chat_message('ai').markdown('```json\n' + response)def main():"""123456784 unmodified lines1314151617181971 unmodified lines91929394959697985 unmodified lines104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177import loggingimport pathlibimport randomimport tempfilefrom typing import Listimport json5import streamlit as st4 unmodified linesfrom langchain_core.runnables.history import RunnableWithMessageHistoryfrom 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 = True71 unmodified lines)for msg in history.messages:# 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()5 unmodified lineslogger.debug('User input: %s', prompt)st.chat_message('user').write(prompt)progress_bar_pptx = st.progress(0, 'Calling LLM...')# As usual, new messages are added to StreamlitChatMessageHistory when the Chain is calledconfig = {'configurable': {'session_id': 'any'}}response: str = chain_with_history.invoke({'question': prompt}, config)st.chat_message('ai').markdown('```json\n' + response)# 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, pptx_template='Blank')progress_bar_pptx.progress(100, text='Done!')def generate_slide_deck(json_str: str, pptx_template: str) -> List:"""Create a slide deck.:param json_str: The content in *valid* JSON format.:param pptx_template: The PPTX template name.: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():"""
chat_app.py+70-4