This commit is contained in:
2026-05-07 00:17:25 +03:00
commit 1daa045273
15 changed files with 2279 additions and 0 deletions
+535
View File
@@ -0,0 +1,535 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Нейрофотосессия - Галерея</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
}
/* Главный контейнер - сплит экран */
.split-container {
display: flex;
width: 100%;
min-height: 100vh;
}
/* Левая половина - галерея фото (50%) */
.gallery-section {
flex: 1;
width: 50%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
overflow-y: auto;
max-height: 100vh;
position: relative;
}
/* Правая половина - QR код (50%) */
.qr-section {
flex: 1;
width: 50%;
background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 40px;
position: relative;
overflow-y: auto;
max-height: 100vh;
}
/* Заголовки */
.header {
text-align: center;
margin-bottom: 40px;
}
.main-title {
font-size: 3rem;
font-weight: 800;
color: white;
text-transform: uppercase;
letter-spacing: 4px;
text-shadow: 3px 3px 6px rgba(0,0,0,0.3);
margin-bottom: 10px;
}
.subtitle {
font-size: 1.2rem;
color: rgba(255,255,255,0.95);
font-weight: 500;
letter-spacing: 2px;
}
/* Галерея фото */
.photos-gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 25px;
margin-top: 20px;
}
.photo-item {
background: white;
border-radius: 20px;
overflow: hidden;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
transition: transform 0.3s ease, box-shadow 0.3s ease;
animation: fadeInUp 0.5s ease;
}
.photo-item:hover {
transform: translateY(-5px);
box-shadow: 0 15px 40px rgba(0,0,0,0.4);
}
.photo-item img {
width: 100%;
height: auto;
display: block;
cursor: pointer;
}
.photo-info {
padding: 12px;
text-align: center;
background: white;
}
.photo-date {
color: #667eea;
font-size: 12px;
font-weight: 600;
margin-bottom: 8px;
}
.download-btn {
display: inline-block;
padding: 8px 16px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
text-decoration: none;
border-radius: 25px;
font-size: 12px;
font-weight: 600;
transition: all 0.3s ease;
border: none;
cursor: pointer;
}
.download-btn:hover {
transform: scale(1.05);
box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}
/* QR секция */
.qr-container {
background: white;
border-radius: 30px;
padding: 40px;
text-align: center;
box-shadow: 0 20px 50px rgba(0,0,0,0.3);
animation: fadeInUp 0.5s ease;
width: 100%;
max-width: 450px;
}
.qr-title {
font-size: 1.8rem;
font-weight: 700;
color: #667eea;
margin-bottom: 20px;
}
.qr-subtitle {
font-size: 1rem;
color: #666;
margin-bottom: 30px;
}
.qr-code-wrapper {
background: white;
padding: 20px;
border-radius: 20px;
display: inline-block;
margin-bottom: 20px;
}
.qr-code-wrapper img {
width: 250px;
height: 250px;
display: block;
}
.current-photo-preview {
margin-top: 20px;
padding-top: 20px;
border-top: 2px solid #eee;
}
.current-photo-preview img {
width: 80px;
height: 80px;
object-fit: cover;
border-radius: 10px;
margin-top: 10px;
box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}
.qr-instruction {
font-size: 14px;
color: #888;
margin-top: 15px;
}
.empty-state {
text-align: center;
color: white;
padding: 60px 20px;
font-size: 1.2rem;
background: rgba(255,255,255,0.1);
border-radius: 20px;
backdrop-filter: blur(10px);
}
.empty-state-icon {
font-size: 64px;
margin-bottom: 20px;
}
/* Анимации */
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* Адаптивность для мобильных устройств */
@media (max-width: 768px) {
.split-container {
flex-direction: column;
}
.gallery-section,
.qr-section {
width: 100%;
max-height: none;
}
.gallery-section {
max-height: 60vh;
overflow-y: auto;
}
.qr-section {
padding: 30px;
}
.main-title {
font-size: 2rem;
}
.subtitle {
font-size: 0.9rem;
}
.qr-container {
padding: 25px;
}
.qr-code-wrapper img {
width: 180px;
height: 180px;
}
}
/* Стиль скроллбара */
.gallery-section::-webkit-scrollbar {
width: 8px;
}
.gallery-section::-webkit-scrollbar-track {
background: rgba(255,255,255,0.2);
border-radius: 10px;
}
.gallery-section::-webkit-scrollbar-thumb {
background: rgba(255,255,255,0.5);
border-radius: 10px;
}
.gallery-section::-webkit-scrollbar-thumb:hover {
background: rgba(255,255,255,0.8);
}
/* Уведомление о новом фото */
.notification {
position: fixed;
bottom: 20px;
right: 20px;
background: #48bb78;
color: white;
padding: 12px 24px;
border-radius: 50px;
font-weight: 600;
animation: slideInRight 0.5s ease;
z-index: 1000;
box-shadow: 0 5px 20px rgba(0,0,0,0.2);
}
@keyframes slideInRight {
from {
transform: translateX(100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
</style>
</head>
<body>
<div class="split-container">
<!-- Левая половина: Галерея фото -->
<div class="gallery-section">
<div class="header">
<div class="main-title">НЕЙРОФОТОСЕССИЯ</div>
<div class="subtitle">Молодежный Парламент ДНР</div>
</div>
<div id="gallery" class="photos-gallery">
<div class="empty-state">
<div class="empty-state-icon">📸</div>
<p>Здесь появятся опубликованные фото</p>
<p style="font-size: 0.9rem; margin-top: 10px;">Оператор опубликует фото, и они сразу появятся здесь</p>
</div>
</div>
</div>
<!-- Правая половина: QR Code -->
<div class="qr-section">
<div id="qrContainer" class="qr-container">
<div class="qr-title">📱 СКАЧАТЬ ФОТО</div>
<div class="qr-subtitle">Отсканируйте QR-код, чтобы скачать последнее фото</div>
<div id="qrCodeWrapper" class="qr-code-wrapper">
<div id="qrPlaceholder" style="width: 250px; height: 250px; display: flex; align-items: center; justify-content: center; background: #f5f5f5; border-radius: 20px;">
<span style="color: #999;">Ожидание фото...</span>
</div>
</div>
<div id="currentPhotoPreview" class="current-photo-preview" style="display: none;">
<div style="font-size: 12px; color: #888;">Текущее фото:</div>
<img id="currentPhotoImg" src="" alt="Текущее фото">
</div>
<div class="qr-instruction">
✨ QR-код обновляется автоматически при публикации нового фото
</div>
</div>
</div>
</div>
<script>
let currentPhotos = [];
let updateInterval = null;
let lastPhotoId = null;
// Загрузка опубликованных фото
async function loadPublishedPhotos() {
try {
const response = await fetch('/get-published-photos');
const data = await response.json();
if (data.photos && data.photos.length > 0) {
updateGallery(data.photos);
// Проверяем, есть ли новое фото
if (lastPhotoId !== data.photos[data.photos.length - 1]?.id) {
const lastPhoto = data.photos[data.photos.length - 1];
if (lastPhoto && lastPhoto.id !== lastPhotoId) {
lastPhotoId = lastPhoto.id;
showNotification('Новое фото опубликовано!');
updateQRCode(lastPhoto);
}
}
} else {
updateGallery([]);
}
} catch (error) {
console.error('Ошибка загрузки фото:', error);
}
}
// Обновление галереи
function updateGallery(photos) {
const gallery = document.getElementById('gallery');
if (!photos || photos.length === 0) {
gallery.innerHTML = `<div class="empty-state">
<div class="empty-state-icon">📸</div>
<p>Здесь появятся опубликованные фото</p>
<p style="font-size: 0.9rem; margin-top: 10px;">Оператор опубликует фото, и они сразу появятся здесь</p>
</div>`;
return;
}
// Проверяем наличие новых фото
const newPhotos = photos.filter(photo => !currentPhotos.find(p => p.id === photo.id));
if (newPhotos.length > 0 || currentPhotos.length !== photos.length) {
// Перестраиваем галерею
gallery.innerHTML = '';
// Показываем фото в обратном порядке (новые сверху)
[...photos].reverse().forEach(photo => {
const photoDiv = createPhotoElement(photo);
gallery.appendChild(photoDiv);
});
currentPhotos = [...photos];
// Если есть новое фото, обновляем QR для последнего
if (newPhotos.length > 0) {
updateQRCode(newPhotos[0]);
// Прокручиваем галерею к новому фото
setTimeout(() => {
const firstPhoto = gallery.firstChild;
if (firstPhoto) {
firstPhoto.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}, 100);
} else if (photos.length > 0) {
// Обновляем QR для последнего фото
updateQRCode(photos[photos.length - 1]);
}
}
}
// Создание элемента фото
function createPhotoElement(photo) {
const div = document.createElement('div');
div.className = 'photo-item';
const downloadUrl = `${window.location.origin}/download-photo/${photo.id}`;
const date = new Date(photo.published_at);
const formattedDate = date.toLocaleString('ru-RU', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
div.innerHTML = `
<img src="${photo.path}" alt="Фото" loading="lazy" onclick="viewFullImage('${photo.path}')">
<div class="photo-info">
<div class="photo-date">📅 ${formattedDate}</div>
<a href="${downloadUrl}" class="download-btn" download>💾 Скачать фото</a>
</div>
`;
return div;
}
// Просмотр полноразмерного изображения
window.viewFullImage = function(url) {
const modal = document.createElement('div');
modal.style.position = 'fixed';
modal.style.top = '0';
modal.style.left = '0';
modal.style.width = '100%';
modal.style.height = '100%';
modal.style.backgroundColor = 'rgba(0,0,0,0.95)';
modal.style.zIndex = '1001';
modal.style.display = 'flex';
modal.style.alignItems = 'center';
modal.style.justifyContent = 'center';
modal.style.cursor = 'pointer';
const img = document.createElement('img');
img.src = url;
img.style.maxWidth = '90%';
img.style.maxHeight = '90%';
img.style.borderRadius = '10px';
img.style.objectFit = 'contain';
modal.appendChild(img);
modal.onclick = () => modal.remove();
document.body.appendChild(modal);
};
// Обновление QR-кода
function updateQRCode(photo) {
if (!photo) return;
const downloadUrl = `${window.location.origin}/download-photo/${photo.id}`;
const qrWrapper = document.getElementById('qrCodeWrapper');
const previewContainer = document.getElementById('currentPhotoPreview');
const previewImg = document.getElementById('currentPhotoImg');
// Создаем QR код через API
const qrImg = document.createElement('img');
qrImg.src = `https://api.qrserver.com/v1/create-qr-code/?size=250x250&margin=10&data=${encodeURIComponent(downloadUrl)}`;
qrImg.alt = 'QR Code';
qrImg.style.width = '250px';
qrImg.style.height = '250px';
qrImg.style.borderRadius = '10px';
qrWrapper.innerHTML = '';
qrWrapper.appendChild(qrImg);
// Обновляем превью текущего фото
previewImg.src = photo.path;
previewContainer.style.display = 'block';
// Добавляем информацию о ссылке в консоль для отладки
console.log('📱 QR код обновлен для фото:', downloadUrl);
}
// Показать уведомление о новом фото
function showNotification(message) {
// Удаляем старые уведомления
const oldNotification = document.querySelector('.notification');
if (oldNotification) {
oldNotification.remove();
}
const notification = document.createElement('div');
notification.className = 'notification';
notification.innerHTML = `${message}`;
document.body.appendChild(notification);
setTimeout(() => {
notification.remove();
}, 3000);
}
// Запускаем периодическое обновление
loadPublishedPhotos();
updateInterval = setInterval(loadPublishedPhotos, 3000);
// Обработка закрытия страницы
window.addEventListener('beforeunload', () => {
if (updateInterval) {
clearInterval(updateInterval);
}
});
</script>
</body>
</html>
+724
View File
@@ -0,0 +1,724 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>Нейрофотосессия - Оператор</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 1400px;
margin: 0 auto;
}
h1 {
color: white;
text-align: center;
margin-bottom: 30px;
font-size: 1.8rem;
}
.camera-section {
background: white;
border-radius: 20px;
padding: 20px;
margin-bottom: 30px;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}
.camera-controls {
display: flex;
gap: 15px;
justify-content: center;
margin-bottom: 20px;
flex-wrap: wrap;
}
button, .file-label {
padding: 12px 24px;
font-size: 16px;
border: none;
border-radius: 10px;
cursor: pointer;
transition: all 0.3s ease;
font-weight: 600;
display: inline-block;
text-align: center;
}
button:active, .file-label:active {
transform: scale(0.95);
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5a67d8;
}
.btn-success {
background: #48bb78;
color: white;
}
.btn-success:hover {
background: #38a169;
}
.btn-danger {
background: #f56565;
color: white;
}
.btn-warning {
background: #ed8936;
color: white;
}
.video-container {
position: relative;
width: 100%;
max-width: 640px;
margin: 0 auto;
border-radius: 10px;
overflow: hidden;
background: #000;
min-height: 300px;
display: flex;
align-items: center;
justify-content: center;
}
video, canvas {
width: 100%;
height: auto;
display: block;
}
canvas {
position: absolute;
top: 0;
left: 0;
}
.file-input {
display: none;
}
.sessions-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 15px;
margin-top: 20px;
}
.session-card {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 15px;
border-radius: 15px;
cursor: pointer;
transition: all 0.3s ease;
text-align: center;
border: 2px solid transparent;
}
.session-card:hover {
transform: translateY(-3px);
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
}
.session-card.selected {
border-color: #ffd700;
background: linear-gradient(135deg, #5a67d8 0%, #6b46a0 100%);
}
.session-icon {
font-size: 40px;
margin-bottom: 10px;
}
.session-name {
font-weight: 600;
font-size: 14px;
margin-bottom: 5px;
}
.session-desc {
font-size: 11px;
opacity: 0.8;
}
.photos-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
margin-top: 20px;
}
.photo-card {
background: white;
border-radius: 15px;
overflow: hidden;
box-shadow: 0 5px 20px rgba(0,0,0,0.2);
transition: transform 0.3s ease;
}
.photo-card:hover {
transform: translateY(-5px);
}
.photo-card img {
width: 100%;
height: auto;
display: block;
cursor: pointer;
}
.photo-info {
padding: 15px;
}
.photo-title {
font-weight: 600;
margin-bottom: 10px;
color: #2d3748;
}
.comparison-container {
display: flex;
gap: 10px;
margin-top: 10px;
}
.comparison-container button {
flex: 1;
padding: 8px;
font-size: 12px;
}
.loading {
text-align: center;
padding: 20px;
color: white;
font-size: 18px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0,0,0,0.9);
border-radius: 20px;
z-index: 1000;
min-width: 250px;
}
.spinner {
border: 3px solid rgba(255,255,255,0.3);
border-top: 3px solid white;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin: 20px auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.camera-placeholder {
color: #999;
text-align: center;
padding: 40px;
}
.status-badge {
position: fixed;
top: 10px;
right: 10px;
padding: 8px 16px;
border-radius: 10px;
color: white;
font-size: 12px;
font-weight: bold;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
z-index: 1000;
}
.section-title {
color: white;
margin: 20px 0 10px;
font-size: 1.2rem;
}
@media (max-width: 768px) {
.sessions-grid {
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}
.photos-grid {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<div id="apiStatus" class="status-badge"></div>
<div class="container">
<h1>📸 Нейрофотосессия - Студия</h1>
<div class="camera-section">
<div class="camera-controls">
<button class="btn-primary" id="startCamera">📷 Включить камеру</button>
<label for="photoUpload" class="file-label btn-warning">📱 Выбрать из галереи</label>
<button class="btn-primary" id="takePhoto" disabled>📸 Сделать фото</button>
<button class="btn-danger" id="stopCamera" disabled>⏹️ Остановить</button>
</div>
<div class="video-container">
<video id="video" autoplay playsinline style="display: none;"></video>
<canvas id="canvas" style="display: none;"></canvas>
<div id="cameraPlaceholder" class="camera-placeholder">
📷 Нажми "Включить камеру" или выбери фото из галереи
</div>
</div>
</div>
<div id="sessionsSection" style="display: none;">
<div class="section-title">🎨 Выбери фотосессию:</div>
<div id="sessionsGrid" class="sessions-grid"></div>
<div class="camera-controls" style="margin-top: 15px;">
<button id="processBtn" class="btn-success" style="display: none;">✨ Обработать фото</button>
</div>
</div>
<div id="photosSection" style="display: none;">
<div class="section-title">🖼️ Обработанные фото:</div>
<div id="photosContainer" class="photos-grid"></div>
</div>
</div>
<input type="file" id="photoUpload" accept="image/*" capture="environment" style="display: none;">
<div id="loading" class="loading" style="display: none;">
<div class="spinner"></div>
<p id="loadingText">Обработка фото...</p>
</div>
<script>
let video = document.getElementById('video');
let canvas = document.getElementById('canvas');
let stream = null;
let cameraActive = false;
let currentSessionId = null;
let currentPreviewUrl = null;
let selectedStyle = null;
let availableSessions = {};
// Проверка статуса API
async function checkAPIStatus() {
try {
const response = await fetch('/health');
const data = await response.json();
const statusDiv = document.getElementById('apiStatus');
if (data.api_configured) {
statusDiv.innerHTML = '✅ Нейросеть готова';
statusDiv.style.backgroundColor = '#48bb78';
} else {
statusDiv.innerHTML = '⚠️ Нейрообработка не настроена';
statusDiv.style.backgroundColor = '#f56565';
}
} catch (error) {
console.error('Ошибка проверки статуса:', error);
}
}
// Загрузка доступных стилей
async function loadSessions() {
try {
const response = await fetch('/sessions');
const data = await response.json();
availableSessions = data.sessions;
const grid = document.getElementById('sessionsGrid');
grid.innerHTML = '';
for (const [id, session] of Object.entries(availableSessions)) {
const card = document.createElement('div');
card.className = 'session-card';
card.setAttribute('data-style-id', id);
card.innerHTML = `
<div class="session-icon">${session.icon}</div>
<div class="session-name">${session.name}</div>
<div class="session-desc">${session.description}</div>
`;
card.onclick = () => selectStyle(id);
grid.appendChild(card);
}
} catch (error) {
console.error('Ошибка загрузки стилей:', error);
}
}
// Выбор стиля
function selectStyle(styleId) {
selectedStyle = styleId;
// Подсветка выбранного стиля
document.querySelectorAll('.session-card').forEach(card => {
card.classList.remove('selected');
if (card.getAttribute('data-style-id') === styleId) {
card.classList.add('selected');
}
});
document.getElementById('processBtn').style.display = 'block';
}
// Запуск камеры
document.getElementById('startCamera').addEventListener('click', async () => {
const takePhotoBtn = document.getElementById('takePhoto');
const stopCameraBtn = document.getElementById('stopCamera');
const placeholder = document.getElementById('cameraPlaceholder');
try {
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
alert('Ваш браузер не поддерживает доступ к камере');
return;
}
const constraints = {
video: { facingMode: { exact: "environment" } }
};
stream = await navigator.mediaDevices.getUserMedia(constraints);
video.srcObject = stream;
video.style.display = 'block';
canvas.style.display = 'none';
placeholder.style.display = 'none';
await video.play();
cameraActive = true;
takePhotoBtn.disabled = false;
stopCameraBtn.disabled = false;
} catch (err) {
try {
stream = await navigator.mediaDevices.getUserMedia({ video: true });
video.srcObject = stream;
video.style.display = 'block';
canvas.style.display = 'none';
placeholder.style.display = 'none';
await video.play();
cameraActive = true;
takePhotoBtn.disabled = false;
stopCameraBtn.disabled = false;
} catch (err2) {
alert('Ошибка доступа к камере. Используйте кнопку "Выбрать из галереи"');
}
}
});
// Остановка камеры
document.getElementById('stopCamera').addEventListener('click', () => {
if (stream) {
stream.getTracks().forEach(track => track.stop());
video.srcObject = null;
video.style.display = 'none';
cameraActive = false;
document.getElementById('takePhoto').disabled = true;
document.getElementById('stopCamera').disabled = true;
const placeholder = document.getElementById('cameraPlaceholder');
placeholder.style.display = 'block';
placeholder.innerHTML = '📷 Камера отключена';
}
});
// Выбор фото из галереи
document.getElementById('photoUpload').addEventListener('change', async (e) => {
const file = e.target.files[0];
if (!file) return;
showLoading('Загрузка фото...');
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch('/upload-temp', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.success) {
currentSessionId = result.session_id;
currentPreviewUrl = result.preview_url;
// Показываем превью
canvas.width = 640;
canvas.height = 640;
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = () => {
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
canvas.style.display = 'block';
video.style.display = 'none';
document.getElementById('cameraPlaceholder').style.display = 'none';
};
img.src = currentPreviewUrl;
// Показываем выбор стилей
document.getElementById('sessionsSection').style.display = 'block';
document.getElementById('photosSection').style.display = 'block';
await loadSessions();
}
} catch (error) {
alert('Ошибка загрузки: ' + error.message);
} finally {
hideLoading();
e.target.value = '';
}
});
// Сделать фото с камеры
document.getElementById('takePhoto').addEventListener('click', () => {
if (!cameraActive || !video.srcObject) {
alert('Сначала включите камеру!');
return;
}
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
canvas.style.display = 'block';
video.style.display = 'none';
canvas.toBlob(async (blob) => {
showLoading('Загрузка фото...');
const formData = new FormData();
formData.append('file', blob, 'photo.jpg');
try {
const response = await fetch('/upload-temp', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.success) {
currentSessionId = result.session_id;
currentPreviewUrl = result.preview_url;
document.getElementById('sessionsSection').style.display = 'block';
document.getElementById('photosSection').style.display = 'block';
await loadSessions();
}
} catch (error) {
alert('Ошибка загрузки: ' + error.message);
} finally {
hideLoading();
video.style.display = 'block';
canvas.style.display = 'none';
}
}, 'image/jpeg', 0.9);
});
// Обработка фото с выбранным стилем
document.getElementById('processBtn').addEventListener('click', async () => {
if (!selectedStyle) {
alert('Выберите стиль фотосессии!');
return;
}
if (!currentSessionId) {
alert('Сначала загрузите фото!');
return;
}
showLoading('Обработка фото через нейросеть...');
const formData = new FormData();
formData.append('session_id', currentSessionId);
formData.append('style_id', selectedStyle);
try {
const response = await fetch('/process-with-style', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.success) {
addPhotoToGrid(result);
if (result.warning) {
setTimeout(() => alert(result.warning), 100);
}
} else {
alert('Ошибка при обработке');
}
} catch (error) {
alert('Ошибка: ' + error.message);
} finally {
hideLoading();
}
});
// Добавление фото в сетку
function addPhotoToGrid(photoData) {
const container = document.getElementById('photosContainer');
const card = document.createElement('div');
card.className = 'photo-card';
card.setAttribute('data-original', photoData.original_url);
card.setAttribute('data-processed', photoData.processed_url);
const timestamp = new Date().toLocaleTimeString();
const styleName = photoData.style_name || 'Обработанное фото';
card.innerHTML = `
<img src="${photoData.processed_url}" alt="Обработанное фото" onclick="showComparison('${photoData.original_url}', '${photoData.processed_url}')">
<div class="photo-info">
<div class="photo-title">✨ ${styleName} | ${timestamp}</div>
<div class="comparison-container">
<button class="btn-primary" onclick="viewFullImage('${photoData.processed_url}')">👁️ Увеличить</button>
<button class="btn-success" onclick="publishPhoto('${photoData.processed_url}')">📢 Опубликовать</button>
</div>
</div>
`;
container.insertBefore(card, container.firstChild);
}
// Просмотр полноразмерного изображения
window.viewFullImage = function(url) {
const modal = document.createElement('div');
modal.style.position = 'fixed';
modal.style.top = '0';
modal.style.left = '0';
modal.style.width = '100%';
modal.style.height = '100%';
modal.style.backgroundColor = 'rgba(0,0,0,0.95)';
modal.style.zIndex = '1001';
modal.style.display = 'flex';
modal.style.alignItems = 'center';
modal.style.justifyContent = 'center';
modal.style.cursor = 'pointer';
const img = document.createElement('img');
img.src = url;
img.style.maxWidth = '90%';
img.style.maxHeight = '90%';
img.style.borderRadius = '10px';
img.style.objectFit = 'contain';
modal.appendChild(img);
modal.onclick = () => modal.remove();
document.body.appendChild(modal);
};
// Сравнение фото
window.showComparison = function(originalUrl, processedUrl) {
const modal = document.createElement('div');
modal.style.position = 'fixed';
modal.style.top = '0';
modal.style.left = '0';
modal.style.width = '100%';
modal.style.height = '100%';
modal.style.backgroundColor = 'rgba(0,0,0,0.95)';
modal.style.zIndex = '1001';
modal.style.display = 'flex';
modal.style.flexDirection = 'column';
modal.style.alignItems = 'center';
modal.style.justifyContent = 'center';
modal.style.padding = '20px';
modal.innerHTML = `
<div style="display: flex; gap: 20px; flex-wrap: wrap; justify-content: center;">
<div>
<h3 style="color: white; text-align: center; margin-bottom: 10px;">📸 Оригинал</h3>
<img src="${originalUrl}" style="max-width: 300px; max-height: 300px; border-radius: 10px; object-fit: contain;">
</div>
<div>
<h3 style="color: white; text-align: center; margin-bottom: 10px;">✨ Обработанное</h3>
<img src="${processedUrl}" style="max-width: 300px; max-height: 300px; border-radius: 10px; object-fit: contain;">
</div>
</div>
<button onclick="this.closest('div').remove()" style="margin-top: 20px; padding: 10px 20px; background: #667eea; color: white; border: none; border-radius: 10px; cursor: pointer;">Закрыть</button>
`;
modal.onclick = (e) => {
if (e.target === modal) modal.remove();
};
document.body.appendChild(modal);
};
// Публикация фото
window.publishPhoto = async function(photoPath) {
const formData = new FormData();
formData.append('photo_path', photoPath);
try {
const response = await fetch('/publish-photo', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.success) {
alert('✅ Фото опубликовано!');
const downloadUrl = `${window.location.origin}/download-photo/${result.photo_id}`;
console.log('Ссылка для скачивания:', downloadUrl);
} else {
alert('Ошибка при публикации');
}
} catch (error) {
alert('Ошибка: ' + error.message);
}
};
function showLoading(text) {
document.getElementById('loadingText').innerText = text;
document.getElementById('loading').style.display = 'block';
}
function hideLoading() {
document.getElementById('loading').style.display = 'none';
}
// Инициализация
checkAPIStatus();
setInterval(checkAPIStatus, 30000);
// Загрузка стилей при старте
loadSessions();
</script>
</body>
</html>