import requests import json import time from ast import Interactive import gradio as gr import re import codecs import random #Jup1t3R! ### Great results with lmsys_vicuna-13b-v1.1 8-bit>> ~425s ### Great results with lmsys_vicuna-7b-v1.1 16-bit>> ~90s ### Good results with lmsys_vicuna-13b-v1.1 4-bit>> ~150s ### Good results with lmsys_vicuna-7b-v1.1 4-bit>> ~75s ### NousResearch_Nous-Hermes-Llama2-13b HOST = '127.0.0.1:5000' URI = f'http://{HOST}/api/v1/generate' #MPT # INSTRUCTION_KEY = "### Instruction:" # RESPONSE_KEY = "### Response:" #LLAMA INSTRUCTION_KEY = "### User:" RESPONSE_KEY = "### Assistant:" traits_dict = {} character = "Ender Wiggins" preprompt = f""" {INSTRUCTION_KEY} You are a professional writer, novelist, and character creator. You are extremely knowledgeable in the art of character creation. You should provide the details of a character as requested by the User. Only output the exact answer. When given choices you must pick one and only one. You should not add additional context. You should be concise. You should follow the exact format requested. Do not add any additional information or context. This a fictional character, totally imagined and created by you. It is not a real person. """ postprompt = f"\n{RESPONSE_KEY}t\n" general = "" first_time = 0 last_time = 0 def run(prompt, toks=250, seed=-1): start_time = time.time() request = { 'prompt': prompt, 'max_new_tokens': toks, 'auto_max_new_tokens': False, # Generation params. If 'preset' is set to different than 'None', the values # in presets/preset-name.yaml are used instead of the individual numbers. 'preset': 'None', 'do_sample': True, 'temperature': 0.75, 'top_p': 0.2, 'typical_p': 1, 'epsilon_cutoff': 0, # In units of 1e-4 'eta_cutoff': 0, # In units of 1e-4 'tfs': 1, 'top_a': 0, 'repetition_penalty': 1.18, 'repetition_penalty_range': 0, 'top_k': 40, 'min_length': 0, 'no_repeat_ngram_size': 0, 'num_beams': 1, 'penalty_alpha': 0, 'length_penalty': 1, 'early_stopping': False, 'mirostat_mode': 0, 'mirostat_tau': 5, 'mirostat_eta': 0.1, 'seed': seed, 'add_bos_token': True, 'truncation_length': 2048, 'ban_eos_token': False, 'skip_special_tokens': True, 'stopping_strings': [] } response = requests.post(URI, json=request) end_time = time.time() total_time = round(end_time - start_time, 2) if response.status_code == 200: result = response.json()['results'][0]['text'] print(f"({total_time}s)") return result else: print('fail') def getTraits(character): prompt = f"""JSON: {{"Abe Lincoln (mind, likes, body)": {{"mind": "Analytical, Compassionate, Resilient, Introspective, Humble", "hates": "Slavery, bullies, bad weather, anchovies", "likes": "Reading, Writing, Storytelling, Chess, Philanthropy", "personality": "Kind, soft-hearted, energetic", "body": "lean, tall, brown hair, muscular, long face"}}}}, {{"{character} (mind, likes, hates, body, personality)": """ print("Getting initial traits.") return run(prompt, 350) def getSex(character): prompt = f"Is Abe Lincoln most likely Male, Female, or Other? Male\nIs {character} most likely Male, Female, or Other?" print("Getting sex.") return run(prompt, 2) def getSexuality(character): prompt = f"Is Abe Lincoln most likely Heterosexual, Homosexual, or Bisexual? Heterosexual.\nIs {character} most likely Heterosexual, Homosexual, or Bisexual?" # prompt = f"Here is a list of whether someone is a \"Heterosexual\",\"Homosexual\", or \"Bisexual\":\nAbe Lincoln's sexualality is \"Heterosexual\"\nElton John's sexualality is \"Homosexual\"\nJames Hille's sexualality is \"Heterosexual\"\nJoey Ball's sexualality is \"Bisexual\"\n{character}'s sexualality is " prompt = preprompt + prompt print("Getting sexuality.") return run(prompt, 6) def getAge(character): prompt = f"Ages:\nAbraham Lincoln: age is \"54\"\nJames Hille: age is \"28\"\nJohnny McBoom: age is \"8\"{character}: age is " print("Getting age.") return run(prompt, 6) def getGeneralDescription(json, name): prompt = f"""Here is a formatted dataset about {name}: {json} Based on this information, use your experience as a writer to write a beautiful 7 sentence summary of {name} for another writer. Although inspired by a real character, create a fictitious version. Use present tense.\n{RESPONSE_KEY}: Sure! Here is a plain-text summary of a fictitious character based on the information you provided:""" print("Getting description.") result = run(preprompt + prompt, 350) return result.strip("`").strip('\n') def getName(character): prompt = f"{RESPONSE_KEY}Here is a list of names that fit with a fictitious character that would appear on their birth certificate without any additional context or information other than their name:\nA childrens book character of a brilliant scientist's name is: Professor Brains\nAbe Licoln's name is: Abraham Licoln\nA fun loving Teddy Bear's name is: Teddy (fuzzmuffin)_McFuzz\nHans from Star War's name is: Hans Solo\n{character}'s name is:" print("Getting name.") prompt = preprompt + prompt return run(prompt, 12).strip() def remove_extra_braces(data_str): parts = data_str.split('}') if len(parts) > 2: data_str = "}".join(parts[:2]) + '}' return data_str def remove_after_first_brace(data_str): return data_str.split('}', 1)[0] + '}' def remove_non_letters(s): return ''.join([char for char in s if char.isalpha()]) def remove_non_numbers(s): return ''.join([char for char in s if char.isdigit()]) def getAllSpeech(general, name, psych): speech_traits = { "formality": "Formality refers to the level of formal language used in writing. A very formal style uses sophisticated grammar and vocabulary, while an informal style uses more slang and colloquialisms. For example, a formal essay would avoid contractions and slang terms.", "pace": "Pace is the speed at which sentences follow each other in writing. A fast pace has short, rapid sentences, while a slow pace uses longer sentences with more pausing. For example, action scenes tend to have a fast pace with terse sentences.", "rhythm": "Rhythm is the pattern and flow of sentences in writing. Choppy writing is fragmented, while melodious writing has a smooth, musical flow. For example, good rhythm makes the writing pleasing to read aloud.", "volume": "Volume is the forcefulness of the writing. Loud writing is emphatic and insistent, while soft writing is understated and subtle. For example, loud writing uses strong statements and bold words.", "emotionality": "Emotionality is how much emotion is conveyed in the writing. Highly emotional writing vividly expresses feelings, while restrained writing holds back. For example, emotional writing might describe reactions in depth.", "directness": "Directness refers to how straightforward the writing is. Very direct writing bluntly states things, while indirect writing implies things more subtly. For example, direct writing avoids euphemisms.", "humor": "Humor is how often comedy or joking is used in the writing. Humorous writing contains jokes and amusing observations, while serious writing avoids comedy. For example, humorous writing might include wry asides or witty wordplay.", "enunciation": "Enunciation is how clearly the writing communicates meaning. Strong enunciation is easy to follow, while weak enunciation is convoluted and unclear. For example, clear enunciation uses precise and accessible language.", "expressiveness": "Expressiveness refers to the use of descriptive language and details. Expressive writing uses vivid descriptions, while reserved writing is sparse on details. For example, expressive writing might paint visual scenes or convey emotions.", "accent": "Accent in writing refers to stylistic quirks that reveal the writer's origins. Strong regional or cultural accents are very noticeable in the writing style. For example, dialect words or colloquialisms can convey accent.", "politeness": "Politeness is the degree of etiquette and manners in writing. Very polite writing humbly apologizes and thanks the reader, while blunt writing is tactless. For example, polite writing uses courtesy words like 'please' and 'thank you'.", "vocabulary": "Vocabulary is the range and complexity of words used. Sophisticated vocabulary uses advanced and precise words, while basic vocabulary uses simpler words. For example, strong vocabulary avoids overuse of generic terms.", "interruptions": "Interruptions refer to abrupt shifts in focus or topic. Writing with frequent interruptions jumps between ideas rapidly, while focused writing maintains continuity. For example, interruptions might take the form of digressions or asides.", "hesitations": "Hesitations are pauses and fillers like 'um' translated to writing. Fluent writing flows smoothly, while hesitant writing seems fragmented and disjointed. For example, hesitations include false starts and rambling.", "sentence structure": "Sentence structure is the complexity and variety of sentences. Complex writing varies sentence structure, while simple writing uses short, basic syntax. For example, sophisticated writing employs devices like subordination and parallelism.", "sarcasm": "Sarcasm refers to the use of irony, satire and hyperbole. Highly sarcastic writing mocks through overstated criticism, while sincere writing avoids sarcasm. For example, sarcastic writing might exaggeratedly praise something terrible.", "colloquialisms": "Colloquialisms are informal words and slang expressions. Writing with many colloquialisms includes words like 'gonna' and 'kinda', while formal writing avoids slang. For example, colloquial writing might use idioms or new slang.", "energy level": "Energy level is the enthusiasm and intensity of the writing. High energy writing is forceful and emphatic, while low energy writing is mellow and laid back. For example, high energy writing uses vivid language and strong statements.", "defiance/rebellion": "Defiance refers to challenging norms and authority. Defiant writing openly bucks convention, while compliant writing respects traditions. For example, defiant writing might flout grammatical rules or social propriety.", "playfulness": "Playfulness is exhibiting a lighthearted, fun tone. Highly playful writing jokes around, while serious writing avoids humor and focuses on facts. For example, playful writing might include silly wordplay or exaggerated scenarios.", "vulgarity": "Vulgarity is the use of profanity and coarse language. Vulgar writing frequently swears, while refined writing uses polite language. For example, vulgarity includes crass and offensive slang.", "idiosyncrasies": "Idiosyncrasies are unique stylistic habits or quirks. Writing with frequent idiosyncrasies has distinctive oddities, while conventional writing is straightforward. For example, idiosyncratic writing might invent new words or phrases.", "emotional tone": "Emotional tone is the overall attitude of the writing. Optimistic writing has a positive outlook, while pessimistic writing views things negatively. For example, an upbeat tone conveys enthusiasm and hope.", "context adaptability": "Context adaptability is tailoring the writing based on the situation. Adaptable writing fits the setting and audience, while inflexible writing doesn't shift in style. For example, academic writing uses more formal language than casual writing.", "subtext": "Subtext is the underlying, implied meaning. Writing with a lot of subtext has layers of hidden significance, while on-the-nose writing is overt and literal. For example, subtext can hint at ideas without stating them directly.", "metaphorical language": "Metaphorical language uses figurative expressions like metaphors. Writing rich in metaphor speaks indirectly through symbolism, while literal writing is straightforward. For example, metaphors make vivid comparisons between unlike things.", "cultural references": "Cultural references are words, phrases or customs specific to a culture. Writing with many cultural references invokes the writer's native culture, while generic writing uses universal language. For example, cultural references might include idioms or references to historical events.", "storytelling ability": "Storytelling ability is skill at narrating events and anecdotes. Strong storytelling engages the reader with detailed accounts, while weak storytelling briefly summarizes. For example, vivid storytelling sets scenes and reveals details gradually.", "abbreviations": "Abbreviations refer to shortened forms like acronyms and initialisms. Writing with many abbreviations uses things like 'LOL' and 'IDK', while formal writing avoids abbreviations. For example, informal writing often contains abbreviations for quick communication.", "grammar spelling": "Grammar and spelling refer to the proper use of syntax, mechanics, and word forms. Strong grammar and spelling adheres to conventions, while poor grammar makes frequent mistakes. For example, correct grammar avoids run-on sentences or tense errors." } speech_traits_concise = { "etiquette": "Etiquette combines formality and politeness. Formal, polite language uses sophistication, while informal, blunt language uses more slang and direct phrasing. For example, formal speech says 'Thank you for your time' rather than 'Thanks'.", "fluency": "Fluency combines pace and hesitations. Fluent speech flows smoothly without pauses or filler words, while disjointed speech is fragmented with um's and ah's. For example, fluent speech avoids rambling run-on sentences.", "articulateness": "Articulateness combines enunciation, grammar and spelling for clarity and correctness. Articulate speech is precise and proper, while inarticulate speech is unclear or ungrammatical. For example, articulate speech avoids slang terms and pronounces words clearly.", "vocabulary": "Vocabulary is the range and complexity of words used. Sophisticated vocabulary uses advanced and precise words, while basic vocabulary uses simpler words. For example, strong vocabulary avoids overuse of generic terms like 'stuff' and 'things'.", "emotional affect": "Emotional affect covers tone, emotionality and optimism/pessimism. Writing can convey a wide range of emotions from positive to negative. For example, an upbeat tone conveys enthusiasm and hope.", "lightheartedness": "Lightheartedness covers playfulness and humor. Light, comedic language uses jokes, amusing observations, and silly wordplay. For example, humorous speech exaggerates scenarios for comic effect.", "vulgarity": "Vulgarity refers to the use of profanity and coarse language. Vulgar speech frequently swears, while refined speech uses polite language. For example, vulgarity includes crass and offensive slang.", "regionalisms": "Regionalisms include accents and colloquialisms that reveal origins through dialects and slang. For example, regional speech may use distinct idioms or pronunciations.", "irreverence": "Irreverence combines defiance and taboo topics that challenge propriety norms. For example, irreverent speech may use inappropriate humor or flout etiquette.", "bluntness vs subtlety": "Bluntness directly states meaning, while subtlety implies meaning indirectly through hints and implications. For example, blunt speech is very direct, while subtle speech hints at ideas.", "narrative vividness": "Narrative vividness covers expressiveness and storytelling ability using descriptive details and accounts. Vivid narratives engage with scenic details, while bare narratives just summarize events." } speech_options = { "formality": ["Very informal","Informal","Neutral","Formal","Very formal"], "pace": ["Very slow","Slow","Moderate","Fast","Very fast"], "rhythm": ["Melodious","Flowing","Varied","Staccato","Choppy"], "volume": ["Very soft","Soft","Moderate","Loud","Very loud"], "emotionality": ["Very restrained","Restrained","Neutral","Expressive","Very expressive"], "directness": ["Very indirect","Indirect","Balanced","Direct","Very direct"], "humor": ["Frequently serious","Occasionally serious","Neutral","Occasionally humorous","Frequently humorous"], "enunciation": ["Mumbled","Relaxed","Neutral","Clear","Very clear"], "expressiveness": ["Very reserved","Reserved","Neutral","Expressive","Very expressive"], "accent": ["Strong foreign accent","Mild foreign accent","Neutral","Mild regional accent","Strong regional accent"], "politeness": ["Very blunt","Blunt","Neutral","Polite","Very polite"], "vocabulary": ["Very basic","Basic","Average","Sophisticated","Highly sophisticated"], "interruptions": ["Frequently allows others to interrupt","Occasionally allows others to interrupt","Balanced","Occasionally interrupts","Frequently interrupts"], "hesitations": ["Frequently fluent","Occasionally fluent","Balanced","Occasionally hesitates","Frequently hesitates"], "sentence_structure": ["Very simple","Simple","Average","Complex","Very complex"], "sarcasm": ["Never sarcastic","Rarely sarcastic","Occasionally sarcastic","Sarcastic","Very sarcastic"], "colloquialisms": ["Never uses colloquialisms","Rarely uses colloquialisms","Balanced","Occasionally uses colloquialisms","Frequently uses colloquialisms"], "energy_level": ["Very low energy","Low energy","Moderate energy","High energy","Very high energy"], "defiance/rebellion": ["Never defiant","Rarely defiant","Balanced","Occasionally defiant","Frequently defiant"], "playfulness": ["Never playful","Rarely playful","Occasionally playful","Playful","Very playful"], "vulgarity": ["Never vulgar","Rarely vulgar","Occasionally vulgar","Vulgar","Very vulgar"], "idiosyncrasies": ["No idiosyncrasies","Rare idiosyncrasies","Balanced","Occasional idiosyncrasies","Frequent idiosyncrasies"], "emotional_tone": ["Very pessimistic","Pessimistic","Neutral","Optimistic","Very optimistic"], "context_adaptability": ["Very inflexible","Inflexible","Balanced","Adaptable","Very adaptable"], "subtext": ["Never uses subtext","Rarely uses subtext","Balanced","Occasionally uses subtext","Frequently uses subtext"], "metaphorical_language": ["Never uses metaphorical language","Rarely uses metaphorical language","Balanced","Occasionally uses metaphorical language","Frequently uses metaphorical language"], "cultural_references": ["Never uses cultural references","Rarely uses cultural references","Balanced","Occasionally uses cultural references","Frequently uses cultural references"], "storytelling_ability": ["Never tells stories","Rarely tells stories","Balanced","Occasional storyteller","Frequent storyteller"], "abbreviations": ["Never","Rarely","Occasionally","Frequently","Very frequently"], "grammar_spelling": ["Very poor","Poor","Average","Good","Excellent"] } traits_dict['speech']={} traits_combo="" for key, value in speech_traits_concise.items(): trait = key definition = value # options = speech_options[trait] # option1 = options[0] # option2 = options[1] # option3 = options[2] # option4 = options[3] # option5 = options[4] prepreface = f"{general} Their psychological profile is {psych}\n" preface = f"{definition}\n" p = f"Based on your knowledge of {name} and your experience as a professional writer describe their {trait},\n{RESPONSE_KEY}" prompt = f"{INSTRUCTION_KEY}\n{prepreface}\n{preface}\n{p}" print(f"Getting speech > {trait}.") response = run(prompt, 90, .4) prompt = f"{INSTRUCTION_KEY}\n{prepreface}\nPlease take the following description and summarize in two sentences:\n{response}\n{RESPONSE_KEY}Sure, here is a shortened description:" print(f"Shortening > {trait}.") response = run(prompt, 70, .8) traits_combo += response prompt = f""" {INSTRUCTION_KEY} Please take this description of a character's speaking pattern, clean it up, remove any non-relevant information, and make sure the description is clear. For example: \"sometimes struggles to find the right words but is generally skilled at communicating\": {traits_combo} {RESPONSE_KEY} Sure! I've removed the name and any irrelevent information. Here is the revised description: """ print(f"Optimizing speech profile.") response = run(prompt, 350, .9) traits_dict['speech_unwrapped'] = response return traits_combo # def unwrapText(traits_dict): # description_unwrapped = f""" # {traits_dict['name']} is a {traits_dict['age']}-year-old {traits_dict['sexuality']} {traits_dict['sex']}.{traits_dict['general']} {traits_dict['name']} likes {traits_dict['likes']}. {traits_dict['name']} hates {traits_dict['hates']}. # """ # traits_dict['description'] = description_unwrapped.strip('\n') # speech_unwrapped = f""" # {traits_dict['name']} speaks with a unique style: # They {"are " + traits_dict['speech']['formality'] + " and" if traits_dict['speech']['formality']!="neutral" else ""} speak at a {traits_dict['speech']['pace']} speed with a {traits_dict['speech']['rhythm']} rhythm. # {traits_dict['name']} {"speaks at a " + traits_dict['speech']['volume'] + " volume and " if traits_dict['speech']['volume']!="moderate" else ""}has a {traits_dict['speech']['emotionality']} level of emotionality. # {traits_dict['name'] + " is " + traits_dict['speech']['directness'] + "." if traits_dict['speech']['directness']!="balanced" else ""} # {traits_dict['name'] + " is " + traits_dict['speech']['humor'] + "." if traits_dict['speech']['humor']!="neutral" else ""} # Their clarity of speech is {traits_dict['speech']['enunciation']} # {traits_dict['name'] + " is " + traits_dict['speech']['expressiveness'] + "." if traits_dict['speech']['expressiveness']!="neutral" else ""} # They have a {traits_dict['speech']['accent']} accent. # {traits_dict['name']} {"is " + traits_dict['speech']['politeness'] + " and " if traits_dict['speech']['politeness']!="neutral" else ""}uses a {traits_dict['speech']['vocabulary']} vocabulary. # {"They " + traits_dict['speech']['interruptions'] + "." if traits_dict['speech']['interruptions']!="balanced" else ""} # {"They " + traits_dict['speech']['hesitations'] + "." if traits_dict['speech']['interruptions']!="balanced" else ""} # {traits_dict['name']} uses a {traits_dict['speech']['sentence_structure']} sentence structure and is {traits_dict['speech']['sarcasm']}{" They " + traits_dict['speech']['colloquialisms'] + "." if traits_dict['speech']['colloquialisms']!="balanced" else ""} # They speak with {traits_dict['speech']['energy_level']}{" and is " + traits_dict['speech']['defiance/rebellion'] + "." if traits_dict['speech']['defiance/rebellion']!="balanced" else "."} # When {traits_dict['name']} speaks it is {traits_dict['speech']['playfulness']} and {traits_dict['speech']['vulgarity']}. # {traits_dict['name'] + " uses " + traits_dict['speech']['idiosyncrasies'] + "." if traits_dict['speech']['idiosyncrasies']!="balanced" else ""} # They have a {traits_dict['speech']['emotional_tone']} tone # {traits_dict['name'] + " is " + traits_dict['speech']['context_adaptability'] + " when the situation changes." if traits_dict['speech']['context_adaptability']!="balanced" else ""} # {"They " + traits_dict['speech']['subtext'] + "." if traits_dict['speech']['subtext']!="Balanced" else ""} # {"They " + traits_dict['speech']['metaphorical_language'] + "." if traits_dict['speech']['metaphorical_language']!="balanced" else ""} # {"They " + traits_dict['speech']['cultural_references'] + "." if traits_dict['speech']['cultural_references']!="balanced" else ""} # {"They " + traits_dict['speech']['storytelling_ability'] + "." if traits_dict['speech']['storytelling_ability']!="balanced" else ""} # {"They write with " + traits_dict['speech']['grammar_spelling'] + " grammar and spelling."} # {"They " + traits_dict['speech']['abbreviations'] + " use of abbreviations like 'lol' and 'brb'."} # """ # traits_dict['speech_unwrapped'] = speech_unwrapped # print(f"{speech_unwrapped} {description_unwrapped}") # prompt = f""" # {INSTRUCTION_KEY} Please take this description of a character's speaking pattern, clean it up, and make sure the description is clear: {speech_unwrapped} # {RESPONSE_KEY} Sure! Here is the revised description: # """ # print(f"Correcting speech profile.") # response = run(prompt, 250) # traits_dict['speech_unwrapped'] = response def getPsychProfile(general): prompt = f""" {preprompt} {general} Based on your understanding of this character, analyze their psychological profile using the standard profiles: 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. Tell me your analysis in this exact 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. {RESPONSE_KEY} Sure! Based on the description of this character, and without any explanation, their psychological profile is """ print(f"Getting psych profile.") response = run(prompt, 120) return response.strip('"') def getThoughtAndInteraction(): prompt="" # how would this character think (self-talk) and what kinds of actions would they commonly take. mannerisms? def test(): prompt = f""" {INSTRUCTION_KEY} {traits_dict['general']} {traits_dict['speech_unwrapped']} Use this information and your writing and creative experience to create a sample dialogue between {traits_dict['name']} and a fictional neutral character named John. {traits_dict['name']} must speak exactly as specified. Words chosen, topic discussed, grammar, sentence structure, and vocabulary should all be considered when shaping this conversation. {RESPONSE_KEY} """ response = run(prompt, 350) print(f"*1* {response} ***") preprompt = prompt + response prompt = f""" {INSTRUCTION_KEY} Using the speaking style described, revise that conversation to best match how {traits_dict['name']} would really speak {RESPONSE_KEY} """ response = run(preprompt + prompt, 500) print(f"*2* {response} ***") # def go(): # first_time = time.time() # cleaned_data = remove_after_first_brace(getTraits(character)) # traits_dict = json.loads(cleaned_data) # for key, value in traits_dict.items(): # if isinstance(value, str): # traits_dict[key] = value.lower() # traits_dict['name'] = getName(character) # traits_dict['sex'] = remove_non_letters(getSex(character)) # traits_dict['sexuality'] = remove_non_letters(getSexuality(character)) # traits_dict['age'] = remove_non_numbers(getAge(character)) # traits_dict['general'] = getGeneralDescription(traits_dict, traits_dict['name']) # traits_dict['psych'] = getPsychProfile(traits_dict['general']) # getAllSpeech(traits_dict['general'], traits_dict['name']) # unwrapText(traits_dict) # last_time = time.time() # total_time = round(last_time - first_time, 2) # print(f"Total time taken >> {total_time}") # print(" ################# OUTPUT #################") # print(json.dumps(traits_dict)) # print(" ################# END #################") # # for key, value in traits_dict.items(): # # print(f"{key}: {value}") # test() with gr.Blocks() as demo: rawQuickResults=gr.Textbox(visible=False) gr.Markdown( """ # Character Maker v0.2 # """) 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.Textbox(label="Quick Start", info="Use AI to fill out all fields based on your description.") generate = gr.Button("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 (this is currently ignored)", interactive=False, 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", visible=False): speechOverview = gr.TextArea(label="Speech 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 genMedical(text): return "none" med_secret_button.click(generateMedicalSecrets, inputs=[conditions_count], outputs=[med_secret]) createJSON = gr.Button("4. Create JSON") quickStartResult = gr.JSON(label="result", interactive=True) def updateFields(text): print("updating fields") charName = text.get('name', '') personality = text.get('personality', '') body = text.get('body', '') likes = text.get('likes', '') hates = text.get('hates', '') sex = text.get('sex', '') sexuality = text.get('sexuality', '') age = text.get('age', '') description = text.get('general', '') personalityProfile = text.get('psych', '') attributes = text.get('attributes', '') speechOverview = text.get('speech_unwrapped', '') return [ charName, personality, body, likes, hates, sex, sexuality, age, description, personalityProfile, attributes, speechOverview ] quickStartResult.change(updateFields, inputs=[quickStartResult], outputs=[ charName, personality, body, likes, hates, sex, sexuality, age, description, personalityProfile, attributes, speechOverview ]) def generateQuickStart(text): first_time = time.time() cleaned_data = remove_after_first_brace(getTraits(text)) traits_dict = json.loads(cleaned_data) for key, value in traits_dict.items(): if isinstance(value, str): traits_dict[key] = value.lower() traits_dict['name'] = getName(text) traits_dict['sex'] = remove_non_letters(getSex(text)) traits_dict['sexuality'] = remove_non_letters(getSexuality(text)) traits_dict['age'] = remove_non_numbers(getAge(text)) traits_dict['general'] = getGeneralDescription(traits_dict, traits_dict['name']) traits_dict['psych'] = getPsychProfile(traits_dict['general']) traits_dict['speech_unwrapped'] = getAllSpeech(traits_dict['general'], traits_dict['name'], traits_dict['psych']) # unwrapText(traits_dict) last_time = time.time() total_time = round(last_time - first_time, 2) print(f"completed in {total_time} s") return traits_dict generate.click(generateQuickStart, inputs=[quickStart], outputs=[quickStartResult]) inst = demo.launch(server_port=7866)