Spaces:
Sleeping
Sleeping
File size: 6,057 Bytes
09b078f 6fa680b 09b078f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 |
import gradio as gr
from sentence_transformers import SentenceTransformer
from sentence_transformers.util import cos_sim
import torch
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Global model variable
model = None
def load_model():
"""Load the sentence transformer model"""
global model
if model is None:
try:
logger.info("Loading sentence transformer model...")
model = SentenceTransformer('nabil-tazi/autotrain-d19rl-a8u4f')
logger.info("Model loaded successfully!")
except Exception as e:
logger.error(f"Failed to load model: {e}")
raise e
return model
def classify_ambiance(user_input):
"""Classify lighting ambiance from user input"""
if not user_input or not user_input.strip():
return "β Please enter some text", {}, ""
try:
# Load model if not already loaded
current_model = load_model()
# Your three reference ambiances
references = ["bright", "cozy", "natural"]
# Get embeddings
user_embedding = current_model.encode([user_input.strip()])
ref_embeddings = current_model.encode(references)
# Calculate similarities
similarities = cos_sim(user_embedding, ref_embeddings)[0]
# Get best match
best_idx = similarities.argmax()
best_ambiance = references[best_idx]
confidence = float(similarities[best_idx])
# Format all scores for debugging
all_scores = {ref: round(float(sim), 4) for ref, sim in zip(references, similarities)}
# Create result with emoji
emoji_map = {"bright": "βοΈ", "cozy": "π―οΈ", "natural": "πΏ"}
result_text = f"## {emoji_map.get(best_ambiance, 'π‘')} **{best_ambiance.upper()}**\n**Confidence:** {confidence:.3f}"
# Create confidence bar
confidence_bar = f"**Confidence Level:** {'β' * int(confidence * 20)}{'β' * (20 - int(confidence * 20))} {confidence:.1%}"
logger.info(f"Classified '{user_input}' as '{best_ambiance}' with confidence {confidence:.3f}")
return result_text, all_scores, confidence_bar
except Exception as e:
error_msg = f"β Error: {str(e)}"
logger.error(f"Classification error: {e}")
return error_msg, {}, ""
# Create Gradio interface
with gr.Blocks(
title="π Lighting Ambiance Classifier",
theme=gr.themes.Soft(),
css="""
.gradio-container {
max-width: 800px !important;
margin: auto !important;
}
.result-box {
background: linear-gradient(45deg, #f0f0f0, #ffffff);
border-radius: 10px;
padding: 20px;
}
"""
) as demo:
# Header
gr.Markdown(
"""
# π Lighting Ambiance Classifier
**Classify your lighting preferences into three categories:**
- βοΈ **Bright**: Well-lit, luminous, clear lighting
- π―οΈ **Cozy**: Warm, dim, soft, ambient lighting
- πΏ **Natural**: Daylight, sunlight, organic lighting
**Supports both English and Japanese!** πΊπΈπ―π΅
"""
)
with gr.Row():
with gr.Column(scale=2):
# Input section
gr.Markdown("### π¬ Enter your lighting preference:")
input_text = gr.Textbox(
label="Your lighting preference",
placeholder="e.g., 'not bright', 'ζγγγͺγ', 'cozy lighting', 'θͺηΆγͺε
γ欲γγ'",
lines=3,
max_lines=5
)
with gr.Row():
submit_btn = gr.Button("π Classify", variant="primary", size="lg")
clear_btn = gr.Button("ποΈ Clear", variant="secondary")
with gr.Column(scale=2):
# Output section
gr.Markdown("### π― Classification Result:")
result = gr.Markdown(value="Enter text and click classify!", elem_classes=["result-box"])
confidence_bar = gr.Markdown(value="")
# Detailed scores
with gr.Row():
scores = gr.JSON(label="π Detailed Similarity Scores", visible=True)
# Example inputs
gr.Markdown("### π‘ Try these examples:")
with gr.Row():
examples = gr.Examples(
examples=[
["not bright"],
["ζγγγͺγ"],
["I want cozy lighting"],
["θͺηΆγͺε
γ欲γγ"],
["make it brighter"],
["ζγγγγ"],
["romantic atmosphere"],
["δ½ζ₯γγγγζγγ"],
["candle light"],
["ε€ͺι½ε
γΏγγ"],
["harsh fluorescent"],
["εͺγγη
§ζ"]
],
inputs=input_text,
examples_per_page=6
)
# Footer
gr.Markdown(
"""
---
**Model:** Fine-tuned multilingual sentence transformer trained on English-Japanese lighting preference pairs.
**How it works:** The model compares your input text with the three ambiance categories and returns the most similar one with a confidence score.
"""
)
# Event handlers
def clear_all():
return "", "Enter text and click classify!", {}, ""
submit_btn.click(
fn=classify_ambiance,
inputs=input_text,
outputs=[result, scores, confidence_bar]
)
input_text.submit(
fn=classify_ambiance,
inputs=input_text,
outputs=[result, scores, confidence_bar]
)
clear_btn.click(
fn=clear_all,
outputs=[input_text, result, scores, confidence_bar]
)
# Launch the app
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860,
show_error=True
) |