""" REST API Endpoints Page for Vietnamese Sentiment Analysis """ import gradio as gr import os def get_api_base_url(): """Get the correct API base URL based on environment""" # Check if we're on Hugging Face Spaces space_id = os.getenv('SPACE_ID') if space_id: # We're on Hugging Face Spaces space_name = os.getenv('SPACE_NAME', 'your-space-name') return f"https://{space_name}.hf.space:7861" else: # We're running locally return "http://localhost:7861" def create_api_endpoints_page(): """Create the REST API endpoints tab""" # Get the correct base URL api_base_url = get_api_base_url() is_hf_spaces = os.getenv('SPACE_ID') is not None # REST API Endpoints Tab with gr.Tab("🌐 REST API Endpoints"): # Create dynamic content based on environment if is_hf_spaces: environment_info = f""" ## 🌐 REST API Endpoints Your sentiment analysis model is now available via REST API! **📍 Environment:** Hugging Face Spaces **🔗 Base URL:** `{api_base_url}` **📚 Interactive Docs:** {api_base_url}/docs """ else: environment_info = f""" ## 🌐 REST API Endpoints Your sentiment analysis model is now available via REST API! **📍 Environment:** Local Development **🔗 Base URL:** `{api_base_url}` **📚 Interactive Docs:** {api_base_url}/docs """ gr.Markdown(environment_info) # Static content gr.Markdown(f""" ### Available Endpoints: #### 📝 Single Text Analysis **POST** `/analyze` ```json {{ "text": "Giảng viên dạy rất hay và tâm huyết.", "language": "vi" }} ``` #### 📊 Batch Analysis **POST** `/analyze/batch` ```json {{ "texts": [ "Text 1", "Text 2", "Text 3" ], "language": "vi" }} ``` #### ❤️ Health Check **GET** `/health` #### ℹ️ Model Information **GET** `/model/info` #### 🧹 Memory Cleanup **POST** `/memory/cleanup` ### 📚 Interactive API Documentation Visit **{api_base_url}/docs** for interactive API documentation with Swagger UI. ### 🚀 Usage Examples **cURL Example:** ```bash curl -X POST "{api_base_url}/analyze" \\ -H "Content-Type: application/json" \\ -d '{{"text": "Giảng viên dạy rất hay và tâm huyết."}}' ``` **Python Example:** ```python import requests response = requests.post( "{api_base_url}/analyze", json={{"text": "Giảng viên dạy rất hay và tâm huyết."}} ) result = response.json() print(f"Sentiment: {{result['sentiment']}}") print(f"Confidence: {{result['confidence']:.2%}}") ``` **JavaScript Example:** ```javascript const response = await fetch('{api_base_url}/analyze', {{ method: 'POST', headers: {{ 'Content-Type': 'application/json' }}, body: JSON.stringify({{ text: 'Giảng viên dạy rất hay và tâm huyết.' }}) }}); const result = await response.json(); console.log('Sentiment:', result.sentiment); console.log('Confidence:', (result.confidence * 100).toFixed(2) + '%'); ``` ### 📝 Response Format ```json {{ "sentiment": "Positive", "confidence": 0.89, "probabilities": {{ "positive": 0.89, "neutral": 0.08, "negative": 0.03 }}, "processing_time": 0.123, "text": "Giảng viên dạy rất hay và tâm huyết." }} ``` ### ⚠️ Rate Limiting & Performance - **Maximum batch size:** 10 texts per request - **Memory management:** Automatic cleanup after each request - **Processing time:** ~100ms per text - **CORS enabled:** Cross-origin requests supported --- *API server runs alongside the Gradio interface for maximum flexibility!* """)