Spaces:
Runtime error
Runtime error
Fix #29: improve JSON handling and keys
Browse filesFiles changed (2)
- app.py+31-20
- helpers/pptx_helper.py+32-24
6 unmodified lines78910111213226 unmodified lines2402412422432442452461 unmodified line2482492502512522532542552562572582592602612624 unmodified lines2672682692702712722732742752762772782792802812822832842852862872882892906 unmodified linesimport pathlibimport randomimport tempfilefrom typing import Listimport json5import streamlit as st226 unmodified linesprogress_bar.progress(1.0, text='Done!')st.chat_message('ai').code(response, language='json')_display_download_button(path)logger.info('#messages in history / 2: %d',1 unmodified line)def generate_slide_deck(json_str: str) -> pathlib.Path:"""Create a slide deck and return the file path. In case there is any error creating the slidedeck, the path may be to an empty file.:param json_str: The content in *valid* JSON format.:return: The file of the .pptx file."""if DOWNLOAD_FILE_KEY in st.session_state:path = pathlib.Path(st.session_state[DOWNLOAD_FILE_KEY])else:4 unmodified linesif temp:temp.close()logger.debug('Creating PPTX file: %s...', st.session_state[DOWNLOAD_FILE_KEY])try:pptx_helper.generate_powerpoint_presentation(json_str,slides_template=pptx_template,output_file_path=path)except ValueError:st.error('Encountered error while parsing JSON...will fix it and retry')logger.error('Caught ValueError: trying again after repairing JSON...')pptx_helper.generate_powerpoint_presentation(text_helper.fix_malformed_json(json_str),slides_template=pptx_template,output_file_path=path)6 unmodified lines78910111213226 unmodified lines2402412422432442452462472481 unmodified line2502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862874 unmodified lines2922932942952962972982993003016 unmodified linesimport pathlibimport randomimport tempfilefrom typing import List, Unionimport json5import streamlit as st226 unmodified linesprogress_bar.progress(1.0, text='Done!')st.chat_message('ai').code(response, language='json')if path:_display_download_button(path)logger.info('#messages in history / 2: %d',1 unmodified line)def generate_slide_deck(json_str: str) -> Union[pathlib.Path, None]:"""Create a slide deck and return the file path. In case there is any error creating the slidedeck, the path may be to an empty file.:param json_str: The content in *valid* JSON format.:return: The path to the .pptx file or `None` in case of error."""try:parsed_data = json5.loads(json_str)except ValueError:st.error('Encountered error while parsing JSON...will fix it and retry')logger.error('Caught ValueError: trying again after repairing JSON...')try:parsed_data = json5.loads(text_helper.fix_malformed_json(json_str))except ValueError:st.error('Encountered an error again while fixing JSON...''the slide deck cannot be created, unfortunately ☹''\nPlease try again later.')logger.error('Caught ValueError: failed to repair JSON!')return Noneif DOWNLOAD_FILE_KEY in st.session_state:path = pathlib.Path(st.session_state[DOWNLOAD_FILE_KEY])else:4 unmodified linesif temp:temp.close()try:logger.debug('Creating PPTX file: %s...', st.session_state[DOWNLOAD_FILE_KEY])pptx_helper.generate_powerpoint_presentation(parsed_data,slides_template=pptx_template,output_file_path=path)
81 unmodified lines828384858687888990919293949596979899100101102134 unmodified lines23723823924024124224324424524624724824925025125225325425525625743 unmodified lines30130230330430530630778 unmodified lines386387388389390391392173 unmodified lines566567568569570571356 unmodified lines9289299309319329339345 unmodified lines94094194294394494594627 unmodified lines97497597697797897998081 unmodified linesdef generate_powerpoint_presentation(structured_data: str,slides_template: str,output_file_path: pathlib.Path) -> List:"""Create and save a PowerPoint presentation file containing the content in JSON format.:param structured_data: The presentation contents as "JSON" (may contain trailing commas).:param slides_template: The PPTX template to use.:param output_file_path: The path of the PPTX file to save as.:return: A list of presentation title and slides headers."""# The structured "JSON" might contain trailing commas, so using json5parsed_data = json5.loads(structured_data)presentation = pptx.Presentation(GlobalConfig.PPTX_TEMPLATE_FILES[slides_template]['file'])slide_width_inch, slide_height_inch = _get_slide_width_height_inches(presentation)134 unmodified linesstatus = Falseif random.random() < IMAGE_DISPLAY_PROBABILITY:if random.random() < FOREGROUND_IMAGE_PROBABILITY:status = _handle_display_image__in_foreground(presentation,slide_json,slide_width_inch,slide_height_inch)else:status = _handle_display_image__in_background(presentation,slide_json,slide_width_inch,slide_height_inch)if status:return43 unmodified linesslide_height_inch: float) -> bool:"""Create a slide with text and image using a picture placeholder layout.:param presentation: The presentation object.:param slide_json: The content of the slide as JSON data.78 unmodified lines) -> bool:"""Add a slide with text and an image in the background. It works just like`_handle_default_display()` but with a background image added.:param presentation: The presentation object.:param slide_json: The content of the slide as JSON data.173 unmodified linesfor run in paragraph.runs:run.font.color.theme_color = pptx.enum.dml.MSO_THEME_COLOR.TEXT_2return Truereturn False356 unmodified lines"AI for predicting student performance and dropout rates"],"key_message": "AI is personalizing education and improving student outcomes","img_keywords": "education, personalized learning, intelligent tutoring, student performance"},{"heading": "Step-by-Step: AI Development Process",5 unmodified lines">> Deploy and monitor the AI system"],"key_message": "Developing AI involves a structured process from problem definition to deployment","img_keywords": "AI development process, problem definition, data collection, model training"},{"heading": "AI Icons: Key Aspects",27 unmodified linesgenerate_powerpoint_presentation(json5.loads(_JSON_DATA),output_file_path=path,slides_template='Minimalist Sales Pitch')print(f'File path: {path}')81 unmodified lines828384858687888990919293949596979899100134 unmodified lines23523623723823924024124224324424524624724824925025125225325425525643 unmodified lines30030130230330430530630778 unmodified lines386387388389390391392393173 unmodified lines567568569570571572573574575576577578579580356 unmodified lines9379389399409419425 unmodified lines94894995095195295395427 unmodified lines98298398498598698798881 unmodified linesdef generate_powerpoint_presentation(parsed_data: dict,slides_template: str,output_file_path: pathlib.Path) -> List:"""Create and save a PowerPoint presentation file containing the content in JSON format.:param parsed_data: The presentation content as parsed JSON data.:param slides_template: The PPTX template to use.:param output_file_path: The path of the PPTX file to save as.:return: A list of presentation title and slides headers."""presentation = pptx.Presentation(GlobalConfig.PPTX_TEMPLATE_FILES[slides_template]['file'])slide_width_inch, slide_height_inch = _get_slide_width_height_inches(presentation)134 unmodified linesstatus = Falseif 'img_keywords' in slide_json:if random.random() < IMAGE_DISPLAY_PROBABILITY:if random.random() < FOREGROUND_IMAGE_PROBABILITY:status = _handle_display_image__in_foreground(presentation,slide_json,slide_width_inch,slide_height_inch)else:status = _handle_display_image__in_background(presentation,slide_json,slide_width_inch,slide_height_inch)if status:return43 unmodified linesslide_height_inch: float) -> bool:"""Create a slide with text and image using a picture placeholder layout. If not image keyword isavailable, it will add only text to the slide.:param presentation: The presentation object.:param slide_json: The content of the slide as JSON data.78 unmodified lines) -> bool:"""Add a slide with text and an image in the background. It works just like`_handle_default_display()` but with a background image added. If not image keyword isavailable, it will add only text to the slide.:param presentation: The presentation object.:param slide_json: The content of the slide as JSON data.173 unmodified linesfor run in paragraph.runs:run.font.color.theme_color = pptx.enum.dml.MSO_THEME_COLOR.TEXT_2_add_text_at_bottom(slide=slide,slide_width_inch=slide_width_inch,slide_height_inch=slide_height_inch,text='More icons available in the SlideDeck AI repository',hyperlink='https://github.com/barun-saha/slide-deck-ai/tree/main/icons/png128')return Truereturn False356 unmodified lines"AI for predicting student performance and dropout rates"],"key_message": "AI is personalizing education and improving student outcomes",},{"heading": "Step-by-Step: AI Development Process",5 unmodified lines">> Deploy and monitor the AI system"],"key_message": "Developing AI involves a structured process from problem definition to deployment","img_keywords": ""},{"heading": "AI Icons: Key Aspects",27 unmodified linesgenerate_powerpoint_presentation(json5.loads(_JSON_DATA),output_file_path=path,slides_template='Basic')print(f'File path: {path}')
app.py+31-20
helpers/pptx_helper.py+32-24