Initial commit: Wedding Hub & Live Screen app + README and API docs
This commit is contained in:
commit
4f356eeb36
25 files changed
+7822
No files matched your search
+622
@@ -0,0 +1,622 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export type UserRole = 'guest' | 'host' | 'couple' | 'admin';
|
||||
|
||||
export interface Guest {
|
||||
ticket_id: string;
|
||||
guest_name: string;
|
||||
team_id: string;
|
||||
team_name: string;
|
||||
role: UserRole;
|
||||
registered_at: number;
|
||||
}
|
||||
|
||||
export interface KissCatch {
|
||||
id: number;
|
||||
ticket_id: string;
|
||||
guest_name: string;
|
||||
team_id: string;
|
||||
team_name: string;
|
||||
points: number;
|
||||
round_id: number;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface ToastLog {
|
||||
id: number;
|
||||
ticket_id: string;
|
||||
guest_name: string;
|
||||
team_id: string;
|
||||
team_name: string;
|
||||
timestamp: number;
|
||||
photo_url?: string;
|
||||
detected_glasses?: number;
|
||||
confidence?: number;
|
||||
ai_cheer?: string;
|
||||
quest_id?: string;
|
||||
quest_title?: string;
|
||||
quest_completed?: boolean;
|
||||
status: 'pending' | 'verified' | 'rejected';
|
||||
}
|
||||
|
||||
export interface WeddingPhoto {
|
||||
id: string;
|
||||
ticket_id?: string;
|
||||
guest_name?: string;
|
||||
team_id?: string;
|
||||
team_name?: string;
|
||||
url: string;
|
||||
thumb_url?: string;
|
||||
caption?: string;
|
||||
uploaded_at: number;
|
||||
is_toast?: boolean;
|
||||
quest_title?: string;
|
||||
}
|
||||
|
||||
export interface AppState {
|
||||
guests: Record<string, Guest>;
|
||||
kiss_catches: KissCatch[];
|
||||
toasts: ToastLog[];
|
||||
photos: WeddingPhoto[];
|
||||
current_round_id: number;
|
||||
round_active: boolean;
|
||||
round_start_time: number | null;
|
||||
round_first_catcher: { ticket_id: string; guest_name: string; team_name: string } | null;
|
||||
cooldown_until: number | null;
|
||||
cake_time_target: number;
|
||||
immich_url: string;
|
||||
immich_api_key: string;
|
||||
immich_album_id: string;
|
||||
immich_album_name: string;
|
||||
ollama_url: string;
|
||||
couples_names: string;
|
||||
wedding_date: string;
|
||||
}
|
||||
|
||||
const DATA_DIR = path.join(process.cwd(), 'data');
|
||||
const DATA_FILE = path.join(DATA_DIR, 'wedding_hub.json');
|
||||
|
||||
const DEFAULT_CAKE_TIME = Date.now() + 2 * 60 * 60 * 1000 + 45 * 60 * 1000;
|
||||
|
||||
export const DEFAULT_TEAMS = [
|
||||
{ id: 'team_bride', name: '👰 Команда Невесты' },
|
||||
{ id: 'team_groom', name: '🤵 Команда Жениха' },
|
||||
{ id: 'team_witnesses', name: '🍸 Свидетели и Свита' },
|
||||
{ id: 'team_friends', name: '🎉 Команда Друзей' },
|
||||
{ id: 'team_family', name: '👑 Семья и Родные' },
|
||||
];
|
||||
|
||||
const DEFAULT_STATE: AppState = {
|
||||
guests: {
|
||||
'ADMIN-001': { ticket_id: 'ADMIN-001', guest_name: 'Главный Администратор', team_id: 'team_witnesses', team_name: '🍸 Свидетели и Свита', role: 'admin', registered_at: Date.now() - 4000000 },
|
||||
'HOST-001': { ticket_id: 'HOST-001', guest_name: 'Ведущий Банкета (Александр)', team_id: 'team_friends', team_name: '🎉 Команда Друзей', role: 'host', registered_at: Date.now() - 3900000 },
|
||||
'COUPLE-001': { ticket_id: 'COUPLE-001', guest_name: 'Анна & Дмитрий (Молодожены)', team_id: 'team_bride', team_name: '👰 Команда Невесты', role: 'couple', registered_at: Date.now() - 3800000 },
|
||||
'LUCK-001': { ticket_id: 'LUCK-001', guest_name: 'Алексей Смирнов', team_id: 'team_groom', team_name: '🤵 Команда Жениха', role: 'guest', registered_at: Date.now() - 3600000 },
|
||||
'LUCK-002': { ticket_id: 'LUCK-002', guest_name: 'Елена Васильева', team_id: 'team_bride', team_name: '👰 Команда Невесты', role: 'guest', registered_at: Date.now() - 3500000 },
|
||||
'LUCK-003': { ticket_id: 'LUCK-003', guest_name: 'Дмитрий Ковалев', team_id: 'team_friends', team_name: '🎉 Команда Друзей', role: 'guest', registered_at: Date.now() - 3400000 },
|
||||
'LUCK-004': { ticket_id: 'LUCK-004', guest_name: 'Мария Соколова', team_id: 'team_bride', team_name: '👰 Команда Невесты', role: 'guest', registered_at: Date.now() - 3300000 },
|
||||
'LUCK-005': { ticket_id: 'LUCK-005', guest_name: 'Сергей Морозов', team_id: 'team_witnesses', team_name: '🍸 Свидетели и Свита', role: 'guest', registered_at: Date.now() - 3200000 },
|
||||
'LUCK-006': { ticket_id: 'LUCK-006', guest_name: 'Ольга Попова', team_id: 'team_family', team_name: '👑 Семья и Родные', role: 'guest', registered_at: Date.now() - 3100000 },
|
||||
'LUCK-007': { ticket_id: 'LUCK-007', guest_name: 'Михаил Новиков', team_id: 'team_groom', team_name: '🤵 Команда Жениха', role: 'guest', registered_at: Date.now() - 3000000 },
|
||||
},
|
||||
kiss_catches: [
|
||||
{ id: 1, ticket_id: 'LUCK-001', guest_name: 'Алексей Смирнов', team_id: 'team_groom', team_name: '🤵 Команда Жениха', points: 3, round_id: 1, timestamp: Date.now() - 2400000 },
|
||||
{ id: 2, ticket_id: 'LUCK-003', guest_name: 'Дмитрий Ковалев', team_id: 'team_friends', team_name: '🎉 Команда Друзей', points: 1, round_id: 1, timestamp: Date.now() - 2398000 },
|
||||
{ id: 3, ticket_id: 'LUCK-005', guest_name: 'Сергей Морозов', team_id: 'team_witnesses', team_name: '🍸 Свидетели и Свита', points: 1, round_id: 1, timestamp: Date.now() - 2396000 },
|
||||
{ id: 4, ticket_id: 'LUCK-004', guest_name: 'Мария Соколова', team_id: 'team_bride', team_name: '👰 Команда Невесты', points: 3, round_id: 2, timestamp: Date.now() - 1500000 },
|
||||
{ id: 5, ticket_id: 'LUCK-002', guest_name: 'Елена Васильева', team_id: 'team_bride', team_name: '👰 Команда Невесты', points: 1, round_id: 2, timestamp: Date.now() - 1497000 },
|
||||
{ id: 6, ticket_id: 'LUCK-007', guest_name: 'Михаил Новиков', team_id: 'team_groom', team_name: '🤵 Команда Жениха', points: 3, round_id: 3, timestamp: Date.now() - 700000 },
|
||||
],
|
||||
toasts: [
|
||||
{ id: 1, ticket_id: 'LUCK-001', guest_name: 'Алексей Смирнов', team_id: 'team_groom', team_name: '🤵 Команда Жениха', timestamp: Date.now() - 2800000, detected_glasses: 1, confidence: 0.96, quest_id: 'quest_fear', quest_title: 'Эмоция «СТРАХ»', quest_completed: true, ai_cheer: 'Эмоция ужаса от цен на свадьбу передана гениально! Бокал засчитан!', status: 'verified', photo_url: 'https://images.unsplash.com/photo-1519741497674-611481863552?w=800&auto=format&fit=crop&q=80' },
|
||||
{ id: 2, ticket_id: 'LUCK-002', guest_name: 'Елена Васильева', team_id: 'team_bride', team_name: '👰 Команда Невесты', timestamp: Date.now() - 2000000, detected_glasses: 1, confidence: 0.98, quest_id: 'quest_couple_bg', quest_title: 'На фоне Молодоженов', quest_completed: true, ai_cheer: 'Молодожены в фокусе, бокал шампанского сияет! За невесту!', status: 'verified', photo_url: 'https://images.unsplash.com/photo-1511285560929-80b456fea0bc?w=800&auto=format&fit=crop&q=80' },
|
||||
{ id: 3, ticket_id: 'LUCK-003', guest_name: 'Дмитрий Ковалев', team_id: 'team_friends', team_name: '🎉 Команда Друзей', timestamp: Date.now() - 1200000, detected_glasses: 2, confidence: 0.92, quest_id: 'quest_superhero', quest_title: 'Поза Супергероя', quest_completed: true, ai_cheer: 'Стойка Тора с бокалом виски! +1 напиток друзьям!', status: 'verified', photo_url: 'https://images.unsplash.com/photo-1465495976277-4387d4b0b4c6?w=800&auto=format&fit=crop&q=80' },
|
||||
{ id: 4, ticket_id: 'LUCK-005', guest_name: 'Сергей Морозов', team_id: 'team_witnesses', team_name: '🍸 Свидетели и Свита', timestamp: Date.now() - 600000, detected_glasses: 1, confidence: 0.95, quest_id: 'quest_serious', quest_title: 'Максимальная Серьезность', quest_completed: true, ai_cheer: 'Лицо министра финансов с бокалом! Безупречно!', status: 'verified', photo_url: 'https://images.unsplash.com/photo-1520854221256-17451cc331bf?w=800&auto=format&fit=crop&q=80' },
|
||||
],
|
||||
photos: [
|
||||
{ id: 'p1', ticket_id: 'LUCK-001', guest_name: 'Алексей Смирнов', team_id: 'team_groom', team_name: '🤵 Команда Жениха', url: 'https://images.unsplash.com/photo-1519741497674-611481863552?w=800&auto=format&fit=crop&q=80', uploaded_at: Date.now() - 2800000, caption: 'Квест «Страх» выполнен!', quest_title: 'Эмоция «СТРАХ»', is_toast: true },
|
||||
{ id: 'p2', ticket_id: 'LUCK-002', guest_name: 'Елена Васильева', team_id: 'team_bride', team_name: '👰 Команда Невесты', url: 'https://images.unsplash.com/photo-1511285560929-80b456fea0bc?w=800&auto=format&fit=crop&q=80', uploaded_at: Date.now() - 2000000, caption: 'Тост за молодых на фоне пары', quest_title: 'На фоне Молодоженов', is_toast: true },
|
||||
{ id: 'p3', ticket_id: 'LUCK-003', guest_name: 'Дмитрий Ковалев', team_id: 'team_friends', team_name: '🎉 Команда Друзей', url: 'https://images.unsplash.com/photo-1465495976277-4387d4b0b4c6?w=800&auto=format&fit=crop&q=80', uploaded_at: Date.now() - 1200000, caption: 'Супергерои вечера', quest_title: 'Поза Супергероя', is_toast: true },
|
||||
{ id: 'p4', ticket_id: 'LUCK-005', guest_name: 'Сергей Морозов', team_id: 'team_witnesses', team_name: '🍸 Свидетели и Свита', url: 'https://images.unsplash.com/photo-1520854221256-17451cc331bf?w=800&auto=format&fit=crop&q=80', uploaded_at: Date.now() - 600000, caption: 'Строгий свидетель', quest_title: 'Максимальная Серьезность', is_toast: true },
|
||||
],
|
||||
current_round_id: 3,
|
||||
round_active: false,
|
||||
round_start_time: null,
|
||||
round_first_catcher: null,
|
||||
cooldown_until: null,
|
||||
cake_time_target: DEFAULT_CAKE_TIME,
|
||||
immich_url: process.env.IMMICH_URL || '',
|
||||
immich_api_key: process.env.IMMICH_API_KEY || '',
|
||||
immich_album_id: process.env.IMMICH_ALBUM_ID || '',
|
||||
immich_album_name: process.env.IMMICH_ALBUM_NAME || '',
|
||||
ollama_url: process.env.OLLAMA_URL || '',
|
||||
couples_names: 'Анна & Дмитрий',
|
||||
wedding_date: '2026-08-27',
|
||||
};
|
||||
|
||||
class WeddingDatabase {
|
||||
private state: AppState;
|
||||
|
||||
constructor() {
|
||||
this.state = this.loadState();
|
||||
}
|
||||
|
||||
private loadState(): AppState {
|
||||
try {
|
||||
if (!fs.existsSync(DATA_DIR)) {
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
}
|
||||
if (fs.existsSync(DATA_FILE)) {
|
||||
const raw = fs.readFileSync(DATA_FILE, 'utf-8');
|
||||
const parsed = JSON.parse(raw);
|
||||
return { ...DEFAULT_STATE, ...parsed };
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('Could not load existing state file, using defaults:', e);
|
||||
}
|
||||
return { ...DEFAULT_STATE };
|
||||
}
|
||||
|
||||
public save(): void {
|
||||
try {
|
||||
if (!fs.existsSync(DATA_DIR)) {
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
}
|
||||
const tmpFile = `${DATA_FILE}.tmp`;
|
||||
fs.writeFileSync(tmpFile, JSON.stringify(this.state, null, 2), 'utf-8');
|
||||
fs.renameSync(tmpFile, DATA_FILE);
|
||||
} catch (e) {
|
||||
console.error('Failed to write database file:', e);
|
||||
}
|
||||
}
|
||||
|
||||
public getState(): AppState {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
// Guests
|
||||
public registerGuest(
|
||||
ticket_id: string,
|
||||
guest_name: string,
|
||||
team_id: string,
|
||||
team_name?: string,
|
||||
role?: UserRole
|
||||
): Guest {
|
||||
const cleanTicket = ticket_id.trim().toUpperCase();
|
||||
const resolvedTeamName = team_name || DEFAULT_TEAMS.find((t) => t.id === team_id)?.name || '🎉 Команда Друзей';
|
||||
|
||||
// Auto-detect role from ticket prefix or explicit role
|
||||
let resolvedRole: UserRole = role || 'guest';
|
||||
if (!role) {
|
||||
if (cleanTicket.startsWith('ADMIN')) resolvedRole = 'admin';
|
||||
else if (cleanTicket.startsWith('HOST')) resolvedRole = 'host';
|
||||
else if (cleanTicket.startsWith('COUPLE')) resolvedRole = 'couple';
|
||||
}
|
||||
|
||||
const guest: Guest = {
|
||||
ticket_id: cleanTicket,
|
||||
guest_name: guest_name.trim(),
|
||||
team_id: team_id || 'team_friends',
|
||||
team_name: resolvedTeamName,
|
||||
role: resolvedRole,
|
||||
registered_at: Date.now(),
|
||||
};
|
||||
this.state.guests[cleanTicket] = guest;
|
||||
this.save();
|
||||
return guest;
|
||||
}
|
||||
|
||||
public getGuest(ticket_id: string): Guest | undefined {
|
||||
return this.state.guests[ticket_id.trim().toUpperCase()];
|
||||
}
|
||||
|
||||
public getAllGuests(): Guest[] {
|
||||
return Object.values(this.state.guests);
|
||||
}
|
||||
|
||||
public removeGuest(ticket_id: string): boolean {
|
||||
const clean = ticket_id.trim().toUpperCase();
|
||||
if (this.state.guests[clean]) {
|
||||
delete this.state.guests[clean];
|
||||
this.save();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public batchRemoveGuests(ticket_ids: string[]): number {
|
||||
let count = 0;
|
||||
for (const tid of ticket_ids) {
|
||||
const clean = tid.trim().toUpperCase();
|
||||
if (this.state.guests[clean]) {
|
||||
delete this.state.guests[clean];
|
||||
count++;
|
||||
}
|
||||
}
|
||||
if (count > 0) {
|
||||
this.save();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
public updateGuest(
|
||||
ticket_id: string,
|
||||
updates: Partial<Pick<Guest, 'guest_name' | 'team_id' | 'team_name' | 'role'>>
|
||||
): Guest | null {
|
||||
const clean = ticket_id.trim().toUpperCase();
|
||||
const guest = this.state.guests[clean];
|
||||
if (!guest) return null;
|
||||
|
||||
if (updates.guest_name) guest.guest_name = updates.guest_name.trim();
|
||||
if (updates.team_id) guest.team_id = updates.team_id;
|
||||
if (updates.team_name) guest.team_name = updates.team_name;
|
||||
if (updates.role) guest.role = updates.role;
|
||||
|
||||
this.save();
|
||||
return guest;
|
||||
}
|
||||
|
||||
// Kisses logic
|
||||
public startKissRound(): { round_id: number; start_time: number } {
|
||||
this.state.current_round_id += 1;
|
||||
this.state.round_active = true;
|
||||
this.state.round_start_time = Date.now();
|
||||
this.state.round_first_catcher = null;
|
||||
this.state.cooldown_until = null;
|
||||
this.save();
|
||||
return { round_id: this.state.current_round_id, start_time: this.state.round_start_time };
|
||||
}
|
||||
|
||||
public endKissRound(): { cooldown_until: number } {
|
||||
this.state.round_active = false;
|
||||
this.state.round_start_time = null;
|
||||
this.state.cooldown_until = Date.now() + 30000;
|
||||
this.save();
|
||||
return { cooldown_until: this.state.cooldown_until };
|
||||
}
|
||||
|
||||
public catchKiss(ticket_id: string): {
|
||||
success: boolean;
|
||||
points: number;
|
||||
is_golden: boolean;
|
||||
reason?: string;
|
||||
round_id: number;
|
||||
guest: Guest;
|
||||
catcher_info?: { ticket_id: string; guest_name: string; team_name: string };
|
||||
} {
|
||||
const guest = this.getGuest(ticket_id);
|
||||
if (!guest) {
|
||||
return { success: false, points: 0, is_golden: false, reason: 'Гость не зарегистрирован', round_id: this.state.current_round_id, guest: null as any };
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
if (this.state.cooldown_until && now < this.state.cooldown_until) {
|
||||
const remaining = Math.ceil((this.state.cooldown_until - now) / 1000);
|
||||
return { success: false, points: 0, is_golden: false, reason: `Кулдаун! Подождите ${remaining} сек.`, round_id: this.state.current_round_id, guest };
|
||||
}
|
||||
|
||||
if (!this.state.round_active) {
|
||||
this.startKissRound();
|
||||
const catchRecord: KissCatch = {
|
||||
id: this.state.kiss_catches.length + 1,
|
||||
ticket_id: guest.ticket_id,
|
||||
guest_name: guest.guest_name,
|
||||
team_id: guest.team_id,
|
||||
team_name: guest.team_name,
|
||||
points: 3,
|
||||
round_id: this.state.current_round_id,
|
||||
timestamp: now,
|
||||
};
|
||||
this.state.kiss_catches.push(catchRecord);
|
||||
this.state.round_first_catcher = {
|
||||
ticket_id: guest.ticket_id,
|
||||
guest_name: guest.guest_name,
|
||||
team_name: guest.team_name,
|
||||
};
|
||||
this.save();
|
||||
return {
|
||||
success: true,
|
||||
points: 3,
|
||||
is_golden: true,
|
||||
round_id: this.state.current_round_id,
|
||||
guest,
|
||||
catcher_info: this.state.round_first_catcher,
|
||||
};
|
||||
}
|
||||
|
||||
const alreadyCaughtInThisRound = this.state.kiss_catches.some(
|
||||
(c) => c.round_id === this.state.current_round_id && c.ticket_id === guest.ticket_id
|
||||
);
|
||||
|
||||
if (alreadyCaughtInThisRound) {
|
||||
return { success: false, points: 0, is_golden: false, reason: 'Вы уже зафиксировали поцелуй в этом раунде!', round_id: this.state.current_round_id, guest };
|
||||
}
|
||||
|
||||
const elapsedMs = now - (this.state.round_start_time || now);
|
||||
if (elapsedMs <= 5500) {
|
||||
const catchRecord: KissCatch = {
|
||||
id: this.state.kiss_catches.length + 1,
|
||||
ticket_id: guest.ticket_id,
|
||||
guest_name: guest.guest_name,
|
||||
team_id: guest.team_id,
|
||||
team_name: guest.team_name,
|
||||
points: 1,
|
||||
round_id: this.state.current_round_id,
|
||||
timestamp: now,
|
||||
};
|
||||
this.state.kiss_catches.push(catchRecord);
|
||||
this.save();
|
||||
return {
|
||||
success: true,
|
||||
points: 1,
|
||||
is_golden: false,
|
||||
round_id: this.state.current_round_id,
|
||||
guest,
|
||||
catcher_info: this.state.round_first_catcher,
|
||||
};
|
||||
} else {
|
||||
this.endKissRound();
|
||||
return { success: false, points: 0, is_golden: false, reason: 'Раунд завершен! Не успели за 5 секунд.', round_id: this.state.current_round_id, guest };
|
||||
}
|
||||
}
|
||||
|
||||
// Toasts / Drinks with strange quests
|
||||
public addToast(
|
||||
ticket_id: string,
|
||||
photo_url?: string,
|
||||
detected_glasses: number = 1,
|
||||
confidence: number = 0.95,
|
||||
ai_cheer?: string,
|
||||
quest_id?: string,
|
||||
quest_title?: string,
|
||||
quest_completed: boolean = true
|
||||
): ToastLog {
|
||||
const guest = this.getGuest(ticket_id);
|
||||
const toast: ToastLog = {
|
||||
id: this.state.toasts.length + 1,
|
||||
ticket_id: ticket_id.trim().toUpperCase(),
|
||||
guest_name: guest ? guest.guest_name : 'Гость',
|
||||
team_id: guest ? guest.team_id : 'team_friends',
|
||||
team_name: guest ? guest.team_name : '🎉 Команда Друзей',
|
||||
timestamp: Date.now(),
|
||||
photo_url,
|
||||
detected_glasses,
|
||||
confidence,
|
||||
ai_cheer: ai_cheer || 'Горько! За счастье молодых!',
|
||||
quest_id,
|
||||
quest_title,
|
||||
quest_completed,
|
||||
status: 'verified',
|
||||
};
|
||||
this.state.toasts.push(toast);
|
||||
|
||||
if (photo_url) {
|
||||
this.state.photos.unshift({
|
||||
id: `toast-${toast.id}-${Date.now()}`,
|
||||
ticket_id: toast.ticket_id,
|
||||
guest_name: toast.guest_name,
|
||||
team_id: toast.team_id,
|
||||
team_name: toast.team_name,
|
||||
url: photo_url,
|
||||
uploaded_at: Date.now(),
|
||||
caption: quest_title ? `Квест «${quest_title}»: ${toast.ai_cheer}` : `Тост: ${toast.ai_cheer}`,
|
||||
quest_title,
|
||||
is_toast: true,
|
||||
});
|
||||
}
|
||||
|
||||
this.save();
|
||||
return toast;
|
||||
}
|
||||
|
||||
// Photos
|
||||
public addPhoto(photo: Omit<WeddingPhoto, 'id' | 'uploaded_at'>): WeddingPhoto {
|
||||
const newPhoto: WeddingPhoto = {
|
||||
...photo,
|
||||
id: `photo-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`,
|
||||
uploaded_at: Date.now(),
|
||||
};
|
||||
this.state.photos.unshift(newPhoto);
|
||||
this.save();
|
||||
return newPhoto;
|
||||
}
|
||||
|
||||
// Aggregated Stats with Personal and Team metrics
|
||||
public getAggregatedStats() {
|
||||
const totalKisses = this.state.kiss_catches.length;
|
||||
const totalToasts = this.state.toasts.length;
|
||||
const totalPhotos = this.state.photos.length;
|
||||
|
||||
// 1. Top Paparazzi (Kiss Hunt Leaderboard)
|
||||
const guestKissPoints: Record<string, { ticket_id: string; guest_name: string; team_name: string; points: number; kisses_count: number }> = {};
|
||||
|
||||
for (const kc of this.state.kiss_catches) {
|
||||
if (!guestKissPoints[kc.ticket_id]) {
|
||||
guestKissPoints[kc.ticket_id] = {
|
||||
ticket_id: kc.ticket_id,
|
||||
guest_name: kc.guest_name,
|
||||
team_name: kc.team_name,
|
||||
points: 0,
|
||||
kisses_count: 0,
|
||||
};
|
||||
}
|
||||
guestKissPoints[kc.ticket_id].points += kc.points;
|
||||
guestKissPoints[kc.ticket_id].kisses_count += 1;
|
||||
}
|
||||
|
||||
const topPaparazzi = Object.values(guestKissPoints)
|
||||
.sort((a, b) => b.points - a.points || b.kisses_count - a.kisses_count)
|
||||
.slice(0, 5);
|
||||
|
||||
// 2. Top Drinkers (Personal Drink Standings / Личный зачет по выпитому)
|
||||
const guestDrinkPoints: Record<string, { ticket_id: string; guest_name: string; team_name: string; drinks_count: number; points: number }> = {};
|
||||
|
||||
for (const t of this.state.toasts) {
|
||||
if (!guestDrinkPoints[t.ticket_id]) {
|
||||
guestDrinkPoints[t.ticket_id] = {
|
||||
ticket_id: t.ticket_id,
|
||||
guest_name: t.guest_name,
|
||||
team_name: t.team_name,
|
||||
drinks_count: 0,
|
||||
points: 0,
|
||||
};
|
||||
}
|
||||
guestDrinkPoints[t.ticket_id].drinks_count += 1;
|
||||
guestDrinkPoints[t.ticket_id].points += 10;
|
||||
}
|
||||
|
||||
const topDrinkers = Object.values(guestDrinkPoints)
|
||||
.sort((a, b) => b.drinks_count - a.drinks_count || b.points - a.points)
|
||||
.slice(0, 5);
|
||||
|
||||
// 3. Team Battle Score (Командный зачет по выпитому и очкам)
|
||||
const teamStats: Record<string, { team_id: string; team_name: string; drinks_count: number; points: number; guest_count: number; kisses_count: number }> = {};
|
||||
|
||||
// Initialize preset teams
|
||||
for (const team of DEFAULT_TEAMS) {
|
||||
teamStats[team.id] = {
|
||||
team_id: team.id,
|
||||
team_name: team.name,
|
||||
drinks_count: 0,
|
||||
points: 0,
|
||||
guest_count: 0,
|
||||
kisses_count: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Count guests in teams
|
||||
for (const g of Object.values(this.state.guests)) {
|
||||
if (!teamStats[g.team_id]) {
|
||||
teamStats[g.team_id] = {
|
||||
team_id: g.team_id,
|
||||
team_name: g.team_name,
|
||||
drinks_count: 0,
|
||||
points: 0,
|
||||
guest_count: 0,
|
||||
kisses_count: 0,
|
||||
};
|
||||
}
|
||||
teamStats[g.team_id].guest_count += 1;
|
||||
}
|
||||
|
||||
// Count drinks / quests in teams (+10 pts per drink)
|
||||
for (const t of this.state.toasts) {
|
||||
if (!teamStats[t.team_id]) {
|
||||
teamStats[t.team_id] = {
|
||||
team_id: t.team_id,
|
||||
team_name: t.team_name,
|
||||
drinks_count: 0,
|
||||
points: 0,
|
||||
guest_count: 0,
|
||||
kisses_count: 0,
|
||||
};
|
||||
}
|
||||
teamStats[t.team_id].drinks_count += 1;
|
||||
teamStats[t.team_id].points += 10;
|
||||
}
|
||||
|
||||
// Count kisses in teams
|
||||
for (const kc of this.state.kiss_catches) {
|
||||
if (!teamStats[kc.team_id]) {
|
||||
teamStats[kc.team_id] = {
|
||||
team_id: kc.team_id,
|
||||
team_name: kc.team_name,
|
||||
drinks_count: 0,
|
||||
points: 0,
|
||||
guest_count: 0,
|
||||
kisses_count: 0,
|
||||
};
|
||||
}
|
||||
teamStats[kc.team_id].kisses_count += 1;
|
||||
teamStats[kc.team_id].points += kc.points;
|
||||
}
|
||||
|
||||
const teamBattle = Object.values(teamStats).sort((a, b) => b.points - a.points || b.drinks_count - a.drinks_count);
|
||||
|
||||
// 4. Detailed Registered Users list for Admin
|
||||
const allGuests = Object.values(this.state.guests);
|
||||
const registeredUsers = allGuests.map((g) => {
|
||||
const kisses = this.state.kiss_catches.filter((k) => k.ticket_id === g.ticket_id);
|
||||
const kissPts = kisses.reduce((acc, k) => acc + k.points, 0);
|
||||
const drinks = this.state.toasts.filter((t) => t.ticket_id === g.ticket_id);
|
||||
const drinkPts = drinks.length * 10;
|
||||
const photos = this.state.photos.filter((p) => p.ticket_id === g.ticket_id);
|
||||
|
||||
return {
|
||||
...g,
|
||||
points: kissPts + drinkPts,
|
||||
kisses_count: kisses.length,
|
||||
drinks_count: drinks.length,
|
||||
photos_count: photos.length,
|
||||
};
|
||||
}).sort((a, b) => b.registered_at - a.registered_at);
|
||||
|
||||
// Format cake target time as HH:MM
|
||||
let cake_time_target_str = '';
|
||||
try {
|
||||
const d = new Date(this.state.cake_time_target);
|
||||
const hours = String(d.getHours()).padStart(2, '0');
|
||||
const mins = String(d.getMinutes()).padStart(2, '0');
|
||||
cake_time_target_str = `${hours}:${mins}`;
|
||||
} catch {
|
||||
cake_time_target_str = '22:30';
|
||||
}
|
||||
|
||||
return {
|
||||
totalKisses,
|
||||
totalToasts,
|
||||
totalPhotos,
|
||||
topPaparazzi,
|
||||
topDrinkers,
|
||||
teamBattle,
|
||||
registeredUsers,
|
||||
round_active: this.state.round_active,
|
||||
round_start_time: this.state.round_start_time,
|
||||
round_first_catcher: this.state.round_first_catcher,
|
||||
cooldown_until: this.state.cooldown_until,
|
||||
cake_time_target: this.state.cake_time_target,
|
||||
cake_time_target_str,
|
||||
couples_names: this.state.couples_names,
|
||||
wedding_date: this.state.wedding_date,
|
||||
immich_url: this.state.immich_url,
|
||||
immich_album_id: this.state.immich_album_id,
|
||||
immich_album_name: this.state.immich_album_name,
|
||||
ollama_url: this.state.ollama_url,
|
||||
};
|
||||
}
|
||||
|
||||
public updateSettings(settings: Partial<AppState>): AppState {
|
||||
this.state = { ...this.state, ...settings };
|
||||
this.save();
|
||||
return this.state;
|
||||
}
|
||||
|
||||
public resetAllData(): void {
|
||||
this.state = {
|
||||
...DEFAULT_STATE,
|
||||
guests: {},
|
||||
kiss_catches: [],
|
||||
toasts: [],
|
||||
photos: [],
|
||||
current_round_id: 0,
|
||||
round_active: false,
|
||||
round_start_time: null,
|
||||
round_first_catcher: null,
|
||||
cooldown_until: null,
|
||||
cake_time_target: Date.now() + 3 * 3600000,
|
||||
};
|
||||
this.save();
|
||||
}
|
||||
|
||||
public seedDemoData(): void {
|
||||
this.state = {
|
||||
...DEFAULT_STATE,
|
||||
cake_time_target: Date.now() + 2 * 3600000 + 30 * 60000,
|
||||
};
|
||||
this.save();
|
||||
}
|
||||
}
|
||||
|
||||
export const db = new WeddingDatabase();
|
||||
@@ -0,0 +1,301 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const UPLOADS_DIR = path.join(process.cwd(), 'data', 'uploads');
|
||||
|
||||
if (!fs.existsSync(UPLOADS_DIR)) {
|
||||
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
export interface ImmichUploadResult {
|
||||
url: string;
|
||||
immichAssetId?: string;
|
||||
syncedToImmich: boolean;
|
||||
albumSynced?: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface ImmichAlbum {
|
||||
id: string;
|
||||
albumName: string;
|
||||
assetCount?: number;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes and determines correct MIME-type and extension for image uploads
|
||||
*/
|
||||
function resolveMimeAndExt(base64OrBuffer: string, providedFilename?: string, providedMime?: string): { mimeType: string; extension: string } {
|
||||
if (providedMime && providedMime.startsWith('image/')) {
|
||||
const sub = providedMime.split('/')[1].toLowerCase();
|
||||
const ext = sub === 'jpeg' || sub === 'jpg' ? 'jpg' : sub === 'png' ? 'png' : sub === 'webp' ? 'webp' : sub === 'heic' ? 'heic' : sub;
|
||||
const standardMime = ext === 'jpg' ? 'image/jpeg' : providedMime;
|
||||
return { mimeType: standardMime, extension: ext };
|
||||
}
|
||||
|
||||
if (base64OrBuffer.startsWith('data:image/')) {
|
||||
const match = base64OrBuffer.match(/^data:(image\/[a-zA-Z0-9.+_-]+);base64,/);
|
||||
if (match && match[1]) {
|
||||
const rawMime = match[1].toLowerCase();
|
||||
const sub = rawMime.split('/')[1];
|
||||
const ext = sub === 'jpeg' || sub === 'jpg' ? 'jpg' : sub;
|
||||
const standardMime = ext === 'jpg' ? 'image/jpeg' : rawMime;
|
||||
return { mimeType: standardMime, extension: ext };
|
||||
}
|
||||
}
|
||||
|
||||
if (providedFilename) {
|
||||
const extMatch = providedFilename.match(/\.([a-zA-Z0-9]+)$/);
|
||||
if (extMatch) {
|
||||
const ext = extMatch[1].toLowerCase();
|
||||
if (ext === 'jpg' || ext === 'jpeg') return { mimeType: 'image/jpeg', extension: 'jpg' };
|
||||
if (ext === 'png') return { mimeType: 'image/png', extension: 'png' };
|
||||
if (ext === 'webp') return { mimeType: 'image/webp', extension: 'webp' };
|
||||
if (ext === 'heic' || ext === 'heif') return { mimeType: 'image/heic', extension: 'heic' };
|
||||
}
|
||||
}
|
||||
|
||||
return { mimeType: 'image/jpeg', extension: 'jpg' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves original photo locally in full uncompressed quality and syncs it to Immich instance (optionally into a dedicated album).
|
||||
*/
|
||||
export async function saveAndSyncPhoto(
|
||||
base64OrBuffer: string,
|
||||
filename?: string,
|
||||
immichUrl?: string,
|
||||
immichApiKey?: string,
|
||||
immichAlbumId?: string,
|
||||
options?: {
|
||||
mimeType?: string;
|
||||
fileCreatedAt?: string;
|
||||
}
|
||||
): Promise<ImmichUploadResult> {
|
||||
try {
|
||||
let buffer: Buffer;
|
||||
const { mimeType, extension } = resolveMimeAndExt(base64OrBuffer, filename, options?.mimeType);
|
||||
|
||||
if (base64OrBuffer.startsWith('data:')) {
|
||||
const commaIdx = base64OrBuffer.indexOf(',');
|
||||
const base64Data = commaIdx >= 0 ? base64OrBuffer.substring(commaIdx + 1) : base64OrBuffer;
|
||||
buffer = Buffer.from(base64Data, 'base64');
|
||||
} else {
|
||||
buffer = Buffer.from(base64OrBuffer, 'base64');
|
||||
}
|
||||
|
||||
const cleanBaseName = filename ? path.parse(filename).name.replace(/[^a-zA-Z0-9_-]/g, '_') : 'photo';
|
||||
const uniqueFileName = `${Date.now()}-${cleanBaseName}.${extension}`;
|
||||
const localFilePath = path.join(UPLOADS_DIR, uniqueFileName);
|
||||
|
||||
// Write exact binary buffer to disk (100% original quality preserved, no recompression)
|
||||
fs.writeFileSync(localFilePath, buffer);
|
||||
|
||||
const localUrl = `/api/uploads/${uniqueFileName}`;
|
||||
let immichAssetId: string | undefined;
|
||||
let syncedToImmich = false;
|
||||
let albumSynced = false;
|
||||
|
||||
// If Immich is configured, upload original binary asset to Immich API
|
||||
if (immichUrl && immichApiKey) {
|
||||
try {
|
||||
const cleanImmichUrl = immichUrl.replace(/\/+$/, '');
|
||||
const formData = new FormData();
|
||||
|
||||
// Use Node Blob with strict standard MIME type
|
||||
const blob = new Blob([buffer], { type: mimeType });
|
||||
const uploadFilename = filename || uniqueFileName;
|
||||
|
||||
formData.append('assetData', blob, uploadFilename);
|
||||
formData.append('deviceAssetId', `${Date.now()}-${uploadFilename}`);
|
||||
formData.append('deviceId', 'wedding-hub-pwa');
|
||||
formData.append('fileCreatedAt', options?.fileCreatedAt || new Date().toISOString());
|
||||
formData.append('fileModifiedAt', new Date().toISOString());
|
||||
formData.append('isFavorite', 'false');
|
||||
|
||||
const uploadRes = await fetch(`${cleanImmichUrl}/api/assets`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'x-api-key': immichApiKey,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (uploadRes.ok) {
|
||||
const immichData = await uploadRes.json();
|
||||
immichAssetId = immichData.id;
|
||||
syncedToImmich = true;
|
||||
|
||||
// If a specific Immich Album is targeted, add this asset to that album
|
||||
if (immichAssetId && immichAlbumId && immichAlbumId.trim() !== '') {
|
||||
try {
|
||||
const targetAlbumId = immichAlbumId.trim();
|
||||
let albumRes = await fetch(`${cleanImmichUrl}/api/albums/${targetAlbumId}/assets`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'x-api-key': immichApiKey,
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
ids: [immichAssetId],
|
||||
}),
|
||||
});
|
||||
|
||||
if (!albumRes.ok) {
|
||||
// Fallback for Immich API variants
|
||||
albumRes = await fetch(`${cleanImmichUrl}/api/albums/${targetAlbumId}/assets`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'x-api-key': immichApiKey,
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
ids: [immichAssetId],
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
if (albumRes.ok) {
|
||||
albumSynced = true;
|
||||
} else {
|
||||
console.warn(`Immich album sync responded with ${albumRes.status}`);
|
||||
}
|
||||
} catch (albumErr) {
|
||||
console.warn('Failed to attach asset to Immich album:', albumErr);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const errText = await uploadRes.text().catch(() => '');
|
||||
console.warn(`Immich asset upload failed (${uploadRes.status}):`, errText);
|
||||
}
|
||||
} catch (immichErr: any) {
|
||||
console.warn('Immich sync network error:', immichErr?.message || immichErr);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
url: localUrl,
|
||||
immichAssetId,
|
||||
syncedToImmich,
|
||||
albumSynced,
|
||||
};
|
||||
} catch (err: any) {
|
||||
console.error('Error saving uploaded photo:', err);
|
||||
return {
|
||||
url: base64OrBuffer.startsWith('data:') ? base64OrBuffer : '',
|
||||
syncedToImmich: false,
|
||||
error: err?.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches list of all albums from Immich instance
|
||||
*/
|
||||
export async function getImmichAlbums(immichUrl: string, immichApiKey: string): Promise<ImmichAlbum[]> {
|
||||
try {
|
||||
const cleanUrl = immichUrl.replace(/\/+$/, '');
|
||||
const res = await fetch(`${cleanUrl}/api/albums`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'x-api-key': immichApiKey,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Immich returned HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
if (Array.isArray(data)) {
|
||||
return data.map((a: any) => ({
|
||||
id: a.id,
|
||||
albumName: a.albumName || a.title || 'Безымянный альбом',
|
||||
assetCount: a.assetCount ?? a.assets?.length ?? 0,
|
||||
description: a.description,
|
||||
}));
|
||||
}
|
||||
return [];
|
||||
} catch (err: any) {
|
||||
console.warn('Failed to fetch Immich albums:', err.message);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a dedicated wedding album in Immich
|
||||
*/
|
||||
export async function createImmichAlbum(
|
||||
immichUrl: string,
|
||||
immichApiKey: string,
|
||||
albumName: string,
|
||||
description?: string
|
||||
): Promise<ImmichAlbum> {
|
||||
const cleanUrl = immichUrl.replace(/\/+$/, '');
|
||||
const res = await fetch(`${cleanUrl}/api/albums`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'x-api-key': immichApiKey,
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
albumName,
|
||||
description: description || 'Свадебные фотографии гостей и интерактивных конкурсов Wedding Hub',
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errText = await res.text().catch(() => '');
|
||||
throw new Error(`Ошибка создания альбома в Immich (${res.status}): ${errText}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
return {
|
||||
id: data.id,
|
||||
albumName: data.albumName || albumName,
|
||||
description: data.description,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates connection to Immich
|
||||
*/
|
||||
export async function testImmichConnection(immichUrl: string, immichApiKey: string): Promise<{ success: boolean; message: string; version?: string; albumCount?: number }> {
|
||||
try {
|
||||
const cleanUrl = immichUrl.replace(/\/+$/, '');
|
||||
|
||||
// Test auth by fetching albums
|
||||
const res = await fetch(`${cleanUrl}/api/albums`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'x-api-key': immichApiKey,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (res.status === 401 || res.status === 403) {
|
||||
return { success: false, message: 'Неверный API ключ Immich (401/403)' };
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
return { success: false, message: `Immich ответил с кодом ошибки ${res.status}` };
|
||||
}
|
||||
|
||||
const albums = await res.json();
|
||||
return {
|
||||
success: true,
|
||||
message: 'Подключение к Immich успешно установлено!',
|
||||
albumCount: Array.isArray(albums) ? albums.length : 0,
|
||||
};
|
||||
} catch (err: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: `Не удалось связаться с сервером Immich: ${err.message || 'Ошибка сети'}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
import { GoogleGenAI } from '@google/genai';
|
||||
|
||||
let geminiClient: GoogleGenAI | null = null;
|
||||
|
||||
function getGemini(): GoogleGenAI | null {
|
||||
if (!geminiClient && process.env.GEMINI_API_KEY) {
|
||||
geminiClient = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
|
||||
}
|
||||
return geminiClient;
|
||||
}
|
||||
|
||||
export interface VLMVerificationResult {
|
||||
has_glass: boolean;
|
||||
quest_completed: boolean;
|
||||
confidence: number;
|
||||
detected_glasses: number;
|
||||
toast_phrase: string;
|
||||
analysis_summary: string;
|
||||
source: 'gemini' | 'ollama' | 'heuristic';
|
||||
}
|
||||
|
||||
class AsyncSemaphore {
|
||||
private capacity: number;
|
||||
private current: number = 0;
|
||||
private queue: (() => void)[] = [];
|
||||
|
||||
constructor(capacity: number) {
|
||||
this.capacity = capacity;
|
||||
}
|
||||
|
||||
async acquire(): Promise<() => void> {
|
||||
if (this.current < this.capacity) {
|
||||
this.current++;
|
||||
return () => this.release();
|
||||
}
|
||||
return new Promise<() => void>((resolve) => {
|
||||
this.queue.push(() => {
|
||||
this.current++;
|
||||
resolve(() => this.release());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private release() {
|
||||
this.current--;
|
||||
if (this.queue.length > 0) {
|
||||
const next = this.queue.shift();
|
||||
if (next) next();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const vlmSemaphore = new AsyncSemaphore(2);
|
||||
|
||||
const TOAST_PHRASES = [
|
||||
'Горько! За долгую и счастливую семейную жизнь!',
|
||||
'За любовь, согласие и взаимопонимание молодых!',
|
||||
'Звон бокалов в честь жениха и невесты! Ура!',
|
||||
'Пусть каждый день будет наполнен нежностью и радостью!',
|
||||
'За самых красивых и счастливых молодоженов!',
|
||||
'Крепкой любви и сладких поцелуев! До дна!',
|
||||
'За новую прекрасную семью! За союз сердец!',
|
||||
];
|
||||
|
||||
export async function verifyToastPhoto(
|
||||
imageBase64OrUrl: string,
|
||||
teamName: string,
|
||||
guestName: string,
|
||||
questInfo?: { id: string; title: string; instruction?: string },
|
||||
ollamaUrl?: string
|
||||
): Promise<VLMVerificationResult> {
|
||||
const release = await vlmSemaphore.acquire();
|
||||
try {
|
||||
const questTitle = questInfo?.title || 'Праздничный тост с бокалом';
|
||||
const questInstruction = questInfo?.instruction || 'Проверь наличие бокала или напитка в руках';
|
||||
|
||||
// 1. Check if Ollama endpoint is configured and active
|
||||
if (ollamaUrl && (ollamaUrl.startsWith('http://') || ollamaUrl.startsWith('https://'))) {
|
||||
try {
|
||||
const prompt = `You are a strict and fun wedding AI referee. Analyze this wedding photo.
|
||||
Guest: "${guestName}", Team: "${teamName}".
|
||||
Challenge: "${questTitle}" (${questInstruction}).
|
||||
Evaluate:
|
||||
1. Is there a drink, glass, cup or champagne flute? (has_glass)
|
||||
2. Is the challenge attempted / satisfied? (quest_completed)
|
||||
Respond ONLY in valid JSON format:
|
||||
{
|
||||
"has_glass": boolean,
|
||||
"quest_completed": boolean,
|
||||
"count": number,
|
||||
"comment": string
|
||||
}`;
|
||||
|
||||
const response = await fetch(`${ollamaUrl.replace(/\/$/, '')}/api/generate`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
model: 'llama3.2-vision',
|
||||
prompt,
|
||||
images: [imageBase64OrUrl.replace(/^data:image\/[a-z]+;base64,/, '')],
|
||||
stream: false,
|
||||
}),
|
||||
});
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
const parsed = JSON.parse(data.response || '{}');
|
||||
return {
|
||||
has_glass: parsed.has_glass ?? true,
|
||||
quest_completed: parsed.quest_completed ?? true,
|
||||
confidence: 0.94,
|
||||
detected_glasses: parsed.count || 1,
|
||||
toast_phrase: parsed.comment || TOAST_PHRASES[Math.floor(Math.random() * TOAST_PHRASES.length)],
|
||||
analysis_summary: `Ollama VLM: Задание «${questTitle}» проверено!`,
|
||||
source: 'ollama',
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Ollama VLM attempt failed, falling back to Gemini / AI pipeline:', err);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Try Gemini 2.5 Flash Multimodal Vision
|
||||
const ai = getGemini();
|
||||
if (ai && imageBase64OrUrl.startsWith('data:image/')) {
|
||||
try {
|
||||
const base64Data = imageBase64OrUrl.split(',')[1];
|
||||
const mimeType = imageBase64OrUrl.substring(imageBase64OrUrl.indexOf(':') + 1, imageBase64OrUrl.indexOf(';')) || 'image/jpeg';
|
||||
|
||||
const prompt = `Ты — строгий, но веселый AI-сомелье и судья свадебных алкогольных квестов.
|
||||
Гость: "${guestName}" (Команда: "${teamName}").
|
||||
Текущее странное задание для зачета бокала: "${questTitle}".
|
||||
Критерий задания: "${questInstruction}".
|
||||
|
||||
Проанализируй фото:
|
||||
1. Есть ли в кадре бокал, фужер, стакан, бутылка или напиток? (has_glass)
|
||||
2. Выполнил ли гость заданный квест (например: эмоция страха, поза супергероя, молодожены на фоне, подмигивание, серьезное лицо и т.д.)? (quest_completed)
|
||||
3. Напиши остроумный, позитивный свадебный комментарий с оценкой актерской игры и тостом!
|
||||
|
||||
Верни строго JSON:
|
||||
{
|
||||
"has_glass": boolean,
|
||||
"quest_completed": boolean,
|
||||
"detected_glasses": number,
|
||||
"confidence": number (0.0 to 1.0),
|
||||
"toast_phrase": string (1-2 забавных праздничных предложения с оценкой выполнения квеста),
|
||||
"analysis_summary": string (краткий вердикт, например: "Эмоция страха передана блестяще, бокал зафиксирован!")
|
||||
}`;
|
||||
|
||||
const response = await ai.models.generateContent({
|
||||
model: 'gemini-2.5-flash',
|
||||
contents: [
|
||||
{
|
||||
role: 'user',
|
||||
parts: [
|
||||
{ text: prompt },
|
||||
{
|
||||
inlineData: {
|
||||
mimeType,
|
||||
data: base64Data,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const text = response.text || '';
|
||||
const jsonMatch = text.match(/\{[\s\S]*\}/);
|
||||
if (jsonMatch) {
|
||||
const result = JSON.parse(jsonMatch[0]);
|
||||
return {
|
||||
has_glass: result.has_glass ?? true,
|
||||
quest_completed: result.quest_completed ?? true,
|
||||
confidence: typeof result.confidence === 'number' ? result.confidence : 0.95,
|
||||
detected_glasses: Math.max(1, result.detected_glasses || 1),
|
||||
toast_phrase: result.toast_phrase || `Задание «${questTitle}» зачтено! Горько!`,
|
||||
analysis_summary: result.analysis_summary || `Задание «${questTitle}» успешно выполнено!`,
|
||||
source: 'gemini',
|
||||
};
|
||||
}
|
||||
} catch (geminiError) {
|
||||
console.warn('Gemini vision detection error:', geminiError);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Fallback
|
||||
return {
|
||||
has_glass: true,
|
||||
quest_completed: true,
|
||||
confidence: 0.93,
|
||||
detected_glasses: 1,
|
||||
toast_phrase: `Задание «${questTitle}» блестяще выполнено гостем ${guestName}! +1 бокал команде ${teamName}!`,
|
||||
analysis_summary: `Задание «${questTitle}» успешно зачтено!`,
|
||||
source: 'heuristic',
|
||||
};
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user