Spaces:
Paused
Paused
Deploy minimal FastAPI app to test Hugging Face Spaces compatibility
Browse files
app.py
CHANGED
@@ -1,202 +1,32 @@
|
|
1 |
-
# app.py - Ultra lightweight version
|
2 |
-
import os
|
3 |
-
os.environ["HOME"] = "/root"
|
4 |
-
os.environ["HF_HOME"] = "/tmp/hf_cache"
|
5 |
-
|
6 |
import logging
|
7 |
-
from fastapi import FastAPI, HTTPException,
|
8 |
from fastapi.responses import JSONResponse
|
9 |
-
import threading
|
10 |
-
import time
|
11 |
-
import tempfile
|
12 |
-
import json
|
13 |
-
from typing import Dict, Any, Optional
|
14 |
|
15 |
# Configure logging
|
16 |
logging.basicConfig(level=logging.INFO)
|
17 |
-
logger = logging.getLogger("
|
18 |
-
|
19 |
-
app = FastAPI(title="Talklas API")
|
20 |
-
|
21 |
-
# Global variables to track application state
|
22 |
-
models_loaded = False
|
23 |
-
loading_in_progress = False
|
24 |
-
loading_thread = None
|
25 |
-
model_status = {
|
26 |
-
"stt": "not_loaded",
|
27 |
-
"mt": "not_loaded",
|
28 |
-
"tts": "not_loaded"
|
29 |
-
}
|
30 |
-
error_message = None
|
31 |
-
|
32 |
-
# A simple in-memory queue for translation requests
|
33 |
-
translation_queue = []
|
34 |
-
translation_results = {}
|
35 |
-
|
36 |
-
# Define the valid languages
|
37 |
-
LANGUAGE_MAPPING = {
|
38 |
-
"English": "eng",
|
39 |
-
"Tagalog": "tgl",
|
40 |
-
"Cebuano": "ceb",
|
41 |
-
"Ilocano": "ilo",
|
42 |
-
"Waray": "war",
|
43 |
-
"Pangasinan": "pag"
|
44 |
-
}
|
45 |
|
46 |
-
|
47 |
-
def load_models_task():
|
48 |
-
global models_loaded, loading_in_progress, model_status, error_message
|
49 |
-
|
50 |
-
try:
|
51 |
-
loading_in_progress = True
|
52 |
-
|
53 |
-
# Import heavy libraries only when needed
|
54 |
-
logger.info("Starting to load STT model...")
|
55 |
-
import torch
|
56 |
-
import numpy as np
|
57 |
-
from transformers import (
|
58 |
-
WhisperProcessor,
|
59 |
-
WhisperForConditionalGeneration
|
60 |
-
)
|
61 |
-
|
62 |
-
# Load STT model
|
63 |
-
try:
|
64 |
-
logger.info("Loading Whisper model...")
|
65 |
-
model_status["stt"] = "loading"
|
66 |
-
# Just create the processor object but don't download weights yet
|
67 |
-
processor = WhisperProcessor.from_pretrained("openai/whisper-tiny", local_files_only=False)
|
68 |
-
logger.info("STT processor initialized")
|
69 |
-
model_status["stt"] = "loaded"
|
70 |
-
except Exception as e:
|
71 |
-
logger.error(f"Failed to load STT model: {str(e)}")
|
72 |
-
model_status["stt"] = "failed"
|
73 |
-
error_message = f"STT model loading failed: {str(e)}"
|
74 |
-
return
|
75 |
-
|
76 |
-
# Similarly initialize MT model
|
77 |
-
try:
|
78 |
-
logger.info("Loading NLLB model...")
|
79 |
-
model_status["mt"] = "loading"
|
80 |
-
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
81 |
-
# Just initialize tokenizer but don't download weights yet
|
82 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
83 |
-
"facebook/nllb-200-distilled-600M",
|
84 |
-
local_files_only=False
|
85 |
-
)
|
86 |
-
logger.info("MT tokenizer initialized")
|
87 |
-
model_status["mt"] = "loaded"
|
88 |
-
except Exception as e:
|
89 |
-
logger.error(f"Failed to load MT model: {str(e)}")
|
90 |
-
model_status["mt"] = "failed"
|
91 |
-
error_message = f"MT model loading failed: {str(e)}"
|
92 |
-
return
|
93 |
-
|
94 |
-
# Similarly initialize TTS model
|
95 |
-
try:
|
96 |
-
logger.info("Loading TTS model...")
|
97 |
-
model_status["tts"] = "loading"
|
98 |
-
from transformers import VitsModel, AutoTokenizer
|
99 |
-
# Just initialize but don't download weights yet
|
100 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
101 |
-
"facebook/mms-tts-eng",
|
102 |
-
local_files_only=False
|
103 |
-
)
|
104 |
-
logger.info("TTS tokenizer initialized")
|
105 |
-
model_status["tts"] = "loaded"
|
106 |
-
except Exception as e:
|
107 |
-
logger.error(f"Failed to load TTS model: {str(e)}")
|
108 |
-
model_status["tts"] = "failed"
|
109 |
-
error_message = f"TTS model loading failed: {str(e)}"
|
110 |
-
return
|
111 |
-
|
112 |
-
models_loaded = True
|
113 |
-
logger.info("All models initialized successfully")
|
114 |
-
|
115 |
-
except Exception as e:
|
116 |
-
error_message = str(e)
|
117 |
-
logger.error(f"Error in model loading task: {str(e)}")
|
118 |
-
finally:
|
119 |
-
loading_in_progress = False
|
120 |
-
|
121 |
-
# Start loading models in background
|
122 |
-
def start_model_loading():
|
123 |
-
global loading_thread, loading_in_progress
|
124 |
-
if not loading_in_progress and not models_loaded:
|
125 |
-
loading_in_progress = True
|
126 |
-
loading_thread = threading.Thread(target=load_models_task)
|
127 |
-
loading_thread.daemon = True
|
128 |
-
loading_thread.start()
|
129 |
-
|
130 |
-
# Start the background process when the app starts
|
131 |
-
@app.on_event("startup")
|
132 |
-
async def startup_event():
|
133 |
-
logger.info("Application starting up...")
|
134 |
-
start_model_loading()
|
135 |
|
136 |
@app.get("/health")
|
137 |
async def health_check():
|
138 |
-
"""Health check endpoint
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
async def update_languages(source_lang: str = Form(...), target_lang: str = Form(...)):
|
152 |
-
if source_lang not in LANGUAGE_MAPPING or target_lang not in LANGUAGE_MAPPING:
|
153 |
-
raise HTTPException(status_code=400, detail="Invalid language selected")
|
154 |
-
|
155 |
-
return {"status": f"Languages updated to {source_lang} → {target_lang}"}
|
156 |
-
|
157 |
-
@app.post("/translate-text")
|
158 |
-
async def translate_text(text: str = Form(...), source_lang: str = Form(...), target_lang: str = Form(...)):
|
159 |
-
"""Endpoint that creates a placeholder for text translation"""
|
160 |
if not text:
|
161 |
raise HTTPException(status_code=400, detail="No text provided")
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
# Create a request ID
|
166 |
-
import uuid
|
167 |
-
request_id = str(uuid.uuid4())
|
168 |
-
|
169 |
-
# Instead of doing the translation now, just return a placeholder
|
170 |
-
return {
|
171 |
-
"request_id": request_id,
|
172 |
-
"status": "processing",
|
173 |
-
"message": "Your request is being processed. This is a placeholder response while models are loading.",
|
174 |
-
"source_text": text,
|
175 |
-
"translated_text": "Translation in progress...",
|
176 |
-
"output_audio": None
|
177 |
-
}
|
178 |
-
|
179 |
-
@app.post("/translate-audio")
|
180 |
-
async def translate_audio(audio: UploadFile = File(...), source_lang: str = Form(...), target_lang: str = Form(...)):
|
181 |
-
"""Endpoint that creates a placeholder for audio translation"""
|
182 |
-
if not audio:
|
183 |
-
raise HTTPException(status_code=400, detail="No audio file provided")
|
184 |
-
if source_lang not in LANGUAGE_MAPPING or target_lang not in LANGUAGE_MAPPING:
|
185 |
-
raise HTTPException(status_code=400, detail="Invalid language selected")
|
186 |
-
|
187 |
-
# Create a request ID
|
188 |
-
import uuid
|
189 |
-
request_id = str(uuid.uuid4())
|
190 |
-
|
191 |
-
# Return a placeholder response
|
192 |
-
return {
|
193 |
-
"request_id": request_id,
|
194 |
-
"status": "processing",
|
195 |
-
"message": "Your audio is being processed. This is a placeholder response while models are loading.",
|
196 |
-
"source_text": "Transcription in progress...",
|
197 |
-
"translated_text": "Translation in progress...",
|
198 |
-
"output_audio": None
|
199 |
-
}
|
200 |
|
201 |
if __name__ == "__main__":
|
202 |
import uvicorn
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import logging
|
2 |
+
from fastapi import FastAPI, HTTPException, Form
|
3 |
from fastapi.responses import JSONResponse
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
# Configure logging
|
6 |
logging.basicConfig(level=logging.INFO)
|
7 |
+
logger = logging.getLogger("minimal-api")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
+
app = FastAPI(title="Minimal API Test")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
@app.get("/health")
|
12 |
async def health_check():
|
13 |
+
"""Health check endpoint to confirm the app is running"""
|
14 |
+
logger.info("Health check requested")
|
15 |
+
return {"status": "healthy"}
|
16 |
+
|
17 |
+
@app.get("/ping")
|
18 |
+
async def ping():
|
19 |
+
"""Simple ping endpoint to test GET requests"""
|
20 |
+
logger.info("Ping requested")
|
21 |
+
return {"message": "pong"}
|
22 |
+
|
23 |
+
@app.post("/echo")
|
24 |
+
async def echo(text: str = Form(...)):
|
25 |
+
"""Echo endpoint to test POST requests with form data"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
if not text:
|
27 |
raise HTTPException(status_code=400, detail="No text provided")
|
28 |
+
logger.info(f"Echo requested with text: {text}")
|
29 |
+
return {"received_text": text}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
if __name__ == "__main__":
|
32 |
import uvicorn
|