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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from transformers import BlipProcessor, BlipForConditionalGeneration
|
| 5 |
+
import time
|
| 6 |
+
from gradio_client import Client
|
| 7 |
+
|
| 8 |
+
blipper="Salesforce/blip-image-captioning-large"
|
| 9 |
+
chatter="K00B404/transcript_image_generator"
|
| 10 |
+
|
| 11 |
+
# Load BLIP model for image captioning
|
| 12 |
+
processor = BlipProcessor.from_pretrained(blipper)
|
| 13 |
+
model = BlipForConditionalGeneration.from_pretrained(blipper)
|
| 14 |
+
|
| 15 |
+
# Initialize the API client for the chatbot
|
| 16 |
+
chatbot_client = Client(chatter)
|
| 17 |
+
|
| 18 |
+
def caption_to_persona(caption):
|
| 19 |
+
"""Convert a basic image caption into a character persona prompt"""
|
| 20 |
+
persona = f"""You are {caption.replace('arafed image of ','a ')}
|
| 21 |
+
|
| 22 |
+
Your personality, speech patterns, knowledge, and behavior should reflect this description.
|
| 23 |
+
When responding to users:
|
| 24 |
+
1. Stay in character at all times
|
| 25 |
+
2. Use speech patterns and vocabulary that would be natural for your character
|
| 26 |
+
3. Reference experiences, emotions, and perspectives that align with your character's background
|
| 27 |
+
4. Maintain a consistent personality throughout the conversation
|
| 28 |
+
|
| 29 |
+
Additional context: Your responses should vary in length based on what would be natural for your character.
|
| 30 |
+
Some characters might be terse while others might be more verbose."""
|
| 31 |
+
|
| 32 |
+
return persona
|
| 33 |
+
|
| 34 |
+
def generate_persona(img, min_len, max_len, persona_detail_level):
|
| 35 |
+
# Process the image
|
| 36 |
+
raw_image = Image.open(img).convert('RGB')
|
| 37 |
+
inputs = processor(raw_image, return_tensors="pt")
|
| 38 |
+
|
| 39 |
+
# Generate caption with specified length constraints
|
| 40 |
+
start = time.time()
|
| 41 |
+
out = model.generate(**inputs, min_length=min_len, max_length=max_len)
|
| 42 |
+
caption = processor.decode(out[0], skip_special_tokens=True)
|
| 43 |
+
|
| 44 |
+
# Enhance the caption based on detail level
|
| 45 |
+
if persona_detail_level == "Basic":
|
| 46 |
+
enhanced_caption = caption
|
| 47 |
+
elif persona_detail_level == "Detailed":
|
| 48 |
+
enhanced_caption = f"{caption} You have a distinct personality with unique mannerisms and speech patterns."
|
| 49 |
+
else: # Comprehensive
|
| 50 |
+
enhanced_caption = f"{caption} You have a complex backstory, rich emotional depth, unique perspectives, and distinctive speech patterns that set you apart."
|
| 51 |
+
|
| 52 |
+
# Generate persona from caption
|
| 53 |
+
persona = caption_to_persona(enhanced_caption)
|
| 54 |
+
|
| 55 |
+
# Calculate processing time
|
| 56 |
+
end = time.time()
|
| 57 |
+
total_time = f"Processing time: {end - start:.2f} seconds"
|
| 58 |
+
|
| 59 |
+
return caption, persona, total_time
|
| 60 |
+
|
| 61 |
+
def chat_with_persona(message, history, system_message, max_tokens, temperature, top_p):
|
| 62 |
+
"""Function to interact with the chatbot API using the generated persona"""
|
| 63 |
+
try:
|
| 64 |
+
# Call the API with the current message and system prompt (persona)
|
| 65 |
+
response = chatbot_client.predict(
|
| 66 |
+
message=message,
|
| 67 |
+
system_message=system_message,
|
| 68 |
+
max_tokens=max_tokens,
|
| 69 |
+
temperature=temperature,
|
| 70 |
+
top_p=top_p,
|
| 71 |
+
api_name="/chat"
|
| 72 |
+
)
|
| 73 |
+
return response
|
| 74 |
+
except Exception as e:
|
| 75 |
+
return f"Error communicating with the chatbot API: {str(e)}"
|
| 76 |
+
|
| 77 |
+
# Create Gradio interface with tabs
|
| 78 |
+
with gr.Blocks(title="Image Character Persona Generator") as iface:
|
| 79 |
+
# Store the generated persona in a state variable to share between tabs
|
| 80 |
+
persona_state = gr.State("")
|
| 81 |
+
|
| 82 |
+
with gr.Tabs():
|
| 83 |
+
# First tab: Persona Generator
|
| 84 |
+
with gr.TabItem("Generate Persona"):
|
| 85 |
+
gr.Markdown("# Image Character Persona Generator")
|
| 86 |
+
gr.Markdown("Upload an image containing a character to generate an LLM persona based on that character.")
|
| 87 |
+
|
| 88 |
+
with gr.Row():
|
| 89 |
+
with gr.Column():
|
| 90 |
+
input_image = gr.Image(type='filepath', label='Character Image')
|
| 91 |
+
min_length = gr.Slider(label='Minimum Description Length', minimum=10, maximum=500, value=50, step=5)
|
| 92 |
+
max_length = gr.Slider(label='Maximum Description Length', minimum=50, maximum=1000, value=200, step=10)
|
| 93 |
+
detail_level = gr.Radio(["Basic", "Detailed", "Comprehensive"], label="Persona Detail Level", value="Comprehensive")
|
| 94 |
+
submit_btn = gr.Button("Generate Character Persona")
|
| 95 |
+
|
| 96 |
+
with gr.Column():
|
| 97 |
+
caption_output = gr.Textbox(label='Character Description (Base Caption)')
|
| 98 |
+
persona_output = gr.Textbox(label='LLM Character Persona Prompt', lines=10)
|
| 99 |
+
time_output = gr.Textbox(label='Processing Information')
|
| 100 |
+
|
| 101 |
+
gr.Markdown("""
|
| 102 |
+
## How to use this tool
|
| 103 |
+
1. Upload an image containing a character (real or fictional)
|
| 104 |
+
2. Adjust the sliders to control description length
|
| 105 |
+
3. Select detail level for the persona
|
| 106 |
+
4. Click "Generate Character Persona"
|
| 107 |
+
5. Switch to the "Test Persona" tab to chat with your character
|
| 108 |
+
""")
|
| 109 |
+
|
| 110 |
+
# Second tab: Test Character Chat
|
| 111 |
+
with gr.TabItem("Test Persona"):
|
| 112 |
+
gr.Markdown("# Test Your Character Persona")
|
| 113 |
+
gr.Markdown("Chat with an AI using your generated character persona to see how it behaves.")
|
| 114 |
+
|
| 115 |
+
with gr.Row():
|
| 116 |
+
with gr.Column():
|
| 117 |
+
system_prompt = gr.Textbox(label="Character Persona (System Prompt)", lines=8)
|
| 118 |
+
|
| 119 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 120 |
+
max_tokens = gr.Slider(label="Max Tokens", minimum=50, maximum=2048, value=512, step=1)
|
| 121 |
+
temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=1.5, value=0.7, step=0.1)
|
| 122 |
+
top_p = gr.Slider(label="Top P", minimum=0.1, maximum=1.0, value=0.95, step=0.05)
|
| 123 |
+
|
| 124 |
+
with gr.Column():
|
| 125 |
+
chatbot = gr.Chatbot(label="Conversation with Character")
|
| 126 |
+
msg = gr.Textbox(label="Your message")
|
| 127 |
+
clear_btn = gr.Button("Clear Conversation")
|
| 128 |
+
|
| 129 |
+
# Handle sending messages in the chat
|
| 130 |
+
def respond(message, chat_history, system_message, max_tokens, temperature, top_p):
|
| 131 |
+
if not message.strip():
|
| 132 |
+
return "", chat_history
|
| 133 |
+
|
| 134 |
+
# Add user message to history
|
| 135 |
+
chat_history.append((message, ""))
|
| 136 |
+
|
| 137 |
+
# Get response from API
|
| 138 |
+
bot_response = chat_with_persona(message, chat_history, system_message, max_tokens, temperature, top_p)
|
| 139 |
+
|
| 140 |
+
# Update the last response in history
|
| 141 |
+
chat_history[-1] = (message, bot_response)
|
| 142 |
+
|
| 143 |
+
return "", chat_history
|
| 144 |
+
|
| 145 |
+
# Clear chat history
|
| 146 |
+
def clear_chat():
|
| 147 |
+
return []
|
| 148 |
+
|
| 149 |
+
# Connect message input to chat response
|
| 150 |
+
msg.submit(respond,
|
| 151 |
+
[msg, chatbot, system_prompt, max_tokens, temperature, top_p],
|
| 152 |
+
[msg, chatbot])
|
| 153 |
+
|
| 154 |
+
clear_btn.click(clear_chat, outputs=chatbot)
|
| 155 |
+
|
| 156 |
+
# Function to update system prompt in Test tab when persona is generated
|
| 157 |
+
def update_persona_state(caption, persona, time_output):
|
| 158 |
+
return persona, persona
|
| 159 |
+
|
| 160 |
+
# Connect the persona generator to update the system prompt
|
| 161 |
+
submit_btn.click(fn=generate_persona,
|
| 162 |
+
inputs=[input_image, min_length, max_length, detail_level],
|
| 163 |
+
outputs=[caption_output, persona_output, time_output])
|
| 164 |
+
|
| 165 |
+
# Update the system prompt in Test tab when persona is generated
|
| 166 |
+
submit_btn.click(fn=update_persona_state,
|
| 167 |
+
inputs=[caption_output, persona_output, time_output],
|
| 168 |
+
outputs=[persona_state, system_prompt])
|
| 169 |
+
|
| 170 |
+
# Launch the interface
|
| 171 |
+
iface.launch()
|