text2image_2 / generate_prompts.py
RanM's picture
Update generate_prompts.py
810d3ae verified
raw
history blame contribute delete
No virus
2.95 kB
import base64
import re
def insert_description(sentence, character, description):
"""
Integrates the character, its type, and its description within the sentence right after the character's name is mentioned.
Parameters:
- sentence (str): The original sentence where the description is to be inserted.
- character (str): The character whose description is to be added.
- description (dict): The dictionary containing the character's type and descriptive words.
Returns:
str: The modified sentence with the character's description if the character is present; otherwise, returns the original sentence.
"""
character_lower = character.lower()
# Use regex to find and replace the character's name with the name plus the description
modified_sentence = re.sub(
fr"\b{character}\b",
fr"{character.capitalize()}{description}",
sentence,
flags=re.IGNORECASE
)
return modified_sentence
def process_text(sentence, character_dict):
"""
Enhances the given sentence by incorporating descriptions for each mentioned character.
Falls back to the original sentence if `character_dict` is empty.
Parameters:
- sentence (str): The original sentence to be processed.
- character_dict (dict): A dictionary mapping characters to their respective descriptions.
Returns:
str: The sentence modified to include character descriptions where applicable, or the original sentence.
"""
try:
# If character_dict is empty, return the original sentence
if not character_dict:
print("Character descriptions are empty, returning the original sentence.")
return sentence
# Start with the original sentence
modified_sentence = sentence
for character, description in character_dict.items():
# Insert description into the sentence where the character is mentioned
modified_sentence = insert_description(modified_sentence, character, description)
print(f'modified_sentence: {modified_sentence}')
return modified_sentence
except Exception as e:
print(f"Error processing text: {e}. Returning original sentence.")
return sentence
def generate_prompt(sentence, character_dict, selected_style):
"""
Generates a prompt for image generation based on the selected style and input text.
Parameters:
- style (str): The chosen illustration style.
- text (str): The input text for the illustration.
Returns:
tuple: A prompt string.
"""
# Retrieve the enhanced sentence associated with the original text
image_descriptions = process_text(sentence, character_dict)
# Define prompts and other parameters
prompt = f"Create a whimsical {selected_style} illustration ideal for a children's book page, from: {image_descriptions}."
return prompt