Spaces:
Running
Running
Download src/server.ts from Leon4gr45/needle-router: direct link, hf CLI and curl.
- Browser
- Download file 5.69 kB
-
https://huggingface.co/spaces/Leon4gr45/needle-router/resolve/main/src/server.ts
- Command line
-
hf download hf://spaces/Leon4gr45/needle-router/src/server.ts
-
curl -L -o server.ts https://huggingface.co/spaces/Leon4gr45/needle-router/resolve/main/src/server.ts
5.69 kB
| import express, { Express, Request, Response, NextFunction } from 'express'; | |
| import * as http from 'http'; | |
| import helmet from 'helmet'; | |
| import cors from 'cors'; | |
| import fileUpload from 'express-fileupload'; | |
| import { LayaService } from './layaService'; | |
| import { LayaVisionService } from './layaVisionService'; | |
| import { layaScheduler, visionScheduler } from './utils/scheduler'; | |
| export class Server { | |
| private app: Express; | |
| private httpServer: http.Server | null = null; | |
| private port: number; | |
| constructor() { | |
| this.app = express(); | |
| this.port = parseInt(process.env.PORT || '7860', 10); | |
| this.initializeMiddleware(); | |
| this.initializeErrorHandling(); | |
| } | |
| private async initializeRoutes(): Promise<void> { | |
| // Import routes (using dynamic import to avoid circular dependencies) | |
| const systemOneRouter = (await import('./routes/systemOne')).default; | |
| // Health check endpoint | |
| this.app.get('/health', (req: Request, res: Response) => { | |
| res.json({ status: 'ok' }); | |
| }); | |
| // Readiness endpoint | |
| this.app.get('/ready', async (req: Request, res: Response) => { | |
| const layaReady = LayaService.getInstance().isModelReady(); | |
| const layaVisionReady = LayaVisionService.getInstance().isModelReady(); | |
| const layaVisionPlaceholder = LayaVisionService.getInstance().isPlaceholder(); | |
| const allRealReady = layaReady && layaVisionReady && !layaVisionPlaceholder; | |
| if (allRealReady) { | |
| res.json({ | |
| status: 'ready', | |
| backends: { | |
| laya: { ready: true }, | |
| 'laya-vision': { ready: true, placeholder: false } | |
| } | |
| }); | |
| } else { | |
| const status = layaReady ? 'partial' : 'not-ready'; | |
| const visionError = LayaVisionService.getInstance().getInitError(); | |
| res.status(status === 'partial' ? 200 : 503).json({ | |
| status, | |
| backends: { | |
| laya: { ready: layaReady }, | |
| 'laya-vision': { | |
| ready: layaVisionReady, | |
| placeholder: layaVisionPlaceholder, | |
| ...(visionError && { error: visionError }) | |
| } | |
| } | |
| }); | |
| } | |
| }); | |
| // Metadata endpoint | |
| this.app.get('/v1/info', (req: Request, res: Response) => { | |
| const layaThreads = LayaService.getInstance().getThreads(); | |
| res.json({ | |
| service: 'system-one', | |
| inference_endpoint: '/v1/system-one', | |
| routing: { | |
| 'text_or_structured': 'laya', | |
| 'visual': 'laya-vision' | |
| }, | |
| backends: { | |
| laya: { | |
| device: 'cpu', | |
| generative: false, | |
| model: 'receptron/laya-onnx', | |
| threads: layaThreads, | |
| max_concurrency: layaScheduler.getMaxConcurrency() | |
| }, | |
| 'laya-vision': { | |
| device: 'cpu', | |
| generative: false, | |
| model: 'thaitea/laya-vision', | |
| parameters: '201M', | |
| runtime: 'python/laya', | |
| threads: LayaVisionService.getInstance().getThreads(), | |
| max_concurrency: visionScheduler.getMaxConcurrency(), | |
| max_queue: visionScheduler.getMaxQueue() | |
| } | |
| }, | |
| capabilities: ['choice', 'score', 'noul', 'vision'] | |
| }); | |
| }); | |
| // Main inference endpoint | |
| this.app.use('/v1/system-one', systemOneRouter); | |
| // 404 handler | |
| this.app.use('*', (req: Request, res: Response) => { | |
| res.status(404).json({ error: 'Not found' }); | |
| }); | |
| } | |
| private initializeMiddleware(): void { | |
| // Security middleware | |
| this.app.use(helmet()); | |
| // CORS middleware | |
| this.app.use(cors({ | |
| origin: true, // Allow all origins in development, should be restricted in production | |
| credentials: true | |
| })); | |
| // Body parsing middleware | |
| this.app.use(express.json({ limit: '10mb' })); | |
| this.app.use(express.urlencoded({ extended: true, limit: '10mb' })); | |
| // File upload middleware for handling images | |
| this.app.use(fileUpload({ | |
| limits: { fileSize: 10 * 1024 * 1024 }, // 10MB limit | |
| abortOnLimit: true, | |
| createParentPath: true | |
| })); | |
| } | |
| private initializeErrorHandling(): void { | |
| // Global error handler | |
| this.app.use((error: Error, _req: Request, res: Response, _next: NextFunction) => { | |
| console.error('Unhandled error:', error); | |
| if (error.message.includes('not ready')) { | |
| return res.status(503).json({ error: 'Service not ready' }); | |
| } | |
| if (error.message.includes('validation')) { | |
| return res.status(400).json({ error: error.message }); | |
| } | |
| res.status(500).json({ error: 'Internal server error' }); | |
| }); | |
| } | |
| public async start(): Promise<void> { | |
| // Initialize routes first | |
| await this.initializeRoutes(); | |
| // Initialize models | |
| try { | |
| await LayaService.getInstance().initialize(); | |
| await LayaVisionService.getInstance().initialize(); | |
| } catch (error) { | |
| console.error('Failed to initialize models:', error); | |
| process.exit(1); | |
| } | |
| // Start server | |
| this.httpServer = this.app.listen(this.port, '0.0.0.0', () => { | |
| console.log(`Server running on http://0.0.0.0:${this.port}`); | |
| }); | |
| } | |
| public async shutdown(): Promise<void> { | |
| await LayaService.getInstance().shutdown(); | |
| await LayaVisionService.getInstance().shutdown(); | |
| // Close server connections | |
| return new Promise((resolve) => { | |
| if (this.httpServer) { | |
| this.httpServer.close(() => { | |
| console.log('Server shutdown complete'); | |
| resolve(); | |
| }); | |
| } else { | |
| resolve(); | |
| } | |
| }); | |
| } | |
| } | |
| export default Server; | |