Spaces:
Runtime error
Runtime error
Merge pull request #23 from barun-saha/visual
Browse files1233 unmodified lines78910111213141531 unmodified lines47484950515253545556575859606162632 unmodified lines66676869707172737435 unmodified lines11011111211311411511614 unmodified lines13113213313413513613713817 unmodified lines15615715815916016116216326 unmodified lines1901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352363 unmodified lines2402412422432442452462472481 unmodified line25025125225325425525625725825926015 unmodified lines2762772782792802812822832842852862872882892902912929 unmodified lines302303304305306307308309import datetimeimport loggingimport pathlib3 unmodified linesimport json5import streamlit as stfrom langchain_community.chat_message_histories import (StreamlitChatMessageHistory)from langchain_core.messages import HumanMessagefrom langchain_core.prompts import ChatPromptTemplate31 unmodified linesreturn 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()2 unmodified linesCHAT_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]35 unmodified lineswith st.expander('Usage Policies and Limitations'):display_page_footer_content()progress_bar.progress(50, text='Setting up chat interface...')set_up_chat_ui()14 unmodified linesst.chat_message('ai').write(random.choice(APP_TEXT['ai_greetings']))progress_bar.progress(100, text='Done!')progress_bar.empty()history = StreamlitChatMessageHistory(key=CHAT_MESSAGES)17 unmodified linesplaceholder=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!'26 unmodified lines})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(3 unmodified lineslogger.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',1 unmodified line)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:15 unmodified linesoutput_file_path=path)except ValueError:# 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))st.error('Encountered error while parsing JSON...will fix it and retry')9 unmodified linesexcept Exception as ex:st.error(APP_TEXT['content_generation_error'])logger.error('Caught a generic exception: %s', str(ex))finally:_display_download_button(path)def _is_it_refinement() -> bool:1234563 unmodified lines1011121314151631 unmodified lines4849505152535455562 unmodified lines5960616263646566676835 unmodified lines10410510610710810914 unmodified lines12412512612712812917 unmodified lines14714814915015115226 unmodified lines1791801811821831841851861871881891901911921931941951961971981992003 unmodified lines2042052062072082092102112122132142151 unmodified line21721821922022122222322422522622722822915 unmodified lines2452462472482492509 unmodified lines260261262263264265266267"""Streamlit app containing the UI and the application logic."""import datetimeimport loggingimport pathlib3 unmodified linesimport json5import streamlit as stfrom langchain_community.chat_message_histories import StreamlitChatMessageHistoryfrom langchain_core.messages import HumanMessagefrom langchain_core.prompts import ChatPromptTemplate31 unmodified linesreturn template@st.cache_resourcedef _get_llm():return llm_helper.get_hf_endpoint()APP_TEXT = _load_strings()2 unmodified linesCHAT_MESSAGES = 'chat_messages'DOWNLOAD_FILE_KEY = 'download_file_name'IS_IT_REFINEMENT = 'is_it_refinement'APPROX_TARGET_LENGTH = GlobalConfig.LLM_MODEL_MAX_OUTPUT_LENGTH / 2logger = logging.getLogger(__name__)texts = list(GlobalConfig.PPTX_TEMPLATE_FILES.keys())captions = [GlobalConfig.PPTX_TEMPLATE_FILES[x]['caption'] for x in texts]35 unmodified lineswith st.expander('Usage Policies and Limitations'):display_page_footer_content()set_up_chat_ui()14 unmodified linesst.chat_message('ai').write(random.choice(APP_TEXT['ai_greetings']))history = StreamlitChatMessageHistory(key=CHAT_MESSAGES)17 unmodified linesplaceholder=APP_TEXT['chat_placeholder'],max_chars=GlobalConfig.LLM_MODEL_MAX_INPUT_LENGTH):if not text_helper.is_valid_prompt(prompt):st.error('Not enough information provided!'26 unmodified lines})progress_bar = st.progress(0, 'Preparing to call LLM...')response = ''for chunk in _get_llm().stream(formatted_template):response += chunk# Update the progress barprogress_percentage = min(len(response) / APPROX_TARGET_LENGTH, 0.95)progress_bar.progress(progress_percentage, text='Streaming content...')history.add_user_message(prompt)history.add_ai_message(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 generatedresponse_cleaned = text_helper.get_clean_json(response)logger.info(3 unmodified lineslogger.debug('Cleaned JSON: %s', response_cleaned)# Now create the PPT fileprogress_bar.progress(0.95, text='Searching photos and generating the slide deck...')path = generate_slide_deck(response_cleaned)progress_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:15 unmodified linesoutput_file_path=path)except ValueError:st.error('Encountered error while parsing JSON...will fix it and retry')9 unmodified linesexcept Exception as ex:st.error(APP_TEXT['content_generation_error'])logger.error('Caught a generic exception: %s', str(ex))return pathdef _is_it_refinement() -> bool:
app.py+29-71