Spaces:
Sleeping
Sleeping
Dan Mo
Enhance Gradio interface with categorized emotion examples based on Plutchik's Wheel of Emotions
dbad28d
""" | |
Main application file for the Emoji Mashup app. | |
This module handles the Gradio interface and application setup. | |
""" | |
import gradio as gr | |
from utils import logger | |
from emoji_processor import EmojiProcessor | |
from config import EMBEDDING_MODELS | |
class EmojiMashupApp: | |
def __init__(self): | |
"""Initialize the Gradio application.""" | |
logger.info("Initializing Emoji Mashup App") | |
self.processor = EmojiProcessor(model_key="mpnet", use_cached_embeddings=True) # Default to mpnet | |
self.processor.load_emoji_dictionaries() | |
def create_model_dropdown_choices(self): | |
"""Create formatted choices for the model dropdown. | |
Returns: | |
List of formatted model choices | |
""" | |
return [ | |
f"{key} ({info['size']}) - {info['notes']}" | |
for key, info in EMBEDDING_MODELS.items() | |
] | |
def handle_model_change(self, dropdown_value, use_cached_embeddings): | |
"""Handle model selection change from dropdown. | |
Args: | |
dropdown_value: Selected value from dropdown | |
use_cached_embeddings: Whether to use cached embeddings | |
Returns: | |
Status message about model change | |
""" | |
# Extract model key from dropdown value (first word before space) | |
model_key = dropdown_value.split()[0] if dropdown_value else "mpnet" | |
# Update processor cache setting | |
self.processor.use_cached_embeddings = use_cached_embeddings | |
if model_key in EMBEDDING_MODELS: | |
success = self.processor.switch_model(model_key) | |
if success: | |
cache_status = "using cached embeddings" if use_cached_embeddings else "computing fresh embeddings" | |
return f"Switched to {model_key} model ({cache_status}): {EMBEDDING_MODELS[model_key]['notes']}" | |
else: | |
return f"Failed to switch to {model_key} model" | |
else: | |
return f"Unknown model: {model_key}" | |
def process_with_model(self, model_selection, text, use_cached_embeddings): | |
"""Process text with selected model. | |
Args: | |
model_selection: Selected model from dropdown | |
text: User input text | |
use_cached_embeddings: Whether to use cached embeddings | |
Returns: | |
Tuple of (emotion emoji, event emoji, mashup image) | |
""" | |
# Extract model key from dropdown value (first word before space) | |
model_key = model_selection.split()[0] if model_selection else "mpnet" | |
# Update processor cache setting | |
self.processor.use_cached_embeddings = use_cached_embeddings | |
if model_key in EMBEDDING_MODELS: | |
self.processor.switch_model(model_key) | |
# Process text with current model | |
return self.processor.sentence_to_emojis(text) | |
def create_interface(self): | |
"""Create and configure the Gradio interface. | |
Returns: | |
Gradio Interface object | |
""" | |
with gr.Blocks(title="Sentence → Emoji Mashup") as interface: | |
gr.Markdown("# Sentence → Emoji Mashup") | |
gr.Markdown("Get the top emotion and event emoji from your sentence, and view the mashup!") | |
with gr.Row(): | |
with gr.Column(scale=3): | |
# Model selection dropdown | |
model_dropdown = gr.Dropdown( | |
choices=self.create_model_dropdown_choices(), | |
value=self.create_model_dropdown_choices()[0], # Default to first model (mpnet) | |
label="Embedding Model", | |
info="Select the model used for text-emoji matching" | |
) | |
# Cache toggle | |
cache_toggle = gr.Checkbox( | |
label="Use cached embeddings", | |
value=True, | |
info="When enabled, embeddings will be saved to and loaded from disk" | |
) | |
# Text input | |
text_input = gr.Textbox( | |
lines=2, | |
placeholder="Type a sentence...", | |
label="Your message" | |
) | |
# Process button | |
submit_btn = gr.Button("Generate Emoji Mashup", variant="primary") | |
with gr.Column(scale=2): | |
# Model info display | |
model_info = gr.Textbox( | |
value=f"Using mpnet model (using cached embeddings): {EMBEDDING_MODELS['mpnet']['notes']}", | |
label="Model Info", | |
interactive=False | |
) | |
# Output displays | |
emotion_out = gr.Text(label="Top Emotion Emoji") | |
event_out = gr.Text(label="Top Event Emoji") | |
mashup_out = gr.Image(label="Mashup Emoji") | |
# Set up event handlers | |
model_dropdown.change( | |
fn=self.handle_model_change, | |
inputs=[model_dropdown, cache_toggle], | |
outputs=[model_info] | |
) | |
cache_toggle.change( | |
fn=self.handle_model_change, | |
inputs=[model_dropdown, cache_toggle], | |
outputs=[model_info] | |
) | |
submit_btn.click( | |
fn=self.process_with_model, | |
inputs=[model_dropdown, text_input, cache_toggle], | |
outputs=[emotion_out, event_out, mashup_out] | |
) | |
# Examples based on Plutchik's Wheel of Emotions | |
with gr.Accordion("Examples", open=False): | |
gr.Markdown("### Primary Emotions") | |
gr.Examples( | |
examples=[ | |
# Joy vs. Sadness | |
["I feel so happy and excited today!"], | |
["I'm feeling really sad and down right now"], | |
# Trust vs. Disgust | |
["I completely trust my best friend with my life"], | |
["That smells absolutely disgusting and makes me nauseous"], | |
# Fear vs. Anger | |
["I'm terrified of what might happen next"], | |
["I'm furious about how they treated me yesterday"], | |
# Surprise vs. Anticipation | |
["Wow! I can't believe what just happened - totally unexpected!"], | |
["I'm eagerly waiting to see what happens next"] | |
], | |
inputs=text_input, | |
label="Primary Emotions" | |
) | |
gr.Markdown("### Secondary Emotions") | |
gr.Examples( | |
examples=[ | |
# Love (Joy + Trust) | |
["I deeply love and adore my family more than anything"], | |
# Submission (Trust + Fear) | |
["I respect their authority and will follow their instructions"], | |
# Awe (Fear + Surprise) | |
["I'm in awe of the magnificent view from the summit"], | |
# Disapproval (Surprise + Sadness) | |
["I'm disappointed by the unexpected poor quality of work"], | |
# Remorse (Sadness + Disgust) | |
["I feel so guilty and ashamed about what I did"], | |
# Contempt (Disgust + Anger) | |
["I have nothing but contempt for their dishonest behavior"], | |
# Aggressiveness (Anger + Anticipation) | |
["I'm determined to confront them about this issue"], | |
# Optimism (Anticipation + Joy) | |
["I'm optimistic and hopeful about what the future holds"] | |
], | |
inputs=text_input, | |
label="Secondary Emotions" | |
) | |
gr.Markdown("### Tertiary Emotions") | |
gr.Examples( | |
examples=[ | |
# Anxiety (Anticipation + Fear) | |
["I'm feeling anxious about my upcoming presentation"], | |
# Hope (Anticipation + Trust) | |
["I'm hopeful that everything will work out in the end"], | |
# Jealousy (Anger + Trust) | |
["I felt jealous when I saw them together laughing"], | |
# Sentimentality (Trust + Sadness) | |
["Looking at old photos makes me feel nostalgic and sentimental"], | |
# Despair (Fear + Sadness) | |
["I'm in complete despair and see no way out of this situation"], | |
# Shame (Fear + Disgust) | |
["I'm so embarrassed and ashamed of my behavior yesterday"], | |
# Morbidness (Disgust + Joy) | |
["I have a strange fascination with creepy abandoned buildings"], | |
# Delight (Surprise + Joy) | |
["I was absolutely delighted by the unexpected gift"] | |
], | |
inputs=text_input, | |
label="Tertiary Emotions" | |
) | |
return interface | |
def run(self, share=True): | |
"""Launch the Gradio application. | |
Args: | |
share: Whether to create a public sharing link | |
""" | |
logger.info("Starting Emoji Mashup App") | |
interface = self.create_interface() | |
interface.launch(share=share) | |
# Main entry point | |
if __name__ == "__main__": | |
app = EmojiMashupApp() | |
app.run(share=True) |