diff --git a/docs/site/demo.html b/docs/site/demo.html deleted file mode 100644 index a73d72aa0..000000000 --- a/docs/site/demo.html +++ /dev/null @@ -1,881 +0,0 @@ - - -
- - -- Experience SAMO-DL's emotion detection API in real-time. Test with your own text and see instant results. -
- -- Enter any text below and watch our AI analyze emotions in real-time -
-Analyzing emotions...
-- Sub-50ms response times with ONNX optimization. -
-- >90% F1 score across 28 emotion categories. -
-- Deployed on Google Cloud Run with 99.9% uptime. -
-- Enterprise-grade emotion detection with >90% F1 score and 2.3x performance optimization. - Ready for production integration with your applications. -
- -F1 Score
-Faster
-Latency
-Uptime
-- Production-ready emotion detection with enterprise-grade reliability and performance -
-- Deployed on Google Cloud Run with 99.9% uptime, auto-scaling, and comprehensive monitoring. -
-- >90% F1 score with 2.3x speedup using ONNX optimization and efficient tokenization. -
-- Rate limiting, input sanitization, CORS protection, and API key authentication. -
-- Simple REST API with comprehensive documentation and examples for all frameworks. -
-- Prometheus metrics, health checks, and comprehensive logging for observability. -
-- Integration guides for backend, frontend, UX, and data science teams. -
-- Test our emotion detection API with your own text and see real-time predictions -
-- Ready-to-use integration examples for all development teams -
-import requests
-
-def detect_emotion(text: str) -> dict:
- response = requests.post(
- "https://samo-emotion-api-xxxxx-ew.a.run.app/predict",
- json={"text": text},
- headers={"Content-Type": "application/json"}
- )
- return response.json()
-
-# Example usage
-emotions = detect_emotion("I'm excited!")
-# Returns: [{"emotion": "excitement", "confidence": 0.92}]
- async function analyzeEmotion(text) {
- const response = await fetch(
- 'https://samo-emotion-api-xxxxx-ew.a.run.app/predict',
- {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ text })
- }
- );
- return await response.json();
-}
-
-// Example usage
-const emotions = await analyzeEmotion("This is amazing!");
-console.log(emotions); // [{emotion: "joy", confidence: 0.89}]
- import pandas as pd
-import requests
-
-def analyze_dataset(texts: list) -> pd.DataFrame:
- results = []
- for text in texts:
- emotions = requests.post(
- "https://samo-emotion-api-xxxxx-ew.a.run.app/predict",
- json={"text": text}
- ).json()
- results.append({
- 'text': text,
- 'emotions': emotions
- })
- return pd.DataFrame(results)
- // React Native / Flutter
-const analyzeUserFeedback = async (feedback) => {
- try {
- const response = await fetch(
- 'https://samo-emotion-api-xxxxx-ew.a.run.app/predict',
- {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ text: feedback })
- }
- );
- const emotions = await response.json();
- return emotions;
- } catch (error) {
- console.error('Error:', error);
- }
-};
- - Complete guides and resources for successful integration -
-- Complete integration guides for backend, frontend, UX, and data science teams. - Get your team up and running with SAMO-DL in minutes. -
-https://samo-emotion-api-xxxxx-ew.a.run.app
- GET /health
- Check API status and model health
-POST /predict
- Analyze text and return detected emotions
-GET /metrics
- Prometheus metrics for monitoring
-Integrate with Python web frameworks
-Integrate with Node.js applications
-pip install requests
-# or
-npm install axios
- import requests
-
-def detect_emotion(text: str) -> dict:
- """Integrate with SAMO Emotion API"""
- try:
- response = requests.post(
- "https://samo-emotion-api-minimal-71517823771.us-central1.run.app/predict",
- json={"text": text},
- headers={"Content-Type": "application/json"},
- timeout=10
- )
- response.raise_for_status()
- return response.json()
- except requests.exceptions.RequestException as e:
- print(f"API Error: {e}")
- return {"error": "Failed to analyze emotions"}
-
-# Example usage
-emotions = detect_emotion("I'm feeling excited about this project!")
-print(emotions) # [{"emotion": "excitement", "confidence": 0.92}]
- def safe_emotion_detection(text: str) -> dict:
- """Safe emotion detection with comprehensive error handling"""
- if not text or len(text.strip()) == 0:
- return {"error": "Empty text provided"}
-
- if len(text) > 1000:
- return {"error": "Text too long (max 1000 characters)"}
-
- try:
- emotions = detect_emotion(text)
- if "error" in emotions:
- return emotions
-
- # Validate response format
- if not isinstance(emotions, list):
- return {"error": "Invalid response format"}
-
- return {"success": True, "emotions": emotions}
- except Exception as e:
- return {"error": f"Unexpected error: {str(e)}"}
- React hooks and components
-Vue composables and components
-Angular services and components
-import React, { useState } from 'react';
-
-// Custom hook for emotion detection
-const useEmotionDetection = () => {
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState(null);
- const [emotions, setEmotions] = useState([]);
-
- const analyzeEmotion = async (text) => {
- setLoading(true);
- setError(null);
-
- try {
- const response = await fetch(
- 'https://samo-emotion-api-minimal-71517823771.us-central1.run.app/predict',
- {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ text })
- }
- );
-
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
-
- const data = await response.json();
- setEmotions(data);
- } catch (err) {
- setError(err.message);
- } finally {
- setLoading(false);
- }
- };
-
- return { analyzeEmotion, emotions, loading, error };
-};
-
-// React component
-const EmotionAnalyzer = () => {
- const [text, setText] = useState('');
- const { analyzeEmotion, emotions, loading, error } = useEmotionDetection();
-
- const handleSubmit = (e) => {
- e.preventDefault();
- if (text.trim()) {
- analyzeEmotion(text);
- }
- };
-
- return (
-
-
-
- {error && (
-
- Error: {error}
-
- )}
-
- {emotions.length > 0 && (
-
- Detected Emotions:
- {emotions.map((emotion, index) => (
-
-
- {emotion.emotion}
-
-
- {Math.round(emotion.confidence * 100)}%
-
-
-
-
- ))}
-
- )}
-
- );
-};
-
-export default EmotionAnalyzer;
- Real-time emotion analysis for user feedback
-Emotion-based personalization features
-// Emotion-based UI adaptation
-class EmotionAwareUI {
- constructor() {
- this.currentEmotion = null;
- this.emotionHistory = [];
- }
-
- async analyzeUserInput(text) {
- try {
- const response = await fetch(
- 'https://samo-emotion-api-xxxxx-ew.a.run.app/predict',
- {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ text })
- }
- );
-
- const emotions = await response.json();
- this.currentEmotion = emotions[0]?.emotion;
- this.emotionHistory.push({
- emotion: this.currentEmotion,
- timestamp: new Date(),
- text: text
- });
-
- this.adaptUI();
- } catch (error) {
- console.error('Emotion analysis failed:', error);
- }
- }
-
- adaptUI() {
- const body = document.body;
-
- // Remove existing emotion classes
- body.classList.remove('emotion-joy', 'emotion-sadness', 'emotion-anger', 'emotion-fear');
-
- // Add emotion-specific styling
- if (this.currentEmotion) {
- body.classList.add(`emotion-${this.currentEmotion}`);
- }
-
- // Update UI elements based on emotion
- this.updateColorScheme();
- this.updateContent();
- this.updateInteractions();
- }
-
- updateColorScheme() {
- const colorSchemes = {
- joy: { primary: '#10b981', secondary: '#34d399' },
- sadness: { primary: '#3b82f6', secondary: '#60a5fa' },
- anger: { primary: '#ef4444', secondary: '#f87171' },
- fear: { primary: '#f59e0b', secondary: '#fbbf24' }
- };
-
- const scheme = colorSchemes[this.currentEmotion] || colorSchemes.joy;
- document.documentElement.style.setProperty('--primary-color', scheme.primary);
- document.documentElement.style.setProperty('--secondary-color', scheme.secondary);
- }
-
- updateContent() {
- const contentAdaptations = {
- joy: {
- greeting: "Great to see you're happy! š",
- suggestions: ["Share your joy", "Celebrate this moment"]
- },
- sadness: {
- greeting: "I understand you're feeling down. š",
- suggestions: ["Take a break", "Talk to someone"]
- },
- anger: {
- greeting: "I sense you're frustrated. š„",
- suggestions: ["Take deep breaths", "Step back for a moment"]
- },
- fear: {
- greeting: "It's okay to feel anxious. š¤",
- suggestions: ["Breathe slowly", "You're safe here"]
- }
- };
-
- const adaptation = contentAdaptations[this.currentEmotion] || contentAdaptations.joy;
-
- // Update UI elements
- const greetingElement = document.getElementById('greeting');
- if (greetingElement) {
- greetingElement.textContent = adaptation.greeting;
- }
- }
-
- updateInteractions() {
- // Adjust interaction patterns based on emotion
- const interactionPatterns = {
- joy: { animationSpeed: 'fast', soundEnabled: true },
- sadness: { animationSpeed: 'slow', soundEnabled: false },
- anger: { animationSpeed: 'fast', soundEnabled: false },
- fear: { animationSpeed: 'slow', soundEnabled: true }
- };
-
- const pattern = interactionPatterns[this.currentEmotion] || interactionPatterns.joy;
-
- // Apply interaction changes
- document.body.style.setProperty('--animation-speed', pattern.animationSpeed);
- if (window.soundManager) {
- window.soundManager.enabled = pattern.soundEnabled;
- }
- }
-}
-
-// Usage
-const emotionUI = new EmotionAwareUI();
-
-// Analyze user input and adapt UI
-document.getElementById('user-input').addEventListener('input', (e) => {
- if (e.target.value.length > 10) {
- emotionUI.analyzeUserInput(e.target.value);
- }
-});
- Structured data collection for analysis
-Performance tracking and monitoring
-Automated model retraining
-import pandas as pd
-import requests
-import numpy as np
-from datetime import datetime
-import logging
-
-class EmotionDataCollector:
- def __init__(self, api_url="https://samo-emotion-api-xxxxx-ew.a.run.app"):
- self.api_url = api_url
- self.session = requests.Session()
- self.logger = logging.getLogger(__name__)
-
- def analyze_batch(self, texts: list) -> pd.DataFrame:
- """Analyze a batch of texts and return structured results"""
- results = []
-
- for i, text in enumerate(texts):
- try:
- response = self.session.post(
- f"{self.api_url}/predict",
- json={"text": text},
- timeout=30
- )
- response.raise_for_status()
-
- emotions = response.json()
- results.append({
- 'text': text,
- 'emotions': emotions,
- 'timestamp': datetime.now(),
- 'status': 'success'
- })
-
- except Exception as e:
- self.logger.error(f"Error analyzing text {i}: {e}")
- results.append({
- 'text': text,
- 'emotions': [],
- 'timestamp': datetime.now(),
- 'status': 'error',
- 'error': str(e)
- })
-
- return pd.DataFrame(results)
-
- def extract_emotion_features(self, df: pd.DataFrame) -> pd.DataFrame:
- """Extract emotion features from API responses"""
- features = []
-
- for _, row in df.iterrows():
- if row['status'] == 'success' and row['emotions']:
- # Get top emotion
- top_emotion = max(row['emotions'], key=lambda x: x['confidence'])
-
- # Create feature vector
- emotion_features = {
- 'text': row['text'],
- 'primary_emotion': top_emotion['emotion'],
- 'primary_confidence': top_emotion['confidence'],
- 'emotion_count': len(row['emotions']),
- 'timestamp': row['timestamp']
- }
-
- # Add individual emotion confidences
- for emotion in row['emotions']:
- emotion_features[f"conf_{emotion['emotion']}"] = emotion['confidence']
-
- features.append(emotion_features)
-
- return pd.DataFrame(features)
-
- def calculate_metrics(self, df: pd.DataFrame) -> dict:
- """Calculate performance and quality metrics"""
- metrics = {
- 'total_requests': len(df),
- 'successful_requests': len(df[df['status'] == 'success']),
- 'error_rate': len(df[df['status'] == 'error']) / len(df),
- 'avg_confidence': df[df['status'] == 'success']['primary_confidence'].mean(),
- 'emotion_distribution': df[df['status'] == 'success']['primary_emotion'].value_counts().to_dict()
- }
-
- return metrics
-
-class ModelMonitor:
- def __init__(self):
- self.performance_history = []
-
- def track_performance(self, metrics: dict):
- """Track model performance over time"""
- metrics['timestamp'] = datetime.now()
- self.performance_history.append(metrics)
-
- def detect_drift(self, window_size: int = 100) -> dict:
- """Detect performance drift"""
- if len(self.performance_history) < window_size:
- return {'drift_detected': False, 'reason': 'Insufficient data'}
-
- recent_metrics = self.performance_history[-window_size:]
- historical_metrics = self.performance_history[:-window_size]
-
- # Calculate drift indicators
- recent_avg_conf = np.mean([m['avg_confidence'] for m in recent_metrics])
- historical_avg_conf = np.mean([m['avg_confidence'] for m in historical_metrics])
-
- confidence_drift = abs(recent_avg_conf - historical_avg_conf) / historical_avg_conf
-
- drift_detected = confidence_drift > 0.1 # 10% threshold
-
- return {
- 'drift_detected': drift_detected,
- 'confidence_drift': confidence_drift,
- 'recent_avg_confidence': recent_avg_conf,
- 'historical_avg_confidence': historical_avg_conf
- }
-
- def generate_report(self) -> str:
- """Generate performance report"""
- if not self.performance_history:
- return "No performance data available"
-
- latest = self.performance_history[-1]
- drift = self.detect_drift()
-
- report = f"""
- SAMO-DL Performance Report
- ==========================
-
- Latest Metrics:
- - Total Requests: {latest['total_requests']}
- - Success Rate: {(1 - latest['error_rate']) * 100:.2f}%
- - Average Confidence: {latest['avg_confidence']:.3f}
-
- Drift Analysis:
- - Drift Detected: {drift['drift_detected']}
- - Confidence Drift: {drift['confidence_drift']:.3f}
-
- Top Emotions:
- {chr(10).join([f"- {emotion}: {count}" for emotion, count in list(latest['emotion_distribution'].items())[:5]])}
- """
-
- return report
-
-# Usage example
-if __name__ == "__main__":
- # Initialize components
- collector = EmotionDataCollector()
- monitor = ModelMonitor()
-
- # Sample texts for analysis
- sample_texts = [
- "I'm feeling really happy today!",
- "This is frustrating and annoying.",
- "I love this new feature!",
- "I'm scared about the upcoming changes.",
- "What a wonderful surprise!"
- ]
-
- # Collect data
- results_df = collector.analyze_batch(sample_texts)
- features_df = collector.extract_emotion_features(results_df)
-
- # Calculate metrics
- metrics = collector.calculate_metrics(results_df)
- monitor.track_performance(metrics)
-
- # Generate report
- report = monitor.generate_report()
- print(report)
-
- # Save results
- features_df.to_csv('emotion_analysis_results.csv', index=False)
- print("Results saved to emotion_analysis_results.csv")
- Main endpoint for emotion detection
-<50ms
-Average response time
-{
- "text": "I am feeling really excited about this project!"
-}
- HTTP/1.1 400 Bad Request
-Content-Type: application/json
-
-{
- "error": "Missing required field: text"
-}
-
- Typical error responses include an appropriate HTTP status code (e.g., 400 Bad Request for invalid input).
- Note: The confidence values for each emotion are always between 0 and 1 (inclusive), representing the model's confidence in the presence of that emotion. These values are independent and do not necessarily sum to 1.
-
{
- "emotions": [
- {
- "emotion": "joy",
- "confidence": 0.92
- },
- {
- "emotion": "optimism",
- "confidence": 0.78
- },
- {
- "emotion": "pride",
- "confidence": 0.65
- }
- ],
- "processing_time": 45,
- "model_version": "v2.1.0"
-}
- - Note: The following list is not exhaustive and may change as the model evolves. Integrators should be prepared to handle additional or unexpected emotions. -
-{
- "error": "Text too long (max 1000 characters)",
- "error_code": "VALIDATION_ERROR"
-}
- from fastapi import FastAPI, HTTPException
-import httpx
-from pydantic import BaseModel, validator
-
-app = FastAPI()
-
-class EmotionRequest(BaseModel):
- text: str
-
- @validator('text')
- def validate_text_length(cls, v):
- if len(v) > 1000:
- raise ValueError('Text must be 1000 characters or less')
- return v
-
-class EmotionResponse(BaseModel):
- emotions: list
- processing_time: int
- model_version: str
-
-@app.post("/analyze-emotions", response_model=EmotionResponse)
-async def analyze_emotions(request: EmotionRequest):
- async with httpx.AsyncClient() as client:
- try:
- response = await client.post(
- "https://samo-emotion-api-minimal-71517823771.us-central1.run.app/predict",
- json={"text": request.text},
- timeout=10.0
- )
- response.raise_for_status()
- return response.json()
- except httpx.HTTPStatusError as e:
- raise HTTPException(status_code=e.response.status_code, detail="API Error")
- except httpx.TimeoutException:
- raise HTTPException(status_code=408, detail="Request timeout")
- const express = require('express');
-const axios = require('axios');
-
-const app = express();
-app.use(express.json());
-
-app.post('/analyze-emotions', async (req, res) => {
- try {
- const { text } = req.body;
-
- if (!text || text.length > 1000) {
- return res.status(400).json({
- error: 'Invalid text length (max 1000 characters)',
- error_code: 'INVALID_TEXT_LENGTH'
- });
- }
-
- const response = await axios.post(
- 'https://samo-emotion-api-minimal-71517823771.us-central1.run.app/predict',
- { text },
- {
- timeout: 10000,
- headers: { 'Content-Type': 'application/json' }
- }
- );
-
- res.json(response.data);
- } catch (error) {
- console.error('API Error:', error.message);
- if (error.response) {
- // Downstream API responded with an error. Propagate it.
- return res.status(error.response.status).json(error.response.data);
- } else if (error.request) {
- // No response received from downstream API.
- return res.status(504).json({ error: 'Gateway Timeout: No response from emotion API' });
- } else {
- // Error setting up the request.
- res.status(500).json({
- error: 'Failed to analyze emotions'
- });
- }
- }
-});
-
-app.listen(3000, () => {
- console.log('Server running on port 3000');
-});
- import { useState, useCallback } from 'react';
-
-const useEmotionAPI = () => {
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState(null);
- const [result, setResult] = useState(null);
-
- const analyzeEmotion = useCallback(async (text) => {
- setLoading(true);
- setError(null);
-
- try {
- const response = await fetch(
- 'https://samo-emotion-api-minimal-71517823771.us-central1.run.app/predict',
- {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ text })
- }
- );
-
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
- }
-
- const data = await response.json();
- setResult(data);
- return data;
- } catch (err) {
- setError(err.message);
- throw err;
- } finally {
- setLoading(false);
- }
- }, []);
-
- return { analyzeEmotion, loading, error, result };
-};
-
-export default useEmotionAPI;
- - Experience the power of SAMO-DL's emotion detection API in real-time. - Test with your own text and see instant results with confidence scores. -
- -F1 Score
-Latency
-Emotions
-Faster
-- Enter any text below and watch our AI analyze emotions in real-time -
-Processing your text with our advanced AI model
-Response Time
- - -Status
- Ready -Confidence
- - -Model
- ONNX Optimized -- Enterprise-grade emotion detection with cutting-edge performance -
-- Sub-50ms response times with ONNX optimization for real-time applications. -
-- >90% F1 score with comprehensive emotion detection across 28 categories. -
-- Deployed on Google Cloud Run with 99.9% uptime and enterprise security. -
-- 100% Priority 1 Features Complete! Enterprise-grade AI platform with JWT authentication, - voice transcription, text summarization, real-time processing, and comprehensive monitoring. + 100% Priority 1 Features Complete! Enterprise-grade AI platform with JWT authentication, + voice transcription, text summarization, real-time processing, and comprehensive monitoring. Production-ready with >90% F1 score and 2.3x performance optimization.
- Complete token lifecycle management with register, login, refresh, logout, and profile endpoints. + Complete token lifecycle management with register, login, refresh, logout, and profile endpoints. Secure with blacklist tracking and permission-based access control.
- Advanced Whisper integration with batch processing, real-time streaming, and comprehensive + Advanced Whisper integration with batch processing, real-time streaming, and comprehensive error handling. Supports multiple audio formats with file validation.
- Multi-model T5 summarization with emotional analysis, key point extraction, and + Multi-model T5 summarization with emotional analysis, key point extraction, and customizable compression ratios. Real-time processing with confidence scoring.
- WebSocket-based real-time processing with progress tracking, partial results, and + WebSocket-based real-time processing with progress tracking, partial results, and comprehensive error handling. Supports concurrent processing with rate limiting.
- Real-time dashboard with system metrics, model performance tracking, error rate monitoring, + Real-time dashboard with system metrics, model performance tracking, error rate monitoring, and health status alerts. Production-ready observability.
- Complete test suite with 1,094 lines of integration tests covering all endpoints, + Complete test suite with 1,094 lines of integration tests covering all endpoints, edge cases, error scenarios, and security validation. 100% code review issues resolved.