barunsaha commited on
Commit
f2885fb
1 Parent(s): 7606a6a

Create PPTX file and allow to download

Browse files
Files changed (1) hide show
  1. chat_app.py +70 -4
chat_app.py CHANGED
@@ -1,5 +1,8 @@
1
  import logging
 
2
  import random
 
 
3
 
4
  import json5
5
  import streamlit as st
@@ -10,8 +13,7 @@ from langchain_core.prompts import ChatPromptTemplate
10
  from langchain_core.runnables.history import RunnableWithMessageHistory
11
 
12
  from global_config import GlobalConfig
13
- from helpers import llm_helper
14
-
15
 
16
  APP_TEXT = json5.loads(open(GlobalConfig.APP_STRINGS_FILE, 'r', encoding='utf-8').read())
17
  # langchain.debug = True
@@ -89,7 +91,8 @@ def set_up_chat_ui():
89
  )
90
 
91
  for msg in history.messages:
92
- st.chat_message(msg.type).markdown(msg.content)
 
93
 
94
  progress_bar.progress(100, text='Done!')
95
  progress_bar.empty()
@@ -101,11 +104,74 @@ def set_up_chat_ui():
101
  logger.debug('User input: %s', prompt)
102
  st.chat_message('user').write(prompt)
103
 
 
 
104
  # As usual, new messages are added to StreamlitChatMessageHistory when the Chain is called
105
  config = {'configurable': {'session_id': 'any'}}
106
- response = chain_with_history.invoke({'question': prompt}, config)
107
  st.chat_message('ai').markdown('```json\n' + response)
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
  def main():
111
  """
 
1
  import logging
2
+ import pathlib
3
  import random
4
+ import tempfile
5
+ from typing import List
6
 
7
  import json5
8
  import streamlit as st
 
13
  from langchain_core.runnables.history import RunnableWithMessageHistory
14
 
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
 
91
  )
92
 
93
  for msg in history.messages:
94
+ # st.chat_message(msg.type).markdown(msg.content)
95
+ st.chat_message(msg.type).code(msg.content, language='json')
96
 
97
  progress_bar.progress(100, text='Done!')
98
  progress_bar.empty()
 
104
  logger.debug('User input: %s', prompt)
105
  st.chat_message('user').write(prompt)
106
 
107
+ progress_bar_pptx = st.progress(0, 'Calling LLM...')
108
+
109
  # As usual, new messages are added to StreamlitChatMessageHistory when the Chain is called
110
  config = {'configurable': {'session_id': 'any'}}
111
+ response: str = chain_with_history.invoke({'question': prompt}, config)
112
  st.chat_message('ai').markdown('```json\n' + response)
113
 
114
+ # The content has been generated as JSON
115
+ # There maybe trailing ``` at the end of the response -- remove them
116
+ # To be careful: ``` may be part of the content as well when code is generated
117
+ str_len = len(response)
118
+ response_cleaned = response
119
+
120
+ progress_bar_pptx.progress(50, 'Analyzing response...')
121
+
122
+ try:
123
+ idx = response.rindex('```')
124
+ logger.debug('str_len: %d, idx of ```: %d', str_len, idx)
125
+
126
+ if idx + 3 == str_len:
127
+ # The response ends with ``` -- most likely the end of JSON response string
128
+ response_cleaned = response[:idx]
129
+ elif idx + 3 < str_len:
130
+ # Looks like there are some more content beyond the last ```
131
+ # In the best case, it would be some additional plain-text response from the LLM
132
+ # and is unlikely to contain } or ] that are present in JSON
133
+ if '}' not in response[idx + 3:]: # the remainder of the text
134
+ response_cleaned = response[:idx]
135
+ except ValueError:
136
+ # No ``` found
137
+ pass
138
+
139
+ # Now create the PPT file
140
+ progress_bar_pptx.progress(75, 'Creating the slide deck...give it a moment')
141
+ generate_slide_deck(response_cleaned, pptx_template='Blank')
142
+ progress_bar_pptx.progress(100, text='Done!')
143
+
144
+
145
+ def generate_slide_deck(json_str: str, pptx_template: str) -> List:
146
+ """
147
+ Create a slide deck.
148
+
149
+ :param json_str: The content in *valid* JSON format.
150
+ :param pptx_template: The PPTX template name.
151
+ :return: A list of all slide headers and the title.
152
+ """
153
+
154
+ # # Get a unique name for the file to save -- use the session ID
155
+ # ctx = st_sr.get_script_run_ctx()
156
+ # session_id = ctx.session_id
157
+ # timestamp = time.time()
158
+ # output_file_name = f'{session_id}_{timestamp}.pptx'
159
+
160
+ temp = tempfile.NamedTemporaryFile(delete=False, suffix='.pptx')
161
+ path = pathlib.Path(temp.name)
162
+
163
+ logger.info('Creating PPTX file...')
164
+ all_headers = pptx_helper.generate_powerpoint_presentation(
165
+ json_str,
166
+ slides_template=pptx_template,
167
+ output_file_path=path
168
+ )
169
+
170
+ with open(path, 'rb') as f:
171
+ st.download_button('Download PPTX file ⇩', f, file_name='Presentation.pptx')
172
+
173
+ return all_headers
174
+
175
 
176
  def main():
177
  """