-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
146 lines (127 loc) · 4.46 KB
/
Copy pathserver.ts
File metadata and controls
146 lines (127 loc) · 4.46 KB
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
import express from 'express';
import path from 'path';
import dotenv from 'dotenv';
import { createServer as createViteServer } from 'vite';
import { GoogleGenAI, Type } from '@google/genai';
dotenv.config();
const app = express();
const PORT = 3000;
app.use(express.json({ limit: '25mb' }));
let genAI: GoogleGenAI | null = null;
function getGenAI(): GoogleGenAI | null {
if (!genAI && process.env.GEMINI_API_KEY) {
genAI = new GoogleGenAI({
apiKey: process.env.GEMINI_API_KEY,
httpOptions: {
headers: {
'User-Agent': 'aistudio-build'
}
}
});
}
return genAI;
}
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', hasGeminiKey: Boolean(process.env.GEMINI_API_KEY) });
});
app.post('/api/detect', async (req, res) => {
try {
const { image } = req.body;
if (!image) {
return res.status(400).json({ error: 'Image data is required' });
}
const ai = getGenAI();
if (!ai) {
return res.status(503).json({ error: 'GEMINI_API_KEY is not set on the server' });
}
let mimeType = 'image/jpeg';
let base64Data = image;
if (image.startsWith('data:')) {
const match = image.match(/^data:(image\/[a-zA-Z+]+);base64,(.+)$/);
if (match) {
mimeType = match[1];
base64Data = match[2];
} else {
base64Data = image.split(',')[1] || image;
}
}
const promptText = `
You are a high-precision AI computer vision object detector for traffic video and image analysis.
Analyze this traffic image with maximum precision.
Detect ALL visible vehicles (cars, SUVs, vans, sedans, trucks) and ALL visible pedestrians (people).
For every vehicle detected:
1. Identify if its dominant exterior paint color is BLUE or ANY OTHER COLOR.
2. If blue, label as "blue car". If any other color, label as "other car".
3. Specify the exact color name in "color" (e.g. "blue", "red", "white", "black", "silver", "gray", "yellow", "green").
4. Provide tight 2D bounding box normalized coordinates in "box_2d": [ymin, xmin, ymax, xmax] on a scale of 0 to 1000. Do NOT include background area, road surface, or stone walls in the box.
For every pedestrian detected:
1. Label as "person".
2. Provide tight 2D bounding box normalized coordinates in "box_2d": [ymin, xmin, ymax, xmax] on a scale of 0 to 1000.
Count the total number of people visible as "people_count".
`;
const response = await ai.models.generateContent({
model: 'gemini-3.6-flash',
contents: [
{
inlineData: {
mimeType,
data: base64Data
}
},
{ text: promptText }
],
config: {
responseMimeType: 'application/json',
responseSchema: {
type: Type.OBJECT,
properties: {
detected_objects: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
label: { type: Type.STRING, description: '"blue car", "other car", or "person"' },
color: { type: Type.STRING, description: 'e.g. blue, red, white, black, silver, yellow, etc.' },
box_2d: {
type: Type.ARRAY,
items: { type: Type.INTEGER },
description: '[ymin, xmin, ymax, xmax] normalized from 0 to 1000'
},
confidence: { type: Type.NUMBER, description: 'Confidence between 0.85 and 0.99' }
},
required: ['label', 'box_2d']
}
},
people_count: { type: Type.INTEGER }
},
required: ['detected_objects', 'people_count']
}
}
});
const text = response.text || '{}';
const jsonResult = JSON.parse(text);
return res.json(jsonResult);
} catch (err: any) {
console.error('Server AI Detection Error:', err);
return res.status(500).json({ error: err.message || 'Detection failed' });
}
});
async function startServer() {
if (process.env.NODE_ENV !== 'production') {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'spa'
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));
app.get('*', (req, res) => {
res.sendFile(path.join(distPath, 'index.html'));
});
}
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server running on http://0.0.0.0:${PORT}`);
});
}
startServer();