Spaces:
Runtime error
Runtime error
File size: 9,099 Bytes
2605d55 1189403 2605d55 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
import pathlib
import logging
import tempfile
from typing import List, Tuple
import json5
import metaphor_python as metaphor
import streamlit as st
from helpers import llm_helper, pptx_helper
from global_config import GlobalConfig
APP_TEXT = json5.loads(open(GlobalConfig.APP_STRINGS_FILE, 'r', encoding='utf-8').read())
GB_CONVERTER = 2 ** 30
logger = logging.getLogger(__name__)
@st.cache_data
def get_contents_wrapper(text: str) -> str:
"""
Fetch and cache the slide deck contents on a topic by calling an external API.
:param text: The presentation topic.
:return: The slide deck contents or outline in JSON format.
"""
logger.info('LLM call because of cache miss...')
return llm_helper.generate_slides_content(text).strip()
@st.cache_resource
def get_metaphor_client_wrapper() -> metaphor.Metaphor:
"""
Create a Metaphor client for semantic Web search.
:return: Metaphor instance.
"""
return metaphor.Metaphor(api_key=GlobalConfig.METAPHOR_API_KEY)
@st.cache_data
def get_web_search_results_wrapper(text: str) -> List[Tuple[str, str]]:
"""
Fetch and cache the Web search results on a given topic.
:param text: The topic.
:return: A list of (title, link) tuples.
"""
results = []
search_results = get_metaphor_client_wrapper().search(
text,
use_autoprompt=True,
num_results=5
)
for a_result in search_results.results:
results.append((a_result.title, a_result.url))
return results
def build_ui():
"""
Display the input elements for content generation. Only covers the first step.
"""
# get_disk_used_percentage()
st.title(APP_TEXT['app_name'])
st.subheader(APP_TEXT['caption'])
st.markdown(
'Powered by'
' [Mistral-7B-Instruct-v0.2](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2).'
)
st.markdown(
'*If the JSON is generated or parsed incorrectly, try again later by making minor changes'
' to the input text.*'
)
with st.form('my_form'):
# Topic input
try:
with open(GlobalConfig.PRELOAD_DATA_FILE, 'r', encoding='utf-8') as in_file:
preload_data = json5.loads(in_file.read())
except (FileExistsError, FileNotFoundError):
preload_data = {'topic': '', 'audience': ''}
topic = st.text_area(
APP_TEXT['input_labels'][0],
value=preload_data['topic']
)
texts = list(GlobalConfig.PPTX_TEMPLATE_FILES.keys())
captions = [GlobalConfig.PPTX_TEMPLATE_FILES[x]['caption'] for x in texts]
pptx_template = st.radio(
'Select a presentation template:',
texts,
captions=captions,
horizontal=True
)
st.divider()
submit = st.form_submit_button('Generate slide deck')
if submit:
# st.write(f'Clicked {time.time()}')
st.session_state.submitted = True
# https://github.com/streamlit/streamlit/issues/3832#issuecomment-1138994421
if 'submitted' in st.session_state:
progress_text = 'Generating the slides...give it a moment'
progress_bar = st.progress(0, text=progress_text)
topic_txt = topic.strip()
generate_presentation(topic_txt, pptx_template, progress_bar)
st.divider()
st.text(APP_TEXT['tos'])
st.text(APP_TEXT['tos2'])
st.markdown(
'![Visitors]'
'(https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2Fbarunsaha%2Fslide-deck-ai&countColor=%23263759)'
)
def generate_presentation(topic: str, pptx_template: str, progress_bar):
"""
Process the inputs to generate the slides.
:param topic: The presentation topic based on which contents are to be generated.
:param pptx_template: The PowerPoint template name to be used.
:param progress_bar: Progress bar from the page.
"""
topic_length = len(topic)
logger.debug('Input length:: topic: %s', topic_length)
if topic_length >= 10:
logger.debug('Topic: %s', topic)
target_length = min(topic_length, GlobalConfig.LLM_MODEL_MAX_INPUT_LENGTH)
try:
# Step 1: Generate the contents in JSON format using an LLM
json_str = process_slides_contents(topic[:target_length], progress_bar)
logger.debug('Truncated topic: %s', topic[:target_length])
logger.debug('Length of JSON: %d', len(json_str))
# Step 2: Generate the slide deck based on the template specified
if len(json_str) > 0:
st.info(
'Tip: The generated content doesn\'t look so great?'
' Need alternatives? Just change your description text and try again.',
icon="💡️"
)
else:
st.error(
'Unfortunately, JSON generation failed, so the next steps would lead'
' to nowhere. Try again or come back later.'
)
return
all_headers = generate_slide_deck(json_str, pptx_template, progress_bar)
# Step 3: Bonus stuff: Web references and AI art
show_bonus_stuff(all_headers)
except ValueError as ve:
st.error(f'Unfortunately, an error occurred: {ve}! '
f'Please change the text, try again later, or report it, sharing your inputs.')
else:
st.error('Not enough information provided! Please be little more descriptive :)')
def process_slides_contents(text: str, progress_bar: st.progress) -> str:
"""
Convert given text into structured data and display. Update the UI.
:param text: The topic description for the presentation.
:param progress_bar: Progress bar for this step.
:return: The contents as a JSON-formatted string.
"""
json_str = ''
try:
logger.info('Calling LLM for content generation on the topic: %s', text)
json_str = get_contents_wrapper(text)
except Exception as ex:
st.error(
f'An exception occurred while trying to convert to JSON. It could be because of heavy'
f' traffic or something else. Try doing it again or try again later.'
f'\nError message: {ex}'
)
progress_bar.progress(50, text='Contents generated')
with st.expander('The generated contents (in JSON format)'):
st.code(json_str, language='json')
return json_str
def generate_slide_deck(json_str: str, pptx_template: str, progress_bar) -> List:
"""
Create a slide deck.
:param json_str: The contents in JSON format.
:param pptx_template: The PPTX template name.
:param progress_bar: Progress bar.
:return: A list of all slide headers and the title.
"""
progress_text = 'Creating the slide deck...give it a moment'
progress_bar.progress(75, text=progress_text)
# # 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
)
progress_bar.progress(100, text='Done!')
with open(path, 'rb') as f:
st.download_button('Download PPTX file', f, file_name='Presentation.pptx')
if temp:
temp.close()
return all_headers
def show_bonus_stuff(ppt_headers: List[str]):
"""
Show bonus stuff for the presentation.
:param ppt_headers: A list of the slide headings.
"""
# Use the presentation title and the slide headers to find relevant info online
logger.info('Calling Metaphor search...')
ppt_text = ' '.join(ppt_headers)
search_results = get_web_search_results_wrapper(ppt_text)
md_text_items = []
for (title, link) in search_results:
md_text_items.append(f'[{title}]({link})')
with st.expander('Related Web references'):
st.markdown('\n\n'.join(md_text_items))
logger.info('Done!')
# # Avoid image generation. It costs time and an API call, so just limit to the text generation.
# with st.expander('AI-generated image on the presentation topic'):
# logger.info('Calling SDXL for image generation...')
# # img_empty.write('')
# # img_text.write(APP_TEXT['image_info'])
# image = get_ai_image_wrapper(ppt_text)
#
# if len(image) > 0:
# image = base64.b64decode(image)
# st.image(image, caption=ppt_text)
# st.info('Tip: Right-click on the image to save it.', icon="💡️")
# logger.info('Image added')
def main():
"""
Trigger application run.
"""
build_ui()
if __name__ == '__main__':
main()
|