Spaces:
Runtime error
Runtime error
Merge pull request #7 from barun-saha/chat-interface
Browse filesFiles changed (13)
- .streamlit/config.tomlAdded+10
- README.md+31-10
- app.py+282-225
- global_config.py+30-2
- helpers/__init__.pyAdded
- llm_helper.py → helpers/llm_helper.pyRenamed+51-16
- pptx_helper.py → helpers/pptx_helper.pyRenamed+18-15
- helpers/text_helper.pyAdded+56
- langchain_templates/chat_prompts/initial_template.txtAdded+41
- langchain_templates/chat_prompts/refinement_template.txtAdded+49
- legacy_app.pyAdded+294
- requirements.txt+6-1
- strings.json+12-4
12345678910[server]runOnSave = trueheadless = falsemaxUploadSize = 0
[browser]gatherUsageStats = false
[theme]base = "dark"3 unmodified lines456789105 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950513 unmodified linescolorFrom: yellowcolorTo: greensdk: streamlitsdk_version: 1.26.0app_file: app.pypinned: falselicense: mit5 unmodified linesWith SlideDeck AI, co-create slide decks on any topic with Generative Artificial Intelligence.Describe your topic and let SlideDeck AI generate a PowerPoint slide deck for you—it's as simple as that!SlideDeck AI is powered by [Mistral 7B Instruct](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1).Originally, it was built using the Llama 2 API provided by Clarifai.# ProcessSlideDeck AI works in the following way:1. Given a topic description, it uses Mistral 7B Instruct to generate the outline/contents of the slides.The output is generated as structured JSON data based on a pre-defined schema.2. Subsequently, it uses the `python-pptx` library to generate the slides,based on the JSON data from the previous step.Here, a user can choose from a set of three pre-defined presentation templates.3. In addition, it uses Metaphor to fetch Web pages related to the topic.4. ~~Finally, it uses Stable Diffusion 2 to generate an image, based on the title and each slide heading.~~# Local DevelopmentSlideDeck AI uses [Mistral 7B Instruct](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1)via the Hugging Face Inference API.To run this project by yourself, you need to provide the `HUGGINGFACEHUB_API_TOKEN` and `METAPHOR_API_KEY` API keys,for example, in a `.env` file. Visit the respective websites to obtain the keys.# Live Demo[SlideDeck AI](https://huggingface.co/spaces/barunsaha/slide-deck-ai)# AwardSlideDeck AI has won the 3rd Place in the [Llama 2 Hackathon with Clarifai](https://lablab.ai/event/llama-2-hackathon-with-clarifai).3 unmodified lines456789105 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071723 unmodified linescolorFrom: yellowcolorTo: greensdk: streamlitsdk_version: 1.32.2app_file: app.pypinned: falselicense: mit5 unmodified linesWith SlideDeck AI, co-create slide decks on any topic with Generative Artificial Intelligence.Describe your topic and let SlideDeck AI generate a PowerPoint slide deck for you—it's as simple as that!SlideDeck AI is powered by [Mistral 7B Instruct](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2).Originally, it was built using the Llama 2 API provided by Clarifai.*Update*: Legacy SlideDeck AI allowed one-shot generation of a slide deck based on the inputs.In contrast, SlideDeck AI *Reloaded* enables an iterative workflow with a conversational interface,where you can create and improve the presentation.# ProcessSlideDeck AI works in the following way:1. Given a topic description, it uses Mistral 7B Instruct to generate the *initial* content of the slides.The output is generated as structured JSON data based on a pre-defined schema.2. Subsequently, it uses the `python-pptx` library to generate the slides,based on the JSON data from the previous step.A user can choose from a set of three pre-defined presentation templates.3. At this stage onward, a user can provide additional instructions to refine the content.For example, one can ask to add another slide or modify an existing slide.A history of instructions is maintained.4. Every time SlideDeck AI generates a PowerPoint presentation, a download button is provided.Clicking on the button will download the file.# Known Issues- **Incorrect JSON**: Sometimes the JSON generated could be syntactically incorrect.You can try asking SlideDeck AI to regenerate the content and fix the JSON syntax error.This, however, is not guaranteed to work. The alternative is to reload the website and try again.- **Connection timeout**: Requests sent to the Hugging Face Inference endpoint might time out.A maximum of five retries are attempted. If it still does not work, wait for a while and try again.The following is not an issue but might appear as a strange behavior:- **Cannot paste text in the input box**: If the length of the copied text is greater than the maximumnumber of allowed characters in the textbox, pasting would not work.# Local DevelopmentSlideDeck AI uses [Mistral 7B Instruct](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2)via the Hugging Face Inference API.To run this project by yourself, you need to provide the `HUGGINGFACEHUB_API_TOKEN` API key,for example, in a `.env` file. Visit the respective websites to obtain the keys.# Live Demo- [SlideDeck AI](https://huggingface.co/spaces/barunsaha/slide-deck-ai) on Hugging Face Spaces- [Demo video](https://youtu.be/QvAKzNKtk9k) of the chat interface on YouTube# AwardSlideDeck AI has won the 3rd Place in the [Llama 2 Hackathon with Clarifai](https://lablab.ai/event/llama-2-hackathon-with-clarifai) in 2023.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309import pathlibimport loggingimport tempfilefrom typing import List, Tupleimport json5import metaphor_python as metaphorimport streamlit as stimport llm_helperimport pptx_helperfrom global_config import GlobalConfigAPP_TEXT = json5.loads(open(GlobalConfig.APP_STRINGS_FILE, 'r', encoding='utf-8').read())GB_CONVERTER = 2 ** 30logging.basicConfig(level=GlobalConfig.LOG_LEVEL,format='%(asctime)s - %(message)s',)@st.cache_datadef 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"""logging.info('LLM call because of cache miss...')return llm_helper.generate_slides_content(text).strip()@st.cache_resourcedef 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_datadef 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 get_disk_used_percentage() -> float:# """# Compute the disk usage.## :return: Percentage of the disk space currently used# """## total, used, free = shutil.disk_usage(__file__)# total = total // GB_CONVERTER# used = used // GB_CONVERTER# free = free // GB_CONVERTER# used_perc = 100.0 * used / total## logging.debug(f'Total: {total} GB\n'# f'Used: {used} GB\n'# f'Free: {free} GB')## logging.debug('\n'.join(os.listdir()))## return used_percdef 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 inputtry: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-1138994421if '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:return:"""topic_length = len(topic)logging.debug('Input length:: topic: %s', topic_length)if topic_length >= 10:logging.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 LLMjson_str = process_slides_contents(topic[:target_length], progress_bar)logging.debug('Truncated topic: %s', topic[:target_length])logging.debug('Length of JSON: %d', len(json_str))# Step 2: Generate the slide deck based on the template specifiedif 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.')returnall_headers = generate_slide_deck(json_str, pptx_template, progress_bar)# Step 3: Bonus stuff: Web references and AI artshow_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:logging.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_strdef 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)logging.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')return all_headersdef 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 onlinelogging.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))logging.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'):# logging.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="💡️")# logging.info('Image added')def main():123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366import datetimeimport loggingimport pathlibimport randomimport tempfilefrom typing import Listimport json5import streamlit as stfrom langchain_community.chat_message_histories import (StreamlitChatMessageHistory)from langchain_core.messages import HumanMessagefrom langchain_core.prompts import ChatPromptTemplate# from transformers import AutoTokenizerfrom global_config import GlobalConfigfrom helpers import llm_helper, pptx_helper, text_helper@st.cache_datadef _load_strings() -> dict:"""Load various strings to be displayed in the app.:return: The dictionary of strings."""with open(GlobalConfig.APP_STRINGS_FILE, 'r', encoding='utf-8') as in_file:return json5.loads(in_file.read())@st.cache_datadef _get_prompt_template(is_refinement: bool) -> str:"""Return a prompt template.:param is_refinement: Whether this is the initial or refinement prompt.:return: The prompt template as f-string."""if is_refinement:with open(GlobalConfig.REFINEMENT_PROMPT_TEMPLATE, 'r', encoding='utf-8') as in_file:template = in_file.read()else:with open(GlobalConfig.INITIAL_PROMPT_TEMPLATE, 'r', encoding='utf-8') as in_file:template = in_file.read()return template# @st.cache_resource# def _get_tokenizer() -> AutoTokenizer:# """# Get Mistral tokenizer for counting tokens.## :return: The tokenizer.# """## return AutoTokenizer.from_pretrained(# pretrained_model_name_or_path=GlobalConfig.HF_LLM_MODEL_NAME# )APP_TEXT = _load_strings()# Session variablesCHAT_MESSAGES = 'chat_messages'DOWNLOAD_FILE_KEY = 'download_file_name'IS_IT_REFINEMENT = 'is_it_refinement'logger = logging.getLogger(__name__)progress_bar = st.progress(0, text='Setting up SlideDeck AI...')texts = list(GlobalConfig.PPTX_TEMPLATE_FILES.keys())captions = [GlobalConfig.PPTX_TEMPLATE_FILES[x]['caption'] for x in texts]pptx_template = st.sidebar.radio('Select a presentation template:',texts,captions=captions,horizontal=True)def display_page_header_content():"""Display content in the page header."""st.title(APP_TEXT['app_name'])st.subheader(APP_TEXT['caption'])st.markdown('' # noqa: E501)def display_page_footer_content():"""Display content in the page footer."""st.text(APP_TEXT['tos'] + '\n\n' + APP_TEXT['tos2'])def build_ui():"""Display the input elements for content generation."""display_page_header_content()with st.expander('Usage Policies and Limitations'):display_page_footer_content()progress_bar.progress(50, text='Setting up chat interface...')set_up_chat_ui()def set_up_chat_ui():"""Prepare the chat interface and related functionality."""with st.expander('Usage Instructions'):st.write(GlobalConfig.CHAT_USAGE_INSTRUCTIONS)st.markdown('SlideDeck AI is powered by'' [Mistral-7B-Instruct-v0.2](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2)')# view_messages = st.expander('View the messages in the session state')st.chat_message('ai').write(random.choice(APP_TEXT['ai_greetings']))progress_bar.progress(100, text='Done!')progress_bar.empty()history = StreamlitChatMessageHistory(key=CHAT_MESSAGES)if _is_it_refinement():template = _get_prompt_template(is_refinement=True)else:template = _get_prompt_template(is_refinement=False)prompt_template = ChatPromptTemplate.from_template(template)# Since Streamlit app reloads at every interaction, display the chat history# from the save session statefor msg in history.messages:msg_type = msg.typeif msg_type == 'user':st.chat_message(msg_type).write(msg.content)else:st.chat_message(msg_type).code(msg.content, language='json')if prompt := st.chat_input(placeholder=APP_TEXT['chat_placeholder'],max_chars=GlobalConfig.LLM_MODEL_MAX_INPUT_LENGTH):progress_bar_pptx = st.progress(0, 'Preparing to run...')if not text_helper.is_valid_prompt(prompt):st.error('Not enough information provided!'' Please be a little more descriptive and type a few words'' with a few characters :)')returnlogger.info('User input: %s | #characters: %d', prompt, len(prompt))st.chat_message('user').write(prompt)user_messages = _get_user_messages()user_messages.append(prompt)list_of_msgs = [f'{idx + 1}. {msg}' for idx, msg in enumerate(user_messages)]list_of_msgs = '\n'.join(list_of_msgs)if _is_it_refinement():formatted_template = prompt_template.format(**{'instructions': list_of_msgs,'previous_content': _get_last_response()})else:formatted_template = prompt_template.format(**{'question': prompt,})progress_bar_pptx.progress(5, 'Calling LLM...will retry if connection times out...')response: dict = llm_helper.hf_api_query({'inputs': formatted_template,'parameters': {'temperature': GlobalConfig.LLM_MODEL_TEMPERATURE,'min_length': GlobalConfig.LLM_MODEL_MIN_OUTPUT_LENGTH,'max_length': GlobalConfig.LLM_MODEL_MAX_OUTPUT_LENGTH,'max_new_tokens': GlobalConfig.LLM_MODEL_MAX_OUTPUT_LENGTH,'num_return_sequences': 1,'return_full_text': False,# "repetition_penalty": 0.0001},'options': {'wait_for_model': True,'use_cache': True}})if len(response) > 0 and 'generated_text' in response[0]:response: str = response[0]['generated_text'].strip()st.chat_message('ai').code(response, language='json')history.add_user_message(prompt)history.add_ai_message(response)# if GlobalConfig.COUNT_TOKENS:# tokenizer = _get_tokenizer()# tokens_count_in = len(tokenizer.tokenize(formatted_template))# tokens_count_out = len(tokenizer.tokenize(response))# logger.debug(# 'Tokens count:: input: %d, output: %d',# tokens_count_in, tokens_count_out# )# _display_messages_history(view_messages)# 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 generatedprogress_bar_pptx.progress(50, 'Analyzing response...')response_cleaned = text_helper.get_clean_json(response)logger.info('Cleaned JSON response:: original length: %d | cleaned length: %d',len(response), len(response_cleaned))logger.debug('Cleaned JSON: %s', response_cleaned)# Now create the PPT fileprogress_bar_pptx.progress(75, 'Creating the slide deck...give it a moment...')generate_slide_deck(response_cleaned)progress_bar_pptx.progress(100, text='Done!')logger.info('#messages in history / 2: %d',len(st.session_state[CHAT_MESSAGES]) / 2)def generate_slide_deck(json_str: str):"""Create a slide deck.:param json_str: The content in *valid* JSON format."""if DOWNLOAD_FILE_KEY in st.session_state:path = pathlib.Path(st.session_state[DOWNLOAD_FILE_KEY])else:temp = tempfile.NamedTemporaryFile(delete=False, suffix='.pptx')path = pathlib.Path(temp.name)st.session_state[DOWNLOAD_FILE_KEY] = str(path)if 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)_display_download_button(path)except ValueError as ve:st.error(f"{APP_TEXT['json_parsing_error']}"f"\n\nAdditional error info: {ve}"f"\n\nHere are some sample instructions that you could try to possibly fix this error;"f" if these don't work, try rephrasing or refreshing:"f"\n\n""- Regenerate content and fix the JSON error.""\n- Regenerate content and fix the JSON error. Quotes inside quotes should be escaped.")logger.error('%s', APP_TEXT['json_parsing_error'])logger.error('Additional error info: %s', str(ve))except Exception as ex:st.error(APP_TEXT['content_generation_error'])logger.error('Caught a generic exception: %s', str(ex))def _is_it_refinement() -> bool:"""Whether it is the initial prompt or a refinement.:return: True if it is the initial prompt; False otherwise."""if IS_IT_REFINEMENT in st.session_state:return Trueif len(st.session_state[CHAT_MESSAGES]) >= 2:# Prepare for the next callst.session_state[IS_IT_REFINEMENT] = Truereturn Truereturn Falsedef _get_user_messages() -> List[str]:"""Get a list of user messages submitted until now from the session state.:return: The list of user messages."""return [msg.content for msg in st.session_state[CHAT_MESSAGES] if isinstance(msg, HumanMessage)]def _get_last_response() -> str:"""Get the last response generated by AI.:return: The response text."""return st.session_state[CHAT_MESSAGES][-1].contentdef _display_messages_history(view_messages: st.expander):"""Display the history of messages.:param view_messages: The list of AI and Human messages."""with view_messages:view_messages.json(st.session_state[CHAT_MESSAGES])def _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():
1238 unmodified lines12131415161718192021222324252627289 unmodified lines383940import osfrom dataclasses import dataclass8 unmodified linesHF_LLM_MODEL_NAME = 'mistralai/Mistral-7B-Instruct-v0.2'LLM_MODEL_TEMPERATURE: float = 0.2LLM_MODEL_MIN_OUTPUT_LENGTH: int = 50LLM_MODEL_MAX_OUTPUT_LENGTH: int = 2000LLM_MODEL_MAX_INPUT_LENGTH: int = 300HUGGINGFACEHUB_API_TOKEN = os.environ.get('HUGGINGFACEHUB_API_TOKEN', '')METAPHOR_API_KEY = os.environ.get('METAPHOR_API_KEY', '')LOG_LEVEL = 'DEBUG'APP_STRINGS_FILE = 'strings.json'PRELOAD_DATA_FILE = 'examples/example_02.json'SLIDES_TEMPLATE_FILE = 'langchain_templates/template_combined.txt'JSON_TEMPLATE_FILE = 'langchain_templates/text_to_json_template_02.txt'PPTX_TEMPLATE_FILES = {'Blank': {9 unmodified lines'caption': 'Marvel in a monochrome dream'}}12348 unmodified lines13141516171819202122232425262728293031329 unmodified lines424344454647484950515253545556575859606162636465666768import loggingimport osfrom dataclasses import dataclass8 unmodified linesHF_LLM_MODEL_NAME = 'mistralai/Mistral-7B-Instruct-v0.2'LLM_MODEL_TEMPERATURE: float = 0.2LLM_MODEL_MIN_OUTPUT_LENGTH: int = 50LLM_MODEL_MAX_OUTPUT_LENGTH: int = 4096LLM_MODEL_MAX_INPUT_LENGTH: int = 750HUGGINGFACEHUB_API_TOKEN = os.environ.get('HUGGINGFACEHUB_API_TOKEN', '')METAPHOR_API_KEY = os.environ.get('METAPHOR_API_KEY', '')LOG_LEVEL = 'DEBUG'COUNT_TOKENS = FalseAPP_STRINGS_FILE = 'strings.json'PRELOAD_DATA_FILE = 'examples/example_02.json'SLIDES_TEMPLATE_FILE = 'langchain_templates/template_combined.txt'JSON_TEMPLATE_FILE = 'langchain_templates/text_to_json_template_02.txt'INITIAL_PROMPT_TEMPLATE = 'langchain_templates/chat_prompts/initial_template.txt'REFINEMENT_PROMPT_TEMPLATE = 'langchain_templates/chat_prompts/refinement_template.txt'PPTX_TEMPLATE_FILES = {'Blank': {9 unmodified lines'caption': 'Marvel in a monochrome dream'}}# This is a long text, so not incorporated as a string in `strings.json`CHAT_USAGE_INSTRUCTIONS = ('Briefly describe your topic of presentation in the textbox provided below.'' For example, "Make a slide deck on AI." Subsequently, you can add follow-up'' instructions, e.g., "Can you add a slide on GPUs?" You can also ask it to refine any'' particular slide, e.g., "Make the slide with title \'Examples of AI\' a bit more'' descriptive." See this [demo video](https://youtu.be/QvAKzNKtk9k).'' As another example, sometimes the formatting of generated Python code can be a bit weird.'' You can try it telling, "Split multi-line codes into multiple lines," and hope for a fix.''\n\n''SlideDeck AI generates only text content. It does not have access to the Web.''\n\n''If you like SlideDeck AI, please consider leaving a heart ❤️ on the'' [Hugging Face Space](https://huggingface.co/spaces/barunsaha/slide-deck-ai/) or'' a star ⭐ on [GitHub](https://github.com/barun-saha/slide-deck-ai).')logging.basicConfig(level=GlobalConfig.LOG_LEVEL,format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',datefmt='%Y-%m-%d %H:%M:%S')
123451 unmodified line789101112131415161718192021222324252627282930313233342 unmodified lines37383940414243441 unmodified line46474849505152532 unmodified lines565758596061627 unmodified lines70717273747576import loggingimport requestsfrom global_config import GlobalConfig1 unmodified lineHF_API_URL = f"https://api-inference.huggingface.co/models/{GlobalConfig.HF_LLM_MODEL_NAME}"HF_API_HEADERS = {"Authorization": f"Bearer {GlobalConfig.HUGGINGFACEHUB_API_TOKEN}"}logging.basicConfig(level=GlobalConfig.LOG_LEVEL,format='%(asctime)s - %(message)s',)# llm = Nonedef hf_api_query(payload: dict):"""Invoke HF inference end-point API.:param payload: The prompt for the LLM and related parameters:return: The output from the LLM"""try:response = requests.post(HF_API_URL, headers=HF_API_HEADERS, json=payload, timeout=15)result = response.json()except requests.exceptions.Timeout as te:logging.error('*** Error: hf_api_query timeout! %s', str(te))result = {}return result2 unmodified lines"""Generate the outline/contents of slides for a presentation on a given topic.:param topic: Topic on which slides are to be generated:return: The content in JSON format"""with open(GlobalConfig.SLIDES_TEMPLATE_FILE, 'r', encoding='utf-8') as in_file:1 unmodified linetemplate_txt = template_txt.replace('<REPLACE_PLACEHOLDER>', topic)output = hf_api_query({"inputs": template_txt,"parameters": {'temperature': GlobalConfig.LLM_MODEL_TEMPERATURE,'min_length': GlobalConfig.LLM_MODEL_MIN_OUTPUT_LENGTH,'max_length': GlobalConfig.LLM_MODEL_MAX_OUTPUT_LENGTH,2 unmodified lines'return_full_text': False,# "repetition_penalty": 0.0001},"options": {'wait_for_model': True,'use_cache': True}7 unmodified lines# logging.debug(f'{json_end_idx=}')output = output[:json_end_idx]logging.debug('generate_slides_content: output: %s', output)return output123456789101 unmodified line121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768692 unmodified lines72737475767778791 unmodified line81828384858687882 unmodified lines919293949596977 unmodified lines105106107108109110111import loggingimport requestsfrom requests.adapters import HTTPAdapterfrom urllib3.util import Retryfrom langchain_community.llms.huggingface_endpoint import HuggingFaceEndpointfrom langchain_core.language_models import LLMfrom global_config import GlobalConfig1 unmodified lineHF_API_URL = f"https://api-inference.huggingface.co/models/{GlobalConfig.HF_LLM_MODEL_NAME}"HF_API_HEADERS = {"Authorization": f"Bearer {GlobalConfig.HUGGINGFACEHUB_API_TOKEN}"}logger = logging.getLogger(__name__)retries = Retry(total=5,backoff_factor=0.25,backoff_jitter=0.3,status_forcelist=[502, 503, 504],allowed_methods={'POST'},)adapter = HTTPAdapter(max_retries=retries)http_session = requests.Session()http_session.mount('https://', adapter)http_session.mount('http://', adapter)def get_hf_endpoint() -> LLM:"""Get an LLM via the HuggingFaceEndpoint of LangChain.:return: The LLM."""logger.debug('Getting LLM via HF endpoint')return HuggingFaceEndpoint(repo_id=GlobalConfig.HF_LLM_MODEL_NAME,max_new_tokens=GlobalConfig.LLM_MODEL_MAX_OUTPUT_LENGTH,top_k=40,top_p=0.95,temperature=GlobalConfig.LLM_MODEL_TEMPERATURE,repetition_penalty=1.03,streaming=True,huggingfacehub_api_token=GlobalConfig.HUGGINGFACEHUB_API_TOKEN,return_full_text=False,stop_sequences=['</s>'],)def hf_api_query(payload: dict) -> dict:"""Invoke HF inference end-point API.:param payload: The prompt for the LLM and related parameters.:return: The output from the LLM."""try:response = http_session.post(HF_API_URL, headers=HF_API_HEADERS, json=payload, timeout=15)result = response.json()except requests.exceptions.Timeout as te:logger.error('*** Error: hf_api_query timeout! %s', str(te))result = []return result2 unmodified lines"""Generate the outline/contents of slides for a presentation on a given topic.:param topic: Topic on which slides are to be generated.:return: The content in JSON format."""with open(GlobalConfig.SLIDES_TEMPLATE_FILE, 'r', encoding='utf-8') as in_file:1 unmodified linetemplate_txt = template_txt.replace('<REPLACE_PLACEHOLDER>', topic)output = hf_api_query({'inputs': template_txt,'parameters': {'temperature': GlobalConfig.LLM_MODEL_TEMPERATURE,'min_length': GlobalConfig.LLM_MODEL_MIN_OUTPUT_LENGTH,'max_length': GlobalConfig.LLM_MODEL_MAX_OUTPUT_LENGTH,2 unmodified lines'return_full_text': False,# "repetition_penalty": 0.0001},'options': {'wait_for_model': True,'use_cache': True}7 unmodified lines# logging.debug(f'{json_end_idx=}')output = output[:json_end_idx]logger.debug('generate_slides_content: output: %s', output)return output
1 unmodified line23456720 unmodified lines282930313233343536373839404142434411 unmodified lines56575859606162636465666768697071724 unmodified lines7778798081828341 unmodified lines125126127128129130131132133106 unmodified lines2402412421 unmodified lineimport pathlibimport reimport tempfilefrom typing import List, Tupleimport json520 unmodified lines}'''logging.basicConfig(level=GlobalConfig.LOG_LEVEL,format='%(asctime)s - %(message)s',)def remove_slide_number_from_heading(header: str) -> str:"""Remove the slide number from a given slide header.:param header: The header of a slide"""if PATTERN.match(header):11 unmodified lines"""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)logging.debug("*** Using PPTX template: %s",GlobalConfig.PPTX_TEMPLATE_FILES[slides_template]['file'])presentation = pptx.Presentation(GlobalConfig.PPTX_TEMPLATE_FILES[slides_template]['file'])4 unmodified linestitle = slide.shapes.titlesubtitle = slide.placeholders[1]title.text = parsed_data['title']logging.debug('Presentation title is: %s', title.text)subtitle.text = 'by Myself and SlideDeck AI :)'all_headers = [title.text, ]41 unmodified linesFlatten a (hierarchical) list of bullet points to a single list containing each item andits level.:param items: A bullet point (string or list):param level: The current level of hierarchy:return: A list of (bullet item text, hierarchical level) tuples"""flat_list = []106 unmodified linesoutput_file_path=path,slides_template='Blank')1 unmodified line234567820 unmodified lines293031323334353637383940414211 unmodified lines54555657585960616263646566676869704 unmodified lines7576777879808182838441 unmodified lines126127128129130131132133134106 unmodified lines2412422432442451 unmodified lineimport pathlibimport reimport tempfilefrom typing import List, Tupleimport json520 unmodified lines}'''logger = logging.getLogger(__name__)def remove_slide_number_from_heading(header: str) -> str:"""Remove the slide number from a given slide header.:param header: The header of a slide."""if PATTERN.match(header):11 unmodified lines"""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)logger.debug('*** Using PPTX template: %s',GlobalConfig.PPTX_TEMPLATE_FILES[slides_template]['file'])presentation = pptx.Presentation(GlobalConfig.PPTX_TEMPLATE_FILES[slides_template]['file'])4 unmodified linestitle = slide.shapes.titlesubtitle = slide.placeholders[1]title.text = parsed_data['title']logger.info('PPT title: %s | #slides: %d',title.text, len(parsed_data['slides']))subtitle.text = 'by Myself and SlideDeck AI :)'all_headers = [title.text, ]41 unmodified linesFlatten a (hierarchical) list of bullet points to a single list containing each item andits level.:param items: A bullet point (string or list).:param level: The current level of hierarchy.:return: A list of (bullet item text, hierarchical level) tuples."""flat_list = []106 unmodified linesoutput_file_path=path,slides_template='Blank')temp.close()
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556def is_valid_prompt(prompt: str) -> bool: """ Verify whether user input satisfies the concerned constraints.
:param prompt: The user input text. :return: True if all criteria are satisfied; False otherwise. """
if len(prompt) < 7 or ' ' not in prompt: return False
return True
def get_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. CAUTION: May not be always accurate.
:param json_str: The input string in JSON format. :return: The "cleaned" JSON string. """
# An example of response containing JSON and other text: # { # "title": "AI and the Future: A Transformative Journey", # "slides": [ # ... # ] # } <<---- This is end of valid JSON content # ``` # # ```vbnet # Please note that the JSON output is in valid format but the content of the "Role of GPUs in AI" slide is just an example and may not be factually accurate. For accurate information, you should consult relevant resources and update the content accordingly. # ``` response_cleaned = json_str
while True: idx = json_str.rfind('```') # -1 on failure
if idx <= 0: break
# In the ideal scenario, the character before the last ``` should be # a new line or a closing bracket } prev_char = json_str[idx - 1]
if prev_char == '}': response_cleaned = json_str[:idx] elif prev_char == '\n' and json_str[idx - 2] == '}': response_cleaned = json_str[:idx]
json_str = json_str[:idx]
return response_cleaned1234567891011121314151617181920212223242526272829303132333435363738394041You are a helpful, intelligent chatbot. Create the slides for a presentation on the given topic.Include main headings for each slide, detailed bullet points for each slide.Add relevant content to each slide.The content of each slide should be verbose, descriptive, and very detailed.If relevant, add one or two examples to illustrate the concept.Unless explicitly specified with the topic, create about 10 slides.
### Topic:{question}
The output must be only a valid and syntactically correct JSON adhering to the following schema:{{ "title": "Presentation Title", "slides": [ {{ "heading": "Heading for the First Slide", "bullet_points": [ "First bullet point", [ "Sub-bullet point 1", "Sub-bullet point 2" ], "Second bullet point" ] }}, {{ "heading": "Heading for the Second Slide", "bullet_points": [ "First bullet point", "Second bullet item", "Third bullet point" ] }} ]}}
### Output:```json12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849You are a helpful, intelligent chatbot. You follow instructions to refine an existing slide deck.A list of user instructions is provided below in sequential order -- from the oldest to the latest.The previously generated content of the slide deck in JSON format is also provided.Follow the instructions to revise the content of the previously generated slides of the presentation on the given topic.Include main headings for each slide, detailed bullet points for each slide.Add relevant content to each slide.The content of the slides should be descriptive, verbose, and detailed.If relevant, add one or two examples to illustrate the concept.Unless explicitly specified with the topic, create about 10 slides.You also fix any syntax error that may be present in the JSON-formatted content.
### List of instructions:{instructions}
### Previously generated slide deck content as JSON:{previous_content}
The output must be only a valid and syntactically correct JSON adhering to the following schema:{{ "title": "Presentation Title", "slides": [ {{ "heading": "Heading for the First Slide", "bullet_points": [ "First bullet point", [ "Sub-bullet point 1", "Sub-bullet point 2" ], "Second bullet point" ] }}, {{ "heading": "Heading for the Second Slide", "bullet_points": [ "First bullet point", "Second bullet item", "Third bullet point" ] }} ]}}
### Output:```json123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294import pathlibimport loggingimport tempfilefrom typing import List, Tuple
import json5import metaphor_python as metaphorimport streamlit as st
from helpers import llm_helper, pptx_helperfrom 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_datadef 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_resourcedef 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_datadef 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()5 unmodified lines67895 unmodified linespython-pptxmetaphor-pythonjson5~=0.9.14requests~=2.31.05 unmodified lines678910111213145 unmodified linespython-pptxmetaphor-pythonjson5~=0.9.14requests~=2.31.0transformers~=4.39.2langchain-communityurllib3~=2.2.1
12345616 unmodified lines23242526272829{"app_name": "SlideDeck AI","caption": "*:green[Co-create your next PowerPoint slide deck with AI]*","section_headers": ["Step 1: Generate your content","Step 2: Make it structured",16 unmodified lines],"urls_info": "Here is a list of some online resources that you can consult for further information on this topic:","image_info": "Got some more minutes? We are also trying to deliver an AI-generated art on the presentation topic, fresh off the studio, just for you!","content_generation_failure_error": "Unfortunately, SlideDeck AI failed to generate any content for you! Please try again later.","tos": "SlideDeck AI is an experimental prototype, and it has its limitations.\nPlease carefully review any and all AI-generated content.","tos2": "By using SlideDeck AI, you agree to fair and responsible usage.\nNo liability assumed by any party."}12345616 unmodified lines232425262728293031323334353637{"app_name": ":green[SlideDeck AI $^{[Reloaded]}$]","caption": "*Converse, create, and improve your next PowerPoint slide deck*","section_headers": ["Step 1: Generate your content","Step 2: Make it structured",16 unmodified lines],"urls_info": "Here is a list of some online resources that you can consult for further information on this topic:","image_info": "Got some more minutes? We are also trying to deliver an AI-generated art on the presentation topic, fresh off the studio, just for you!","content_generation_error": "Unfortunately, SlideDeck AI failed to generate any content for you! Please try again later.","json_parsing_error": "Unfortunately, SlideDeck AI failed to parse the response from LLM! Please try again by rephrasing the query or refreshing the page.","tos": "SlideDeck AI is an experimental prototype, and it has its limitations.\nPlease carefully review any and all AI-generated content.","tos2": "By using SlideDeck AI, you agree to fair and responsible usage.\nNo liability assumed by any party.","ai_greetings": ["How may I help you today?","Stuck with creating your presentation? Let me help you.","Looks like you have a looming deadline. Can I help you get started with your slide deck?","Hello! What topic do you have on your mind today?"],"chat_placeholder": "Write the topic or instructions here"}
.streamlit/config.tomlAdded+10
README.md+31-10
app.py+282-225
global_config.py+30-2
helpers/__init__.pyAdded
llm_helper.py → helpers/llm_helper.pyRenamed+51-16
pptx_helper.py → helpers/pptx_helper.pyRenamed+18-15
helpers/text_helper.pyAdded+56
langchain_templates/chat_prompts/initial_template.txtAdded+41
langchain_templates/chat_prompts/refinement_template.txtAdded+49
legacy_app.pyAdded+294
requirements.txt+6-1
strings.json+12-4