", unsafe_allow_html=True)
# --- Use Case Functions ---
def get_use_cases():
"""Returns detailed use cases for each model"""
return {
'sentiment_analysis': {
'title': "π Social Media Sentiment Analysis",
'description': "Automatically identify sentiment (positive, negative, or neutral) in comments about your brand.",
'example': "Monitor mentions of your product on Twitter to detect customer dissatisfaction and respond quickly.",
'benefit': "Reduce crisis response time by 40% and increase customer satisfaction by 25%.",
'demo_input': "I love the new product design! But the battery could last longer.",
'demo_type': 'text',
'model_key': 'sentiment_analysis'
},
'text_classification': {
'title': "ποΈ Automated Ticket Classification",
'description': "Automatically classify support tickets into categories for efficient routing.",
'example': "Direct technical tickets to engineering and refund requests to finance.",
'benefit': "Reduce resolution time by 60% and increase routing accuracy by 30%.",
'demo_input': "My order #12345 hasn't arrived. I need help tracking it.",
'demo_type': 'text',
'model_key': 'text_classification'
},
'summarization': {
'title': "π Automatic Report Summarization",
'description': "Condense long reports into easy-to-understand executive summaries.",
'example': "Turn 50-page quarterly financial reports into 1-page summaries for management.",
'benefit': "Save 15 hours/month in document analysis and speed up decision making.",
'demo_input': """The company reported 15% revenue growth last quarter, reaching $120 million.
The increase was driven by the launch of the new product X2, contributing $18 million in sales.
Operating costs rose 5% due to logistics investments.""",
'demo_type': 'text',
'model_key': 'summarization'
},
'question_answering': {
'title': "β Intelligent FAQ for Support",
'description': "Automated Q&A system based on your manuals and documents.",
'example': "Chatbot that answers technical product questions directly from the user manual.",
'benefit': "Reduce support call volume by 50%.",
'demo_input': {
'context': "Product X has a 24-month warranty. To activate, register on the website with the invoice. Technical support within 48 business hours.",
'question': "What is the warranty period?"
},
'demo_type': 'qa',
'model_key': 'question_answering'
},
'translation': {
'title': "π Content Translation for Global Expansion",
'description': "Automatically translate marketing content for new markets.",
'example': "Translate product descriptions from English to Portuguese for launch in Brazil.",
'benefit': "Reduce human translation costs by 70% and speed up 10x.",
'demo_input': "Our premium subscription offers ad-free experience and exclusive content.",
'demo_type': 'text',
'model_key': 'translation'
},
'ner': {
'title': "π Information Extraction from Contracts",
'description': "Automatically identify parties, amounts, and deadlines in legal documents.",
'example': "Extract party names, amounts, and due dates from supplier contracts.",
'benefit': "Reduce contract review time by 80% and minimize human errors.",
'demo_input': "Agreement between ABC Ltd. (Tax ID 12.345/0001-01) and XYZ Inc. (Tax ID 98.765/0001-02) signed on 01/15/2023.",
'demo_type': 'text',
'model_key': 'ner'
},
'text_generation': {
'title': "βοΈ Marketing Content Generation",
'description': "Create creative texts for campaigns, ads, and social media.",
'example': "Generate copywriting variations for email marketing campaigns.",
'benefit': "Triple content production and reduce copywriting costs.",
'demo_input': "Write a creative ad for a new smartphone with a 108MP camera:",
'demo_type': 'text',
'model_key': 'text_generation'
},
'image_classification': {
'title': "πΌοΈ Automated Quality Control",
'description': "Automatically classify products on production lines.",
'example': "Identify defects in manufactured parts using production line images.",
'benefit': "Increase defect detection by 25% and reduce rework by 40%.",
'demo_input': None,
'demo_type': 'image',
'model_key': 'image_classification'
},
'object_detection': {
'title': "π¦ Smart Inventory Monitoring",
'description': "Count and identify items on shelves using images.",
'example': "Monitor stock levels in real-time through shelf images.",
'benefit': "Reduce stockouts by 30% and increase inventory accuracy by 50%.",
'demo_input': None,
'demo_type': 'image',
'model_key': 'object_detection'
},
'image_segmentation': {
'title': "π₯ Medical Image Analysis",
'description': "Segment areas of interest in medical imaging exams.",
'example': "Identify tumors in MRI scans to assist diagnosis.",
'benefit': "Increase diagnostic accuracy by 20% and reduce analysis time by 30%.",
'demo_input': None,
'demo_type': 'image',
'model_key': 'image_segmentation'
},
'facial_recognition': {
'title': "π Customer Satisfaction Analysis",
'description': "Measure customer emotions at points of sale.",
'example': "Analyze facial expressions of customers interacting with products in stores.",
'benefit': "Gain valuable insights into customer preferences and pain points.",
'demo_input': None,
'demo_type': 'image',
'model_key': 'facial_recognition'
},
'speech_to_text': {
'title': "ποΈ Automatic Meeting Transcription",
'description': "Convert meeting recordings into text minutes automatically.",
'example': "Transcribe board meetings to create actionable records.",
'benefit': "Save 5 hours/week on documentation and improve record accuracy.",
'demo_input': None,
'demo_type': 'audio',
'model_key': 'speech_to_text'
},
'audio_classification': {
'title': "π Call Center Emotion Analysis",
'description': "Classify emotional tone in support calls.",
'example': "Identify frustrated customers for priority escalation.",
'benefit': "Increase customer satisfaction by 35% and reduce churn by 25%.",
'demo_input': None,
'demo_type': 'audio',
'model_key': 'audio_classification'
},
'text_to_image': {
'title': "π¨ Visual Content Generation for Marketing",
'description': "Create custom images for campaigns from text descriptions.",
'example': "Generate promotional banners for social media campaigns.",
'benefit': "Reduce visual production time by 90% and design costs.",
'demo_input': "A futuristic landscape with flying cars over a high-tech city at night",
'demo_type': 'text',
'model_key': 'text_to_image'
}
}
def handle_use_case_demo(models, use_case_key, use_case):
"""
Executes and displays a demo of a specific use case
Args:
models: Dictionary of loaded models
use_case_key: Identifier key of the use case
use_case: Dictionary with use case settings
"""
if use_case['demo_input'] is None:
st.warning("β οΈ Demo requires file upload")
return
st.markdown("""
""", unsafe_allow_html=True)
st.subheader("π Live Demo")
try:
# Load model if needed
model = models.get(use_case_key)
if model is None:
with st.spinner(f"Loading {use_case_key.replace('_', ' ').title()} model..."):
model = load_model(use_case_key)
models[use_case_key] = model
if model is None:
st.error("Failed to load model for demo")
return
# Process based on demo type
if use_case['demo_type'] == 'text':
with st.spinner("Analyzing text..."):
result = model(use_case['demo_input'])
display_demo_results(result, use_case_key, use_case['demo_input'])
elif use_case['demo_type'] == 'qa':
with st.spinner("Processing question..."):
result = model(
question=use_case['demo_input']['question'],
context=use_case['demo_input']['context']
)
st.success("π‘ Answer Found")
st.markdown(f"**Context:** {use_case['demo_input']['context']}")
st.markdown(f"**Question:** {use_case['demo_input']['question']}")
st.markdown(f"**Answer:** `{result['answer']}`")
st.markdown(f"**Confidence:** {result['score']:.2%}")
except Exception as e:
st.error(f"β Demo failed: {str(e)}")
logging.error(f"Use case error {use_case_key}: {str(e)}")
finally:
st.markdown("
", unsafe_allow_html=True)
def display_demo_results(result, model_key, input_text=None):
"""
Displays the formatted demo results
Args:
result: Result returned by the model
model_key: Model identifier
input_text: Original text (optional)
"""
with st.expander("π Analysis Details", expanded=True):
if input_text:
st.markdown("**Input:**")
st.write(input_text)
st.markdown("**Results:**")
if model_key in ['sentiment_analysis', 'text_classification']:
for item in result:
label = item['label']
score = item['score']
st.progress(float(score),
text=f"{label} ({score:.2%})")
elif model_key == 'summarization':
st.markdown("**Generated Summary:**")
st.info(result[0]['summary_text'])
elif model_key == 'translation':
st.markdown("**Translation:**")
st.success(result[0]['translation_text'])
elif model_key == 'ner':
st.markdown("**Identified Entities:**")
for entity in result:
st.write(f"- {entity['word']} ({entity['entity_group']})")
elif model_key == 'text_generation':
st.markdown("**Generated Text:**")
st.write(result[0]['generated_text'])
elif model_key == 'text_to_image':
st.image(result[0], caption="Image generated by the model")
def render_use_cases(models):
"""
Renders all use cases in the interface
Args:
models: Dictionary of loaded models
"""
st.header("π Practical Use Cases")
st.markdown("Explore real examples of application of our AI models")
use_cases = get_use_cases()
for key, case in use_cases.items():
with st.container():
st.subheader(case['title'])
st.markdown(f"**{case['description']}**")
with st.expander("βΉοΈ Use Case Details", expanded=False):
st.markdown(f"π **Practical Example:** {case['example']}")
st.markdown(f"β **Benefit:** {case['benefit']}")
# Interactive demo section
if case.get('demo_input') is not None:
if st.button(
"βΆ Run Demo",
key=f"demo_{key}",
type="primary",
help=f"Test {case['title'].split(' ')[-1]} with example data"
):
handle_use_case_demo(models, key, case)
else:
# Automatic uploader depending on case type
if "image" in key or "visual" in key:
file = st.file_uploader("πΈ Upload an image", type=["jpg", "jpeg", "png"], key=f"upload_{key}")
if file:
case["demo_input"] = file
handle_use_case_demo(models, key, case)
elif "speech" in key or "audio" in key or "call" in key:
file = st.file_uploader("ποΈ Upload an audio file", type=["wav", "mp3", "m4a"], key=f"upload_{key}")
if file:
case["demo_input"] = file
handle_use_case_demo(models, key, case)
elif "medical" in key:
file = st.file_uploader("π₯ Upload a medical image (PNG/JPG/DICOM)", type=["png", "jpg", "jpeg", "dcm"], key=f"upload_{key}")
if file:
case["demo_input"] = file
handle_use_case_demo(models, key, case)
elif "document" in key or "summarization" in key or "extraction" in key:
file = st.file_uploader("π Upload a document", type=["pdf", "docx"], key=f"upload_{key}")
if file:
case["demo_input"] = file
handle_use_case_demo(models, key, case)
else:
st.warning("β οΈ This use case requires a specific file input")
st.divider()
# --- Layout and Components ---
def load_branding(username):
branding = {
'admin': {'logo': None, 'title': 'Welcome, Administrator!', 'color': '#2c3e50'},
'cliente': {'logo': None, 'title': 'Welcome, Client!', 'color': '#3498db'},
'empresa1': {'logo': None, 'title': 'Welcome, Company One!', 'color': '#e74c3c'}
}
return branding.get(username, {'logo': None, 'title': 'Welcome!', 'color': '#3498db'})
def feature_card(title, description, icon):
return f"""
{icon}
{title}
{description}
"""
def render_login(authenticator):
st.title("AiiT Services - AI Platform")
st.markdown("""
Multimodal Artificial Intelligence
Advanced AI solutions for text, image, and audio analysis
""", unsafe_allow_html=True)
cols = st.columns(3)
with cols[0]:
st.markdown(feature_card("Smart Text", "Text analysis, classification, and generation", "π"), unsafe_allow_html=True)
with cols[1]:
st.markdown(feature_card("Computer Vision", "Image and object recognition", "πΌοΈ"), unsafe_allow_html=True)
with cols[2]:
st.markdown(feature_card("Audio Processing", "Transcription and sentiment analysis in audio", "π΅"), unsafe_allow_html=True)
authenticator.login(location='main')
def render_main_interface(authenticator, config, models):
name = st.session_state["name"]
username = st.session_state["username"]
role = st.session_state.get("role") or config['credentials']['usernames'][username]['role']
branding = load_branding(username)
st.sidebar.title(f"π€ {name}")
authenticator.logout("Logout", "sidebar")
if role == "admin":
admin_panel(authenticator)
st.title(f"{branding['title']}")
st.markdown(f"", unsafe_allow_html=True)
model_categories = {
"π Text Processing": [
("Sentiment Analysis", "sentiment_analysis"),
("Text Classification", "text_classification"),
("Text Summarization", "summarization"),
("Question Answering", "question_answering"),
("Translation (ENβPT)", "translation"),
("Named Entity Recognition", "ner"),
("Text Generation", "text_generation")
],
"πΌοΈ Image Processing": [
("Image Classification", "image_classification"),
("Object Detection", "object_detection"),
("Image Segmentation", "image_segmentation"),
("Facial Recognition", "facial_recognition")
],
"π΅ Audio Processing": [
("Audio Transcription", "speech_to_text"),
("Emotion Classification", "audio_classification")
],
"β¨ Generative Models": [
("Text to Image", "text_to_image")
]
}
tab1, tab2 = st.tabs(["π§ Explore Models", "πΌ Use Cases"])
with tab1:
selected_category = st.sidebar.selectbox(
"Category",
list(model_categories.keys()),
index=0
)
selected_model = st.sidebar.selectbox(
"Model",
[name for name, key in model_categories[selected_category]],
index=0
)
model_key = next(key for name, key in model_categories[selected_category] if name == selected_model)
st.header(f"{selected_model}")
st.markdown(f"
", unsafe_allow_html=True)
if model_key not in models:
models[model_key] = load_model(model_key)
if not models[model_key]:
st.error("β Model not available")
return
try:
if model_key in ['sentiment_analysis', 'text_classification', 'summarization',
'translation', 'text_generation', 'ner']:
handle_text_models(models, model_key, selected_model)
elif model_key == 'question_answering':
handle_qa_model(models, model_key)
elif model_key in ['image_classification', 'object_detection',
'image_segmentation', 'facial_recognition']:
handle_image_models(models, model_key, selected_model)
elif model_key in ['speech_to_text', 'audio_classification']:
handle_audio_models(models, model_key)
elif model_key == 'text_to_image':
handle_generative_models(models, model_key)
except Exception as e:
st.error(f"β Execution error: {str(e)}")
st.markdown("
", unsafe_allow_html=True)
with tab2:
st.header("πΌ Practical Use Cases")
st.markdown("Explore real applications of our AI models")
use_cases = get_use_cases()
cols = st.columns(2)
for idx, (key, case) in enumerate(use_cases.items()):
with cols[idx % 2]:
st.markdown(f"""
{case['title']}
Description: {case['description']}
Benefit: {case['benefit']}
""", unsafe_allow_html=True)
if st.button("View Demo", key=f"useCase_{key}"):
handle_use_case_demo(models, key, case)
# --- Handlers for Model Types ---
def handle_text_models(models, model_key, model_name):
examples = {
'sentiment_analysis': "The delivery was super fast, I loved it!",
'text_classification': "I am dissatisfied with the product",
'summarization': "Company XYZ reported a 15% growth last quarter...",
'translation': "Our product ensures high performance",
'ner': "Microsoft signed a contract with company XYZ in New York",
'text_generation': "A future where technology connects everyone"
}
col1, col2 = st.columns([0.85, 0.15])
with col1:
input_text = st.text_area(
f"Enter text for {model_name.lower()}:",
height=200,
placeholder="Paste or type your text here..."
)
with col2:
st.write("")
st.write("")
if st.button("π Example", use_container_width=True):
input_text = examples.get(model_key, "")
advanced_params = {}
if model_key == 'summarization':
with st.expander("βοΈ Advanced Parameters"):
advanced_params['max_length'] = st.slider("Max Length", 50, 300, 150)
advanced_params['min_length'] = st.slider("Min Length", 10, 100, 30)
if model_key == 'text_generation':
with st.expander("βοΈ Advanced Parameters"):
advanced_params['max_length'] = st.slider("Text Length", 50, 500, 100)
advanced_params['temperature'] = st.slider("Creativity", 0.1, 1.0, 0.7)
advanced_params['num_return_sequences'] = st.slider("Number of outputs", 1, 5, 1)
if st.button(f"π Run {model_name}", type="primary", use_container_width=True):
if input_text.strip():
with st.spinner("Processing..."):
try:
result = models[model_key](input_text, **advanced_params)
display_demo_results(result, model_key, input_text=input_text)
except Exception as e:
st.error(f"β Error processing text: {str(e)}")
else:
st.warning("β οΈ Please enter valid text")
def handle_qa_model(models, model_key):
col1, col2 = st.columns(2)
with col1:
context = st.text_area(
"Context:",
height=200,
placeholder="Text containing the information...",
value="Product X has a 2-year warranty and can be configured via app in 5 minutes."
)
with col2:
question = st.text_area(
"Question:",
height=150,
placeholder="Ask your question about the context...",
value="What is the warranty period of product X?"
)
with st.expander("βοΈ Advanced Parameters"):
confidence_threshold = st.slider("Confidence threshold", 0.0, 1.0, 0.5, 0.01)
if st.button("π Run Question and Answer", type="primary", use_container_width=True):
if context.strip() and question.strip():
with st.spinner("Searching for answer..."):
try:
result = models[model_key](question=question, context=context)
if result['score'] < confidence_threshold:
st.warning(f"β οΈ Low confidence in answer ({result['score']:.2%})")
st.success("π Answer found:")
st.markdown(f"**Question:** {question}")
st.markdown(f"**Answer:** {result['answer']}")
st.markdown(f"**Confidence:** {result['score']:.2%}")
except Exception as e:
st.error(f"β Error processing Q&A: {str(e)}")
else:
st.warning("β οΈ Please fill in context and question")
def handle_image_models(models, model_key, model_name):
uploaded_file = st.file_uploader(
"Upload an image",
type=["jpg", "png", "jpeg", "bmp"],
help="Supported formats: JPG, PNG, JPEG, BMP"
)
if uploaded_file:
if not validate_image_file(uploaded_file):
st.error("β οΈ Invalid format or corrupted file")
return
col1, col2 = st.columns(2)
with col1:
st.subheader("πΌοΈ Original Image")
image = process_image_file(uploaded_file)
if image:
st.image(image, use_column_width=True)
with col2:
st.subheader("π Results")
if st.button(f"π Run {model_name}", type="primary", use_container_width=True):
if image:
with st.spinner("Analyzing image..."):
try:
result = models[model_key](image)
display_demo_results(result, model_key)
except Exception as e:
st.error(f"β Error processing image: {str(e)}")
def handle_audio_models(models, model_key):
model_name = "Audio Transcription" if model_key == 'speech_to_text' else "Audio Classification"
uploaded_file = st.file_uploader(
f"Upload an audio file for {model_name}",
type=["wav", "mp3", "flac", "m4a"],
help="Supported formats: WAV, MP3, FLAC, M4A"
)
if uploaded_file:
if not validate_audio_file(uploaded_file):
st.error("β οΈ Unsupported file format")
return
st.audio(uploaded_file, format="audio/wav")
if st.button(f"π Run {model_name}", type="primary", use_container_width=True):
with st.spinner("Processing audio..."):
try:
audio_array = process_audio_file(uploaded_file)
if audio_array is not None:
result = models[model_key](audio_array)
display_demo_results(result, model_key)
except Exception as e:
st.error(f"β Error processing audio: {str(e)}")
def handle_generative_models(models, model_key):
prompt = st.text_area(
"Image description:",
height=150,
placeholder="Describe the image you want to generate...",
value="A tropical landscape at sunset"
)
with st.expander("βοΈ Advanced Parameters"):
cols = st.columns(2)
with cols[0]:
width = st.slider("Width", 256, 1024, 512, 64)
with cols[1]:
height = st.slider("Height", 256, 1024, 512, 64)
num_images = st.slider("Number of images", 1, 4, 1)
guidance_scale = st.slider("Guidance scale", 1.0, 20.0, 7.5)
if st.button("π Generate Image", type="primary", use_container_width=True):
if prompt.strip():
with st.spinner("Creating image..."):
try:
result = models[model_key](
prompt,
height=height,
width=width,
num_images_per_prompt=num_images,
guidance_scale=guidance_scale
).images
display_demo_results(result, model_key)
except Exception as e:
st.error(f"β Error generating image: {str(e)}")
else:
st.warning("β οΈ Please enter a description for the image")
# --- Main function ---
def main():
init_db()
config = load_users_from_db()
if not config:
st.error("β οΈ Authentication system not configured")
return
authenticator = stauth.Authenticate(
config['credentials'],
config['cookie']['name'],
config['cookie']['key'],
config['cookie']['expiry_days']
)
if 'authentication_status' not in st.session_state:
st.session_state.authentication_status = None
if st.session_state.get("authentication_status"):
models = st.session_state.setdefault("models", {})
render_main_interface(authenticator, config, models)
# Moved inside the authenticated block
tab1, tab2 = st.tabs(["Models", "Use Cases"])
with tab2:
render_use_cases(models) # Render all use cases
else:
render_login(authenticator)
if st.session_state.get("authentication_status") is False:
st.error("β Invalid credentials")
elif st.session_state.get("authentication_status") is None:
st.info("π Please log in to access the platform")
if __name__ == "__main__":
main()