Kim Adams commited on
Commit ·
0db90d6
1
Parent(s): f0c57bb
organizing
Browse filesFiles changed (19)
- __pycache__/app_theme.cpython-311.pyc
- app.py+35-213
- app_theme.py+14-1
- requirements.txt+2-1
- utilities/__pycache__/clean_text.cpython-311.pycAdded
- utilities/__pycache__/constants.cpython-311.pyc
- utilities/__pycache__/embeddings.cpython-311.pycAdded
- utilities/__pycache__/image_generation.cpython-311.pycAdded
- utilities/__pycache__/persona_prompts.cpython-311.pycAdded
- utilities/__pycache__/system_prompts.cpython-311.pycAdded
- utilities/__pycache__/user_prompts.cpython-311.pycAdded
- utilities/__pycache__/voice_handling.cpython-311.pycAdded
- utilities/clean_text.pyAdded+5
- utilities/constants.py+4-2
- utilities/embeddings.pyAdded+9
- utilities/image_generation.pyAdded+47
- utilities/system_prompts.pyAdded+32
- utilities/user_prompts.pyAdded+69
- utilities/voice_handling.pyAdded+101
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816920 unmodified lines19019119219319419519619719819920020120214 unmodified lines21721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827919 unmodified lines29930030130230330430530630730820 unmodified lines3293303313323333343353363373381 unmodified line34034134234334434534615 unmodified lines36236336436536636736817 unmodified lines386387388389390import gradio as grimport openai, reimport pandas as pdimport numpy as npimport gradio as grfrom gradio.themes.default import Defaultfrom gradio.themes.utils import colors, fonts, sizesimport openai, os, re, inflectimport requests, base64from io import BytesIOfrom huggingface_hub import Repositoryfrom utilities import api_keys, prompts, constants, translate_pdf_to_textfrom create_embedding import QueryEmbeddingsfrom app_theme import SoftBlueopenai.api_key = api_keys.APIKeys().get_key('OPENAI_API_KEY')eleven_api_key = api_keys.APIKeys().get_key('ELEVEN_LABS_API_KEY')voice_id1 = api_keys.APIKeys().get_key('VOICE_ID1')voice_id2 = api_keys.APIKeys().get_key('VOICE_ID2')voice_id3 = api_keys.APIKeys().get_key('VOICE_ID3')voice_id4 = api_keys.APIKeys().get_key('VOICE_ID4')voice_id5 = api_keys.APIKeys().get_key('VOICE_ID5')voice_id6 = api_keys.APIKeys().get_key('VOICE_ID6')voice_id7 = api_keys.APIKeys().get_key('VOICE_ID7')voice_id8 = api_keys.APIKeys().get_key('VOICE_ID8')voice_id9 = api_keys.APIKeys().get_key('VOICE_ID9')voice_id = voice_id1eval_sentiment=Falseeval_emotion=Falsemessages = []def ReplaceNumbersWithWords(text):p = inflect.engine()words = text.split()for i, word in enumerate(words):if word.isdigit():words[i] = p.number_to_words(word)elif word in constants.SYMBOL_TO_WORD:words[i] = constants.SYMBOL_TO_WORD[word]reply=' '.join(words)return replydef PrepareForVoice(text):prepped_text = text.replace('"', '').replace('401k', '4 oh 1 k').replace('10k', 'ten thousand').replace('slalom', "slallum").replace('Slalom', "slallum").replace('IT 101', "IT 1 oh 1")prepped_text = re.sub(r'\$(\d+)', r'\1 dollars', prepped_text)return ReplaceNumbersWithWords(prepped_text)def Clear():global audioaudio.value=Nonedef ChangePersona(newPersona):global messages,personaprint("***ChangePersona, newPersona: "+newPersona+ " persona: "+persona.value)messages = []alabel=constants.DEFAULT_QUESTIONSif newPersona==constants.PERSONA_INVESTIGATOR:alabel=constants.QUESTIONS_INVESTIGATORmessages.append({"role": "system", "content": prompts.INVESTIGATOR_PROMPT})elif newPersona==constants.PERSONA_CUS_SERVICE:alabel=constants.QUESTIONS_CUSTOMER_SERVICEmessages.append({"role": "system", "content": prompts.CUSTOMER_SERVICE_PROMPT})elif newPersona==constants.PERSONA_FIN_EXPERT:alabel=constants.QUESTIONS_FINANCIAL_EXPERTmessages.append({"role": "system", "content": prompts.FINANCIAL_EXPERT_PROMPT})elif newPersona==constants.PERSONA_IT_EXPERT:alabel=constants.QUESTIONS_IT_EXPERTmessages.append({"role": "system", "content": prompts.IT_EXPERT_PROMPT})elif newPersona==constants.PERSONA_INS_AGENT:alabel=constants.QUESTIONS_INSURANCE_AGENTmessages.append({"role": "system", "content": prompts.INSURANCE_AGENT_PROMPT})else:alabel=constants.QUESTIONS_HR_EXPERTmessages.append({"role": "system", "content": prompts.HR_EXPERT_PROMPT})persona.value=newPersonareturn alabeldef GetVoiceId(voice):global promptif voice==constants.VOICE_2:return voice_id2elif voice==constants.VOICE_3:return voice_id3elif voice==constants.VOICE_4:return voice_id4elif voice==constants.VOICE_5:return voice_id5elif voice==constants.VOICE_6:return voice_id6elif voice==constants.VOICE_7:return voice_id7elif voice==constants.VOICE_8:return voice_id8elif voice==constants.VOICE_9:return voice_id9else:return voice_id1def RemoveRole(text):return re.sub(r"^[a-zA-Z0-9_]+:\s*", "", text)def AddLanguage(language):global promptif language==constants.LANGUAGE_2:prompt= prompts.SPANISH_PROMPTelif language==constants.LANGUAGE_3:prompt= prompts.FRENCH_PROMPTelse:prompt= prompts.ENGLISH_PROMPTreturn promptdef ApplyEmbeddings(message):global persona, promptprint("persona: "+persona.value + " prompt: "+prompt)if(persona.value==constants.PERSONA_HR_EXPERT):return QueryEmbeddings(message)else:return ""def ProcessGPTResponse():global messagesresponse = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages)return RemoveRole(response["choices"][0]["message"]["content"])def ProcessAudio(preppedText):url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}/stream"data = {"text": preppedText,"voice_settings":{ "stability": 0.95,"similarity_boost": 0.93}}r = requests.post(url, headers={'xi-api-key':eleven_api_key}, json=data)r_audio =r.contentaudio_io = BytesIO(r_audio)audio_io.seek(0)audio_base64 = base64.b64encode(audio_io.read()).decode("utf-8")return f'<audio src="data:audio/aac;base64,{audio_base64}" controls autoplay playsinline></audio>'def Transcribe(audio, voice, language, persona):global messages, voice_id, promptprompt= AddLanguage(language)voice_id=GetVoiceId(voice)#prepare voice to textaudio_filename_with_extension = audio + '.wav'os.rename(audio, audio_filename_with_extension)audio_file= open(audio_filename_with_extension, "rb")transcript = openai.Audio.transcribe("whisper-1", audio_file)#apply embedding, if appropriatebest_answer= ApplyEmbeddings(transcript['text'])#build prompt & fetch gpt responseuser_text = f"Using the following text, answer the question '{transcript['text']}'. {ApplyOptionals(prompt)} {best_answer}"messages.append({"role": "user", "content": user_text})system_message= ProcessGPTResponse()messages.append({"role": "assistant", "content": system_message})#prep and call ai voice apiaudio_html=ProcessAudio(PrepareForVoice(system_message))df = pd.DataFrame(messages)return df, audio_htmldef SummarizeCompletion(code):overflow_message=""20 unmodified lineselse:return translate_pdf_to_text.PreparePDF(f"{constants.PDF_PREFIX}{fileName}")def ApplyOptionals(prompt):if eval_sentiment:prompt= prompt + " " + prompts.SENTIMENT_PROMPTif eval_emotion:prompt= prompt + " " + prompts.EMOTION_PROMPTreturn promptdef ToggleSentiment(sentiment):global eval_sentimentif sentiment:14 unmodified linessettingOptions.value=settingprint("after, settingOptions="+settingOptions.value)def UpdateArtStyle(art):global artOptionsprint("UpdateArtSetting: artOptions "+artOptions.value + " art: "+art)artOptions.value=artprint("after, artOptions="+artOptions.value)def AddArtSetting():global settingOptionsprint("AddArtSetting: "+settingOptions.value)if settingOptions.value== constants.IMAGE_SETTING_2:return prompts.HISTORICAL_PROMPTelif settingOptions.value== constants.IMAGE_SETTING_3:return prompts.PORTRAIT_PROMPTelif settingOptions.value== constants.IMAGE_SETTING_4:return prompts.HIGH_FASHION_PROMPTelif settingOptions.value== constants.IMAGE_SETTING_5:return prompts.ABSTRACT_PROMPTelif settingOptions.value== constants.IMAGE_SETTING_6:return prompts.TRAVEL_AND_ADVENTURE_PROMPTelif settingOptions.value== constants.IMAGE_SETTING_7:return prompts.STEAMPUNK_PROMPTelif settingOptions.value== constants.IMAGE_SETTING_8:return prompts.SCI_FI_PROMPTelif settingOptions.value== constants.IMAGE_SETTING_9:return prompts.LANDSCAPE_PROMPTelif settingOptions.value== constants.IMAGE_SETTING_10:return prompts.WILDLIFE_PROMPTelse:return prompts.STILL_LIFE_PROMPTdef AddArtStyle():global artOptionsprint("AddArtStyle: "+artOptions.value)if artOptions.value== constants.IMAGE_ART_2:return prompts.POP_ART_PROMPTelif artOptions.value== constants.IMAGE_ART_3:return prompts.CUBISM_PROMPTelif artOptions.value== constants.IMAGE_ART_4:return prompts.BAROQUE_PROMPTelif artOptions.value== constants.IMAGE_ART_5:return prompts.PHOTOREALISTIC_PROMPTelif artOptions.value== constants.IMAGE_ART_6:return prompts.CARTOON_PROMPTelif artOptions.value== constants.IMAGE_ART_7:return prompts.SURREALISM_PROMPTelif artOptions.value== constants.IMAGE_ART_8:return prompts.POINTALISM_PROMPTelif artOptions.value== constants.IMAGE_ART_9:return prompts.BLUE_PRINT_PROMPTelif artOptions.value== constants.IMAGE_ART_10:return prompts.LINE_ART_PROMPTelse:return prompts.IMPRESSIONISM_PROMPTdef Generate(imageDescription):system_text = "In 875 characters or less create a prompt for image creation. " + AddArtStyle() + " "+ AddArtSetting()print("system_text" + system_text)user_text = f"{imageDescription}"imgMessages = []19 unmodified linesreturn response['data'][0]['url'], response['data'][1]['url'], response['data'][2]['url'], dfgrTheme=SoftBlue()with gr.Blocks(theme=grTheme) as ui1:label = gr.Label(show_label=False, value="Prompt Builder", container=False)gr.Markdown(f"## {constants.QUESTIONS_PREFIX}")question=gr.Markdown(show_label=False, value=constants.DEFAULT_QUESTIONS, container=False)with gr.Row():with gr.Column():persona = gr.Radio([constants.PERSONA_HR_EXPERT, constants.PERSONA_CUS_SERVICE,20 unmodified lineswith gr.Row():clear=gr.Button(value="Clear")submit=gr.Button(value="Submit", variant="primary")with gr.Column():dataframe = gr.DataFrame(type="pandas", value=pd.DataFrame({"role": [""], "content": [""] }), wrap=True, label="OpenAI Communication Log")audio_html = gr.HTML()persona.input(ChangePersona,inputs=[persona], outputs=[question])clear.click(Clear, inputs=[], outputs=[audio])submit.click(Transcribe, inputs=[audio,voice,language,persona], outputs=[dataframe, audio_html])sentiment.change(ToggleSentiment, inputs=[sentiment], outputs=[])1 unmodified linewith gr.Blocks(theme=grTheme) as ui2:label = gr.Label(show_label=False, value="Summarization", container=False)#gr.Markdown(constants.SUMMARY_MD_HEAD)gr.Markdown(constants.SUMMARY_MD_SUBHEAD)with gr.Row():with gr.Column():15 unmodified lineswith gr.Blocks(theme=grTheme) as ui3:label = gr.Label(show_label=False, value="Create an Image", container=False)imageDescription = gr.Textbox(label="Image Prompt", interactive=True, placeholder="Enter a description of what you'd like to see.", lines=3)with gr.Row():artOptions = gr.Radio([constants.IMAGE_ART_1, constants.IMAGE_ART_2, constants.IMAGE_ART_3, constants.IMAGE_ART_4, constants.IMAGE_ART_5,17 unmodified linesui = gr.TabbedInterface( [ui1,ui2,ui3], (constants.UI_1, constants.UI_2, constants.UI_3), theme=grTheme)ChangePersona(constants.PERSONA_HR_EXPERT)ui.launch()12345678910111213141516171819202122232425262728293020 unmodified lines51525354555614 unmodified lines71727374757677787980818283848519 unmodified lines10510610710810911011111211311411511611711811912012112212312412512612712812920 unmodified lines1501511521531541551561571581591601 unmodified line16216316416516616715 unmodified lines18318418518618718818919017 unmodified lines208209210211212import gradio as grimport openaiimport pandas as pdimport gradio as grfrom gradio.themes.default import Defaultimport openai, os, refrom huggingface_hub import Repositoryfrom utilities import api_keys, prompts, constants, system_prompts, user_prompts, clean_text, translate_pdf_to_text, voice_handling,embeddings,image_generationfrom app_theme import SoftBlueopenai.api_key = api_keys.APIKeys().get_key('OPENAI_API_KEY')eval_sentiment=Falseeval_emotion=Falsemessages = []def Clear():global audioaudio.value=Nonedef Transcribe(audio, voice, language, persona):global messages, prompt, eval_sentiment, eval_emotionprompt= user_prompts.AddLanguage(language)voice_handling.SetVoiceId(voice)a_messages, df, a_html = voice_handling.TranslateAndProcessAudio(audio, prompt, eval_sentiment, eval_emotion, messages, persona)messages=a_messagesreturn df, a_htmldef SummarizeCompletion(code):overflow_message=""20 unmodified lineselse:return translate_pdf_to_text.PreparePDF(f"{constants.PDF_PREFIX}{fileName}")def ToggleSentiment(sentiment):global eval_sentimentif sentiment:14 unmodified linessettingOptions.value=settingprint("after, settingOptions="+settingOptions.value)def UpdateArtStyle(art):global artOptionsprint("UpdateArtSetting: artOptions "+artOptions.value + " art: "+art)artOptions.value=artprint("after, artOptions="+artOptions.value)def Generate(imageDescription):global artOptions, settingOptionssystem_text = "In 875 characters or less create a prompt for image creation. " + image_generation.AddArtStyle(artOptions) + " "+ image_generation.AddArtSetting(settingOptions)print("system_text" + system_text)user_text = f"{imageDescription}"imgMessages = []19 unmodified linesreturn response['data'][0]['url'], response['data'][1]['url'], response['data'][2]['url'], dfgrTheme=SoftBlue()def UpdatePersonas(person_new):global persona, messageslabel, messages, persona.value = system_prompts.ChangePersona(person_new,[],persona)return label#gradio UI for html using SoftBlue theme and html_font_style(heading)with gr.Blocks() as ui1:label = gr.Markdown(show_label=False, value="Prompt Builder", container=False)with gr.Row():with gr.Column():gr.Markdown("### Purpose")gr.Markdown(constants.PROMPT_DESCRIPTION)with gr.Column():gr.Markdown("### Directions")gr.Markdown(value=constants.PROMPT_DIRECTIONS)with gr.Row():question= gr.Textbox (label=constants.QUESTIONS_PREFIX, value=constants.DEFAULT_QUESTIONS)with gr.Row():with gr.Column():persona = gr.Radio([constants.PERSONA_HR_EXPERT, constants.PERSONA_CUS_SERVICE,20 unmodified lineswith gr.Row():clear=gr.Button(value="Clear")submit=gr.Button(value="Submit", variant="primary")with gr.Column():dataframe = gr.DataFrame(type="pandas", value=pd.DataFrame({"role": [""], "content": [""] }), wrap=True, label="OpenAI Communication Log")audio_html = gr.HTML()persona.input(UpdatePersonas,inputs=[persona], outputs=[question])clear.click(Clear, inputs=[], outputs=[audio])submit.click(Transcribe, inputs=[audio,voice,language,persona], outputs=[dataframe, audio_html])sentiment.change(ToggleSentiment, inputs=[sentiment], outputs=[])1 unmodified linewith gr.Blocks(theme=grTheme) as ui2:label = gr.Label(show_label=False, value="Summarization", container=False)gr.Markdown(constants.SUMMARY_MD_SUBHEAD)with gr.Row():with gr.Column():15 unmodified lineswith gr.Blocks(theme=grTheme) as ui3:label = gr.Label(show_label=False, value="Create an Image", container=False)imageDescription = gr.Textbox(label="Image Prompt", interactive=True,placeholder="Enter a description of what you'd like to see.", lines=3)with gr.Row():artOptions = gr.Radio([constants.IMAGE_ART_1, constants.IMAGE_ART_2, constants.IMAGE_ART_3, constants.IMAGE_ART_4, constants.IMAGE_ART_5,17 unmodified linesui = gr.TabbedInterface( [ui1,ui2,ui3], (constants.UI_1, constants.UI_2, constants.UI_3), theme=grTheme)UpdatePersonas(constants.PERSONA_HR_EXPERT)ui.launch()
38 unmodified lines3940414238 unmodified linestext_size=text_size,font=font,font_mono=font_mono,)38 unmodified lines394041424344454647484950515253545538 unmodified linestext_size=text_size,font=font,font_mono=font_mono,)# html font style accepts a string heading or body and returns the style for that element, should follow styles in class with exception that heading is +2 pts and bolddef html_font_style(self, element: str) -> str:if element == "heading":return f"font-family: {self.font_mono}; font-size: {self.text_sm}; font-weight: bold;"elif element == "body":return f"font-family: {self.font_mono}; font-size: {self.text_sm};"elif element == "mono":return f"font-family: {self.font_mono}; font-size: {self.text_sm};"else:raise ValueError(f"Element must be one of 'heading', 'body', or 'mono', not {element}")
18 unmodified lines1920212218 unmodified lineslxml==4.9.3PyPDF2==3.0.1tiktoken==0.4.0inflect==7.0.018 unmodified lines192021222318 unmodified lineslxml==4.9.3PyPDF2==3.0.1tiktoken==0.4.0inflect==7.0.0diffusers==0.10.2
12345import re
def RemoveRole(text): return re.sub(r"^[a-zA-Z0-9_]+:\s*", "", text) 12360 unmodified lines6465666768697071727374VOICE_1="Sally"VOICE_2="Earl"VOICE_3="Luke"60 unmodified linesQUESTIONS_INSURANCE_AGENT="What is the process for filing a claim? What is the deductible? How long will it take to process my claim?"QUESTIONS_INVESTIGATOR="How do I report a crime? What is the process for filing a police report? What information do you need?"UI_1="NLP Explorer"UI_2="Summary Extraction"UI_3="Image Creation"SUMMARY_MD_HEAD="## Summary"SUMMARY_MD_SUBHEAD="##### Understand legacy software, complex or technical documents with summarization."SUMMARY_MD_DIRECTIONS="Enter text or select one of the Code & Document Examples, below. Then tap Summarize."12345660 unmodified lines67686970717273747576PROMPT_DESCRIPTION="Explore how generative AI can be used to create content. Personas let you explore the variety of roles the system can take on. Translation options specify the language for your response. Voice options are an assortment of AI voices that will bring messages to life. Check the Sentiment box to see how the system identifies sentiment from conversation. Check the emotion to see how the sytem detects your emotion."PROMPT_DIRECTIONS="To get started, select a Persona, Language, and Voice. If you'd like Sentiment or Emotion analysis, check the respective box. Tap the 'Record from microphone' button and say what's on your mind, tap 'Stop recording' when your done. If you're happy with what you've said, tap 'Submit' to send your request, otherwise tap 'Clear' to record a new message."PROMPT_DIRECTION="Directions"VOICE_1="Sally"VOICE_2="Earl"VOICE_3="Luke"60 unmodified linesQUESTIONS_INSURANCE_AGENT="What is the process for filing a claim? What is the deductible? How long will it take to process my claim?"QUESTIONS_INVESTIGATOR="How do I report a crime? What is the process for filing a police report? What information do you need?"UI_1="Prompt Builder"UI_2="Summary Extraction"UI_3="Image Creation"SUMMARY_MD_HEAD="## Summary"SUMMARY_MD_SUBHEAD="##### Understand legacy software, complex or technical documents with summarization."SUMMARY_MD_DIRECTIONS="Enter text or select one of the Code & Document Examples, below. Then tap Summarize."
123456789from utilities import prompts, constantsfrom create_embedding import QueryEmbeddings
def ApplyEmbeddings(message, persona): print("persona: "+persona) if(persona==constants.PERSONA_HR_EXPERT): return QueryEmbeddings(message) else: return ""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647from utilities import prompts, constants
def AddArtStyle(artOptions): print("AddArtStyle: "+artOptions.value) if artOptions.value== constants.IMAGE_ART_2: return prompts.POP_ART_PROMPT elif artOptions.value== constants.IMAGE_ART_3: return prompts.CUBISM_PROMPT elif artOptions.value== constants.IMAGE_ART_4: return prompts.BAROQUE_PROMPT elif artOptions.value== constants.IMAGE_ART_5: return prompts.PHOTOREALISTIC_PROMPT elif artOptions.value== constants.IMAGE_ART_6: return prompts.CARTOON_PROMPT elif artOptions.value== constants.IMAGE_ART_7: return prompts.SURREALISM_PROMPT elif artOptions.value== constants.IMAGE_ART_8: return prompts.POINTALISM_PROMPT elif artOptions.value== constants.IMAGE_ART_9: return prompts.BLUE_PRINT_PROMPT elif artOptions.value== constants.IMAGE_ART_10: return prompts.LINE_ART_PROMPT else: return prompts.IMPRESSIONISM_PROMPT def AddArtSetting(settingOptions): print("AddArtSetting: "+settingOptions.value) if settingOptions.value== constants.IMAGE_SETTING_2: return prompts.HISTORICAL_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_3: return prompts.PORTRAIT_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_4: return prompts.HIGH_FASHION_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_5: return prompts.ABSTRACT_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_6: return prompts.TRAVEL_AND_ADVENTURE_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_7: return prompts.STEAMPUNK_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_8: return prompts.SCI_FI_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_9: return prompts.LANDSCAPE_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_10: return prompts.WILDLIFE_PROMPT else: return prompts.STILL_LIFE_PROMPT1234567891011121314151617181920212223242526272829303132
from utilities import prompts, constants
def ChangePersona(newPersona, messages, persona): #global messages,persona print("***ChangePersona, newPersona: "+newPersona+ " persona: "+persona.value) messages = [] alabel=constants.DEFAULT_QUESTIONS if newPersona==constants.PERSONA_INVESTIGATOR: alabel=constants.QUESTIONS_INVESTIGATOR messages.append({"role": "system", "content": prompts.INVESTIGATOR_PROMPT}) elif newPersona==constants.PERSONA_CUS_SERVICE: alabel=constants.QUESTIONS_CUSTOMER_SERVICE messages.append({"role": "system", "content": prompts.CUSTOMER_SERVICE_PROMPT}) elif newPersona==constants.PERSONA_FIN_EXPERT: alabel=constants.QUESTIONS_FINANCIAL_EXPERT messages.append({"role": "system", "content": prompts.FINANCIAL_EXPERT_PROMPT}) elif newPersona==constants.PERSONA_IT_EXPERT: alabel=constants.QUESTIONS_IT_EXPERT messages.append({"role": "system", "content": prompts.IT_EXPERT_PROMPT}) elif newPersona==constants.PERSONA_INS_AGENT: alabel=constants.QUESTIONS_INSURANCE_AGENT messages.append({"role": "system", "content": prompts.INSURANCE_AGENT_PROMPT}) else: alabel=constants.QUESTIONS_HR_EXPERT messages.append({"role": "system", "content": prompts.HR_EXPERT_PROMPT}) persona=newPersona return alabel, messages, persona
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869from utilities import prompts, constants
def AddLanguage(language): prompt="" if language==constants.LANGUAGE_2: prompt= prompts.SPANISH_PROMPT elif language==constants.LANGUAGE_3: prompt= prompts.FRENCH_PROMPT else: prompt= prompts.ENGLISH_PROMPT return prompt
def ApplyOptionals(prompt, eval_sentiment, eval_emotion): if eval_sentiment: prompt= prompt + " " + prompts.SENTIMENT_PROMPT if(eval_emotion): prompt=prompt + ", " if eval_emotion: prompt= prompt + " " + prompts.EMOTION_PROMPT print ("prompt: "+prompt) return prompt
def AddArtStyle(artOptions): print("AddArtStyle: "+artOptions.value) if artOptions.value== constants.IMAGE_ART_2: return prompts.POP_ART_PROMPT elif artOptions.value== constants.IMAGE_ART_3: return prompts.CUBISM_PROMPT elif artOptions.value== constants.IMAGE_ART_4: return prompts.BAROQUE_PROMPT elif artOptions.value== constants.IMAGE_ART_5: return prompts.PHOTOREALISTIC_PROMPT elif artOptions.value== constants.IMAGE_ART_6: return prompts.CARTOON_PROMPT elif artOptions.value== constants.IMAGE_ART_7: return prompts.SURREALISM_PROMPT elif artOptions.value== constants.IMAGE_ART_8: return prompts.POINTALISM_PROMPT elif artOptions.value== constants.IMAGE_ART_9: return prompts.BLUE_PRINT_PROMPT elif artOptions.value== constants.IMAGE_ART_10: return prompts.LINE_ART_PROMPT else: return prompts.IMPRESSIONISM_PROMPT def AddArtSetting(settingOptions): print("AddArtSetting: "+settingOptions.value) if settingOptions.value== constants.IMAGE_SETTING_2: return prompts.HISTORICAL_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_3: return prompts.PORTRAIT_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_4: return prompts.HIGH_FASHION_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_5: return prompts.ABSTRACT_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_6: return prompts.TRAVEL_AND_ADVENTURE_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_7: return prompts.STEAMPUNK_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_8: return prompts.SCI_FI_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_9: return prompts.LANDSCAPE_PROMPT elif settingOptions.value== constants.IMAGE_SETTING_10: return prompts.WILDLIFE_PROMPT else: return prompts.STILL_LIFE_PROMPT123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101import inflect, re, requests, base64, os, openaiimport pandas as pdfrom io import BytesIOfrom utilities import constants,api_keys, embeddings, clean_text, user_prompts
openai.api_key = api_keys.APIKeys().get_key('OPENAI_API_KEY')eleven_api_key = api_keys.APIKeys().get_key('ELEVEN_LABS_API_KEY')voice_id1 = api_keys.APIKeys().get_key('VOICE_ID1')voice_id2 = api_keys.APIKeys().get_key('VOICE_ID2')voice_id3 = api_keys.APIKeys().get_key('VOICE_ID3')voice_id4 = api_keys.APIKeys().get_key('VOICE_ID4')voice_id5 = api_keys.APIKeys().get_key('VOICE_ID5')voice_id6 = api_keys.APIKeys().get_key('VOICE_ID6')voice_id7 = api_keys.APIKeys().get_key('VOICE_ID7')voice_id8 = api_keys.APIKeys().get_key('VOICE_ID8')voice_id9 = api_keys.APIKeys().get_key('VOICE_ID9')
voice_id = voice_id1
def SetVoiceId(newVoice): global voice_id print("SetVoiceId: voice_id: "+voice_id + " newVoice "+newVoice) voice_id = GetVoiceId(newVoice)
def ReplaceNumbersWithWords(text): p = inflect.engine() words = text.split() for i, word in enumerate(words): if word.isdigit(): words[i] = p.number_to_words(word) elif word in constants.SYMBOL_TO_WORD: words[i] = constants.SYMBOL_TO_WORD[word] reply=' '.join(words) return reply
def PrepareForVoice(text): prepped_text = text.replace('"', '').replace('401k', '4 oh 1 k').replace('10k', 'ten thousand').replace('slalom', "slallum").replace('Slalom', "slallum").replace('IT 101', "IT 1 oh 1") prepped_text = re.sub(r'\$(\d+)', r'\1 dollars', prepped_text) return ReplaceNumbersWithWords(prepped_text)
def GetVoiceId(voice): if voice==constants.VOICE_2: return voice_id2 elif voice==constants.VOICE_3: return voice_id3 elif voice==constants.VOICE_4: return voice_id4 elif voice==constants.VOICE_5: return voice_id5 elif voice==constants.VOICE_6: return voice_id6 elif voice==constants.VOICE_7: return voice_id7 elif voice==constants.VOICE_8: return voice_id8 elif voice==constants.VOICE_9: return voice_id9 else: return voice_id1
def ProcessAudio(preppedText): global voice_id url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}/stream" data = { "text": preppedText, "voice_settings": { "stability": 0.95, "similarity_boost": 0.93 } } r = requests.post(url, headers={'xi-api-key':eleven_api_key}, json=data) r_audio =r.content audio_io = BytesIO(r_audio) audio_io.seek(0) audio_base64 = base64.b64encode(audio_io.read()).decode("utf-8") return f'<audio src="data:audio/aac;base64,{audio_base64}" controls autoplay playsinline></audio>'
def TranslateAudio(audio): audio_filename_with_extension = audio + '.wav' os.rename(audio, audio_filename_with_extension) audio_file= open(audio_filename_with_extension, "rb") return openai.Audio.transcribe("whisper-1", audio_file)
def ProcessGPTResponse(messages): response = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages) cleaned_text= clean_text.RemoveRole(response["choices"][0]["message"]["content"]) return cleaned_text
def TranslateAndProcessAudio(audio, prompt, eval_sentiment, eval_emotion, messages, persona): transcript = TranslateAudio(audio) print("transcript: "+transcript['text'] + " messages: "+str(messages) + " persona: "+persona) best_answer= embeddings.ApplyEmbeddings(transcript['text'], persona) optionals = user_prompts.ApplyOptionals(prompt, eval_sentiment, eval_emotion) user_text = f"Using the following text, answer the question '{transcript['text']}'. {optionals} {best_answer}" messages.append({"role": "user", "content": user_text}) system_message = ProcessGPTResponse( messages) messages.append({"role": "assistant", "content": system_message}) audio_html=ProcessAudio(PrepareForVoice(system_message)) df = pd.DataFrame(messages) return messages, df, audio_html __pycache__/app_theme.cpython-311.pyc
app.py+35-213
app_theme.py+14-1
requirements.txt+2-1
utilities/__pycache__/clean_text.cpython-311.pycAdded
utilities/__pycache__/constants.cpython-311.pyc
utilities/__pycache__/embeddings.cpython-311.pycAdded
utilities/__pycache__/image_generation.cpython-311.pycAdded
utilities/__pycache__/persona_prompts.cpython-311.pycAdded
utilities/__pycache__/system_prompts.cpython-311.pycAdded
utilities/__pycache__/user_prompts.cpython-311.pycAdded
utilities/__pycache__/voice_handling.cpython-311.pycAdded
utilities/clean_text.pyAdded+5
utilities/constants.py+4-2
utilities/embeddings.pyAdded+9
utilities/image_generation.pyAdded+47
utilities/system_prompts.pyAdded+32
utilities/user_prompts.pyAdded+69
utilities/voice_handling.pyAdded+101