Spaces:
Sleeping
Sleeping
Upload 8 files
Browse files- Dockerfile +11 -29
- app/main.py +95 -0
- config.json +5 -0
- requirements.txt +8 -7
- static/index.html +47 -0
- static/pop.mp3 +0 -0
- static/script.js +172 -0
- static/styles.css +18 -0
Dockerfile
CHANGED
|
@@ -1,29 +1,11 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
# Устанавливаем рабочую директорию
|
| 13 |
-
WORKDIR /app
|
| 14 |
-
|
| 15 |
-
# Сначала копируем только requirements.txt (для кэширования слоев Docker)
|
| 16 |
-
COPY --chown=user ./requirements.txt requirements.txt
|
| 17 |
-
|
| 18 |
-
# Устанавливаем зависимости
|
| 19 |
-
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
| 20 |
-
|
| 21 |
-
# Теперь копируем весь остальной код (main.py, index.html и др.)
|
| 22 |
-
COPY --chown=user . .
|
| 23 |
-
|
| 24 |
-
# Hugging Face Spaces ожидают, что приложение будет слушать порт 7860
|
| 25 |
-
EXPOSE 7860
|
| 26 |
-
|
| 27 |
-
# Запускаем приложение через Uvicorn
|
| 28 |
-
# main:app означает: файл main.py, объект app
|
| 29 |
-
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
|
|
|
| 1 |
+
FROM python:3.9-slim
|
| 2 |
+
WORKDIR /app
|
| 3 |
+
RUN useradd -m -u 1000 user
|
| 4 |
+
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 HOME=/home/user PATH=/home/user/.local/bin:$PATH
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
| 7 |
+
RUN python -m textblob.download_corpora
|
| 8 |
+
COPY --chown=user . .
|
| 9 |
+
USER user
|
| 10 |
+
EXPOSE 7860
|
| 11 |
+
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app/main.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, File, WebSocket, WebSocketDisconnect
|
| 2 |
+
from fastapi.staticfiles import StaticFiles
|
| 3 |
+
from fastapi.responses import FileResponse
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
+
from textblob import TextBlob
|
| 6 |
+
from typing import List
|
| 7 |
+
import os
|
| 8 |
+
import json
|
| 9 |
+
import base64
|
| 10 |
+
from google.oauth2.credentials import Credentials
|
| 11 |
+
from googleapiclient.discovery import build
|
| 12 |
+
from googleapiclient.http import MediaIoBaseUpload
|
| 13 |
+
|
| 14 |
+
app = FastAPI(title="The Zenith Messenger")
|
| 15 |
+
|
| 16 |
+
# --- CONFIG LOADING ---
|
| 17 |
+
# Пытаемся взять из переменных окружения (HF Spaces), если нет - из локального файла
|
| 18 |
+
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
| 19 |
+
SUPABASE_KEY = os.getenv("SUPABASE_KEY")
|
| 20 |
+
GDRIVE_TOKEN_B64 = os.getenv("GDRIVE_TOKEN_B64")
|
| 21 |
+
|
| 22 |
+
# Fallback для локального запуска
|
| 23 |
+
if not SUPABASE_URL:
|
| 24 |
+
try:
|
| 25 |
+
with open("config.json", "r") as f:
|
| 26 |
+
data = json.load(f)
|
| 27 |
+
SUPABASE_URL = data.get("SUPABASE_URL")
|
| 28 |
+
SUPABASE_KEY = data.get("SUPABASE_KEY")
|
| 29 |
+
GDRIVE_TOKEN_B64 = data.get("GDRIVE_TOKEN_B64")
|
| 30 |
+
except: pass
|
| 31 |
+
|
| 32 |
+
# --- GOOGLE DRIVE ---
|
| 33 |
+
def get_drive_service():
|
| 34 |
+
try:
|
| 35 |
+
if not GDRIVE_TOKEN_B64: return None
|
| 36 |
+
creds_json = base64.b64decode(GDRIVE_TOKEN_B64).decode('utf-8')
|
| 37 |
+
creds_dict = json.loads(creds_json)
|
| 38 |
+
creds = Credentials.from_authorized_user_info(creds_dict)
|
| 39 |
+
return build('drive', 'v3', credentials=creds)
|
| 40 |
+
except Exception as e:
|
| 41 |
+
print(f"Drive Error: {e}")
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
# --- MODELS & WEBSOCKET ---
|
| 45 |
+
class MessageInput(BaseModel): text: str
|
| 46 |
+
class MoodResponse(BaseModel): mood_color: str; emoji: str; sentiment: float
|
| 47 |
+
class ConfigResponse(BaseModel): supabase_url: str; supabase_key: str
|
| 48 |
+
|
| 49 |
+
class ConnectionManager:
|
| 50 |
+
def __init__(self): self.active_connections: List[WebSocket] = []
|
| 51 |
+
async def connect(self, websocket: WebSocket): await websocket.accept(); self.active_connections.append(websocket)
|
| 52 |
+
def disconnect(self, websocket: WebSocket): self.active_connections.remove(websocket)
|
| 53 |
+
async def broadcast(self, message: str, sender: WebSocket):
|
| 54 |
+
for connection in self.active_connections:
|
| 55 |
+
if connection != sender: await connection.send_text(message)
|
| 56 |
+
manager = ConnectionManager()
|
| 57 |
+
|
| 58 |
+
# --- ROUTES ---
|
| 59 |
+
@app.get("/api/config", response_model=ConfigResponse)
|
| 60 |
+
async def get_config(): return ConfigResponse(supabase_url=SUPABASE_URL or "", supabase_key=SUPABASE_KEY or "")
|
| 61 |
+
|
| 62 |
+
@app.post("/api/analyze_mood", response_model=MoodResponse)
|
| 63 |
+
async def analyze_mood(msg: MessageInput):
|
| 64 |
+
blob = TextBlob(msg.text)
|
| 65 |
+
p = blob.sentiment.polarity
|
| 66 |
+
if p > 0.5: return MoodResponse(mood_color="#00f2ea", emoji="✨", sentiment=p)
|
| 67 |
+
elif p > 0: return MoodResponse(mood_color="#4facfe", emoji="😌", sentiment=p)
|
| 68 |
+
elif p < -0.5: return MoodResponse(mood_color="#ff0055", emoji="🔥", sentiment=p)
|
| 69 |
+
elif p < 0: return MoodResponse(mood_color="#8e44ad", emoji="🥀", sentiment=p)
|
| 70 |
+
return MoodResponse(mood_color="#ffffff", emoji="🌫️", sentiment=p)
|
| 71 |
+
|
| 72 |
+
@app.websocket("/ws/signal")
|
| 73 |
+
async def websocket_endpoint(websocket: WebSocket):
|
| 74 |
+
await manager.connect(websocket)
|
| 75 |
+
try:
|
| 76 |
+
while True:
|
| 77 |
+
data = await websocket.receive_text()
|
| 78 |
+
await manager.broadcast(data, websocket)
|
| 79 |
+
except WebSocketDisconnect: manager.disconnect(websocket)
|
| 80 |
+
|
| 81 |
+
@app.post("/api/upload_file")
|
| 82 |
+
async def upload_file(file: UploadFile = File(...)):
|
| 83 |
+
service = get_drive_service()
|
| 84 |
+
if not service: return {"error": "Google Drive not configured"}
|
| 85 |
+
try:
|
| 86 |
+
meta = {'name': file.filename}
|
| 87 |
+
media = MediaIoBaseUpload(file.file, mimetype=file.content_type, resumable=True)
|
| 88 |
+
up_file = service.files().create(body=meta, media_body=media, fields='id, webContentLink, webViewLink').execute()
|
| 89 |
+
service.permissions().create(fileId=up_file.get('id'), body={'type': 'anyone', 'role': 'reader'}).execute()
|
| 90 |
+
return {"url": up_file.get('webContentLink'), "view_url": up_file.get('webViewLink'), "filename": file.filename, "mime": file.content_type}
|
| 91 |
+
except Exception as e: return {"error": str(e)}
|
| 92 |
+
|
| 93 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 94 |
+
@app.get("/")
|
| 95 |
+
async def read_index(): return FileResponse('static/index.html')
|
config.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"SUPABASE_URL": "https://ilbswgrxtjsssuqrehqv.supabase.co",
|
| 3 |
+
"SUPABASE_KEY": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImlsYnN3Z3J4dGpzc3N1cXJlaHF2Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc2NDM5MjMxNywiZXhwIjoyMDc5OTY4MzE3fQ.7KDvpUH2Isu9b-lh2scSn6w-RGzi-Mlpvl6Xl67sAnc",
|
| 4 |
+
"GDRIVE_TOKEN_B64": "eyJ0b2tlbiI6ICJ5YTI5LmEwQWE3cENBOGZZNC1hUjRWa1pQT2dnZWgyT2RBVGtqSnd6MkNmejBzVW5CLU45NWtHS2Y4b0VZbkVuVndsdlpIYVpqR2JRZDlwWUpLZVJ3dEtaOVlVdndINWFycWVsaHFwTlZBTlRyakdENEduT3BnTUtkTmlUM0RpSXREMW5LSzJTWGlkMldzWnJuT2FkRUFGZV9odkh6Yl94MWV1c0pRdk4zR1VzV3FFcUpTVENZaVZaeEIxRjRKWmVRODdrWVpZV24wUVR2NGFDZ1lLQWNjU0FSUVNGUUhHWDJNaWJDNFcwM3ppY1B6d25tSUNVUUFvaXcwMjA2IiwgInJlZnJlc2hfdG9rZW4iOiAiMS8vMGNKc095c3kwYUdhLUNnWUlBUkFBR0F3U053Ri1MOUlyWnBYZ2IxUnd5RkhzV1U3VXJsSldXa21OUjlkTUhmZFRsOGc3TWhLZW5VOHdId3V6cVpFejNRWnh2dVJ1RlVCdFNDWSIsICJ0b2tlbl91cmkiOiAiaHR0cHM6Ly9vYXV0aDIuZ29vZ2xlYXBpcy5jb20vdG9rZW4iLCAiY2xpZW50X2lkIjogIjU4MTA1NDA1NTYwNi1vaTJlcHZiN280YzRoZjA0dWJmYzBwbmxhbDNyYzkydi5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsICJjbGllbnRfc2VjcmV0IjogIkdPQ1NQWC1aTlNjQnJLaXBtWjh2SkJDNFNtVkNuVHJYbk13IiwgInNjb3BlcyI6IFsiaHR0cHM6Ly93d3cuZ29vZ2xlYXBpcy5jb20vYXV0aC9kcml2ZS5maWxlIl0sICJ1bml2ZXJzZV9kb21haW4iOiAiZ29vZ2xlYXBpcy5jb20iLCAiYWNjb3VudCI6ICIiLCAiZXhwaXJ5IjogIjIwMjUtMTItMTNUMTA6MzQ6MTZaIn0="
|
| 5 |
+
}
|
requirements.txt
CHANGED
|
@@ -1,7 +1,8 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
| 1 |
+
fastapi==0.109.0
|
| 2 |
+
uvicorn==0.27.0
|
| 3 |
+
textblob==0.17.1
|
| 4 |
+
pydantic==2.5.3
|
| 5 |
+
python-multipart
|
| 6 |
+
google-api-python-client
|
| 7 |
+
google-auth
|
| 8 |
+
google-auth-oauthlib
|
static/index.html
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>The Zenith Messenger</title>
|
| 7 |
+
<script src="https://cdn.tailwindcss.com"></script>
|
| 8 |
+
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
|
| 9 |
+
<link rel="stylesheet" href="/static/styles.css">
|
| 10 |
+
</head>
|
| 11 |
+
<body class="h-screen w-full overflow-hidden text-white">
|
| 12 |
+
<div class="background-container">
|
| 13 |
+
<div class="blob blob-1"></div>
|
| 14 |
+
<div class="blob blob-2"></div>
|
| 15 |
+
<div class="blob blob-3"></div>
|
| 16 |
+
</div>
|
| 17 |
+
<canvas id="particle-canvas"></canvas>
|
| 18 |
+
<div class="relative z-10 flex flex-col h-full max-w-4xl mx-auto p-4 md:p-8">
|
| 19 |
+
<header class="glass-panel mb-4 p-4 flex justify-between items-center rounded-2xl">
|
| 20 |
+
<h1 class="text-2xl font-bold tracking-wider uppercase">Zenith</h1>
|
| 21 |
+
<div class="flex items-center gap-4">
|
| 22 |
+
<button id="voice-btn" class="p-2 rounded-full bg-white/10 hover:bg-white/20 transition-all border border-white/10 relative group">
|
| 23 |
+
<svg id="mic-icon-off" class="w-6 h-6 text-white/70" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M19.114 5.636a9 9 0 010 12.728M16.463 8.288a5.25 5.25 0 010 7.424M6.75 8.25l4.72-4.72a.75.75 0 011.28.53v15.88a.75.75 0 01-1.28.53l-4.72-4.72H4.51c-.88 0-1.704-.507-1.938-1.354A9.01 9.01 0 012.25 12c0-.83.112-1.633.322-2.396C2.806 8.756 3.63 8.25 4.51 8.25H6.75z" /></svg>
|
| 24 |
+
<svg id="mic-icon-on" class="w-6 h-6 hidden animate-pulse" fill="none" viewBox="0 0 24 24" stroke="#00f2ea" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M12 18.75a6 6 0 006-6v-1.5m-6 7.5a6 6 0 01-6-6v-1.5m6 7.5v3.75m-3.75 0h7.5M12 15.75a3 3 0 01-3-3V4.5a3 3 0 116 0v8.25a3 3 0 01-3 3z" /></svg>
|
| 25 |
+
</button>
|
| 26 |
+
<div id="mood-indicator" class="text-2xl transition-transform duration-500 hover:scale-110">✨</div>
|
| 27 |
+
</div>
|
| 28 |
+
</header>
|
| 29 |
+
<div id="chat-window" class="glass-panel flex-1 overflow-y-auto p-6 rounded-2xl mb-4 space-y-4 custom-scrollbar">
|
| 30 |
+
<div class="text-center text-white/50 text-sm mt-10">Добро пожаловать в Zenith. Эфир чист.</div>
|
| 31 |
+
</div>
|
| 32 |
+
<form id="message-form" class="glass-panel p-2 rounded-2xl flex items-center gap-2 relative">
|
| 33 |
+
<label class="cursor-pointer p-3 rounded-xl hover:bg-white/10 transition-all text-white/70 hover:text-white">
|
| 34 |
+
<input type="file" id="file-input" class="hidden">
|
| 35 |
+
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"><path stroke-linecap="round" stroke-linejoin="round" d="M18.375 12.739l-7.693 7.693a4.5 4.5 0 01-6.364-6.364l10.94-10.94A3 3 0 1119.5 7.372L8.552 18.32m.009-.01l-.01.01m5.699-9.941l-7.81 7.81a1.5 1.5 0 002.112 2.13" /></svg>
|
| 36 |
+
</label>
|
| 37 |
+
<div id="upload-status" class="absolute -top-8 left-4 text-xs bg-black/80 px-2 py-1 rounded hidden">Uploading...</div>
|
| 38 |
+
<input type="text" id="message-input" autocomplete="off" class="bg-transparent flex-1 p-3 outline-none text-white placeholder-white/50" placeholder="Транслируй свои мысли...">
|
| 39 |
+
<button type="submit" class="bg-white/10 hover:bg-white/20 transition-all text-white p-3 rounded-xl backdrop-blur-md border border-white/10">
|
| 40 |
+
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"><path stroke-linecap="round" stroke-linejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5" /></svg>
|
| 41 |
+
</button>
|
| 42 |
+
</form>
|
| 43 |
+
</div>
|
| 44 |
+
<audio id="pop-sound" src="/static/pop.mp3" preload="auto"></audio>
|
| 45 |
+
<script src="/static/script.js"></script>
|
| 46 |
+
</body>
|
| 47 |
+
</html>
|
static/pop.mp3
ADDED
|
File without changes
|
static/script.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
document.addEventListener('DOMContentLoaded', async () => {
|
| 2 |
+
let supabase;
|
| 3 |
+
let userId = 'user_' + Math.random().toString(36).substr(2, 9);
|
| 4 |
+
try {
|
| 5 |
+
const configRes = await fetch('/api/config');
|
| 6 |
+
const config = await configRes.json();
|
| 7 |
+
if (config.supabase_url) supabase = window.supabase.createClient(config.supabase_url, config.supabase_key);
|
| 8 |
+
} catch (e) { console.error("Config Error", e); }
|
| 9 |
+
const chatWindow = document.getElementById('chat-window');
|
| 10 |
+
const form = document.getElementById('message-form');
|
| 11 |
+
const input = document.getElementById('message-input');
|
| 12 |
+
const fileInput = document.getElementById('file-input');
|
| 13 |
+
const uploadStatus = document.getElementById('upload-status');
|
| 14 |
+
const moodIndicator = document.getElementById('mood-indicator');
|
| 15 |
+
const popSound = document.getElementById('pop-sound');
|
| 16 |
+
if (supabase) {
|
| 17 |
+
supabase.channel('room1').on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'messages' }, payload => {
|
| 18 |
+
renderMessage(payload.new);
|
| 19 |
+
playPopSound();
|
| 20 |
+
}).subscribe();
|
| 21 |
+
}
|
| 22 |
+
let currentAttachment = null;
|
| 23 |
+
fileInput.addEventListener('change', async (e) => {
|
| 24 |
+
const file = e.target.files[0];
|
| 25 |
+
if (!file) return;
|
| 26 |
+
uploadStatus.classList.remove('hidden');
|
| 27 |
+
uploadStatus.textContent = `Загрузка ${file.name}...`;
|
| 28 |
+
const formData = new FormData();
|
| 29 |
+
formData.append('file', file);
|
| 30 |
+
try {
|
| 31 |
+
const res = await fetch('/api/upload_file', { method: 'POST', body: formData });
|
| 32 |
+
const data = await res.json();
|
| 33 |
+
if (data.error) throw new Error(data.error);
|
| 34 |
+
currentAttachment = data;
|
| 35 |
+
uploadStatus.textContent = "Файл прикреплен!";
|
| 36 |
+
uploadStatus.style.color = "#00f2ea";
|
| 37 |
+
input.placeholder = `Прикреплен: ${file.name}. Напиши сообщение...`;
|
| 38 |
+
input.focus();
|
| 39 |
+
} catch (err) {
|
| 40 |
+
console.error(err);
|
| 41 |
+
uploadStatus.textContent = "Ошибка загрузки";
|
| 42 |
+
uploadStatus.style.color = "#ff0055";
|
| 43 |
+
}
|
| 44 |
+
});
|
| 45 |
+
form.addEventListener('submit', async (e) => {
|
| 46 |
+
e.preventDefault();
|
| 47 |
+
const text = input.value.trim();
|
| 48 |
+
if (!text && !currentAttachment) return;
|
| 49 |
+
input.value = '';
|
| 50 |
+
input.placeholder = "Транслируй свои мысли...";
|
| 51 |
+
uploadStatus.classList.add('hidden');
|
| 52 |
+
let moodData = { mood_color: '#ffffff', emoji: '🌫️' };
|
| 53 |
+
if (text) {
|
| 54 |
+
try {
|
| 55 |
+
const res = await fetch('/api/analyze_mood', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }) });
|
| 56 |
+
moodData = await res.json();
|
| 57 |
+
updateTheme(moodData.mood_color, moodData.emoji);
|
| 58 |
+
} catch (err) { console.error(err); }
|
| 59 |
+
}
|
| 60 |
+
if (supabase) {
|
| 61 |
+
const payload = { content: text, user_id: userId, mood_color: moodData.mood_color, attachment_url: currentAttachment ? currentAttachment.url : null, attachment_type: currentAttachment ? currentAttachment.mime : null };
|
| 62 |
+
const { error } = await supabase.from('messages').insert(payload);
|
| 63 |
+
if (error) console.error(error);
|
| 64 |
+
}
|
| 65 |
+
currentAttachment = null;
|
| 66 |
+
fileInput.value = '';
|
| 67 |
+
});
|
| 68 |
+
|
| 69 |
+
// Voice / WebRTC (Audio Only)
|
| 70 |
+
const voiceBtn = document.getElementById('voice-btn');
|
| 71 |
+
const micOff = document.getElementById('mic-icon-off');
|
| 72 |
+
const micOn = document.getElementById('mic-icon-on');
|
| 73 |
+
let localStream, remoteStream, peerConnection, audioContext, analyser, dataArray, ws, isVoiceActive = false;
|
| 74 |
+
const rtcConfig = { iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] };
|
| 75 |
+
voiceBtn.addEventListener('click', toggleVoiceMode);
|
| 76 |
+
async function toggleVoiceMode() { if (isVoiceActive) stopVoice(); else await startVoice(); }
|
| 77 |
+
async function startVoice() {
|
| 78 |
+
try {
|
| 79 |
+
localStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
|
| 80 |
+
setupAudioVisualizer(localStream);
|
| 81 |
+
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
| 82 |
+
ws = new WebSocket(`${protocol}//${window.location.host}/ws/signal`);
|
| 83 |
+
ws.onmessage = async (event) => {
|
| 84 |
+
const data = JSON.parse(event.data);
|
| 85 |
+
if (!peerConnection) createPeerConnection();
|
| 86 |
+
if (data.type === 'offer') {
|
| 87 |
+
await peerConnection.setRemoteDescription(new RTCSessionDescription(data));
|
| 88 |
+
const answer = await peerConnection.createAnswer();
|
| 89 |
+
await peerConnection.setLocalDescription(answer);
|
| 90 |
+
ws.send(JSON.stringify({ type: 'answer', sdp: answer.sdp }));
|
| 91 |
+
} else if (data.type === 'answer') { await peerConnection.setRemoteDescription(new RTCSessionDescription(data));
|
| 92 |
+
} else if (data.type === 'candidate') { if (data.candidate) await peerConnection.addIceCandidate(new RTCIceCandidate(data.candidate)); }
|
| 93 |
+
};
|
| 94 |
+
ws.onopen = () => { createPeerConnection(); createOffer(); };
|
| 95 |
+
micOff.classList.add('hidden'); micOn.classList.remove('hidden'); voiceBtn.classList.add('border-cyan-400', 'shadow-[0_0_15px_rgba(0,242,234,0.5)]'); isVoiceActive = true;
|
| 96 |
+
} catch (err) { console.error("Voice Error", err); alert("Microphone access denied"); }
|
| 97 |
+
}
|
| 98 |
+
function stopVoice() {
|
| 99 |
+
if (peerConnection) peerConnection.close();
|
| 100 |
+
if (localStream) localStream.getTracks().forEach(t => t.stop());
|
| 101 |
+
if (ws) ws.close();
|
| 102 |
+
peerConnection = null; localStream = null;
|
| 103 |
+
micOff.classList.remove('hidden'); micOn.classList.add('hidden'); voiceBtn.classList.remove('border-cyan-400', 'shadow-[0_0_15px_rgba(0,242,234,0.5)]'); isVoiceActive = false;
|
| 104 |
+
}
|
| 105 |
+
function createPeerConnection() {
|
| 106 |
+
peerConnection = new RTCPeerConnection(rtcConfig);
|
| 107 |
+
localStream.getTracks().forEach(track => peerConnection.addTrack(track, localStream));
|
| 108 |
+
peerConnection.ontrack = (event) => { const remoteAudio = new Audio(); remoteAudio.srcObject = event.streams[0]; remoteAudio.autoplay = true; };
|
| 109 |
+
peerConnection.onicecandidate = (event) => { if (event.candidate) ws.send(JSON.stringify({ type: 'candidate', candidate: event.candidate })); };
|
| 110 |
+
}
|
| 111 |
+
async function createOffer() { const offer = await peerConnection.createOffer(); await peerConnection.setLocalDescription(offer); ws.send(JSON.stringify({ type: 'offer', sdp: offer.sdp })); }
|
| 112 |
+
function setupAudioVisualizer(stream) {
|
| 113 |
+
if (!audioContext) audioContext = new (window.AudioContext || window.webkitAudioContext)();
|
| 114 |
+
const source = audioContext.createMediaStreamSource(stream);
|
| 115 |
+
analyser = audioContext.createAnalyser();
|
| 116 |
+
analyser.fftSize = 64;
|
| 117 |
+
source.connect(analyser);
|
| 118 |
+
dataArray = new Uint8Array(analyser.frequencyBinCount);
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
function renderMessage(msg) {
|
| 122 |
+
const div = document.createElement('div');
|
| 123 |
+
const isOwn = msg.user_id === userId;
|
| 124 |
+
div.className = `message ${isOwn ? 'own' : 'other'}`;
|
| 125 |
+
div.style.boxShadow = `0 0 15px ${msg.mood_color || '#fff'}40`;
|
| 126 |
+
let html = `<div>${msg.content || ''}</div>`;
|
| 127 |
+
if (msg.attachment_url) {
|
| 128 |
+
if (msg.attachment_type && msg.attachment_type.startsWith('image/')) { html += `<img src="${msg.attachment_url}" alt="Image">`; }
|
| 129 |
+
else { html += `<a href="${msg.attachment_url}" target="_blank" class="file-link">📎 Скачать файл</a>`; }
|
| 130 |
+
}
|
| 131 |
+
div.innerHTML = html;
|
| 132 |
+
chatWindow.appendChild(div);
|
| 133 |
+
chatWindow.scrollTop = chatWindow.scrollHeight;
|
| 134 |
+
}
|
| 135 |
+
function updateTheme(color, emoji) {
|
| 136 |
+
document.documentElement.style.setProperty('--dynamic-bg-color', color);
|
| 137 |
+
moodIndicator.textContent = emoji;
|
| 138 |
+
}
|
| 139 |
+
function playPopSound() { if(popSound) { popSound.currentTime = 0; popSound.play().catch(e=>{}); } }
|
| 140 |
+
|
| 141 |
+
// --- Visuals ---
|
| 142 |
+
const canvas = document.getElementById('particle-canvas');
|
| 143 |
+
const ctx = canvas.getContext('2d');
|
| 144 |
+
let particles = [];
|
| 145 |
+
function resize() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; }
|
| 146 |
+
window.addEventListener('resize', resize); resize();
|
| 147 |
+
class Particle {
|
| 148 |
+
constructor() { this.reset(); }
|
| 149 |
+
reset() { this.x = Math.random() * canvas.width; this.y = Math.random() * canvas.height; this.size = Math.random() * 2; this.speedX = Math.random() * 0.5 - 0.25; this.speedY = Math.random() * 0.5 - 0.25; this.opacity = Math.random() * 0.5; }
|
| 150 |
+
update() { this.x += this.speedX; this.y += this.speedY; if(this.x<0 || this.x>canvas.width) this.speedX*=-1; if(this.y<0 || this.y>canvas.height) this.speedY*=-1; }
|
| 151 |
+
draw() { ctx.fillStyle = `rgba(255,255,255,${this.opacity})`; ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, Math.PI*2); ctx.fill(); }
|
| 152 |
+
}
|
| 153 |
+
for(let i=0; i<50; i++) particles.push(new Particle());
|
| 154 |
+
function animate() {
|
| 155 |
+
ctx.clearRect(0,0,canvas.width,canvas.height);
|
| 156 |
+
let audioFactor = 0;
|
| 157 |
+
if (isVoiceActive && analyser && dataArray) {
|
| 158 |
+
analyser.getByteFrequencyData(dataArray);
|
| 159 |
+
audioFactor = (dataArray.reduce((a, b) => a + b) / dataArray.length) / 50;
|
| 160 |
+
}
|
| 161 |
+
particles.forEach(p => {
|
| 162 |
+
if(isVoiceActive) {
|
| 163 |
+
p.x += p.speedX * (1+audioFactor); p.y += p.speedY * (1+audioFactor);
|
| 164 |
+
let ps = p.size + (audioFactor*2);
|
| 165 |
+
ctx.fillStyle = `rgba(255,255,255,${p.opacity})`; ctx.beginPath(); ctx.arc(p.x, p.y, ps>0?ps:0, 0, Math.PI*2); ctx.fill();
|
| 166 |
+
} else { p.update(); p.draw(); }
|
| 167 |
+
if(p.x<0 || p.x>canvas.width) p.speedX*=-1; if(p.y<0 || p.y>canvas.height) p.speedY*=-1;
|
| 168 |
+
});
|
| 169 |
+
requestAnimationFrame(animate);
|
| 170 |
+
}
|
| 171 |
+
animate();
|
| 172 |
+
});
|
static/styles.css
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
:root { --dynamic-bg-color: #4facfe; --glass-border: rgba(255, 255, 255, 0.1); --glass-bg: rgba(255, 255, 255, 0.05); }
|
| 2 |
+
body { background: #0f0c29; font-family: 'Inter', sans-serif; transition: background 1s ease; }
|
| 3 |
+
.background-container { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 0; overflow: hidden; filter: blur(80px); }
|
| 4 |
+
.blob { position: absolute; border-radius: 50%; opacity: 0.6; animation: float 10s infinite ease-in-out; }
|
| 5 |
+
.blob-1 { width: 500px; height: 500px; background: var(--dynamic-bg-color); top: -100px; left: -100px; transition: background 1s ease; }
|
| 6 |
+
.blob-2 { width: 400px; height: 400px; background: #764ba2; bottom: -50px; right: -50px; animation-delay: 2s; }
|
| 7 |
+
.blob-3 { width: 300px; height: 300px; background: #00f2ea; top: 40%; left: 40%; animation-delay: 4s; }
|
| 8 |
+
@keyframes float { 0% { transform: translate(0, 0) scale(1); } 33% { transform: translate(30px, -50px) scale(1.1); } 66% { transform: translate(-20px, 20px) scale(0.9); } 100% { transform: translate(0, 0) scale(1); } }
|
| 9 |
+
#particle-canvas { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 1; pointer-events: none; }
|
| 10 |
+
.glass-panel { background: var(--glass-bg); backdrop-filter: blur(16px); border: 1px solid var(--glass-border); box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1); }
|
| 11 |
+
.message { padding: 10px 16px; border-radius: 12px; max-width: 80%; animation: popIn 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); position: relative; word-break: break-word; }
|
| 12 |
+
.message img { max-width: 100%; border-radius: 8px; margin-top: 5px; border: 1px solid rgba(255,255,255,0.2); }
|
| 13 |
+
.message a.file-link { display: block; margin-top: 5px; color: #00f2ea; text-decoration: underline; font-size: 0.9em; }
|
| 14 |
+
.message.own { background: linear-gradient(135deg, rgba(255,255,255,0.2), rgba(255,255,255,0.05)); align-self: flex-end; margin-left: auto; border: 1px solid rgba(255,255,255,0.2); }
|
| 15 |
+
.message.other { background: rgba(0, 0, 0, 0.2); align-self: flex-start; margin-right: auto; border: 1px solid rgba(255,255,255,0.05); }
|
| 16 |
+
@keyframes popIn { 0% { opacity: 0; transform: scale(0.8) translateY(10px); } 100% { opacity: 1; transform: scale(1) translateY(0); } }
|
| 17 |
+
.custom-scrollbar::-webkit-scrollbar { width: 6px; }
|
| 18 |
+
.custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 3px; }
|