Spaces:
Runtime error
Runtime error
File size: 4,471 Bytes
b8ae42e 74bc2f3 b8ae42e 74bc2f3 b8ae42e 74bc2f3 b8ae42e 74bc2f3 b8ae42e 74bc2f3 b8ae42e 74bc2f3 b8ae42e 74bc2f3 b8ae42e 74bc2f3 b8ae42e 74bc2f3 b8ae42e 74bc2f3 b8ae42e |
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 |
"""
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!*
""") |