from ast import Interactive import gradio as gr from langchain.chains import LLMChain from langchain.chains import SimpleSequentialChain from langchain.llms import OpenAI from langchain.prompts import PromptTemplate from langchain.chains import SequentialChain import openai import os import base64 import requests import json import re import codecs import random ## Remember to set $env:OPENAI_API_KEY="keyhere" openai.api_key = os.getenv("OPENAI_API_KEY") #openai.api_key = "" def getAndParseQuickStart(text, count): print("Asking AI for a character of " + text + " with trait count:") print(count) instruction_prompt = f""" You are an AI bot that creates profiles of characters based on a simple input. You generate and give detailed characters in the following format: Name: descriptors Mind: descriptors (comma separated properties) Personality: descriptors (comma separated properties, at least {count} traits) Body: descriptors (comma separated properties, at least {count} traits) Likes: descriptors (comma separated properties, at least {count} traits) Hates: descriptors (comma separated properties, at least {count} traits) Attributes: descriptors (comma separated properties, at least {count} traits) Clothes: descriptors (comma separated properties) Sex: descriptor (choose only from: Male, Female, or Other) Sexuality: descriptor (choose only from: Gay, Straight, Bi, or Asexual. Default to Asexual) Age: descriptor (as an integer, no additional text) Description: descriptor (3 sentences, do not repeat any previous information) Personality_Summary: descriptor """ prompt = """ Please generate a character based on the following description assuming this is a real person, make sure any dialog is accurate as to how this specific character sounds. The dialog should give a good indication of the manner in which the character speaks:\n """ + text response = openai.ChatCompletion.create( model="gpt-3.5-turbo-0613", messages=[ {"role": "system", "content": instruction_prompt}, {"role": "user", "content": prompt} ]) #print(response) # Parse the AI's response response_content = response['choices'][0]['message']['content'] print(response_content) example_chat_index = response_content.find('Example_Chat:') if example_chat_index != -1: # Extract 'Example Chat' and everything after it example_chat_content = response_content[example_chat_index:] # Split the content into lines example_chat_lines = example_chat_content.split('\n') # The first line is 'Example Chat: ' # So we need to remove 'Example Chat: ' from it example_chat_lines[0] = example_chat_lines[0][len('Example_Chat: '):] # Join the lines back together to get the full 'Example Chat' example_chat = '\n'.join(example_chat_lines) traits_dict = {'Example_Chat': example_chat.strip()} # Remove the 'Example Chat' part from the response content so it won't be processed again in the loop api_response = response_content[:example_chat_index] else: traits_dict = {} traits = response_content.split('\n') print(traits) raw = traits #print(locked_fields) for trait in traits: if ': ' in trait: key, value = trait.split(': ', 1) # Split at the first occurrence of ': ' key = key.lower() key = key.replace(' ', '_') #if key in locked_fields: # continue if key == 'name': traits_dict[key.capitalize()] = value elif key == 'first_message': traits_dict['First_Message'] = value elif key == 'personality_summary': traits_dict['Personality_Summary'] = value else: traits_dict[key.capitalize()] = value charName = traits_dict.get('Name', '') personality = traits_dict.get('Personality', '') body = traits_dict.get('Body', '') likes = traits_dict.get('Likes', '') hates = traits_dict.get('Hates', '') sex = traits_dict.get('Sex', '') sexuality = traits_dict.get('Sexuality', '') age = traits_dict.get('Age', '') description = traits_dict.get('Description', '') personalityProfile = traits_dict.get('Personality_Profile', '') attributes = traits_dict.get('Attributes', '') return [ raw, charName, personality, body, likes, hates, sex, sexuality, age, description, personalityProfile, attributes ] def generateSpeakingStyle(text): print("Asking AI for a speaking style from:\n" + text) prompt = """ Here is a detailed summary of a character:\n """ + text + """ \n Based on that, determine the speaking style that would best express how this character would talk. For each of the following, choose the best option for this character: """ + prompt_Personality + """ Please return your choices in JSON format: {"property":"choice", "property":"choice", ....etc}\n Do not change any capitalization. Do not include any new lines. Only a correct JSON format. """ response = openai.ChatCompletion.create( model="gpt-4-0613", messages=[ {"role": "system", "content": "You are a world-class writer and character designer."}, {"role": "user", "content": prompt} ]) print(response) response_content = response['choices'][0]['message']['content'] response = json.loads(response_content) return [ response.get('formality', ''), response.get('pace', ''), response.get('rhythm', ''), response.get('volume', ''), response.get('emotionality', ''), response.get('directness', ''), response.get('humor', ''), response.get('enunciation', ''), response.get('expressiveness', ''), response.get('accent', ''), response.get('politeness', ''), response.get('vocabulary', ''), response.get('interruptions', ''), response.get('hesitations', ''), response.get('sentence structure', ''), response.get('sarcasm', ''), response.get('colloquialisms', ''), response.get('energy level', ''), response.get('defiance/rebellion', ''), response.get('playfulness', ''), response.get('vulgarity', ''), response.get('idiosyncrasies', ''), response.get('emotional tone', ''), response.get('context adaptability', ''), response.get('subtext', ''), response.get('metaphorical language', ''), response.get('cultural references', ''), response.get('storytelling ability', '') ] def saveKey(text): openai.api_key = text with gr.Blocks() as demo: rawQuickResults=gr.Textbox(visible=False) gr.Markdown( """ # Character Maker v0.1 # """) # with gr.Row(): # myKey = gr.Text(label="OPENAI API KEY", info="must have gpt4 access (for now)") # keySave = gr.Button(value="Set") # keySave.click(saveKey, inputs=[myKey]) with gr.Row(): gr.Markdown( """ This is a very early prototype of a character generator/assistant. The goal is to create a detailed but concise profile that can be used in chat programs and guide the AI in acting realistic.
1. Adjust the traits count slider for how many traits you want the AI to return 2. Give a general description or starting point and click (1) Generate Quick Start (ex. "Winnie the Pooh but he is a cat") 3. Edit response fields as needed 4. Click (2) Analyze to create a Psychological Profile 5. Click (3) Generate Speaking Style 6. Edit any fields as you want 7. Click (4) Create JSON """) gr.Markdown( """ ### Not Working Yet ### - Scenario, Setting, Dialogue - Secrets ### To Do ### - Scenario and setting creator - Chat sample creator and chooser - Testable playground built-in - Add grammar and spelling variable - Have AI choose and expand on appropriate secrets - Use Dall-E to generate profile pics - Selection of JSON format to export as - Add token count - Add shorten function to send JSON to AI and ask to remove duplicate information """) numTraits = 8 def updateTraitCount(text): numTraits = text print (numTraits) def generateMedicalSecrets(count): with open('medical_secrets.txt', 'r') as file: lines = file.readlines() selected_lines = random.sample(lines, count) codes = [re.search(r'\((.*?)\)', line).group(1) for line in selected_lines] codes_string = ', '.join(codes) print(codes) return "medical conditions: " + codes_string with gr.Row(): quickStart = gr.TextArea(label="Quick Start", info="Use AI to fill out all fields based on your description.") generate = gr.Button("1. Generate Quick Start") with gr.Row(): with gr.Column(scale=1, min_width=600): trait_count = gr.Slider(4, 20, label="Minimum number of traits for each category", interactive=True, step=1.0, value=8) trait_count.change(updateTraitCount, inputs=[trait_count]) charName = gr.Textbox(label="Name", interactive=True) personality = gr.Textbox(label="Personality", interactive=True) body = gr.Textbox(label="Physical Description", interactive=True) with gr.Row(): likes = gr.Textbox(label="Likes", interactive=True) hates = gr.Textbox(label="Hates", interactive=True) with gr.Row(): sex = gr.Dropdown(["Male", "Female", "Other"], label="Sex", interactive=True) sexuality = gr.Textbox(label="Sexuality", interactive=True) age = gr.Slider(1, 100, label="Age", info="Choose between 1 and 100", interactive=True, step=1.0, value=21) description = gr.Textbox(label="Description", interactive=True) attributes = gr.Textbox(label="Attributes", interactive=True) with gr.Row(): personalityProfile = gr.Textbox(label="Psychological Profile", interactive=True) generatePersonality = gr.Button("2. Analyze Personality") with gr.Accordion("Speaking Traits"): genProfile = gr.Button("3. Generate Speaking Style", interactive=True) with gr.Column(scale=1, min_width=600): with gr.Row(): formality = gr.Dropdown(["Very formal", "Formal", "Neutral", "Informal", "Very informal"], label="Formality", interactive=True) pace = gr.Dropdown(["Very fast", "Fast", "Moderate", "Slow", "Very slow"], label="Pace", interactive=True) rhythm = gr.Dropdown(["Choppy", "Staccato", "Varied", "Flowing", "Melodious"], label="Rhythm", interactive=True) volume = gr.Dropdown(["Very loud", "Loud", "Moderate", "Soft", "Very soft"], label="Volume", interactive=True) emotionality = gr.Dropdown(["Very expressive", "Expressive", "Neutral", "Restrained", "Very restrained"], label="Emotionality", interactive=True) directness = gr.Dropdown(["Very direct", "Direct", "Balanced", "Indirect", "Very indirect"], label="Directness", interactive=True) with gr.Row(): humor = gr.Dropdown(["Frequently humorous", "Occasionally humorous", "Neutral", "Occasionally serious", "Frequently serious"], label="Humor", interactive=True) enunciation = gr.Dropdown(["Very clear", "Clear", "Neutral", "Relaxed", "Mumbled"], label="Enunciation", interactive=True) expressiveness = gr.Dropdown(["Very expressive", "Expressive", "Neutral", "Reserved", "Very reserved"], label="Expressiveness", interactive=True) accent_dialect = gr.Dropdown(["Strong regional accent", "Mild regional accent", "Neutral", "Mild foreign accent", "Strong foreign accent"], label="Accent/Dialect", interactive=True) politeness = gr.Dropdown(["Very polite", "Polite", "Neutral", "Blunt", "Very blunt"], label="Politeness", interactive=True) vocabulary = gr.Dropdown(["Highly sophisticated", "Sophisticated", "Average", "Basic", "Very basic"], label="Vocabulary", interactive=True) with gr.Row(): interruptions = gr.Dropdown(["Frequently interrupts", "Occasionally interrupts", "Balanced", "Occasionally allows others to interrupt", "Frequently allows others to interrupt"], label="Interruptions", interactive=True) hesitations = gr.Dropdown(["Frequently hesitates", "Occasionally hesitates", "Balanced", "Occasionally fluent", "Frequently fluent"], label="Hesitations", interactive=True) sentence_structure = gr.Dropdown(["Very complex", "Complex", "Average", "Simple", "Very simple"], label="Sentence Structure", interactive=True) sarcasm = gr.Dropdown(["Very sarcastic", "Sarcastic", "Occasionally sarcastic", "Rarely sarcastic", "Never sarcastic"], label="Sarcasm", interactive=True) colloquialisms = gr.Dropdown(["Frequently uses colloquialisms", "Occasionally uses colloquialisms", "Balanced", "Rarely uses colloquialisms", "Never uses colloquialisms"], label="Colloquialisms", interactive=True) energy_level = gr.Dropdown(["Very high energy", "High energy", "Moderate energy", "Low energy", "Very low energy"], label="Energy Level", interactive=True) with gr.Row(): defiance_rebellion = gr.Dropdown(["Frequently defiant", "Occasionally defiant", "Balanced", "Rarely defiant", "Never defiant"], label="Defiance/Rebellion", interactive=True) playfulness = gr.Dropdown(["Very playful", "Playful", "Occasionally playful", "Rarely playful", "Never playful"], label="Playfulness", interactive=True) vulgarity = gr.Dropdown(["Very vulgar", "Vulgar", "Occasionally vulgar", "Rarely vulgar", "Never vulgar"], label="Vulgarity", interactive=True) idiosyncrasies = gr.Dropdown(["Frequent idiosyncrasies", "Occasional idiosyncrasies", "Balanced", "Rare idiosyncrasies", "No idiosyncrasies"], label="Idiosyncrasies", interactive=True) emotional_tone = gr.Dropdown(["Very optimistic", "Optimistic", "Neutral", "Pessimistic", "Very pessimistic"], label="Emotional Tone", interactive=True) context_adaptability = gr.Dropdown(["Very adaptable", "Adaptable", "Balanced", "Inflexible", "Very inflexible"], label="Context Adaptability", interactive=True) with gr.Row(): subtext = gr.Dropdown(["Frequently uses subtext", "Occasionally uses subtext", "Balanced", "Rarely uses subtext", "Never uses subtext"], label="Subtext", interactive=True) metaphorical_language = gr.Dropdown(["Frequently uses metaphorical language", "Occasionally uses metaphorical language", "Balanced", "Rarely uses metaphorical language", "Never uses metaphorical language"], label="Metaphorical Language", interactive=True) cultural_references = gr.Dropdown(["Frequently uses cultural references", "Occasionally uses cultural references", "Balanced", "Rarely uses cultural references", "Never uses cultural references"], label="Cultural References", interactive=True) storytelling_ability = gr.Dropdown(["Frequent storyteller", "Occasional storyteller", "Balanced", "Rarely tells stories", "Never tells stories"], label="Storytelling Ability", interactive=True) with gr.Column(scale=1, min_width=600): gr.Markdown("""**SECRETS**\n Medical conditions : This will choose a random medical condition(s) that this character suffers from. Conditions will be saved only as a medical diagnosis code to save on token space and so it can be a secret to YOU as well. """) with gr.Row(): conditions_count = gr.Slider(1, 10, label="Number of conditions", info="Choose between 1 and 10", interactive=True, step=1.0, value=1) med_secret_button = gr.Button("5. Generate secret medical condition(s) (COMING SOON)", interactive=True) med_secret = gr.Textbox(label="Secrets", interactive=True, type='password') gr.Markdown("""Trauma : This will choose a random psychological event that affects how this character behaves. Example: Experiencing discrimination """) with gr.Row(): secrets_count = gr.Slider(1, 10, label="Number of issues", info="Choose between 1 and 10", interactive=True, step=1.0) secret_button = gr.Button("6. Generate secret issues(s) (COMING SOON)", interactive=False) secret = gr.Textbox(label="Secrets", interactive=True, type='password') situation = gr.TextArea(label="Situation (COMING SOON)", interactive=False) starting_message = gr.TextArea(label="Starting message (COMING SOON)", interactive=False) # sample_starters = gr.CheckboxGroup(["This year is flying by so fast.", # "It's quite sunny outside today.", # "People seem to be in a hurry all the time.", # "I hear birds chirping. It must be spring already.", # "The city looks different at night."], # label="Example conversation starters", info="These are simple statements designed to evoke a unique response without adding additional context. ", interactive=True), with gr.Row(): with gr.Column(scale=1): examples = gr.TextArea(label="Example chats (COMING SOON)", value="\n") def test(): print("trying....") state = demo.state state.inputs["charName"] = "New Name" demo.update(state) def genMedical(text): return "none" med_secret_button.click(generateMedicalSecrets, inputs=[conditions_count], outputs=[med_secret]) generate.click(getAndParseQuickStart, inputs=[quickStart, trait_count], outputs=[ rawQuickResults, charName, personality, body, likes, hates, sex, sexuality, age, description, personalityProfile, attributes ]) createJSON = gr.Button("4. Create JSON") quickStartResult = gr.JSON(label="result", interactive=False) def makePersonality(text): print("Asking AI for a profile") prompt = "Here are the details for you to analyze. Remember to return in the specified format: " + text response = openai.ChatCompletion.create( model="gpt-4-0613", messages=[ {"role": "system", "content": prompt_profile}, {"role": "user", "content": prompt} ]) response_content = response['choices'][0]['message']['content'] print(response_content) return response_content generatePersonality.click(makePersonality, inputs=[rawQuickResults], outputs=[personalityProfile]) genProfile.click(generateSpeakingStyle, inputs=[rawQuickResults], outputs=[ formality, pace, rhythm, volume, emotionality, directness, humor, enunciation, expressiveness, accent_dialect, politeness, vocabulary, interruptions, hesitations, sentence_structure, sarcasm, colloquialisms, energy_level, defiance_rebellion, playfulness, vulgarity, idiosyncrasies, emotional_tone, context_adaptability, subtext, metaphorical_language, cultural_references, storytelling_ability ]) def createJSONfile(charName, personality, body, likes, hates, sex, sexuality, age, description, personalityProfile, attributes, formality, pace, rhythm, volume, emotionality, directness, humor, enunciation, expressiveness, accent_dialect, politeness, vocabulary, interruptions, hesitations, sentence_structure, sarcasm, colloquialisms, energy_level, defiance_rebellion, playfulness, vulgarity, idiosyncrasies, emotional_tone, context_adaptability, subtext, metaphorical_language, cultural_references, storytelling_ability): ### Merging things into description description_unwrapped = f""" {charName} is a {age}-year-old {sexuality} {sex}. {description}. {charName} is {body}. {charName} likes {likes}. {charName} hates {hates}. """ speech_unwrapped = f""" {charName} speaks with a unique style: They {"are " + formality + " and" if formality!="Neutral" else ""} and speaks at a {pace} speed with a {rhythm} rhythm. {charName} {"speaks at a " + volume + " volume and " if volume!="Moderate" else ""}has a {emotionality} level of emotionality. {charName + " is " + directness + "." if directness!="Balanced" else ""} {charName + " is " + humor + "." if humor!="Neutral" else ""} Their clarity of speech is {enunciation} {charName + " is " + expressiveness + "." if expressiveness!="Neutral" else ""} They have a {accent_dialect} accent. {charName} {"is " + politeness + " and " if politeness!="Neutral" else ""}uses a {vocabulary} vocabulary. {"They " + interruptions + "." if interruptions!="Balanced" else ""} {"They " + hesitations + "." if interruptions!="Balanced" else ""} {charName} uses a {sentence_structure} sentence structure and is {sarcasm} {"They " + colloquialisms + "." if colloquialisms!="Balanced" else ""} They speak with {energy_level}{" and is " + defiance_rebellion + "." if defiance_rebellion!="Balanced" else "."} When {charName} speaks it is {playfulness} and {vulgarity}. {charName + " uses " + idiosyncrasies + "." if idiosyncrasies!="Balanced" else ""} They have a {emotional_tone} tone {charName + " is " + context_adaptability + " when the situation changes." if context_adaptability!="Balanced" else ""} {"They " + subtext + "." if subtext!="Balanced" else ""} {"They " + metaphorical_language + "." if metaphorical_language!="Balanced" else ""} {"They " + cultural_references + "." if cultural_references!="Balanced" else ""} {"They " + storytelling_ability + "." if storytelling_ability!="Balanced" else ""} """ output = f"""{{"name": "{charName}", "personality": "{personality}", "description": "{description_unwrapped}", "attributes" : "{attributes}", "psych_profile" : "{personalityProfile}", "speech_style": "{speech_unwrapped}" }}""" output = output.replace('\n', '') json_string = codecs.getdecoder("unicode_escape")(output)[0] # Load the JSON string into a Python object data = json.loads(json_string) # Clean up the data for key, value in data.items(): if isinstance(value, str): # Remove leading/trailing white spaces, newlines and replace multiple spaces with a single space cleaned_value = re.sub('\s+', ' ', value.strip()) data[key] = cleaned_value # Convert the cleaned data back to a compact JSON string cleaned_json_string = json.dumps(data, separators=(',', ':')) print(cleaned_json_string) return cleaned_json_string createJSON.click(createJSONfile, scroll_to_output=True, inputs=[ charName, personality, body, likes, hates, sex, sexuality, age, description, personalityProfile, attributes, formality, pace, rhythm, volume, emotionality, directness, humor, enunciation, expressiveness, accent_dialect, politeness, vocabulary, interruptions, hesitations, sentence_structure, sarcasm, colloquialisms, energy_level, defiance_rebellion, playfulness, vulgarity, idiosyncrasies, emotional_tone, context_adaptability, subtext, metaphorical_language, cultural_references, storytelling_ability ], outputs=[quickStartResult]) prompt_chat_test = """ Scenario: descriptor (Minimum 4 sentences) First_Message: descriptor (do not include any quotation marks. At least 3 sentences) Example_Chat: descriptor (do not print names or quotation marks, only use the format of starting with > for the user name and >> for the character name, for example: >Hi\n>>Hello! **i pick up a book**\n>What's up? What are you reading?\n>>**Looks at the book cover** Nothing much)""" prompt_Personality = """ formality (level of formal language use): Very formal, Formal, Neutral, Informal, Very informal\n pace (speed of speech): Very fast, Fast, Moderate, Slow, Very slow\n rhythm (pattern of speech): Choppy, Staccato, Varied, Flowing, Melodious\n volume (loudness of speech): Very loud, Loud, Moderate, Soft, Very soft\n emotionality (level of emotional expression): Very expressive, Expressive, Neutral, Restrained, Very restrained\n directness (level of straightforwardness): Very direct, Direct, Balanced, Indirect, Very indirect\n humor (frequency of humor in speech): Frequently humorous, Occasionally humorous, Neutral, Occasionally serious, Frequently serious\n enunciation (clarity of speech): Very clear, Clear, Neutral, Relaxed, Mumbled\n expressiveness (use of gestures and body language): Very expressive, Expressive, Neutral, Reserved, Very reserved\n accent (type of accent or dialect): Strong regional accent, Mild regional accent, neutral, Mild foreign accent, Strong foreign accent\n politeness (degree of politeness): Very polite, Polite, Neutral, Blunt, Very blunt\n vocabulary (range and type of words used): Highly sophisticated, Sophisticated, Average, Basic, Very basic\n interruptions (frequency of interruptions): Frequently interrupts, Occasionally interrupts, Balanced, Occasionally allows others to interrupt, Frequently allows others to interrupt\n hesitations (frequency of pauses or fillers): Frequently hesitates, Occasionally hesitates, Balanced, Occasionally fluent, Frequently fluent\n sentence structure (complexity of sentences): Very complex, Complex, Average, Simple, Very simple\n sarcasm (frequency and intensity of sarcasm): Very sarcastic, Sarcastic, Occasionally sarcastic, Rarely sarcastic, Never sarcastic\n colloquialisms (use of slang or colloquial language): Frequently uses colloquialisms, Occasionally uses colloquialisms, Balanced, Rarely uses colloquialisms, Never uses colloquialisms\n energy level (level of enthusiasm or intensity in speech): Very high energy, High energy, Moderate energy, Low energy, Very low energy\n defiance/rebellion (tendency to challenge or question things in speech): Frequently defiant, Occasionally defiant, Balanced, Rarely defiant, Never defiant\n playfulness (exhibits a playful tone in speech): Very playful, Playful, Occasionally playful, Rarely playful, Never playful\n vulgarity (frequency and intensity of crude language or coarse expressions): Very vulgar, Vulgar, Occasionally vulgar, Rarely vulgar, Never vulgar\n idiosyncrasies (unique speech habits or quirks): Frequent idiosyncrasies, Occasional idiosyncrasies, Balanced, Rare idiosyncrasies, No idiosyncrasies\n emotional tone (overall emotional 'color' of the character's speech): Very optimistic, Optimistic, Neutral, Pessimistic, Very pessimistic\n context adaptability (how a character's speech changes depending on the situation or person they're speaking to): Very adaptable, Adaptable, Balanced, Inflexible, Very inflexible\n subtext (the underlying, implied meaning in a character's speech): Frequently uses subtext, Occasionally uses subtext, Balanced, Rarely uses subtext, Never uses subtext\n metaphorical language (use of metaphors, similes, and other figurative language in a character's speech): Frequently uses metaphorical language, Occasionally uses metaphorical language, Balanced, Rarely uses metaphorical language, Never uses metaphorical language\n cultural references (references to their culture, such as idioms, phrases, or words from their native language, references to cultural practices or beliefs): Frequently uses cultural references, Occasionally uses cultural references, Balanced, Rarely uses cultural references, Never uses cultural references\n storytelling ability (frequency of telling stories or anecdotes in their speech): Frequent storyteller, Occasional storyteller, Balanced, Rarely tells stories, Never tells stories\n """ prompt_profile = """ Based on your understanding of this character, please provide a brief personality assessment using the following typologies: Myers-Briggs Type Indicator (MBTI): Introverted/Extraverted, Sensing/Intuitive, Thinking/Feeling, Judging/Perceiving. Enneagram: main type, wing, and instinctual variant (self-preservation/sp, social/so, or sexual/sx). Enneagram Tritype: two additional types from different centers of intelligence. Socionics: similar to MBTI, identify the character's personality type. Global 5/SLOAN: Reserved/Social, Calm/Limbic, Organized/Unstructured, Accommodating/Egocentric, Non-Curious/Inquisitive. Please return the result codes in this format: "MBTI - Enneagram - Instinctual Variant - Tritype - Socionics - SLOAN". For example: INTJ - 3w4 - sp/sx - 358 - LIE - RCOEI". Do not explain or add other text or context. """ inst = demo.launch()