Monteeq CI commited on
Commit
0eeeed2
Β·
1 Parent(s): 91bc8a2

πŸš€ Deploy from GitHub @ d68e85c218a2e847f727d1a8b36d05cd81b68b1a

Browse files

Triggered by: Smasduq
Message: fix(backend): import Session in seo endpoint and use .venv in dev scripts

.env.example ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Required
2
+ DATABASE_URL=postgresql://user:password@host:5432/dbname
3
+ SECRET_KEY=your-secret-key-here
4
+ REDIS_URL=rediss://default:password@redis.example.com:443
5
+
6
+ # Gemini API (editing feedback)
7
+ GEMINI_API_KEY=your-gemini-api-key
8
+
9
+ # AWS / S3
10
+ AWS_ACCESS_KEY_ID=
11
+ AWS_SECRET_ACCESS_KEY=
12
+ AWS_STORAGE_BUCKET_NAME=monteeq
13
+ AWS_S3_REGION_NAME=eu-central-1
14
+ AWS_CLOUDFRONT_DOMAIN=cdn.example.com
15
+ STORAGE_MODE=s3
16
+
17
+ # Auth
18
+ GOOGLE_CLIENT_ID=
19
+ JWT_ALGORITHM=HS256
20
+ ACCESS_TOKEN_EXPIRE_MINUTES=43200
21
+
22
+ # URLs
23
+ BASE_URL=http://localhost:8000
24
+ FRONTEND_URL=http://localhost:3000
25
+ RUST_SERVICE_URL=http://127.0.0.1:7860
26
+
27
+ # CORS
28
+ CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173
29
+
30
+ # Email
31
+ SMTP_HOST=smtp.example.com
32
+ SMTP_PORT=587
33
+ SMTP_USER=
34
+ SMTP_PASS=
35
+ SMTP_FROM=noreply@example.com
36
+ SMTP_FROM_NAME=Monteeq
37
+
38
+ # Payment
39
+ PAYSTACK_SECRET_KEY=
40
+ STRIPE_SECRET_KEY=
41
+ STRIPE_WEBHOOK_SECRET=
42
+
43
+ # Push notifications
44
+ VAPID_PUBLIC_KEY=
45
+ VAPID_PRIVATE_KEY=
46
+ VAPID_EMAIL=hello@example.com
alembic/versions/08a64feff54a_merge_media_analysis_and_previous_heads.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """merge_media_analysis_and_previous_heads
2
+
3
+ Revision ID: 08a64feff54a
4
+ Revises: a1b2c3d4e5f6, d3a4b5c6e7f8
5
+ Create Date: 2026-07-28 14:17:18.366617
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+ import sqlalchemy as sa
12
+
13
+
14
+ # revision identifiers, used by Alembic.
15
+ revision: str = '08a64feff54a'
16
+ down_revision: Union[str, Sequence[str], None] = ('a1b2c3d4e5f6', 'd3a4b5c6e7f8')
17
+ branch_labels: Union[str, Sequence[str], None] = None
18
+ depends_on: Union[str, Sequence[str], None] = None
19
+
20
+
21
+ def upgrade() -> None:
22
+ """Upgrade schema."""
23
+ pass
24
+
25
+
26
+ def downgrade() -> None:
27
+ """Downgrade schema."""
28
+ pass
alembic/versions/a1b2c3d4e5f6_add_media_analysis_table.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Add media_analysis table with pgvector embedding
2
+
3
+ Revision ID: a1b2c3d4e5f6
4
+ Revises: e8a1b2c3d4f5
5
+ Create Date: 2026-07-28 00:00:00.000000
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+ import sqlalchemy as sa
12
+ from sqlalchemy.dialects import postgresql
13
+
14
+ revision: str = 'a1b2c3d4e5f6'
15
+ down_revision: Union[str, Sequence[str], None] = 'e8a1b2c3d4f5'
16
+ branch_labels: Union[str, Sequence[str], None] = None
17
+ depends_on: Union[str, Sequence[str], None] = None
18
+
19
+
20
+ def upgrade() -> None:
21
+ op.execute("CREATE EXTENSION IF NOT EXISTS vector")
22
+
23
+ op.create_table(
24
+ 'media_analysis',
25
+ sa.Column('id', sa.Integer(), primary_key=True, autoincrement=True),
26
+ sa.Column('video_id', sa.Integer(), sa.ForeignKey('videos.id', ondelete='CASCADE'), nullable=False, unique=True),
27
+ sa.Column('status', sa.Text(), nullable=False, server_default='pending'),
28
+ sa.Column('frame_sample_paths', postgresql.JSONB(), nullable=True),
29
+ sa.Column('scene_cuts', postgresql.JSONB(), nullable=True),
30
+ sa.Column('beat_timestamps', postgresql.JSONB(), nullable=True),
31
+ sa.Column('caption_embedding', postgresql.dialects.postgresql.VECTOR(384), nullable=True),
32
+ sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.func.now()),
33
+ sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.func.now(), onupdate=sa.func.now()),
34
+ )
35
+ op.create_index('ix_media_analysis_video_id', 'media_analysis', ['video_id'])
36
+ op.create_index('ix_media_analysis_status', 'media_analysis', ['status'])
37
+
38
+
39
+ def downgrade() -> None:
40
+ op.drop_index('ix_media_analysis_status', table_name='media_analysis')
41
+ op.drop_index('ix_media_analysis_video_id', table_name='media_analysis')
42
+ op.drop_table('media_analysis')
alembic/versions/b7e2f4a1c8d3_add_visual_embedding_to_media_analysis.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Add visual_embedding vector(512) column + ivfflat index to media_analysis.
2
+
3
+ Uses CLIP ViT-B/32 (output dim = 512).
4
+
5
+ Revision ID: b7e2f4a1c8d3
6
+ Revises: fe9cdefede17
7
+ Create Date: 2026-07-28 00:00:00.000000
8
+ """
9
+ from typing import Sequence, Union
10
+
11
+ from alembic import op
12
+
13
+ revision: str = "b7e2f4a1c8d3"
14
+ down_revision: Union[str, Sequence[str], None] = "fe9cdefede17"
15
+ branch_labels: Union[str, Sequence[str], None] = None
16
+ depends_on: Union[str, Sequence[str], None] = None
17
+
18
+
19
+ def upgrade() -> None:
20
+ # Add the visual_embedding column (CLIP ViT-B/32 β†’ 512 dims)
21
+ op.execute(
22
+ "ALTER TABLE media_analysis "
23
+ "ADD COLUMN IF NOT EXISTS visual_embedding vector(512)"
24
+ )
25
+
26
+ # ivfflat index β€” skip if fewer than 10 rows (ivfflat requires lists <= rows)
27
+ op.execute(
28
+ """
29
+ DO $$
30
+ DECLARE
31
+ row_count integer;
32
+ BEGIN
33
+ SELECT count(*) INTO row_count FROM media_analysis;
34
+ IF row_count >= 10 THEN
35
+ CREATE INDEX IF NOT EXISTS ix_media_analysis_visual_embedding
36
+ ON media_analysis
37
+ USING ivfflat (visual_embedding vector_cosine_ops)
38
+ WITH (lists = 10);
39
+ END IF;
40
+ END$$;
41
+ """
42
+ )
43
+
44
+
45
+ def downgrade() -> None:
46
+ op.execute("DROP INDEX IF EXISTS ix_media_analysis_visual_embedding")
47
+ op.execute("ALTER TABLE media_analysis DROP COLUMN IF EXISTS visual_embedding")
alembic/versions/d1e2f3a4b5c6_add_edit_feedback_table.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Add edit_feedback table for AI editing critique history.
2
+
3
+ Revision ID: d1e2f3a4b5c6
4
+ Revises: b7e2f4a1c8d3
5
+ Create Date: 2026-07-30 12:00:00.000000
6
+ """
7
+ from typing import Sequence, Union
8
+
9
+ from alembic import op
10
+ import sqlalchemy as sa
11
+ from sqlalchemy.dialects.postgresql import JSONB
12
+
13
+ # revision identifiers, used by Alembic.
14
+ revision: str = "d1e2f3a4b5c6"
15
+ down_revision: Union[str, None] = "b7e2f4a1c8d3"
16
+ branch_labels: Union[str, Sequence[str], None] = None
17
+ depends_on: Union[str, Sequence[str], None] = None
18
+
19
+
20
+ def upgrade() -> None:
21
+ op.create_table(
22
+ "edit_feedback",
23
+ sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
24
+ sa.Column("video_id", sa.Integer(), sa.ForeignKey("videos.id", ondelete="CASCADE"), nullable=False),
25
+ sa.Column("feedback_text", sa.Text(), nullable=False),
26
+ sa.Column("metrics_snapshot", JSONB(), nullable=False),
27
+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
28
+ sa.PrimaryKeyConstraint("id"),
29
+ )
30
+ op.create_index(op.f("ix_edit_feedback_video_id"), "edit_feedback", ["video_id"])
31
+
32
+
33
+ def downgrade() -> None:
34
+ op.drop_index(op.f("ix_edit_feedback_video_id"), table_name="edit_feedback")
35
+ op.drop_table("edit_feedback")
alembic/versions/d3a4b5c6e7f8_merge_cover_and_video_type.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """merge cover_fields_to_videos and video_type_to_upload_jobs
2
+
3
+ Revision ID: d3a4b5c6e7f8
4
+ Revises: c5e8f0b2d4a1, c1d2e3f4a5b6
5
+ Create Date: 2026-07-22 22:00:00.000000
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+ import sqlalchemy as sa
12
+
13
+
14
+ # revision identifiers, used by Alembic.
15
+ revision: str = "d3a4b5c6e7f8"
16
+ down_revision: Union[str, Sequence[str], None] = ("c5e8f0b2d4a1", "c1d2e3f4a5b6")
17
+ branch_labels: Union[str, Sequence[str], None] = None
18
+ depends_on: Union[str, Sequence[str], None] = None
19
+
20
+
21
+ def upgrade() -> None:
22
+ pass
23
+
24
+
25
+ def downgrade() -> None:
26
+ pass
alembic/versions/e8a1b2c3d4f5_add_video_events_table.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Add video_events table for engagement tracking
2
+
3
+ Revision ID: e8a1b2c3d4f5
4
+ Revises: 7acd76e1bfde
5
+ Create Date: 2026-07-27 00:00:00.000000
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+ import sqlalchemy as sa
12
+
13
+
14
+ # revision identifiers, used by Alembic.
15
+ revision: str = 'e8a1b2c3d4f5'
16
+ down_revision: Union[str, Sequence[str], None] = '7acd76e1bfde'
17
+ branch_labels: Union[str, Sequence[str], None] = None
18
+ depends_on: Union[str, Sequence[str], None] = None
19
+
20
+
21
+ def upgrade() -> None:
22
+ op.create_table(
23
+ 'video_events',
24
+ sa.Column('id', sa.BigInteger(), primary_key=True, autoincrement=True),
25
+ sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id', ondelete='CASCADE'), nullable=False),
26
+ sa.Column('video_id', sa.Integer(), sa.ForeignKey('videos.id', ondelete='CASCADE'), nullable=False),
27
+ sa.Column('event_type', sa.Text(), nullable=False),
28
+ sa.Column('watch_seconds', sa.Integer(), nullable=True),
29
+ sa.Column('session_id', sa.Text(), nullable=True),
30
+ sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.func.now()),
31
+ )
32
+ op.create_index('ix_video_events_user_created', 'video_events', ['user_id', 'created_at'])
33
+ op.create_index('ix_video_events_video_event', 'video_events', ['video_id', 'event_type'])
34
+ op.create_index('ix_video_events_video_created', 'video_events', ['video_id', 'created_at'])
35
+
36
+
37
+ def downgrade() -> None:
38
+ op.drop_index('ix_video_events_video_created', table_name='video_events')
39
+ op.drop_index('ix_video_events_video_event', table_name='video_events')
40
+ op.drop_index('ix_video_events_user_created', table_name='video_events')
41
+ op.drop_table('video_events')
alembic/versions/fe9cdefede17_add_ivfflat_index_on_caption_embedding.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Add ivfflat index on media_analysis.caption_embedding for fast cosine similarity.
2
+
3
+ Revision ID: fe9cdefede17
4
+ Revises: 08a64feff54a
5
+ Create Date: 2026-07-28 00:00:00.000000
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+
12
+ revision: str = "fe9cdefede17"
13
+ down_revision: Union[str, Sequence[str], None] = "08a64feff54a"
14
+ branch_labels: Union[str, Sequence[str], None] = None
15
+ depends_on: Union[str, Sequence[str], None] = None
16
+
17
+
18
+ def upgrade() -> None:
19
+ # ivfflat requires at least `lists` rows in the table.
20
+ # If fewer rows exist, skip index creation β€” it can be added later when
21
+ # enough data accumulates. Use lists=10 as a safe starting point.
22
+ op.execute(
23
+ """
24
+ DO $$
25
+ DECLARE
26
+ row_count integer;
27
+ BEGIN
28
+ SELECT count(*) INTO row_count FROM media_analysis;
29
+ IF row_count >= 10 THEN
30
+ CREATE INDEX IF NOT EXISTS ix_media_analysis_caption_embedding
31
+ ON media_analysis
32
+ USING ivfflat (caption_embedding vector_cosine_ops)
33
+ WITH (lists = 10);
34
+ END IF;
35
+ END$$;
36
+ """
37
+ )
38
+
39
+
40
+ def downgrade() -> None:
41
+ op.execute(
42
+ "DROP INDEX IF EXISTS ix_media_analysis_caption_embedding"
43
+ )
app/api/v1/api.py CHANGED
@@ -1,5 +1,5 @@
1
  from fastapi import APIRouter
2
- from app.api.v1.endpoints import auth, videos, admin, users, posts, achievements, notifications, ads, chat, challenges, monetization, video_views, seo, recommendations, partners, categories, library, history, watch_later, liked, following, metrics, email, reports, comments
3
 
4
 
5
  api_router = APIRouter()
@@ -28,6 +28,7 @@ api_router.include_router(metrics.router, prefix="/metrics", tags=["metrics"])
28
  api_router.include_router(email.router, prefix="/email", tags=["email"])
29
  api_router.include_router(reports.router, prefix="/reports", tags=["reports"])
30
  api_router.include_router(comments.router, prefix="/comments", tags=["comments"])
 
31
 
32
 
33
 
 
1
  from fastapi import APIRouter
2
+ from app.api.v1.endpoints import auth, videos, admin, users, posts, achievements, notifications, ads, chat, challenges, monetization, video_views, seo, recommendations, partners, categories, library, history, watch_later, liked, following, metrics, email, reports, comments, events
3
 
4
 
5
  api_router = APIRouter()
 
28
  api_router.include_router(email.router, prefix="/email", tags=["email"])
29
  api_router.include_router(reports.router, prefix="/reports", tags=["reports"])
30
  api_router.include_router(comments.router, prefix="/comments", tags=["comments"])
31
+ api_router.include_router(events.router, prefix="/events", tags=["events"])
32
 
33
 
34
 
app/api/v1/endpoints/chat.py CHANGED
@@ -316,7 +316,7 @@ def acknowledge_messages(
316
  current_user: User = Depends(get_current_user)
317
  ):
318
  if not message_ids:
319
- return {"status": "ok", "deleted": 0}
320
 
321
  # Find conversations the user belongs to
322
  user_conv_ids = [
@@ -325,14 +325,13 @@ def acknowledge_messages(
325
  ).all()
326
  ]
327
 
328
- # Perform bulk delete on matching messages, bypassing session state sync warnings
329
- deleted_count = db.query(ChatMessage).filter(
330
  ChatMessage.id.in_(message_ids),
331
  ChatMessage.conversation_id.in_(user_conv_ids)
332
- ).delete(synchronize_session=False)
333
 
334
- db.commit()
335
- return {"status": "ok", "deleted": deleted_count}
336
 
337
  @router.post("/upload", response_model=schemas.AttachmentResponse)
338
  def upload_attachment(
 
316
  current_user: User = Depends(get_current_user)
317
  ):
318
  if not message_ids:
319
+ return {"status": "ok", "acknowledged": 0, "deleted": 0}
320
 
321
  # Find conversations the user belongs to
322
  user_conv_ids = [
 
325
  ).all()
326
  ]
327
 
328
+ # Count matching messages for the current user's conversations without deleting them from the database
329
+ ack_count = db.query(ChatMessage).filter(
330
  ChatMessage.id.in_(message_ids),
331
  ChatMessage.conversation_id.in_(user_conv_ids)
332
+ ).count()
333
 
334
+ return {"status": "ok", "acknowledged": ack_count, "deleted": 0}
 
335
 
336
  @router.post("/upload", response_model=schemas.AttachmentResponse)
337
  def upload_attachment(
app/api/v1/endpoints/events.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ from typing import List, Union
4
+
5
+ from fastapi import APIRouter, Response
6
+ from app.schemas.video_events import VideoEventIn, VideoEventBatch
7
+ from app.core.redis import redis_client
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ router = APIRouter()
12
+
13
+ PENDING_KEY = "video_events:pending"
14
+
15
+
16
+ @router.post("/video", status_code=202)
17
+ def ingest_video_events(payload: Union[VideoEventBatch, List[VideoEventIn]]):
18
+ """Accept one or a batch of video engagement events and push to Redis for async processing."""
19
+ events = payload.events if isinstance(payload, VideoEventBatch) else payload
20
+
21
+ if not events:
22
+ return Response(status_code=202)
23
+
24
+ pipe = redis_client.pipeline()
25
+ for ev in events:
26
+ pipe.rpush(
27
+ PENDING_KEY,
28
+ json.dumps({
29
+ "user_id": ev.user_id,
30
+ "video_id": ev.video_id,
31
+ "event_type": ev.event_type.value,
32
+ "watch_seconds": ev.watch_seconds,
33
+ "session_id": ev.session_id,
34
+ }),
35
+ )
36
+ pipe.execute()
37
+
38
+ logger.debug("Enqueued %d video events to Redis", len(events))
39
+ return Response(status_code=202)
app/api/v1/endpoints/seo.py CHANGED
@@ -1,16 +1,31 @@
1
- from fastapi import APIRouter, Depends, Response
2
- from sqlalchemy.orm import Session
3
  from sqlalchemy import text
 
4
  from app.db.session import get_db
5
  from app.core import config
6
  from app.core.storage import storage
 
 
7
  import xml.etree.ElementTree as ET
8
- from datetime import datetime
9
 
10
  router = APIRouter()
11
 
12
  BASE_URL = config.FRONTEND_URL.rstrip('/')
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  def _resolve_url(url):
16
  """Inline CDN resolver β€” avoids loading the full Video ORM (which may have columns not yet migrated)."""
@@ -24,20 +39,21 @@ def _resolve_url(url):
24
  return url
25
 
26
 
27
- _VIDEOS_SQL = text("""
28
- SELECT id, title, description, video_url, thumbnail_url, tags,
29
- duration, created_at, owner_id, status
30
- FROM videos
31
- WHERE status = :status
32
- """)
 
 
33
 
34
 
35
  @router.get("/sitemap.xml")
36
  async def get_sitemap(db: Session = Depends(get_db)):
37
  """Generates a standard XML sitemap for general pages + video watch pages."""
38
- urlset = ET.Element("urlset", xmlns="http://www.sitemaps.org/schemas/sitemap/0.9")
39
 
40
- # Static Public Pages
41
  pages = [
42
  {"path": "", "priority": "1.0"},
43
  {"path": "/home", "priority": "0.9"},
@@ -54,7 +70,6 @@ async def get_sitemap(db: Session = Depends(get_db)):
54
  ET.SubElement(url_el, "changefreq").text = "daily"
55
  ET.SubElement(url_el, "priority").text = page["priority"]
56
 
57
- # Dynamic Video Pages β€” raw SQL to avoid ORM column-mismatch crashes
58
  rows = db.execute(_VIDEOS_SQL, {"status": "approved"}).fetchall()
59
  for row in rows:
60
  if not row.created_at:
@@ -65,18 +80,13 @@ async def get_sitemap(db: Session = Depends(get_db)):
65
  ET.SubElement(url_el, "changefreq").text = "weekly"
66
  ET.SubElement(url_el, "priority").text = "0.6"
67
 
68
- xml_data = b'<?xml version="1.0" encoding="UTF-8"?>\n' + ET.tostring(urlset, encoding="utf-8", method="xml")
69
- return Response(content=xml_data, media_type="application/xml")
70
 
71
 
72
  @router.get("/video-sitemap.xml")
73
  async def get_video_sitemap(db: Session = Depends(get_db)):
74
  """Generates a Google Video Sitemap for video indexing."""
75
- urlset = ET.Element("urlset", {
76
- "xmlns": "http://www.sitemaps.org/schemas/sitemap/0.9",
77
- "xmlns:video": "http://www.google.com/schemas/sitemap-video/1.1",
78
- })
79
- video_ns = "{http://www.google.com/schemas/sitemap-video/1.1}"
80
 
81
  rows = db.execute(_VIDEOS_SQL, {"status": "approved"}).fetchall()
82
 
@@ -91,28 +101,106 @@ async def get_video_sitemap(db: Session = Depends(get_db)):
91
  url_el = ET.SubElement(urlset, "url")
92
  ET.SubElement(url_el, "loc").text = f"{BASE_URL}/watch/{row.id}"
93
 
94
- video_el = ET.SubElement(url_el, f"{video_ns}video")
95
- ET.SubElement(video_el, f"{video_ns}thumbnail_loc").text = thumbnail
96
- ET.SubElement(video_el, f"{video_ns}title").text = row.title or ""
97
- ET.SubElement(video_el, f"{video_ns}description").text = (
98
  row.description or f"Watch {row.title} on Monteeq."
99
  )
100
- # player_loc: Google crawls this page which embeds the HLS player
101
- ET.SubElement(video_el, f"{video_ns}player_loc").text = f"{BASE_URL}/watch/{row.id}"
102
 
103
- # Duration β€” Google requires HH:MM:SS
104
  dur = int(row.duration or 0)
105
  hours, remainder = divmod(dur, 3600)
106
  minutes, seconds = divmod(remainder, 60)
107
- ET.SubElement(video_el, f"{video_ns}duration").text = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
108
 
109
  pub_date = row.created_at.strftime("%Y-%m-%d")
110
- ET.SubElement(video_el, f"{video_ns}publication_date").text = pub_date
111
 
112
- # Tags (comma-separated in DB)
113
  if row.tags:
114
  for tag in [t.strip() for t in row.tags.split(",") if t.strip()][:32]:
115
- ET.SubElement(video_el, f"{video_ns}tag").text = tag
116
 
117
- xml_data = b'<?xml version="1.0" encoding="UTF-8"?>\n' + ET.tostring(urlset, encoding="utf-8", method="xml")
118
- return Response(content=xml_data, media_type="application/xml")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends, Response, Query, HTTPException
2
+ from fastapi.responses import JSONResponse
3
  from sqlalchemy import text
4
+ from sqlalchemy.orm import Session
5
  from app.db.session import get_db
6
  from app.core import config
7
  from app.core.storage import storage
8
+ import re
9
+ import json
10
  import xml.etree.ElementTree as ET
 
11
 
12
  router = APIRouter()
13
 
14
  BASE_URL = config.FRONTEND_URL.rstrip('/')
15
 
16
+ # Register namespace prefixes so ET serialises them correctly
17
+ _NS_SITEMAP = 'http://www.sitemaps.org/schemas/sitemap/0.9'
18
+ _NS_VIDEO = 'http://www.google.com/schemas/sitemap-video/1.1'
19
+ ET.register_namespace('', _NS_SITEMAP)
20
+ ET.register_namespace('video', _NS_VIDEO)
21
+
22
+ _VIDEOS_SQL = text("""
23
+ SELECT id, title, description, video_url, thumbnail_url, tags,
24
+ duration, created_at, owner_id, status
25
+ FROM videos
26
+ WHERE status = :status
27
+ """)
28
+
29
 
30
  def _resolve_url(url):
31
  """Inline CDN resolver β€” avoids loading the full Video ORM (which may have columns not yet migrated)."""
 
39
  return url
40
 
41
 
42
+ def _to_xml(root):
43
+ """Serialize an ElementTree root to bytes with XML declaration."""
44
+ return ET.tostring(root, encoding='unicode', xml_declaration=True).encode('utf-8')
45
+
46
+
47
+ def _video_el(tag):
48
+ """Build a Clark-notation tag name in the video namespace."""
49
+ return f'{{{_NS_VIDEO}}}{tag}'
50
 
51
 
52
  @router.get("/sitemap.xml")
53
  async def get_sitemap(db: Session = Depends(get_db)):
54
  """Generates a standard XML sitemap for general pages + video watch pages."""
55
+ urlset = ET.Element("urlset")
56
 
 
57
  pages = [
58
  {"path": "", "priority": "1.0"},
59
  {"path": "/home", "priority": "0.9"},
 
70
  ET.SubElement(url_el, "changefreq").text = "daily"
71
  ET.SubElement(url_el, "priority").text = page["priority"]
72
 
 
73
  rows = db.execute(_VIDEOS_SQL, {"status": "approved"}).fetchall()
74
  for row in rows:
75
  if not row.created_at:
 
80
  ET.SubElement(url_el, "changefreq").text = "weekly"
81
  ET.SubElement(url_el, "priority").text = "0.6"
82
 
83
+ return Response(content=_to_xml(urlset), media_type="application/xml")
 
84
 
85
 
86
  @router.get("/video-sitemap.xml")
87
  async def get_video_sitemap(db: Session = Depends(get_db)):
88
  """Generates a Google Video Sitemap for video indexing."""
89
+ urlset = ET.Element("urlset")
 
 
 
 
90
 
91
  rows = db.execute(_VIDEOS_SQL, {"status": "approved"}).fetchall()
92
 
 
101
  url_el = ET.SubElement(urlset, "url")
102
  ET.SubElement(url_el, "loc").text = f"{BASE_URL}/watch/{row.id}"
103
 
104
+ video_el = ET.SubElement(url_el, _video_el("video"))
105
+ ET.SubElement(video_el, _video_el("thumbnail_loc")).text = thumbnail
106
+ ET.SubElement(video_el, _video_el("title")).text = row.title or ""
107
+ ET.SubElement(video_el, _video_el("description")).text = (
108
  row.description or f"Watch {row.title} on Monteeq."
109
  )
110
+ ET.SubElement(video_el, _video_el("player_loc")).text = f"{BASE_URL}/watch/{row.id}"
 
111
 
 
112
  dur = int(row.duration or 0)
113
  hours, remainder = divmod(dur, 3600)
114
  minutes, seconds = divmod(remainder, 60)
115
+ ET.SubElement(video_el, _video_el("duration")).text = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
116
 
117
  pub_date = row.created_at.strftime("%Y-%m-%d")
118
+ ET.SubElement(video_el, _video_el("publication_date")).text = pub_date
119
 
 
120
  if row.tags:
121
  for tag in [t.strip() for t in row.tags.split(",") if t.strip()][:32]:
122
+ ET.SubElement(video_el, _video_el("tag")).text = tag
123
 
124
+ return Response(content=_to_xml(urlset), media_type="application/xml")
125
+
126
+
127
+ _VIDEO_BY_ID_SQL = text("""
128
+ SELECT v.id, v.title, v.description, v.thumbnail_url, v.duration,
129
+ v.created_at, v.status,
130
+ u.username, u.profile_pic
131
+ FROM videos v
132
+ LEFT JOIN users u ON v.owner_id = u.id
133
+ WHERE v.id = :vid OR v.public_id = :pub_id
134
+ LIMIT 1
135
+ """)
136
+
137
+
138
+ def _parse_video_id(url: str):
139
+ """Extract the video ID from a Monteeq watch URL."""
140
+ patterns = [
141
+ r'/watch/(\d+)',
142
+ r'/watch/([a-zA-Z0-9_-]+)',
143
+ r'/embed/(\d+)',
144
+ r'/embed/([a-zA-Z0-9_-]+)',
145
+ ]
146
+ for pat in patterns:
147
+ m = re.search(pat, url)
148
+ if m:
149
+ return m.group(1)
150
+ return None
151
+
152
+
153
+ @router.get("/oembed")
154
+ def oembed(
155
+ url: str = Query(..., description="URL of the video"),
156
+ format: str = Query("json", description="Response format: json or xml"),
157
+ maxwidth: int = Query(None, description="Maximum width"),
158
+ maxheight: int = Query(None, description="Maximum height"),
159
+ db: Session = Depends(get_db),
160
+ ):
161
+ video_id = _parse_video_id(url)
162
+ if not video_id:
163
+ raise HTTPException(status_code=400, detail="Invalid video URL")
164
+
165
+ vid_int = int(video_id) if video_id.isdigit() else None
166
+ row = db.execute(_VIDEO_BY_ID_SQL, {"vid": vid_int, "pub_id": video_id}).fetchone()
167
+ if not row:
168
+ raise HTTPException(status_code=404, detail="Video not found")
169
+
170
+ width = maxwidth or 640
171
+ height = maxheight or 360
172
+
173
+ watch_url = f"{BASE_URL}/watch/{row.id}"
174
+ embed_url = f"{BASE_URL}/embed/{row.id}"
175
+ thumbnail = _resolve_url(row.thumbnail_url) if row.thumbnail_url else ""
176
+
177
+ result = {
178
+ "type": "video",
179
+ "version": "1.0",
180
+ "provider_name": "Monteeq",
181
+ "provider_url": BASE_URL,
182
+ "title": row.title or "",
183
+ "author_name": row.username or "",
184
+ "author_url": f"{BASE_URL}/profile/{row.username}" if row.username else "",
185
+ "thumbnail_url": thumbnail,
186
+ "thumbnail_width": 1280,
187
+ "thumbnail_height": 720,
188
+ "width": width,
189
+ "height": height,
190
+ "html": f'<iframe src="{embed_url}" width="{width}" height="{height}" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>',
191
+ }
192
+
193
+ if format == "xml":
194
+ xml_str = '<?xml version="1.0" encoding="utf-8"?>\n<oembed>\n'
195
+ for k, v in result.items():
196
+ xml_str += f" <{k}>{v}</{k}>\n"
197
+ xml_str += "</oembed>"
198
+ return Response(content=xml_str.encode("utf-8"), media_type="text/xml")
199
+
200
+ return JSONResponse(
201
+ content=result,
202
+ headers={
203
+ "Access-Control-Allow-Origin": "*",
204
+ "Cache-Control": "public, max-age=3600",
205
+ },
206
+ )
app/api/v1/endpoints/users.py CHANGED
@@ -1,4 +1,5 @@
1
  from fastapi import APIRouter, Depends, HTTPException, status, File, UploadFile, BackgroundTasks
 
2
  from sqlalchemy.orm import Session
3
  from sqlalchemy import or_, func
4
  from typing import List, Optional
@@ -111,24 +112,81 @@ def follow_user(
111
 
112
  @router.get("/search", response_model=schemas.UnifiedSearchResponse)
113
  def search_unified(
114
- q: str = "",
 
115
  db: Session = Depends(get_db)
116
  ):
117
  if not q:
118
- return {"videos": [], "users": []}
119
-
120
- # Search for users
121
  users = db.query(User).filter(
122
  or_(
123
  User.username.ilike(f"%{q}%"),
124
  User.full_name.ilike(f"%{q}%")
125
  )
126
  ).limit(10).all()
127
-
128
  from app.crud import video as crud_video
129
- videos = crud_video.search_videos(db, query_str=q)
130
- posts = crud_video.search_posts(db, query_str=q)
131
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  return {"videos": videos, "users": users, "posts": posts}
133
 
134
  @router.post("/upload-avatar")
@@ -812,6 +870,57 @@ def link_google_account(
812
  raise HTTPException(status_code=500, detail=str(e))
813
 
814
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
815
  @router.get("/{username}/followers", response_model=List[schemas.User])
816
  def get_user_followers(
817
  username: str,
 
1
  from fastapi import APIRouter, Depends, HTTPException, status, File, UploadFile, BackgroundTasks
2
+ from pydantic import BaseModel, ConfigDict
3
  from sqlalchemy.orm import Session
4
  from sqlalchemy import or_, func
5
  from typing import List, Optional
 
112
 
113
  @router.get("/search", response_model=schemas.UnifiedSearchResponse)
114
  def search_unified(
115
+ q: str = "",
116
+ mode: str = "hybrid",
117
  db: Session = Depends(get_db)
118
  ):
119
  if not q:
120
+ return {"videos": [], "users": [], "posts": []}
121
+
122
+ # ── User search (always runs, unaffected by mode) ──
123
  users = db.query(User).filter(
124
  or_(
125
  User.username.ilike(f"%{q}%"),
126
  User.full_name.ilike(f"%{q}%")
127
  )
128
  ).limit(10).all()
129
+
130
  from app.crud import video as crud_video
131
+
132
+ # ── Keyword search (runs for both 'keyword' and 'hybrid') ──
133
+ keyword_videos = []
134
+ keyword_video_ids = []
135
+ posts = []
136
+
137
+ if mode in ("keyword", "hybrid"):
138
+ keyword_videos = crud_video.search_videos(db, query_str=q)
139
+ keyword_video_ids = [v.id for v in keyword_videos]
140
+ posts = crud_video.search_posts(db, query_str=q)
141
+
142
+ # ── Semantic search (runs for both 'semantic' and 'hybrid') ──
143
+ semantic_results = []
144
+ if mode in ("semantic", "hybrid"):
145
+ try:
146
+ from app.services.hybrid_search import semantic_search
147
+ semantic_results = semantic_search(db, q, limit=30)
148
+ except Exception as e:
149
+ # Semantic search is best-effort; keyword results still stand
150
+ import logging
151
+ logging.getLogger(__name__).warning("Semantic search failed: %s", e)
152
+
153
+ # ── Merge & rank (hybrid mode only β€” otherwise pass through) ──
154
+ if mode == "hybrid" and semantic_results:
155
+ from app.services.hybrid_search import merge_search_results
156
+ ranked = merge_search_results(keyword_video_ids, semantic_results, limit=50)
157
+
158
+ # Build an id→Video lookup from keyword results (already has owner loaded)
159
+ kw_lookup = {v.id: v for v in keyword_videos}
160
+
161
+ # Fetch any semantic-only videos not in keyword results
162
+ semantic_only_ids = [vid for vid, _ in ranked if vid not in kw_lookup]
163
+ if semantic_only_ids:
164
+ from sqlalchemy.orm import joinedload
165
+ extra_videos = (
166
+ db.query(Video)
167
+ .options(joinedload(Video.owner))
168
+ .filter(Video.id.in_(semantic_only_ids), Video.status == "approved")
169
+ .all()
170
+ )
171
+ for v in extra_videos:
172
+ kw_lookup[v.id] = v
173
+
174
+ # Build final ordered list, preserving rank order
175
+ videos = [kw_lookup[vid] for vid, _ in ranked if vid in kw_lookup]
176
+
177
+ elif mode == "semantic" and semantic_results:
178
+ # Pure semantic: fetch full Video objects for the ranked IDs
179
+ from sqlalchemy.orm import joinedload
180
+ sem_ids = [vid for vid, _ in semantic_results]
181
+ videos = (
182
+ db.query(Video)
183
+ .options(joinedload(Video.owner))
184
+ .filter(Video.id.in_(sem_ids), Video.status == "approved")
185
+ .all()
186
+ )
187
+ else:
188
+ videos = keyword_videos
189
+
190
  return {"videos": videos, "users": users, "posts": posts}
191
 
192
  @router.post("/upload-avatar")
 
870
  raise HTTPException(status_code=500, detail=str(e))
871
 
872
 
873
+ class RecommendationItem(BaseModel):
874
+ video_id: int
875
+ title: Optional[str] = None
876
+ thumbnail_url: Optional[str] = None
877
+ cover_url: Optional[str] = None
878
+ creator_username: str = "Unknown"
879
+ similarity_score: float = 0.0
880
+
881
+ model_config = ConfigDict(from_attributes=True)
882
+
883
+
884
+ @router.get("/{user_id}/recommendations", response_model=List[RecommendationItem])
885
+ def get_user_recommendations(
886
+ user_id: int,
887
+ limit: int = 20,
888
+ offset: int = 0,
889
+ db: Session = Depends(get_db),
890
+ ):
891
+ """Content-based video recommendations for a user.
892
+
893
+ Uses pgvector caption embeddings to find visually/semantically similar
894
+ videos to the user's liked history. Falls back to trending (most-liked
895
+ videos from the past 7 days) for new users or when no embeddings are
896
+ available yet.
897
+
898
+ Results are cached in Redis for 15 minutes per user.
899
+ """
900
+ if limit < 1 or limit > 50:
901
+ raise HTTPException(status_code=400, detail="limit must be between 1 and 50")
902
+ if offset < 0:
903
+ raise HTTPException(status_code=400, detail="offset must be >= 0")
904
+
905
+ cache_key = f"recs:{user_id}:{limit}:{offset}"
906
+ try:
907
+ cached = redis_client.get(cache_key)
908
+ if cached:
909
+ return json.loads(cached)
910
+ except Exception:
911
+ pass
912
+
913
+ from app.services.recommendations import get_user_recommendations as _get_recs
914
+ results = _get_recs(db, user_id=user_id, limit=limit, offset=offset)
915
+
916
+ try:
917
+ redis_client.setex(cache_key, 900, json.dumps(results))
918
+ except Exception:
919
+ pass
920
+
921
+ return results
922
+
923
+
924
  @router.get("/{username}/followers", response_model=List[schemas.User])
925
  def get_user_followers(
926
  username: str,
app/api/v1/endpoints/videos.py CHANGED
@@ -167,6 +167,61 @@ def check_premium_access(db: Session, request: Request):
167
  raise HTTPException(status_code=403, detail="1080p and above quality levels are restricted to Premium members")
168
 
169
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  @router.get("/{video_id}/stream/{sub_path:path}")
171
  @router.get("/{video_id}/stream")
172
  async def stream_video(video_id: str, request: Request, db: Session = Depends(get_db), sub_path: str = None):
@@ -236,6 +291,8 @@ async def stream_video(video_id: str, request: Request, db: Session = Depends(ge
236
  response_headers = {
237
  "Accept-Ranges": "bytes",
238
  "Content-Encoding": "identity",
 
 
239
  }
240
  content_type = resp.headers.get("Content-Type")
241
  if content_type:
@@ -326,6 +383,8 @@ async def stream_video_resolution(
326
  response_headers = {
327
  "Accept-Ranges": "bytes",
328
  "Content-Encoding": "identity",
 
 
329
  }
330
  content_type = resp.headers.get("Content-Type")
331
  if content_type:
@@ -773,7 +832,7 @@ async def finalize_upload(
773
  video.status = "failed"
774
  db.commit()
775
  raise HTTPException(status_code=400, detail="Cover file required when cover_source is custom")
776
- cover_s3_key = f"covers/{job.id}.jpg"
777
  try:
778
  cover_url = await storage.async_upload_file_obj(cover.file, cover_s3_key)
779
  job.cover_s3_key = cover_s3_key
@@ -1004,7 +1063,7 @@ async def _direct_upload_one(
1004
  job.error_message = "cover_source is custom but no cover file was provided"
1005
  db.commit()
1006
  return _fail("Cover file required when cover_source is custom", status_code=400)
1007
- cover_s3_key = f"covers/{job.id}.jpg"
1008
  try:
1009
  cover_url = await storage.async_upload_file_obj(thumbnail.file, cover_s3_key)
1010
  job.cover_s3_key = cover_s3_key
@@ -1451,3 +1510,157 @@ def delete_comment(
1451
  if result is False:
1452
  raise HTTPException(status_code=403, detail="Not authorized to delete this comment")
1453
  return {"status": "success", "message": "Comment deleted successfully"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  raise HTTPException(status_code=403, detail="1080p and above quality levels are restricted to Premium members")
168
 
169
 
170
+ @router.get("/{video_id}/stream-url")
171
+ async def get_stream_url(video_id: str, request: Request, db: Session = Depends(get_db)):
172
+ """Return a CloudFront signed URL for the video's HLS manifest.
173
+
174
+ Client fetches this ONCE, then loads manifest + all segments directly
175
+ from CloudFront β€” no backend proxy involved in actual streaming.
176
+
177
+ Auth/premium check runs here (same logic as the old proxy endpoint).
178
+ If CloudFront signing is not configured, falls back to the raw CDN URL.
179
+ """
180
+ quality = request.query_params.get("quality", "original")
181
+ if quality.lower() in ("1080p", "2k", "4k"):
182
+ check_premium_access(db, request)
183
+
184
+ video = get_video_db(db, video_id)
185
+ if not video:
186
+ raise HTTPException(status_code=404, detail="Video not found")
187
+
188
+ base_url = video.video_url
189
+ if not base_url:
190
+ raise HTTPException(status_code=400, detail="Video has no URL")
191
+
192
+ # Resolve to CDN URL if stored as S3/HF path
193
+ if "amazonaws.com" in base_url or "monteeq.s3" in base_url or "cdn.monteeq.com" in base_url:
194
+ try:
195
+ if ".com/" in base_url:
196
+ parts = base_url.split(".com/")
197
+ if len(parts) > 1:
198
+ base_url = storage.get_url(parts[1])
199
+ except Exception as e:
200
+ logger.warning(f"Failed to resolve CDN URL for stream-url: {e}")
201
+
202
+ # If CloudFront signing is not configured, return the raw URL
203
+ # (the old proxy endpoint is still available as fallback)
204
+ from app.utils.cloudfront_signer import is_cloudfront_configured, generate_signed_url
205
+
206
+ if not is_cloudfront_configured():
207
+ return {
208
+ "url": base_url,
209
+ "expires_at": 0,
210
+ "signed": False,
211
+ }
212
+
213
+ # Video duration + 1 hour buffer, capped at 6 hours
214
+ duration_buffer = min((video.duration or 3600) + 3600, 21600)
215
+ signed_url = generate_signed_url(base_url, duration_buffer)
216
+
217
+ import time
218
+ return {
219
+ "url": signed_url,
220
+ "expires_at": int(time.time()) + duration_buffer,
221
+ "signed": True,
222
+ }
223
+
224
+
225
  @router.get("/{video_id}/stream/{sub_path:path}")
226
  @router.get("/{video_id}/stream")
227
  async def stream_video(video_id: str, request: Request, db: Session = Depends(get_db), sub_path: str = None):
 
291
  response_headers = {
292
  "Accept-Ranges": "bytes",
293
  "Content-Encoding": "identity",
294
+ "X-Deprecated": "true",
295
+ "X-Deprecation-Notice": "Use /stream-url for direct CDN access",
296
  }
297
  content_type = resp.headers.get("Content-Type")
298
  if content_type:
 
383
  response_headers = {
384
  "Accept-Ranges": "bytes",
385
  "Content-Encoding": "identity",
386
+ "X-Deprecated": "true",
387
+ "X-Deprecation-Notice": "Use /stream-url for direct CDN access",
388
  }
389
  content_type = resp.headers.get("Content-Type")
390
  if content_type:
 
832
  video.status = "failed"
833
  db.commit()
834
  raise HTTPException(status_code=400, detail="Cover file required when cover_source is custom")
835
+ cover_s3_key = f"thumbnails/{job.id}.jpg"
836
  try:
837
  cover_url = await storage.async_upload_file_obj(cover.file, cover_s3_key)
838
  job.cover_s3_key = cover_s3_key
 
1063
  job.error_message = "cover_source is custom but no cover file was provided"
1064
  db.commit()
1065
  return _fail("Cover file required when cover_source is custom", status_code=400)
1066
+ cover_s3_key = f"thumbnails/{job.id}.jpg"
1067
  try:
1068
  cover_url = await storage.async_upload_file_obj(thumbnail.file, cover_s3_key)
1069
  job.cover_s3_key = cover_s3_key
 
1510
  if result is False:
1511
  raise HTTPException(status_code=403, detail="Not authorized to delete this comment")
1512
  return {"status": "success", "message": "Comment deleted successfully"}
1513
+
1514
+
1515
+ # ── Media Analysis ────────────────────────────────────────────────────────────
1516
+
1517
+ @router.get("/{video_id}/analysis")
1518
+ def get_media_analysis(video_id: str, db: Session = Depends(get_db)):
1519
+ """Return the media_analysis row for a video (frames, scene cuts, beats, embedding)."""
1520
+ from sqlalchemy import text
1521
+ row = db.execute(
1522
+ text("SELECT * FROM media_analysis WHERE video_id = :vid"),
1523
+ {"vid": video_id},
1524
+ ).mappings().first()
1525
+
1526
+ if not row:
1527
+ raise HTTPException(status_code=404, detail="No analysis found for this video")
1528
+
1529
+ return dict(row)
1530
+
1531
+
1532
+ # ── Editing Feedback ──────────────────────────────────────────────────────────
1533
+
1534
+ RATE_LIMIT_KEY_PREFIX = "rate_limit:feedback:"
1535
+ RATE_LIMIT_MAX = 10 # requests per window
1536
+ RATE_LIMIT_WINDOW = 3600 # 1 hour in seconds
1537
+
1538
+
1539
+ def _check_feedback_rate_limit(user_id: int) -> None:
1540
+ """Raise 429 if the user has exceeded the feedback request limit."""
1541
+ key = f"{RATE_LIMIT_KEY_PREFIX}{user_id}"
1542
+ try:
1543
+ current = redis_client.get(key)
1544
+ if current is not None and int(current) >= RATE_LIMIT_MAX:
1545
+ raise HTTPException(
1546
+ status_code=429,
1547
+ detail="Rate limit exceeded. You can request feedback up to 10 times per hour.",
1548
+ )
1549
+ redis_client.incr(key)
1550
+ redis_client.expire(key, RATE_LIMIT_WINDOW, nx=True)
1551
+ except HTTPException:
1552
+ raise
1553
+ except Exception:
1554
+ pass # Redis down β€” allow request rather than blocking users
1555
+
1556
+
1557
+ @router.post("/{video_id}/feedback")
1558
+ def post_edit_feedback(
1559
+ video_id: str,
1560
+ db: Session = Depends(get_db),
1561
+ current_user: schemas.User = Depends(get_current_user),
1562
+ ):
1563
+ """Generate AI editing feedback for a video based on its scene_cuts and beat_timestamps.
1564
+
1565
+ Returns the feedback text plus the raw metrics dict. Rate-limited to 10
1566
+ requests per hour per user.
1567
+ """
1568
+ video = get_video_db(db, video_id)
1569
+ if not video:
1570
+ raise HTTPException(status_code=404, detail="Video not found")
1571
+
1572
+ _check_feedback_rate_limit(current_user.id)
1573
+
1574
+ from sqlalchemy import text as sql_text
1575
+
1576
+ # 1. Fetch media_analysis row
1577
+ row = db.execute(
1578
+ sql_text("SELECT * FROM media_analysis WHERE video_id = :vid"),
1579
+ {"vid": video.id},
1580
+ ).mappings().first()
1581
+
1582
+ if not row:
1583
+ raise HTTPException(status_code=404, detail="No media analysis found for this video")
1584
+
1585
+ if not row.get("scene_cuts") or not row.get("beat_timestamps"):
1586
+ raise HTTPException(
1587
+ status_code=409,
1588
+ detail="Editing feedback is not available yet β€” scene cut or beat detection has not finished. "
1589
+ "Wait for media analysis to complete and try again.",
1590
+ )
1591
+
1592
+ # 2. Compute metrics
1593
+ from app.services.editing_feedback import compute_edit_metrics, generate_feedback
1594
+
1595
+ metrics = compute_edit_metrics(
1596
+ scene_cuts=list(row["scene_cuts"]),
1597
+ beat_timestamps=list(row["beat_timestamps"]),
1598
+ )
1599
+
1600
+ # 3. Generate AI feedback
1601
+ feedback_text = generate_feedback(metrics, video.title or "Untitled")
1602
+
1603
+ # 4. Persist to edit_feedback table
1604
+ from app.models.edit_feedback import EditFeedback
1605
+
1606
+ feedback_record = EditFeedback(
1607
+ video_id=video.id,
1608
+ feedback_text=feedback_text,
1609
+ metrics_snapshot=metrics,
1610
+ )
1611
+ db.add(feedback_record)
1612
+ db.commit()
1613
+
1614
+ return {
1615
+ "feedback_id": feedback_record.id,
1616
+ "feedback_text": feedback_text,
1617
+ "metrics": metrics,
1618
+ "created_at": feedback_record.created_at.isoformat() if feedback_record.created_at else None,
1619
+ }
1620
+
1621
+
1622
+ @router.get("/{video_id}/feedback")
1623
+ def get_edit_feedback(
1624
+ video_id: str,
1625
+ db: Session = Depends(get_db),
1626
+ current_user: User = Depends(get_current_user),
1627
+ ):
1628
+ """Return the most recent editing feedback entry for this video.
1629
+
1630
+ The caller must own the video (or be an admin). Returns a 200 with
1631
+ ``feedback_text`` / ``metrics`` / ``created_at`` all set to ``null``
1632
+ when no previous feedback exists β€” the frontend treats this as a
1633
+ normal empty state, not an error.
1634
+ """
1635
+ video = get_video_db(db, video_id)
1636
+ if not video:
1637
+ raise HTTPException(status_code=404, detail="Video not found")
1638
+
1639
+ if video.owner_id != current_user.id and current_user.role != "admin":
1640
+ raise HTTPException(status_code=403, detail="Not authorized to view feedback for this video")
1641
+
1642
+ from sqlalchemy import text as sql_text
1643
+
1644
+ row = db.execute(
1645
+ sql_text(
1646
+ "SELECT feedback_text, metrics_snapshot, created_at "
1647
+ "FROM edit_feedback "
1648
+ "WHERE video_id = :vid "
1649
+ "ORDER BY created_at DESC "
1650
+ "LIMIT 1"
1651
+ ),
1652
+ {"vid": video.id},
1653
+ ).mappings().first()
1654
+
1655
+ if not row:
1656
+ return {
1657
+ "feedback_text": None,
1658
+ "metrics": None,
1659
+ "created_at": None,
1660
+ }
1661
+
1662
+ return {
1663
+ "feedback_text": row["feedback_text"],
1664
+ "metrics": row["metrics_snapshot"],
1665
+ "created_at": row["created_at"].isoformat() if row["created_at"] else None,
1666
+ }
app/core/config.py CHANGED
@@ -35,7 +35,7 @@ CORS_ALLOW_ORIGIN_REGEX = os.getenv(
35
 
36
 
37
  # Database Configuration
38
- DATABASE_URL = os.getenv("DATABASE_URL")
39
 
40
  # Quota Limits
41
  FLASH_QUOTA_LIMIT = 50
@@ -51,6 +51,10 @@ _raw_endpoint = os.getenv("S3_ENDPOINT") or ""
51
  S3_ENDPOINT = _raw_endpoint.strip() or None # empty string β†’ native AWS
52
  AWS_S3_USE_ACCELERATE = os.getenv("AWS_S3_USE_ACCELERATE", "false").lower() == "true"
53
  AWS_CLOUDFRONT_DOMAIN = os.getenv("AWS_CLOUDFRONT_DOMAIN", "")
 
 
 
 
54
 
55
  PAYSTACK_SECRET_KEY = os.getenv("PAYSTACK_SECRET_KEY", "")
56
  # STRIPE_SECRET_KEY = os.getenv("STRIPE_SECRET_KEY", "")
 
35
 
36
 
37
  # Database Configuration
38
+ DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./sql_app.db")
39
 
40
  # Quota Limits
41
  FLASH_QUOTA_LIMIT = 50
 
51
  S3_ENDPOINT = _raw_endpoint.strip() or None # empty string β†’ native AWS
52
  AWS_S3_USE_ACCELERATE = os.getenv("AWS_S3_USE_ACCELERATE", "false").lower() == "true"
53
  AWS_CLOUDFRONT_DOMAIN = os.getenv("AWS_CLOUDFRONT_DOMAIN", "")
54
+ CLOUDFRONT_KEY_PAIR_ID = os.getenv("CLOUDFRONT_KEY_PAIR_ID", "")
55
+ # NOTE: For production, consider migrating this to AWS Secrets Manager
56
+ # (fetched at startup, cached in memory) instead of an env var.
57
+ CLOUDFRONT_PRIVATE_KEY = os.getenv("CLOUDFRONT_PRIVATE_KEY", "")
58
 
59
  PAYSTACK_SECRET_KEY = os.getenv("PAYSTACK_SECRET_KEY", "")
60
  # STRIPE_SECRET_KEY = os.getenv("STRIPE_SECRET_KEY", "")
app/db/async_session.py CHANGED
@@ -1,16 +1,22 @@
1
  from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
2
  from app.core.config import DATABASE_URL
3
 
4
- # Convert postgresql:// to postgresql+asyncpg:// if needed
5
- ASYNC_SQLALCHEMY_DATABASE_URL = DATABASE_URL.replace("postgresql://", "postgresql+asyncpg://")
 
 
 
 
 
 
 
6
 
7
  async_engine = create_async_engine(
8
  ASYNC_SQLALCHEMY_DATABASE_URL,
9
  echo=False,
10
  future=True,
11
- pool_size=3, # Reduced to prevent Supabase pool exhaustion (max 15 clients)
12
- max_overflow=2, # Reduced to prevent Supabase pool exhaustion
13
- connect_args={"statement_cache_size": 0}
14
  )
15
 
16
  AsyncSessionLocal = async_sessionmaker(
 
1
  from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
2
  from app.core.config import DATABASE_URL
3
 
4
+ # Convert postgresql:// to postgresql+asyncpg:// or sqlite:// to sqlite+aiosqlite://
5
+ if DATABASE_URL.startswith("sqlite"):
6
+ ASYNC_SQLALCHEMY_DATABASE_URL = DATABASE_URL.replace("sqlite://", "sqlite+aiosqlite://")
7
+ connect_args = {"check_same_thread": False}
8
+ extra_engine_args = {}
9
+ else:
10
+ ASYNC_SQLALCHEMY_DATABASE_URL = DATABASE_URL.replace("postgresql://", "postgresql+asyncpg://")
11
+ connect_args = {"statement_cache_size": 0}
12
+ extra_engine_args = {"pool_size": 3, "max_overflow": 2}
13
 
14
  async_engine = create_async_engine(
15
  ASYNC_SQLALCHEMY_DATABASE_URL,
16
  echo=False,
17
  future=True,
18
+ connect_args=connect_args,
19
+ **extra_engine_args
 
20
  )
21
 
22
  AsyncSessionLocal = async_sessionmaker(
app/models/edit_feedback.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy import Column, Integer, Text, DateTime, ForeignKey, func
2
+ from sqlalchemy.dialects.postgresql import JSONB
3
+ from app.db.base import Base
4
+
5
+
6
+ class EditFeedback(Base):
7
+ __tablename__ = "edit_feedback"
8
+
9
+ id = Column(Integer, primary_key=True, autoincrement=True)
10
+ video_id = Column(Integer, ForeignKey("videos.id", ondelete="CASCADE"), nullable=False, index=True)
11
+ feedback_text = Column(Text, nullable=False)
12
+ metrics_snapshot = Column(JSONB, nullable=False)
13
+ created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
app/models/models.py CHANGED
@@ -29,6 +29,7 @@ class UploadJobStatus(str, enum.Enum):
29
  FAILED = "failed"
30
 
31
  from app.models.library import WatchHistory, LibraryWatchLater, LikedVideo
 
32
 
33
  class User(Base):
34
 
 
29
  FAILED = "failed"
30
 
31
  from app.models.library import WatchHistory, LibraryWatchLater, LikedVideo
32
+ from app.models.edit_feedback import EditFeedback
33
 
34
  class User(Base):
35
 
app/schemas/video_events.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, field_validator
2
+ from typing import Optional, List, Union
3
+ import enum
4
+
5
+
6
+ class VideoEventType(str, enum.Enum):
7
+ VIEW = "view"
8
+ WATCH_25 = "watch_25"
9
+ WATCH_50 = "watch_50"
10
+ WATCH_75 = "watch_75"
11
+ COMPLETE = "complete"
12
+ LIKE = "like"
13
+ SHARE = "share"
14
+ SKIP = "skip"
15
+
16
+
17
+ class VideoEventIn(BaseModel):
18
+ user_id: int
19
+ video_id: int
20
+ event_type: VideoEventType
21
+ watch_seconds: Optional[int] = None
22
+ session_id: Optional[str] = None
23
+
24
+ @field_validator("event_type", mode="before")
25
+ @classmethod
26
+ def coerce_event_type(cls, v):
27
+ if isinstance(v, VideoEventType):
28
+ return v
29
+ try:
30
+ return VideoEventType(v)
31
+ except ValueError:
32
+ raise ValueError(f"Invalid event_type: {v}. Must be one of: {[e.value for e in VideoEventType]}")
33
+
34
+
35
+ class VideoEventBatch(BaseModel):
36
+ events: List[VideoEventIn]
app/services/clip_utils.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CLIP model utilities β€” image and text encoding via openai/clip-vit-base-patch32.
3
+
4
+ Uses the ``transformers`` library (already installed as a sentence-transformers
5
+ dependency) so no new heavy pip package is needed.
6
+
7
+ Models are loaded once at import time (module-level singletons) because
8
+ initialisation takes several seconds. Both the Celery worker and the FastAPI
9
+ process import this module, so each process gets its own independent copy in
10
+ memory.
11
+
12
+ CLIP ViT-B/32 output dimensionality: **512**.
13
+ """
14
+ import logging
15
+ from typing import List
16
+
17
+ import numpy as np
18
+ import torch
19
+ from PIL import Image
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ # ---------------------------------------------------------------------------
24
+ # Lazy-loaded singletons (loaded on first use, not at import time, so that
25
+ # importing this module doesn't block startup when CLIP isn't needed).
26
+ # ---------------------------------------------------------------------------
27
+ _model = None
28
+ _processor = None
29
+
30
+
31
+ def _load():
32
+ global _model, _processor
33
+ if _model is not None:
34
+ return
35
+ from transformers import CLIPModel, CLIPProcessor
36
+
37
+ model_id = "openai/clip-vit-base-patch32"
38
+ logger.info("Loading CLIP model %s …", model_id)
39
+ _processor = CLIPProcessor.from_pretrained(model_id)
40
+ _model = CLIPModel.from_pretrained(model_id)
41
+ _model.eval()
42
+ logger.info("CLIP model loaded (dim=%d)", embedding_dim())
43
+
44
+
45
+ def embedding_dim() -> int:
46
+ """Return the output dimensionality of the CLIP model (512 for ViT-B/32)."""
47
+ return 512
48
+
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # Image encoding
52
+ # ---------------------------------------------------------------------------
53
+
54
+ def encode_images(image_paths: List[str], batch_size: int = 8) -> np.ndarray:
55
+ """Encode a list of local image files into CLIP embeddings.
56
+
57
+ Returns an ``(N, 512)`` float32 array, L2-normalized per row.
58
+ Images that fail to load are skipped (resulting array may be shorter).
59
+ """
60
+ _load()
61
+
62
+ embeddings: List[np.ndarray] = []
63
+ for start in range(0, len(image_paths), batch_size):
64
+ batch_paths = image_paths[start : start + batch_size]
65
+ images = []
66
+ for p in batch_paths:
67
+ try:
68
+ images.append(Image.open(p).convert("RGB"))
69
+ except Exception:
70
+ logger.warning("Could not load image %s β€” skipping", p)
71
+
72
+ if not images:
73
+ continue
74
+
75
+ inputs = _processor(images=images, return_tensors="pt", padding=True)
76
+ with torch.no_grad():
77
+ outputs = _model.get_image_features(**inputs)
78
+ features = outputs.image_embeds if not isinstance(outputs, torch.Tensor) else outputs
79
+
80
+ # L2-normalize each row
81
+ features = features / features.norm(dim=-1, keepdim=True)
82
+ embeddings.append(features.cpu().numpy().astype(np.float32))
83
+
84
+ if not embeddings:
85
+ return np.zeros((0, embedding_dim()), dtype=np.float32)
86
+
87
+ return np.concatenate(embeddings, axis=0)
88
+
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # Text encoding
92
+ # ---------------------------------------------------------------------------
93
+
94
+ def encode_text(text: str) -> np.ndarray:
95
+ """Encode a text string into a CLIP embedding.
96
+
97
+ Returns a ``(512,)`` float32 vector, L2-normalized.
98
+ """
99
+ _load()
100
+
101
+ inputs = _processor(text=[text], return_tensors="pt", padding=True, truncation=True)
102
+ with torch.no_grad():
103
+ outputs = _model.get_text_features(**inputs)
104
+ features = outputs.text_embeds if not isinstance(outputs, torch.Tensor) else outputs
105
+
106
+ features = features / features.norm(dim=-1, keepdim=True)
107
+ return features.cpu().numpy().astype(np.float32).flatten()
app/services/editing_feedback.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import statistics
3
+ from typing import List
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+ # ---------------------------------------------------------------------------
8
+ # Pure metric computation (no I/O, fully testable)
9
+ # ---------------------------------------------------------------------------
10
+
11
+ BEAT_SYNC_TOLERANCE_MS = 150 # Β±150 ms window for a cut to be considered on-beat
12
+
13
+
14
+ def compute_edit_metrics(
15
+ scene_cuts: List[float],
16
+ beat_timestamps: List[float],
17
+ ) -> dict:
18
+ """Analyse scene-cut timing relative to beats.
19
+
20
+ Parameters
21
+ ----------
22
+ scene_cuts : list[float]
23
+ Timestamps (seconds) where scene cuts occur.
24
+ beat_timestamps : list[float]
25
+ Timestamps (seconds) of detected beats.
26
+
27
+ Returns
28
+ -------
29
+ dict with keys:
30
+ cut_count, cut_durations (list[float]), avg_cut_duration,
31
+ min_cut_duration, max_cut_duration, std_cut_duration,
32
+ beat_sync_score (float 0-100), beat_offsets_ms (list[float]),
33
+ total_duration_seconds, total_beats
34
+ """
35
+ if not scene_cuts or len(scene_cuts) < 2:
36
+ return {
37
+ "cut_count": 0,
38
+ "cut_durations": [],
39
+ "avg_cut_duration": 0.0,
40
+ "min_cut_duration": 0.0,
41
+ "max_cut_duration": 0.0,
42
+ "std_cut_duration": 0.0,
43
+ "beat_sync_score": 0.0,
44
+ "beat_offsets_ms": [],
45
+ "total_duration_seconds": 0.0,
46
+ "total_beats": len(beat_timestamps),
47
+ }
48
+
49
+ # --- Cut durations ---
50
+ cut_durations = []
51
+ for i in range(1, len(scene_cuts)):
52
+ dur = scene_cuts[i] - scene_cuts[i - 1]
53
+ if dur > 0:
54
+ cut_durations.append(dur)
55
+
56
+ if not cut_durations:
57
+ return {
58
+ "cut_count": 0,
59
+ "cut_durations": [],
60
+ "avg_cut_duration": 0.0,
61
+ "min_cut_duration": 0.0,
62
+ "max_cut_duration": 0.0,
63
+ "std_cut_duration": 0.0,
64
+ "beat_sync_score": 0.0,
65
+ "beat_offsets_ms": [],
66
+ "total_duration_seconds": scene_cuts[-1] - scene_cuts[0] if len(scene_cuts) > 1 else 0.0,
67
+ "total_beats": len(beat_timestamps),
68
+ }
69
+
70
+ # For each cut (transition point at scene_cuts[i]), find the nearest beat
71
+ beat_offsets_ms = []
72
+ on_beat_count = 0
73
+ total_beats = len(beat_timestamps)
74
+
75
+ # The cut "moment" is the end of each segment: scene_cuts[i]
76
+ for i in range(1, len(scene_cuts)):
77
+ cut_ts = scene_cuts[i]
78
+ if not beat_timestamps:
79
+ beat_offsets_ms.append(0.0)
80
+ continue
81
+
82
+ nearest_beat = min(beat_timestamps, key=lambda b: abs(b - cut_ts))
83
+ offset_ms = (cut_ts - nearest_beat) * 1000.0
84
+ beat_offsets_ms.append(offset_ms)
85
+
86
+ if abs(offset_ms) <= BEAT_SYNC_TOLERANCE_MS:
87
+ on_beat_count += 1
88
+
89
+ total_cuts = len(scene_cuts) - 1 # number of cut transitions
90
+ beat_sync_score = (on_beat_count / total_cuts * 100.0) if total_cuts > 0 else 0.0
91
+
92
+ return {
93
+ "cut_count": total_cuts,
94
+ "cut_durations": cut_durations,
95
+ "avg_cut_duration": statistics.mean(cut_durations),
96
+ "min_cut_duration": min(cut_durations),
97
+ "max_cut_duration": max(cut_durations),
98
+ "std_cut_duration": statistics.stdev(cut_durations) if len(cut_durations) > 1 else 0.0,
99
+ "beat_sync_score": round(beat_sync_score, 1),
100
+ "beat_offsets_ms": [round(o, 2) for o in beat_offsets_ms],
101
+ "total_duration_seconds": round(scene_cuts[-1] - scene_cuts[0], 2),
102
+ "total_beats": total_beats,
103
+ }
104
+
105
+
106
+ # ---------------------------------------------------------------------------
107
+ # AI feedback generation (calls Gemini 2.5 Flash via google-genai SDK)
108
+ # ---------------------------------------------------------------------------
109
+
110
+ SYSTEM_PROMPT = """You are an experienced AMV (anime music video) and video-edit critique assistant. You are given structured numeric metrics about an edit β€” cut durations, beat sync offsets, and overall pacing stats β€” plus the video title.
111
+
112
+ Your job: provide specific, actionable feedback grounded in the actual numbers. Do NOT give generic advice like \"try cutting to the beat\". Instead:
113
+
114
+ 1. Write a 2-3 sentence overall summary of the edit quality.
115
+ 2. Then provide 3-5 specific bullet points. Where relevant, reference actual timestamp ranges (e.g. \"the 0:45-1:10 section has cuts averaging 2.1s while the rest of the edit averages 0.8s\") and the beat sync percentage.
116
+
117
+ Focus on:
118
+ - Pacing consistency β€” are cut durations uniform or highly variable? Is the average too fast/slow for the feel of the edit?
119
+ - Beat sync quality β€” how many cuts land within Β±150ms of a beat? Are there sections that drift off-beat?
120
+ - Whether specific sections feel rushed or dragging, based on the distribution of cut durations.
121
+
122
+ Be direct and constructive. Use natural language. Do not use markdown formatting."""
123
+
124
+
125
+ def generate_feedback(metrics: dict, video_title: str) -> str:
126
+ """Call Gemini 2.5 Flash to generate editing feedback.
127
+
128
+ Parameters
129
+ ----------
130
+ metrics : dict
131
+ The dict returned by ``compute_edit_metrics()``.
132
+ video_title : str
133
+ Title of the video, used as context.
134
+
135
+ Returns
136
+ -------
137
+ str β€” the raw feedback text from the model.
138
+ """
139
+ api_key = _get_gemini_api_key()
140
+ if not api_key:
141
+ logger.warning("GEMINI_API_KEY not set β€” using fallback feedback")
142
+ return _compute_offline_fallback(metrics, video_title)
143
+
144
+ from google import genai
145
+
146
+ client = genai.Client(api_key=api_key)
147
+
148
+ metrics_text = _build_metrics_text(metrics)
149
+
150
+ user_content = (
151
+ f"Video title: {video_title}\n\n"
152
+ f"Edit metrics:\n{metrics_text}\n\n"
153
+ "Please provide specific, actionable editing feedback based on these numbers."
154
+ )
155
+
156
+ try:
157
+ response = client.models.generate_content(
158
+ model="gemini-2.5-flash",
159
+ contents=user_content,
160
+ config=genai.types.GenerateContentConfig(
161
+ system_instruction=SYSTEM_PROMPT,
162
+ max_output_tokens=1024,
163
+ ),
164
+ )
165
+ if not response.text:
166
+ logger.warning("Gemini returned empty response β€” using fallback feedback")
167
+ return _compute_offline_fallback(metrics, video_title)
168
+ return response.text
169
+ except Exception as exc:
170
+ logger.warning("Gemini API call failed β€” using fallback feedback: %s", exc)
171
+ return _compute_offline_fallback(metrics, video_title)
172
+
173
+
174
+ # ---------------------------------------------------------------------------
175
+ # Helpers
176
+ # ---------------------------------------------------------------------------
177
+
178
+
179
+ def _get_gemini_api_key() -> str | None:
180
+ """Read GEMINI_API_KEY from config or environment."""
181
+ try:
182
+ from app.core import config
183
+
184
+ return getattr(config, "GEMINI_API_KEY", None) or None
185
+ except (ImportError, AttributeError):
186
+ import os
187
+ return os.getenv("GEMINI_API_KEY") or None
188
+
189
+
190
+ def _build_metrics_text(metrics: dict) -> str:
191
+ cuts = metrics.get("cut_durations", [])
192
+ lines = [
193
+ f"- Total cuts: {metrics.get('cut_count', 0)}",
194
+ f"- Average cut duration: {metrics.get('avg_cut_duration', 0):.2f}s",
195
+ f"- Shortest cut: {metrics.get('min_cut_duration', 0):.2f}s",
196
+ f"- Longest cut: {metrics.get('max_cut_duration', 0):.2f}s",
197
+ f"- Cut duration std dev: {metrics.get('std_cut_duration', 0):.2f}s",
198
+ f"- Beat sync score: {metrics.get('beat_sync_score', 0):.1f}% of cuts within Β±150ms of a beat",
199
+ f"- Total edit duration: {metrics.get('total_duration_seconds', 0):.1f}s",
200
+ f"- Total beats in track: {metrics.get('total_beats', 0)}",
201
+ ]
202
+ if cuts and len(cuts) >= 3:
203
+ # Show first few cut durations to give a sense of pacing pattern
204
+ sample = [round(d, 2) for d in cuts[:10]]
205
+ lines.append(f"- Cut duration sequence (first 10): {sample}{'…' if len(cuts) > 10 else ''}")
206
+
207
+ return "\n".join(lines)
208
+
209
+
210
+ def _compute_offline_fallback(metrics: dict, video_title: str) -> str:
211
+ """Generate a purely data-driven feedback string when the AI API is unavailable.
212
+
213
+ This mirrors the spirit of the AI prompt: summary + bullet points grounded in numbers.
214
+ """
215
+ avg = metrics.get("avg_cut_duration", 0)
216
+ std = metrics.get("std_cut_duration", 0)
217
+ sync = metrics.get("beat_sync_score", 0)
218
+ count = metrics.get("cut_count", 0)
219
+ total_dur = metrics.get("total_duration_seconds", 0)
220
+ cuts = metrics.get("cut_durations", [])
221
+
222
+ summary = (
223
+ f"Your edit for \"{video_title}\" contains {count} cuts over {total_dur:.0f}s "
224
+ f"({total_dur / 60:.1f}m). "
225
+ )
226
+ if avg > 0:
227
+ summary += f"Cuts average {avg:.1f}s each. "
228
+ if std > 1.0:
229
+ summary += "Pacing varies considerably between sections. "
230
+ elif count > 0:
231
+ summary += "Pacing is fairly consistent. "
232
+
233
+ bullets = []
234
+
235
+ # Pacing assessment
236
+ if avg > 4.0:
237
+ bullets.append(f"Average cut length of {avg:.1f}s suggests a slow, atmospheric edit. If the track is energetic, consider tighter cuts (under 3s).")
238
+ elif avg > 2.0:
239
+ bullets.append(f"Average cut length of {avg:.1f}s is moderate. If the section around 0:{int(total_dur*0.3)}-0:{int(total_dur*0.5)} has longer cuts, check whether it drags relative to the energy of that part of the song.")
240
+ elif avg > 0.5:
241
+ bullets.append(f"Cuts averaging {avg:.1f}s give the edit a brisk pace. Watch for sections where cuts cluster below 1s β€” they can feel jarring if the music doesn't support that speed.")
242
+ else:
243
+ bullets.append("Very fast cutting rate (under 1s average). Ensure each cut has visual purpose rather than just hitting every drum hit.")
244
+
245
+ # Variability
246
+ if std > 0 and count > 0:
247
+ rel_std = std / avg if avg > 0 else 0
248
+ if rel_std > 1.0:
249
+ bullets.append(f"High duration variability (std dev {std:.1f}s, {rel_std:.0%} of mean). The edit jumps between very short and long cuts β€” check whether this is intentional for the song structure or feels disjointed.")
250
+ elif rel_std < 0.3 and count > 5:
251
+ bullets.append(f"Very uniform cut durations (std dev {std:.1f}s). Consider varying cut length more to match musical phrasing rather than a metronomic rhythm.")
252
+
253
+ # Beat sync
254
+ if sync >= 80:
255
+ bullets.append(f"Excellent beat sync ({sync:.0f}% of cuts on-beat). The edit is well-timed to the music.")
256
+ elif sync >= 50:
257
+ bullets.append(f"Moderate beat sync ({sync:.0f}%). Some cuts land off-beat β€” review the sections around the largest offsets (over 200ms) and nudge those cut points.")
258
+ else:
259
+ bullets.append(f"Low beat sync ({sync:.0f}%). Many cuts do not align with a nearby beat. Consider re-timing larger sections to land on downbeats for a more satisfying rhythm.")
260
+
261
+ return summary + "\n\n" + "\n".join(f"- {b}" for b in bullets)
app/services/hybrid_search.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hybrid search β€” merges keyword (ILIKE) and semantic (pgvector) search results.
3
+
4
+ The keyword path lives in app.crud.video.search_videos / search_posts (untouched).
5
+ This module adds the semantic path and the merge/ranking logic.
6
+
7
+ Semantic search now blends two embedding types:
8
+ - **caption_embedding** (384-dim, sentence-transformers all-MiniLM-L6-v2)
9
+ - **visual_embedding** (512-dim, CLIP ViT-B/32)
10
+ """
11
+ import logging
12
+ from typing import List, Optional, Tuple
13
+
14
+ from sqlalchemy.orm import Session
15
+
16
+ from app.services.pgvector_utils import (
17
+ blended_cosine_similarity_query,
18
+ cosine_similarity_query,
19
+ vector_to_str,
20
+ )
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ # ---------------------------------------------------------------------------
25
+ # Tuning constants β€” adjust these to shift ranking between text and visual
26
+ # ---------------------------------------------------------------------------
27
+ CAPTION_WEIGHT = 0.5 # weight for sentence-transformers text similarity
28
+ VISUAL_WEIGHT = 0.5 # weight for CLIP visual similarity
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Model singletons β€” loaded once, reused across requests
32
+ # ---------------------------------------------------------------------------
33
+ _caption_encoder = None
34
+ _visual_encoder_loaded = False
35
+
36
+
37
+ def _get_caption_encoder():
38
+ global _caption_encoder
39
+ if _caption_encoder is None:
40
+ from sentence_transformers import SentenceTransformer
41
+ _caption_encoder = SentenceTransformer("all-MiniLM-L6-v2")
42
+ logger.info("Loaded sentence-transformers model all-MiniLM-L6-v2")
43
+ return _caption_encoder
44
+
45
+
46
+ def _ensure_visual_encoder():
47
+ """Eagerly load the CLIP text encoder (module-level singleton via clip_utils)."""
48
+ global _visual_encoder_loaded
49
+ if not _visual_encoder_loaded:
50
+ from app.services.clip_utils import _load
51
+ _load()
52
+ _visual_encoder_loaded = True
53
+
54
+
55
+ # ---------------------------------------------------------------------------
56
+ # Semantic search via pgvector (blended caption + visual)
57
+ # ---------------------------------------------------------------------------
58
+
59
+ def semantic_search(
60
+ db: Session,
61
+ query: str,
62
+ limit: int = 20,
63
+ status: str = "approved",
64
+ ) -> List[Tuple[int, float]]:
65
+ """Return [(video_id, blended_score), ...] ranked by combined similarity.
66
+
67
+ Encodes the query with both sentence-transformers (caption) and CLIP
68
+ (visual), then runs a single blended pgvector query. If CLIP is
69
+ unavailable or the visual column is NULL for a video, that side
70
+ contributes 0 via COALESCE β€” no errors, no zeroing of the whole score.
71
+ """
72
+ if not query or not query.strip():
73
+ return []
74
+
75
+ # Caption embedding (sentence-transformers)
76
+ caption_encoder = _get_caption_encoder()
77
+ caption_emb = caption_encoder.encode(query.strip(), normalize_embeddings=True)
78
+ caption_str = vector_to_str(caption_emb)
79
+
80
+ # Visual embedding (CLIP text encoder)
81
+ visual_str = None
82
+ try:
83
+ _ensure_visual_encoder()
84
+ from app.services.clip_utils import encode_text
85
+ visual_emb = encode_text(query.strip())
86
+ visual_str = vector_to_str(visual_emb)
87
+ except Exception as exc:
88
+ logger.warning("CLIP text encoding failed β€” falling back to caption-only: %s", exc)
89
+
90
+ if visual_str is not None:
91
+ return blended_cosine_similarity_query(
92
+ db,
93
+ caption_str,
94
+ visual_str,
95
+ caption_weight=CAPTION_WEIGHT,
96
+ visual_weight=VISUAL_WEIGHT,
97
+ limit=limit,
98
+ status=status,
99
+ )
100
+
101
+ # Fallback: caption-only (CLIP unavailable)
102
+ return cosine_similarity_query(
103
+ db, caption_str, limit=limit, status=status,
104
+ )
105
+
106
+
107
+ # ---------------------------------------------------------------------------
108
+ # Pure merge / ranking function
109
+ # ---------------------------------------------------------------------------
110
+
111
+ KEYWORD_BOOST = 1.0 # Added to raw similarity so keyword matches always rank above semantic-only
112
+
113
+
114
+ def merge_search_results(
115
+ keyword_video_ids: List[int],
116
+ semantic_results: List[Tuple[int, float]],
117
+ limit: int = 50,
118
+ ) -> List[Tuple[int, float]]:
119
+ """Merge keyword and semantic video results into a single ranked list.
120
+
121
+ - keyword_video_ids: list of video IDs from ILIKE search (order = relevance)
122
+ - semantic_results: list of (video_id, similarity_score) from pgvector
123
+ - Returns [(video_id, final_score), ...] sorted descending, capped to *limit*.
124
+
125
+ A video matching both gets KEYWORD_BOOST + its semantic score (not double-counted).
126
+ Keyword-only matches get KEYWORD_BOOST + 0.
127
+ Semantic-only matches get their raw similarity score.
128
+ """
129
+ scores = {}
130
+
131
+ # Keyword results β€” assign boost + recency tiebreaker from position
132
+ for idx, vid in enumerate(keyword_video_ids):
133
+ recency = max(0.0, 1.0 - idx * 0.01) # slight tiebreak for earlier results
134
+ scores[vid] = KEYWORD_BOOST + recency
135
+
136
+ # Semantic results β€” merge or add
137
+ for vid, sim in semantic_results:
138
+ if vid in scores:
139
+ # Already a keyword hit β€” use keyword-boosted score (higher)
140
+ pass
141
+ else:
142
+ scores[vid] = sim
143
+
144
+ ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
145
+ return ranked[:limit]
app/services/media_analysis.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Media analysis pipeline β€” extracts frames, scene cuts, beat timestamps,
3
+ and caption embeddings from a transcoded video.
4
+
5
+ Called by the Celery task after transcoding completes.
6
+ """
7
+ import os
8
+ import tempfile
9
+ import shutil
10
+ import logging
11
+ import subprocess
12
+ import json
13
+ from typing import List, Optional
14
+
15
+ import numpy as np
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ def extract_frames(video_path: str, video_id: str) -> List[str]:
21
+ """Sample 1 frame per second from the video, upload each to S3, return S3 keys."""
22
+ from app.core.storage import storage
23
+
24
+ frames_dir = tempfile.mkdtemp(prefix="frames_")
25
+ try:
26
+ subprocess.run(
27
+ [
28
+ "ffmpeg", "-i", video_path,
29
+ "-vf", "fps=1",
30
+ "-q:v", "3",
31
+ os.path.join(frames_dir, "frame_%04d.jpg"),
32
+ ],
33
+ check=True,
34
+ capture_output=True,
35
+ timeout=600,
36
+ )
37
+
38
+ s3_keys = []
39
+ for fname in sorted(os.listdir(frames_dir)):
40
+ local_path = os.path.join(frames_dir, fname)
41
+ s3_key = f"analysis/{video_id}/frames/{fname}"
42
+ storage.upload_file(local_path, s3_key)
43
+ s3_keys.append(s3_key)
44
+
45
+ logger.info("Uploaded %d frames for video %s", len(s3_keys), video_id)
46
+ return s3_keys
47
+ finally:
48
+ shutil.rmtree(frames_dir, ignore_errors=True)
49
+
50
+
51
+ def detect_scene_cuts(video_path: str) -> List[float]:
52
+ """Detect scene cuts using pyscenedetect ContentDetector. Returns timestamps in seconds."""
53
+ from scenedetect import open_video, SceneManager
54
+ from scenedetect.detectors import ContentDetector
55
+
56
+ video = open_video(video_path)
57
+ scene_manager = SceneManager()
58
+ scene_manager.add_detector(ContentDetector(threshold=27.0))
59
+ scene_manager.detect_scenes(video, show_progress=False)
60
+
61
+ scene_list = scene_manager.get_scene_list()
62
+ # Return the start time of each scene as seconds
63
+ timestamps = [round(scene[0].get_seconds(), 3) for scene in scene_list]
64
+ logger.info("Detected %d scene cuts", len(timestamps))
65
+ return timestamps
66
+
67
+
68
+ def detect_beats(video_path: str) -> List[float]:
69
+ """Extract audio and detect beat timestamps using librosa. Returns timestamps in seconds."""
70
+ import librosa
71
+
72
+ # Extract audio to a temp WAV file
73
+ audio_tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
74
+ audio_tmp.close()
75
+ try:
76
+ subprocess.run(
77
+ [
78
+ "ffmpeg", "-i", video_path,
79
+ "-vn", "-acodec", "pcm_s16le", "-ar", "22050", "-ac", "1",
80
+ "-y", audio_tmp.name,
81
+ ],
82
+ check=True,
83
+ capture_output=True,
84
+ timeout=300,
85
+ )
86
+
87
+ y, sr = librosa.load(audio_tmp.name, sr=22050)
88
+ tempo, beat_frames = librosa.beat.beat_track(y=y, sr=sr)
89
+ beat_times = librosa.frames_to_time(beat_frames, sr=sr).tolist()
90
+ beat_times = [round(t, 3) for t in beat_times]
91
+ logger.info("Detected %d beat timestamps", len(beat_times))
92
+ return beat_times
93
+ finally:
94
+ os.unlink(audio_tmp.name)
95
+
96
+
97
+ def generate_caption_embedding(title: str, tags: Optional[str]) -> Optional[List[float]]:
98
+ """Generate a 384-dim embedding from title+tags using all-MiniLM-L6-v2."""
99
+ from sentence_transformers import SentenceTransformer
100
+
101
+ text = title or ""
102
+ if tags:
103
+ tag_str = " ".join(t.strip() for t in tags.split(",") if t.strip())
104
+ text = f"{text} {tag_str}"
105
+
106
+ text = text.strip()
107
+ if not text:
108
+ return None
109
+
110
+ model = SentenceTransformer("all-MiniLM-L6-v2")
111
+ embedding = model.encode(text, normalize_embeddings=True)
112
+ return embedding.tolist()
113
+
114
+
115
+ def download_video_from_s3(video_s3_key: str) -> str:
116
+ """Download a video from S3 to a temp path. Returns the local file path."""
117
+ from app.core.storage import storage
118
+ from app.core import config
119
+
120
+ suffix = os.path.splitext(video_s3_key)[-1] or ".mp4"
121
+ tmp = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
122
+ tmp.close()
123
+
124
+ try:
125
+ storage.s3_client.download_file(
126
+ config.AWS_STORAGE_BUCKET_NAME,
127
+ video_s3_key,
128
+ tmp.name,
129
+ )
130
+ return tmp.name
131
+ except Exception:
132
+ os.unlink(tmp.name)
133
+ raise
134
+
135
+
136
+ # ---------------------------------------------------------------------------
137
+ # CLIP visual embedding
138
+ # ---------------------------------------------------------------------------
139
+
140
+ # Number of evenly-spaced frames to sample for visual embedding
141
+ _VISUAL_SAMPLE_COUNT = 8
142
+
143
+
144
+ def generate_visual_embedding(frame_s3_keys: List[str]) -> Optional[List[float]]:
145
+ """Compute a single 512-dim visual embedding from a subset of extracted frames.
146
+
147
+ Selects ``_VISUAL_SAMPLE_COUNT`` evenly-spaced frames from the full list,
148
+ downloads them from S3, runs them through CLIP ViT-B/32, averages the
149
+ per-frame embeddings, and L2-normalizes the result.
150
+
151
+ Returns ``None`` when no frames are available or all downloads fail.
152
+ """
153
+ if not frame_s3_keys:
154
+ return None
155
+
156
+ # Pick evenly-spaced frames across the video's duration
157
+ n = len(frame_s3_keys)
158
+ if n <= _VISUAL_SAMPLE_COUNT:
159
+ selected = frame_s3_keys
160
+ else:
161
+ indices = np.linspace(0, n - 1, _VISUAL_SAMPLE_COUNT, dtype=int)
162
+ selected = [frame_s3_keys[i] for i in indices]
163
+
164
+ # Download selected frames from S3 to local temp files
165
+ from app.core.storage import storage
166
+ from app.core import config
167
+
168
+ local_paths: List[str] = []
169
+ for s3_key in selected:
170
+ tmp = tempfile.NamedTemporaryFile(suffix=".jpg", delete=False)
171
+ tmp.close()
172
+ try:
173
+ storage.s3_client.download_file(
174
+ config.AWS_STORAGE_BUCKET_NAME, s3_key, tmp.name
175
+ )
176
+ local_paths.append(tmp.name)
177
+ except Exception:
178
+ logger.warning("Failed to download frame %s from S3 β€” skipping", s3_key)
179
+ try:
180
+ os.unlink(tmp.name)
181
+ except OSError:
182
+ pass
183
+
184
+ if not local_paths:
185
+ return None
186
+
187
+ try:
188
+ from app.services.clip_utils import encode_images
189
+
190
+ frame_embeddings = encode_images(local_paths)
191
+ if frame_embeddings.shape[0] == 0:
192
+ return None
193
+
194
+ # Average + L2-normalize
195
+ avg = frame_embeddings.mean(axis=0)
196
+ norm = np.linalg.norm(avg)
197
+ if norm > 0:
198
+ avg = avg / norm
199
+ return avg.tolist()
200
+ finally:
201
+ for p in local_paths:
202
+ try:
203
+ os.unlink(p)
204
+ except OSError:
205
+ pass
app/services/pgvector_utils.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shared pgvector query helpers.
3
+
4
+ Both hybrid_search.py and recommendations.py call into these utilities
5
+ so the raw cosine-similarity SQL is written exactly once.
6
+ """
7
+ import logging
8
+ from typing import List, Optional, Tuple
9
+
10
+ from sqlalchemy import text
11
+ from sqlalchemy.orm import Session
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def vector_to_str(embedding) -> str:
17
+ """Convert a numpy / list embedding to the literal string pgvector expects."""
18
+ return "[" + ",".join(str(float(v)) for v in embedding) + "]"
19
+
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # Single-column similarity (used by legacy callers / fallback)
23
+ # ---------------------------------------------------------------------------
24
+
25
+ def cosine_similarity_query(
26
+ db: Session,
27
+ embedding_str: str,
28
+ *,
29
+ vector_column: str = "caption_embedding",
30
+ limit: int = 20,
31
+ offset: int = 0,
32
+ status: str = "approved",
33
+ exclude_video_ids: Optional[List[int]] = None,
34
+ ) -> List[Tuple[int, float]]:
35
+ """Run a pgvector cosine-similarity search against media_analysis + videos.
36
+
37
+ Returns [(video_id, similarity_score), ...] ordered by similarity DESC.
38
+
39
+ Parameters
40
+ ----------
41
+ embedding_str : str
42
+ Pre-formatted vector string, e.g. ``"[0.1,0.2,...]"``.
43
+ vector_column : str
44
+ Which pgvector column to compare against (default ``caption_embedding``).
45
+ exclude_video_ids : list[int], optional
46
+ Video IDs to exclude from results (e.g. already-liked videos).
47
+ """
48
+ exclude_clause = ""
49
+ params: dict = {
50
+ "embedding": embedding_str,
51
+ "status": status,
52
+ "limit": limit,
53
+ "offset": offset,
54
+ }
55
+
56
+ if exclude_video_ids:
57
+ exclude_clause = "AND v.id NOT IN :exclude_ids"
58
+ params["exclude_ids"] = tuple(exclude_video_ids)
59
+
60
+ sql = text(f"""
61
+ SELECT ma.video_id,
62
+ (1 - (ma.{vector_column} <=> CAST(:embedding AS vector))) AS similarity
63
+ FROM media_analysis ma
64
+ JOIN videos v ON v.id = ma.video_id
65
+ WHERE ma.{vector_column} IS NOT NULL
66
+ AND v.status = :status
67
+ AND v.video_url IS NOT NULL
68
+ AND v.video_url != ''
69
+ AND ma.status = 'done'
70
+ {exclude_clause}
71
+ ORDER BY ma.{vector_column} <=> CAST(:embedding AS vector)
72
+ LIMIT :limit OFFSET :offset
73
+ """)
74
+
75
+ rows = db.execute(sql, params).fetchall()
76
+ return [(row[0], float(row[1])) for row in rows]
77
+
78
+
79
+ # ---------------------------------------------------------------------------
80
+ # Blended dual-column similarity (caption + visual)
81
+ # ---------------------------------------------------------------------------
82
+
83
+ def blended_cosine_similarity_query(
84
+ db: Session,
85
+ caption_embedding_str: Optional[str],
86
+ visual_embedding_str: Optional[str],
87
+ *,
88
+ caption_weight: float = 0.5,
89
+ visual_weight: float = 0.5,
90
+ limit: int = 20,
91
+ offset: int = 0,
92
+ status: str = "approved",
93
+ exclude_video_ids: Optional[List[int]] = None,
94
+ ) -> List[Tuple[int, float]]:
95
+ """Cosine similarity against both caption and visual embeddings, blended.
96
+
97
+ Returns [(video_id, blended_score), ...] ordered by blended_score DESC.
98
+
99
+ If a video has only one embedding type (the other is NULL), the NULL side
100
+ contributes 0 via COALESCE so the score degrades gracefully rather than
101
+ producing NULL.
102
+
103
+ Either embedding string can be ``None`` (e.g. no visual taste vector
104
+ computed). When one is None, the query falls back to single-column mode
105
+ for that side.
106
+ """
107
+ exclude_clause = ""
108
+ params: dict = {
109
+ "caption_weight": caption_weight,
110
+ "visual_weight": visual_weight,
111
+ "status": status,
112
+ "limit": limit,
113
+ "offset": offset,
114
+ }
115
+
116
+ if exclude_video_ids:
117
+ exclude_clause = "AND v.id NOT IN :exclude_ids"
118
+ params["exclude_ids"] = tuple(exclude_video_ids)
119
+
120
+ # Build per-side COALESCE expressions
121
+ if caption_embedding_str is not None:
122
+ params["caption_vec"] = caption_embedding_str
123
+ caption_expr = "COALESCE(1 - (ma.caption_embedding <=> CAST(:caption_vec AS vector)), 0)"
124
+ else:
125
+ caption_expr = "0"
126
+
127
+ if visual_embedding_str is not None:
128
+ params["visual_vec"] = visual_embedding_str
129
+ visual_expr = "COALESCE(1 - (ma.visual_embedding <=> CAST(:visual_vec AS vector)), 0)"
130
+ else:
131
+ visual_expr = "0"
132
+
133
+ # At least one side must be active, otherwise there's nothing to score
134
+ if caption_embedding_str is None and visual_embedding_str is None:
135
+ return []
136
+
137
+ # We need at least one non-null embedding column to filter on
138
+ if caption_embedding_str is not None and visual_embedding_str is not None:
139
+ non_null_filter = "(ma.caption_embedding IS NOT NULL OR ma.visual_embedding IS NOT NULL)"
140
+ elif caption_embedding_str is not None:
141
+ non_null_filter = "ma.caption_embedding IS NOT NULL"
142
+ else:
143
+ non_null_filter = "ma.visual_embedding IS NOT NULL"
144
+
145
+ sql = text(f"""
146
+ SELECT ma.video_id,
147
+ :caption_weight * {caption_expr}
148
+ + :visual_weight * {visual_expr} AS blended_sim
149
+ FROM media_analysis ma
150
+ JOIN videos v ON v.id = ma.video_id
151
+ WHERE {non_null_filter}
152
+ AND v.status = :status
153
+ AND v.video_url IS NOT NULL
154
+ AND v.video_url != ''
155
+ AND ma.status = 'done'
156
+ {exclude_clause}
157
+ ORDER BY blended_sim DESC
158
+ LIMIT :limit OFFSET :offset
159
+ """)
160
+
161
+ rows = db.execute(sql, params).fetchall()
162
+ return [(row[0], float(row[1])) for row in rows]
163
+
164
+
165
+ # ---------------------------------------------------------------------------
166
+ # Trending fallback (no embeddings required)
167
+ # ---------------------------------------------------------------------------
168
+
169
+ def trending_query(
170
+ db: Session,
171
+ *,
172
+ limit: int = 20,
173
+ offset: int = 0,
174
+ days: int = 7,
175
+ ) -> List[Tuple[int, float]]:
176
+ """Fallback query: most-liked videos from the last *days* days.
177
+
178
+ Returns [(video_id, score), ...] where score is normalised likes_count.
179
+
180
+ Used when a user has no embedding history (new user or no embeddings yet).
181
+ """
182
+ sql = text("""
183
+ SELECT v.id, LEAST(v.likes_count, 1000)::float AS score
184
+ FROM videos v
185
+ WHERE v.status = 'approved'
186
+ AND v.video_url IS NOT NULL
187
+ AND v.video_url != ''
188
+ AND v.created_at >= NOW() - (:days || ' days')::interval
189
+ ORDER BY v.likes_count DESC, v.views DESC
190
+ LIMIT :limit OFFSET :offset
191
+ """)
192
+
193
+ rows = db.execute(sql, {"days": days, "limit": limit, "offset": offset}).fetchall()
194
+ return [(row[0], float(row[1])) for row in rows]
app/services/recommendations.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Content-based video recommendations using pgvector embeddings.
3
+
4
+ Workflow
5
+ --------
6
+ 1. Fetch the user's most-recently-liked videos (up to 50).
7
+ 2. Look up each video's ``media_analysis.caption_embedding`` (vector(384))
8
+ AND ``media_analysis.visual_embedding`` (vector(512)).
9
+ 3. Average each set of non-null embeddings into separate query vectors.
10
+ 4. Run a **blended** pgvector cosine-similarity scan against every published
11
+ video, weighting caption and visual similarity equally (tune via
12
+ ``CAPTION_WEIGHT`` / ``VISUAL_WEIGHT``).
13
+ 5. Exclude videos the user already liked or watched.
14
+
15
+ Trending fallback
16
+ -----------------
17
+ If the user is new (no likes) **or** none of their liked videos have a
18
+ completed embedding yet, the endpoint silently falls back to a trending
19
+ query: most-liked videos from the past 7 days, same response shape. This
20
+ ensures new users always get results rather than an empty list.
21
+ """
22
+ import logging
23
+ from typing import Dict, List, Optional, Tuple
24
+
25
+ import numpy as np
26
+ from sqlalchemy import text
27
+ from sqlalchemy.orm import Session
28
+
29
+ from app.models.models import Like
30
+ from app.models.library import WatchHistory
31
+ from app.services.pgvector_utils import (
32
+ blended_cosine_similarity_query,
33
+ cosine_similarity_query,
34
+ trending_query,
35
+ vector_to_str,
36
+ )
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+ # How many of the user's recent likes to consider for the taste vector
41
+ _MAX_HISTORY = 50
42
+
43
+ # Blending weights β€” adjust to shift ranking between text and visual
44
+ CAPTION_WEIGHT = 0.5
45
+ VISUAL_WEIGHT = 0.5
46
+
47
+
48
+ def _get_liked_video_ids(db: Session, user_id: int) -> List[int]:
49
+ """Return the user's most-recent video like IDs (likes table, video_id IS NOT NULL)."""
50
+ rows = (
51
+ db.query(Like.video_id)
52
+ .filter(Like.user_id == user_id, Like.video_id.isnot(None))
53
+ .order_by(Like.created_at.desc())
54
+ .limit(_MAX_HISTORY)
55
+ .all()
56
+ )
57
+ return [r[0] for r in rows]
58
+
59
+
60
+ def _get_watched_video_ids(db: Session, user_id: int) -> List[int]:
61
+ """Return video IDs the user has liked or watched (exclude set)."""
62
+ liked = set(_get_liked_video_ids(db, user_id))
63
+
64
+ watched_rows = (
65
+ db.query(WatchHistory.video_id)
66
+ .filter(WatchHistory.user_id == user_id)
67
+ .order_by(WatchHistory.watched_at.desc())
68
+ .limit(_MAX_HISTORY)
69
+ .all()
70
+ )
71
+ for row in watched_rows:
72
+ liked.add(row[0])
73
+
74
+ return list(liked)
75
+
76
+
77
+ def _get_user_taste_vectors(
78
+ db: Session, video_ids: List[int]
79
+ ) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]:
80
+ """Average caption and visual embeddings for *video_ids* into query vectors.
81
+
82
+ Returns ``(caption_vector, visual_vector)``. Either can be ``None``
83
+ when none of the videos have that embedding type.
84
+ """
85
+ if not video_ids:
86
+ return None, None
87
+
88
+ rows = db.execute(
89
+ text(
90
+ """
91
+ SELECT ma.caption_embedding, ma.visual_embedding
92
+ FROM media_analysis ma
93
+ WHERE ma.video_id = ANY(:ids)
94
+ AND ma.status = 'done'
95
+ AND (ma.caption_embedding IS NOT NULL OR ma.visual_embedding IS NOT NULL)
96
+ """
97
+ ),
98
+ {"ids": video_ids},
99
+ ).fetchall()
100
+
101
+ if not rows:
102
+ return None, None
103
+
104
+ caption_vecs = []
105
+ visual_vecs = []
106
+ for caption_emb, visual_emb in rows:
107
+ if caption_emb is not None:
108
+ caption_vecs.append(np.array(caption_emb, dtype=np.float32))
109
+ if visual_emb is not None:
110
+ visual_vecs.append(np.array(visual_emb, dtype=np.float32))
111
+
112
+ def _avg_normalise(vecs):
113
+ if not vecs:
114
+ return None
115
+ avg = np.mean(vecs, axis=0)
116
+ norm = np.linalg.norm(avg)
117
+ if norm > 0:
118
+ avg = avg / norm
119
+ return avg
120
+
121
+ return _avg_normalise(caption_vecs), _avg_normalise(visual_vecs)
122
+
123
+
124
+ def _enrich_results(
125
+ db: Session,
126
+ raw: List[Tuple[int, float]],
127
+ ) -> List[Dict]:
128
+ """Hydrate raw (video_id, score) pairs into dicts with video metadata."""
129
+ if not raw:
130
+ return []
131
+
132
+ video_ids = [vid for vid, _ in raw]
133
+ score_map = {vid: score for vid, score in raw}
134
+
135
+ from app.models.models import Video
136
+
137
+ videos = (
138
+ db.query(Video)
139
+ .filter(Video.id.in_(video_ids))
140
+ .all()
141
+ )
142
+ video_map = {v.id: v for v in videos}
143
+
144
+ results = []
145
+ for vid in video_ids:
146
+ v = video_map.get(vid)
147
+ if v is None:
148
+ continue
149
+ results.append({
150
+ "video_id": v.id,
151
+ "title": v.title,
152
+ "thumbnail_url": v.thumbnail_url,
153
+ "cover_url": v.cover_url or v.thumbnail_url,
154
+ "video_type": v.video_type,
155
+ "creator_username": v.owner.username if v.owner else "Unknown",
156
+ "creator_profile_pic": v.owner.profile_pic if v.owner else None,
157
+ "views": v.views,
158
+ "created_at": v.created_at.isoformat() if v.created_at else None,
159
+ "similarity_score": round(score_map[vid], 6),
160
+ })
161
+
162
+ return results
163
+
164
+
165
+ def get_user_recommendations(
166
+ db: Session,
167
+ user_id: int,
168
+ limit: int = 20,
169
+ offset: int = 0,
170
+ ) -> List[Dict]:
171
+ """Return personalised video recommendations for *user_id*.
172
+
173
+ Uses both caption and visual embeddings for blended scoring (50/50 by
174
+ default). Falls back to a trending query (most-liked videos from the
175
+ past 7 days) when the user has no like history or none of their liked
176
+ videos have any completed embeddings.
177
+ """
178
+ liked_ids = _get_liked_video_ids(db, user_id)
179
+ caption_vec, visual_vec = _get_user_taste_vectors(db, liked_ids)
180
+
181
+ exclude_ids = _get_watched_video_ids(db, user_id)
182
+
183
+ if caption_vec is not None or visual_vec is not None:
184
+ caption_str = vector_to_str(caption_vec) if caption_vec is not None else None
185
+ visual_str = vector_to_str(visual_vec) if visual_vec is not None else None
186
+
187
+ if caption_str is not None and visual_str is not None:
188
+ raw = blended_cosine_similarity_query(
189
+ db,
190
+ caption_str,
191
+ visual_str,
192
+ caption_weight=CAPTION_WEIGHT,
193
+ visual_weight=VISUAL_WEIGHT,
194
+ limit=limit,
195
+ offset=offset,
196
+ exclude_video_ids=exclude_ids or None,
197
+ )
198
+ else:
199
+ # Only one embedding type available β€” single-column query
200
+ col = "caption_embedding" if caption_str is not None else "visual_embedding"
201
+ vec = caption_str if caption_str is not None else visual_str
202
+ raw = cosine_similarity_query(
203
+ db,
204
+ vec,
205
+ vector_column=col,
206
+ limit=limit,
207
+ offset=offset,
208
+ exclude_video_ids=exclude_ids or None,
209
+ )
210
+ else:
211
+ logger.info(
212
+ "No taste vectors for user %d β€” falling back to trending", user_id
213
+ )
214
+ raw = trending_query(db, limit=limit, offset=offset)
215
+
216
+ return _enrich_results(db, raw)
app/tasks/event_tasks.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ from datetime import datetime, timezone
4
+
5
+ from celery import shared_task
6
+ from sqlalchemy import text
7
+
8
+ # Bind @shared_task to the Redis-backed worker app
9
+ import app.worker # noqa: F401
10
+ from app.db.session import SessionLocal
11
+ from app.core.redis import redis_client
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ PENDING_KEY = "video_events:pending"
16
+ FAILED_KEY = "video_events:failed"
17
+ BATCH_SIZE = 500
18
+
19
+
20
+ @shared_task(name="tasks.events.flush_video_events")
21
+ def flush_video_events():
22
+ """LPOP up to 500 pending events from Redis and bulk-insert into video_events."""
23
+ events = []
24
+ for _ in range(BATCH_SIZE):
25
+ raw = redis_client.lpop(PENDING_KEY)
26
+ if raw is None:
27
+ break
28
+ try:
29
+ events.append(json.loads(raw))
30
+ except (json.JSONDecodeError, TypeError):
31
+ logger.warning("Skipping malformed event: %s", raw)
32
+
33
+ if not events:
34
+ return
35
+
36
+ db = SessionLocal()
37
+ try:
38
+ db.execute(
39
+ text(
40
+ "INSERT INTO video_events (user_id, video_id, event_type, watch_seconds, session_id, created_at) "
41
+ "VALUES (:user_id, :video_id, :event_type, :watch_seconds, :session_id, now())"
42
+ ),
43
+ events,
44
+ )
45
+ db.commit()
46
+ logger.info("Flushed %d video events to database", len(events))
47
+ except Exception as e:
48
+ db.rollback()
49
+ logger.error("Failed to flush %d video events: %s", len(events), e)
50
+ pipe = redis_client.pipeline()
51
+ for ev in events:
52
+ pipe.rpush(FAILED_KEY, json.dumps(ev))
53
+ pipe.execute()
54
+ finally:
55
+ db.close()
app/tasks/media_tasks.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+ import tempfile
5
+
6
+ from celery import shared_task
7
+
8
+ # Bind @shared_task to the Redis-backed worker app
9
+ import app.worker # noqa: F401
10
+ from app.db.session import SessionLocal
11
+ from app.models.models import Video
12
+ from app.services.media_analysis import (
13
+ extract_frames,
14
+ detect_scene_cuts,
15
+ detect_beats,
16
+ generate_caption_embedding,
17
+ generate_visual_embedding,
18
+ download_video_from_s3,
19
+ )
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ @shared_task(name="tasks.media.analyze_media", max_retries=2, default_retry_delay=120)
25
+ def analyze_media(video_id: int):
26
+ """Download transcoded video, run frame extraction, scene detection,
27
+ beat tracking, and caption embedding, then write results to media_analysis.
28
+
29
+ After completion, fires ``generate_visual_embedding`` as a follow-up task
30
+ so the heavier CLIP work is retryable independently.
31
+ """
32
+
33
+ db = SessionLocal()
34
+ video = None
35
+ local_video_path = None
36
+ status = "processing"
37
+
38
+ try:
39
+ video = db.query(Video).filter(Video.id == video_id).first()
40
+ if not video:
41
+ logger.error("analyze_media: video %s not found", video_id)
42
+ return
43
+
44
+ # Ensure a media_analysis row exists
45
+ from app.models.models import Base
46
+ # Lazy import to avoid circular
47
+ from sqlalchemy import text
48
+ db.execute(
49
+ text(
50
+ "INSERT INTO media_analysis (video_id, status, created_at, updated_at) "
51
+ "VALUES (:vid, 'processing', now(), now()) "
52
+ "ON CONFLICT (video_id) DO UPDATE SET status='processing', updated_at=now()"
53
+ ),
54
+ {"vid": video_id},
55
+ )
56
+ db.commit()
57
+
58
+ # Resolve the S3 key for the master HLS manifest or fallback mp4
59
+ # The transcoded video lives under videos/{task_id}/master.m3u8
60
+ # For analysis we want the MP4 source β€” but after finalization source is deleted.
61
+ # Use the cover/thumbnail as a proxy is not useful.
62
+ # Instead, we re-download from the first quality variant's segments.
63
+ # Actually: the original upload is deleted. We need the HLS stream.
64
+ # For frame extraction, we can use the HLS URL directly via ffmpeg.
65
+ video_s3_key = f"videos/{video.processing_key}/master.m3u8" if video.processing_key else None
66
+
67
+ # Download the video β€” try HLS master first, fall back to direct mp4
68
+ hls_url = video.video_url
69
+ if hls_url:
70
+ # ffmpeg can read HLS directly β€” download to a local mp4 for analysis
71
+ local_video_path = tempfile.mktemp(suffix=".mp4")
72
+ import subprocess
73
+ subprocess.run(
74
+ [
75
+ "ffmpeg", "-i", hls_url,
76
+ "-c", "copy",
77
+ "-bsf:a", "aac_adtstoasc",
78
+ "-y", local_video_path,
79
+ ],
80
+ check=True,
81
+ capture_output=True,
82
+ timeout=900,
83
+ )
84
+ logger.info("Downloaded HLS stream to %s for video %s", local_video_path, video_id)
85
+ else:
86
+ logger.error("analyze_media: no video_url for video %s", video_id)
87
+ status = "failed"
88
+ return
89
+
90
+ # 1) Frame extraction
91
+ frame_paths = extract_frames(local_video_path, str(video_id))
92
+
93
+ # 2) Scene cuts
94
+ scene_cuts = detect_scene_cuts(local_video_path)
95
+
96
+ # 3) Beat detection
97
+ beat_timestamps = detect_beats(local_video_path)
98
+
99
+ # 4) Caption embedding
100
+ caption_embedding = generate_caption_embedding(video.title, video.tags)
101
+
102
+ # Write results
103
+ from sqlalchemy import text as sa_text
104
+ db.execute(
105
+ sa_text(
106
+ "UPDATE media_analysis SET "
107
+ " status = 'done',"
108
+ " frame_sample_paths = :frames,"
109
+ " scene_cuts = :scenes,"
110
+ " beat_timestamps = :beats,"
111
+ " caption_embedding = :embedding,"
112
+ " updated_at = now() "
113
+ "WHERE video_id = :vid"
114
+ ),
115
+ {
116
+ "frames": json.dumps(frame_paths),
117
+ "scenes": json.dumps(scene_cuts),
118
+ "beats": json.dumps(beat_timestamps),
119
+ "embedding": str(caption_embedding) if caption_embedding else None,
120
+ "vid": video_id,
121
+ },
122
+ )
123
+ db.commit()
124
+ logger.info("Media analysis completed for video %s", video_id)
125
+
126
+ # Fire follow-up CLIP visual embedding task (independent retry)
127
+ generate_visual_embedding.delay(video_id)
128
+
129
+ except Exception as e:
130
+ logger.exception("Media analysis failed for video %s: %s", video_id, e)
131
+ status = "failed"
132
+ try:
133
+ if video:
134
+ from sqlalchemy import text as sa_text
135
+ db.execute(
136
+ sa_text(
137
+ "UPDATE media_analysis SET status='failed', updated_at=now() WHERE video_id = :vid"
138
+ ),
139
+ {"vid": video_id},
140
+ )
141
+ db.commit()
142
+ except Exception:
143
+ db.rollback()
144
+ finally:
145
+ if local_video_path and os.path.exists(local_video_path):
146
+ try:
147
+ os.unlink(local_video_path)
148
+ except OSError:
149
+ pass
150
+ db.close()
151
+
152
+
153
+ @shared_task(
154
+ name="tasks.media.generate_visual_embedding",
155
+ max_retries=3,
156
+ default_retry_delay=60,
157
+ autoretry_for=(Exception,),
158
+ retry_backoff=True,
159
+ retry_backoff_max=300,
160
+ retry_jitter=True,
161
+ )
162
+ def generate_visual_embedding(video_id: int):
163
+ """Download representative frames from S3, encode with CLIP ViT-B/32,
164
+ and write the averaged L2-normalized vector to visual_embedding.
165
+
166
+ This task is decoupled from ``analyze_media`` so transient S3 or model
167
+ failures can retry without re-running the full analysis pipeline.
168
+ """
169
+ db = SessionLocal()
170
+ try:
171
+ from sqlalchemy import text as sa_text
172
+
173
+ row = db.execute(
174
+ sa_text(
175
+ "SELECT frame_sample_paths FROM media_analysis "
176
+ "WHERE video_id = :vid AND status = 'done'"
177
+ ),
178
+ {"vid": video_id},
179
+ ).fetchone()
180
+
181
+ if not row or not row[0]:
182
+ logger.warning(
183
+ "generate_visual_embedding: no frame_sample_paths for video %s", video_id
184
+ )
185
+ return
186
+
187
+ frame_s3_keys = row[0]
188
+ from app.services.media_analysis import generate_visual_embedding as _gen
189
+ visual_vec = _gen(frame_s3_keys)
190
+
191
+ if visual_vec is None:
192
+ logger.warning(
193
+ "generate_visual_embedding: could not produce embedding for video %s",
194
+ video_id,
195
+ )
196
+ return
197
+
198
+ from app.services.pgvector_utils import vector_to_str
199
+
200
+ db.execute(
201
+ sa_text(
202
+ "UPDATE media_analysis SET visual_embedding = :vec, updated_at = now() "
203
+ "WHERE video_id = :vid"
204
+ ),
205
+ {"vec": vector_to_str(visual_vec), "vid": video_id},
206
+ )
207
+ db.commit()
208
+ logger.info("Visual embedding written for video %s", video_id)
209
+
210
+ except Exception as e:
211
+ logger.exception("generate_visual_embedding failed for video %s: %s", video_id, e)
212
+ raise # let autoretry handle it
213
+ finally:
214
+ db.close()
app/tasks/video_tasks.py CHANGED
@@ -197,6 +197,13 @@ def _finalize_transcode_success(
197
  except Exception as e:
198
  logger.warning(f"Failed to delete source directory uploads/{task_id}/: {e}")
199
 
 
 
 
 
 
 
 
200
  return {"status": "success", "video_id": video_id}
201
 
202
 
 
197
  except Exception as e:
198
  logger.warning(f"Failed to delete source directory uploads/{task_id}/: {e}")
199
 
200
+ # Fire-and-forget: run media analysis pipeline asynchronously
201
+ try:
202
+ from app.tasks.media_tasks import analyze_media
203
+ analyze_media.delay(video_id)
204
+ except Exception as e:
205
+ logger.warning(f"Failed to enqueue media analysis for video {video_id}: {e}")
206
+
207
  return {"status": "success", "video_id": video_id}
208
 
209
 
app/utils/cloudfront_signer.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CloudFront signed URL generation for direct CDN video streaming.
3
+
4
+ Uses a custom policy with a path wildcard so the signed URL covers:
5
+ - The master manifest (master.m3u8)
6
+ - All segment files (.ts/.m4s) referenced by the manifest
7
+
8
+ AWS requires SHA-1 for CloudFront signing (hard requirement, not a choice).
9
+ """
10
+
11
+ import re
12
+ import logging
13
+ from datetime import datetime, timezone
14
+ from urllib.parse import quote
15
+
16
+ from app.core import config
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ def _rsa_signer(message: bytes) -> bytes:
22
+ from cryptography.hazmat.primitives import hashes, serialization
23
+ from cryptography.hazmat.primitives.asymmetric import padding
24
+
25
+ private_key = serialization.load_pem_private_key(
26
+ config.CLOUDFRONT_PRIVATE_KEY.encode(), password=None
27
+ )
28
+ return private_key.sign(message, padding.PKCS1v15(), hashes.SHA1())
29
+
30
+
31
+ def _get_signer():
32
+ from botocore.signers import CloudFrontSigner
33
+ return CloudFrontSigner(config.CLOUDFRONT_KEY_PAIR_ID, _rsa_signer)
34
+
35
+
36
+ def generate_signed_url(resource_url: str, expires_in_seconds: int = 21600) -> str:
37
+ """
38
+ Generate a CloudFront signed URL with a custom policy.
39
+
40
+ The policy covers the video's directory path with a wildcard (*),
41
+ so the manifest AND all segment files are accessible with one signature.
42
+
43
+ Args:
44
+ resource_url: Full CDN URL to the master manifest, e.g.
45
+ https://d123.cloudfront.net/videos/123/hls/master.m3u8
46
+ expires_in_seconds: Time until the signed URL expires (default 6h).
47
+
48
+ Returns:
49
+ Signed URL string.
50
+ """
51
+ signer = _get_signer()
52
+
53
+ # Build wildcard resource: replace the filename with *
54
+ # https://d123.cloudfront.net/videos/123/hls/master.m3u8
55
+ # β†’ https://d123.cloudfront.net/videos/123/hls/*
56
+ base_path = re.sub(r'[^/]+\.m3u8$', '*', resource_url)
57
+
58
+ expiration = datetime.now(timezone.utc).timestamp() + expires_in_seconds
59
+ expiration_dt = datetime.fromtimestamp(expiration, tz=timezone.utc)
60
+
61
+ policy = signer.build_policy(
62
+ resource=base_path,
63
+ date_less_than=expiration_dt,
64
+ )
65
+
66
+ return signer.generate_presigned_url(
67
+ resource_url,
68
+ policy=policy,
69
+ )
70
+
71
+
72
+ def is_cloudfront_configured() -> bool:
73
+ """Check if CloudFront signing is configured."""
74
+ return bool(config.CLOUDFRONT_KEY_PAIR_ID and config.CLOUDFRONT_PRIVATE_KEY)
app/worker.py CHANGED
@@ -17,6 +17,8 @@ celery_app = Celery(
17
  "app.tasks.video_tasks",
18
  "app.tasks.email_tasks",
19
  "app.tasks.morning_notifications",
 
 
20
  ]
21
  )
22
 
@@ -79,6 +81,11 @@ celery_app.conf.update(
79
  "task": "tasks.email.flush_social_batch",
80
  "schedule": crontab(hour=18, minute=0),
81
  },
 
 
 
 
 
82
  },
83
  )
84
 
 
17
  "app.tasks.video_tasks",
18
  "app.tasks.email_tasks",
19
  "app.tasks.morning_notifications",
20
+ "app.tasks.event_tasks",
21
+ "app.tasks.media_tasks",
22
  ]
23
  )
24
 
 
81
  "task": "tasks.email.flush_social_batch",
82
  "schedule": crontab(hour=18, minute=0),
83
  },
84
+ # Video engagement events β€” flush every 60 seconds
85
+ "flush-video-events": {
86
+ "task": "tasks.events.flush_video_events",
87
+ "schedule": 60.0,
88
+ },
89
  },
90
  )
91
 
main.py CHANGED
@@ -160,14 +160,49 @@ async def websocket_chat(websocket: WebSocket, token: str = Query(...)):
160
  # ── Initialization ────────────────────────────────────────────────────────────
161
  @app.on_event("startup")
162
  async def startup():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  from app.core.config import REDIS_URL
164
- redis = aioredis.from_url(
165
- REDIS_URL,
166
- encoding="utf8",
167
- decode_responses=True,
168
- max_connections=5,
169
- )
170
- FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
 
 
 
 
 
 
171
 
172
  @app.get("/", tags=["System"])
173
  async def root_health():
 
160
  # ── Initialization ────────────────────────────────────────────────────────────
161
  @app.on_event("startup")
162
  async def startup():
163
+ # Ensure database tables exist
164
+ try:
165
+ from app.db.session import engine
166
+ from app.models.models import Base
167
+ Base.metadata.create_all(bind=engine)
168
+ except Exception as db_err:
169
+ logger.warning(f"DB table creation warning: {db_err}")
170
+
171
+ # Guarantee critical columns exist before any ORM query runs.
172
+ try:
173
+ from app.db.session import SessionLocal
174
+ from sqlalchemy import text
175
+ db = SessionLocal()
176
+ try:
177
+ db.execute(text("ALTER TABLE videos ADD COLUMN IF NOT EXISTS cover_url VARCHAR"))
178
+ db.execute(text("ALTER TABLE videos ADD COLUMN IF NOT EXISTS cover_source VARCHAR"))
179
+ db.execute(text("ALTER TABLE upload_jobs ADD COLUMN IF NOT EXISTS video_type VARCHAR"))
180
+ db.execute(text("ALTER TABLE upload_jobs ADD COLUMN IF NOT EXISTS cover_source VARCHAR"))
181
+ db.execute(text("ALTER TABLE upload_jobs ADD COLUMN IF NOT EXISTS cover_s3_key VARCHAR"))
182
+ db.commit()
183
+ logger.info("Critical columns verified in DB")
184
+ except Exception as e:
185
+ db.rollback()
186
+ logger.warning(f"Column guard skipped: {e}")
187
+ finally:
188
+ db.close()
189
+ except Exception as e:
190
+ logger.warning(f"DB column guard skipped: {e}")
191
+
192
  from app.core.config import REDIS_URL
193
+ if REDIS_URL:
194
+ try:
195
+ redis = aioredis.from_url(
196
+ REDIS_URL,
197
+ encoding="utf8",
198
+ decode_responses=True,
199
+ max_connections=5,
200
+ )
201
+ FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
202
+ except Exception as cache_err:
203
+ logger.warning(f"Redis cache initialization skipped: {cache_err}")
204
+ else:
205
+ logger.info("REDIS_URL not set; skipping Redis cache initialization")
206
 
207
  @app.get("/", tags=["System"])
208
  async def root_health():
requirements.txt CHANGED
@@ -28,3 +28,16 @@ brotli
28
  fastapi-cache2[redis]
29
  tenacity
30
  stripe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  fastapi-cache2[redis]
29
  tenacity
30
  stripe
31
+ cryptography
32
+ scenedetect[opencv]
33
+ librosa
34
+ sentence-transformers
35
+ pgvector
36
+ openai
37
+ google-genai
38
+ # ── CLIP visual embeddings (ViT-B/32, 512-dim) ──────────────────────────
39
+ # transformers is already installed via sentence-transformers above.
40
+ # The CLIP model (~350 MB) is downloaded lazily on first use by clip_utils.py.
41
+ # WARNING: This adds ~1.5 GB VRAM/RAM to the Celery worker and API server
42
+ # when the CLIP model is loaded. Monitor worker memory on deployment.
43
+ # transformers # already pulled in by sentence-transformers
scripts/backfill_visual_embeddings.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Backfill visual_embedding for existing media_analysis rows.
3
+
4
+ Queries media_analysis rows where visual_embedding IS NULL but
5
+ frame_sample_paths IS NOT NULL (i.e. the frames exist but the CLIP
6
+ embedding was never computed), runs CLIP encode, and writes the result.
7
+
8
+ Dry-run by default. Pass --apply to execute.
9
+
10
+ Usage:
11
+ python scripts/backfill_visual_embeddings.py # dry-run
12
+ python scripts/backfill_visual_embeddings.py --apply # execute
13
+ python scripts/backfill_visual_embeddings.py --batch-size 20
14
+ """
15
+ import logging
16
+ import os
17
+ import sys
18
+ import time
19
+ from argparse import ArgumentParser
20
+
21
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
22
+
23
+ from sqlalchemy import text
24
+
25
+ from app.core.config import DATABASE_URL
26
+ from app.db.session import SessionLocal
27
+
28
+ logging.basicConfig(
29
+ level=logging.INFO,
30
+ format="%(asctime)s [%(levelname)s] %(message)s",
31
+ )
32
+ logger = logging.getLogger("backfill_visual_embeddings")
33
+
34
+
35
+ def count_pending(db) -> int:
36
+ return db.execute(
37
+ text(
38
+ "SELECT COUNT(*) FROM media_analysis "
39
+ "WHERE status = 'done' "
40
+ "AND visual_embedding IS NULL "
41
+ "AND frame_sample_paths IS NOT NULL"
42
+ )
43
+ ).scalar()
44
+
45
+
46
+ def fetch_batch(db, offset: int, limit: int):
47
+ return db.execute(
48
+ text(
49
+ "SELECT video_id, frame_sample_paths FROM media_analysis "
50
+ "WHERE status = 'done' "
51
+ "AND visual_embedding IS NULL "
52
+ "AND frame_sample_paths IS NOT NULL "
53
+ "ORDER BY video_id "
54
+ "LIMIT :lim OFFSET :off"
55
+ ),
56
+ {"lim": limit, "off": offset},
57
+ ).fetchall()
58
+
59
+
60
+ def main():
61
+ parser = ArgumentParser(description="Backfill visual_embedding for existing media_analysis rows")
62
+ parser.add_argument("--apply", action="store_true", help="Execute updates (default is dry-run)")
63
+ parser.add_argument("--batch-size", type=int, default=10, help="Rows to process per batch")
64
+ parser.add_argument("--sleep", type=float, default=1.0, help="Seconds between batches to avoid hammering CLIP/S3")
65
+ args = parser.parse_args()
66
+
67
+ print("=== Backfill visual_embedding ===\n")
68
+
69
+ db = SessionLocal()
70
+ try:
71
+ total = count_pending(db)
72
+ print(f"Found {total} media_analysis rows missing visual_embedding\n")
73
+
74
+ if total == 0:
75
+ print("Nothing to backfill.")
76
+ return
77
+
78
+ processed = 0
79
+ errors = 0
80
+ offset = 0
81
+
82
+ while offset < total:
83
+ rows = fetch_batch(db, offset, args.batch_size)
84
+ if not rows:
85
+ break
86
+
87
+ for row in rows:
88
+ video_id = row[0]
89
+ frame_s3_keys = row[1]
90
+ logger.info(
91
+ "[%d/%d] Processing video %s (%d frames)",
92
+ offset + 1, total, video_id, len(frame_s3_keys) if frame_s3_keys else 0,
93
+ )
94
+
95
+ if args.apply:
96
+ try:
97
+ from app.services.media_analysis import generate_visual_embedding
98
+ from app.services.pgvector_utils import vector_to_str
99
+
100
+ visual_vec = generate_visual_embedding(frame_s3_keys)
101
+ if visual_vec is None:
102
+ logger.warning(" -> Could not produce embedding for video %s (skipping)", video_id)
103
+ errors += 1
104
+ offset += 1
105
+ continue
106
+
107
+ db.execute(
108
+ text(
109
+ "UPDATE media_analysis "
110
+ "SET visual_embedding = :vec, updated_at = now() "
111
+ "WHERE video_id = :vid"
112
+ ),
113
+ {"vec": vector_to_str(visual_vec), "vid": video_id},
114
+ )
115
+ db.commit()
116
+ processed += 1
117
+ except Exception as e:
118
+ db.rollback()
119
+ logger.exception(" -> Failed for video %s: %s", video_id, e)
120
+ errors += 1
121
+ else:
122
+ # dry-run: just log
123
+ print(f" Would process video {video_id} ({len(frame_s3_keys) or 0} frames)")
124
+ processed += 1
125
+
126
+ offset += 1
127
+
128
+ if args.sleep and args.apply and offset < total:
129
+ time.sleep(args.sleep)
130
+
131
+ print()
132
+ print("=== Summary ===")
133
+ print(f" Total pending: {total}")
134
+ print(f" Processed: {processed}")
135
+ print(f" Errors: {errors}")
136
+ if args.apply:
137
+ print(" Backfill complete.")
138
+ else:
139
+ print(" Dry-run complete. Re-run with --apply to execute.")
140
+
141
+ finally:
142
+ db.close()
143
+
144
+
145
+ if __name__ == "__main__":
146
+ main()
scripts/migrate_covers_to_thumbnails.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Migrate S3 objects from covers/ to thumbnails/ and patch DB URLs.
3
+
4
+ Run from the backend/ directory:
5
+ python scripts/migrate_covers_to_thumbnails.py
6
+
7
+ Dry-run by default. Pass --apply to execute.
8
+ """
9
+ import sys, os, argparse
10
+
11
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
12
+
13
+ from app.core import config
14
+ from app.core.storage import storage
15
+ from app.db.session import SessionLocal
16
+ from sqlalchemy import text
17
+
18
+ BUCKET = config.AWS_STORAGE_BUCKET_NAME
19
+ SRC_PREFIX = "covers/"
20
+ DST_PREFIX = "thumbnails/"
21
+
22
+
23
+ def list_s3_keys(prefix: str) -> list[str]:
24
+ keys = []
25
+ paginator = storage.s3_client.get_paginator("list_objects_v2")
26
+ for page in paginator.paginate(Bucket=BUCKET, Prefix=prefix):
27
+ for obj in page.get("Contents", []):
28
+ keys.append(obj["Key"])
29
+ return keys
30
+
31
+
32
+ def copy_s3_object(src_key: str, dst_key: str):
33
+ copy_source = {"Bucket": BUCKET, "Key": src_key}
34
+ storage.s3_client.copy_object(
35
+ Bucket=BUCKET, CopySource=copy_source, Key=dst_key
36
+ )
37
+
38
+
39
+ def delete_s3_object(key: str):
40
+ storage.s3_client.delete_object(Bucket=BUCKET, Key=key)
41
+
42
+
43
+ def patch_db_urls(db):
44
+ """Replace covers/ with thumbnails/ in thumbnail_url and cover_url columns."""
45
+ for col in ("thumbnail_url", "cover_url"):
46
+ result = db.execute(
47
+ text(f"SELECT id, {col} FROM videos WHERE {col} LIKE :pat"),
48
+ {"pat": f"%/{SRC_PREFIX}%"},
49
+ ).fetchall()
50
+ for row in result:
51
+ old_url = getattr(row, col)
52
+ new_url = old_url.replace(f"/{SRC_PREFIX}", f"/{DST_PREFIX}")
53
+ db.execute(
54
+ text(f"UPDATE videos SET {col} = :new WHERE id = :id"),
55
+ {"new": new_url, "id": row.id},
56
+ )
57
+ print(f" DB [{col}] video {row.id}: {old_url} -> {new_url}")
58
+ db.commit()
59
+
60
+
61
+ def main():
62
+ parser = argparse.ArgumentParser()
63
+ parser.add_argument("--apply", action="store_true", help="Execute (default is dry-run)")
64
+ args = parser.parse_args()
65
+
66
+ apply = args.apply
67
+ mode = "APPLY" if apply else "DRY-RUN"
68
+
69
+ print(f"=== Migrate covers/ -> thumbnails/ [{mode}] ===\n")
70
+
71
+ # 1) S3 migration
72
+ keys = list_s3_keys(SRC_PREFIX)
73
+ print(f"Found {len(keys)} objects under s3://{BUCKET}/{SRC_PREFIX}\n")
74
+
75
+ for key in keys:
76
+ dst_key = DST_PREFIX + key[len(SRC_PREFIX):]
77
+ print(f" {key} -> {dst_key}")
78
+ if apply:
79
+ copy_s3_object(key, dst_key)
80
+ delete_s3_object(key)
81
+
82
+ # 2) DB URL patching
83
+ print("\nPatching database URLs...")
84
+ db = SessionLocal()
85
+ try:
86
+ if apply:
87
+ patch_db_urls(db)
88
+ else:
89
+ for col in ("thumbnail_url", "cover_url"):
90
+ result = db.execute(
91
+ text(f"SELECT id, {col} FROM videos WHERE {col} LIKE :pat"),
92
+ {"pat": f"%/{SRC_PREFIX}%"},
93
+ ).fetchall()
94
+ for row in result:
95
+ old_url = getattr(row, col)
96
+ new_url = old_url.replace(f"/{SRC_PREFIX}", f"/{DST_PREFIX}")
97
+ print(f" DB [{col}] video {row.id}: {old_url} -> {new_url}")
98
+ print(f" ({len(result)} rows would be patched in [{col}])")
99
+
100
+ # Also patch cover_s3_key on upload_jobs (S3 keys, not full URLs)
101
+ src_key_pattern = f"{SRC_PREFIX}%"
102
+ result = db.execute(
103
+ text("SELECT id, cover_s3_key FROM upload_jobs WHERE cover_s3_key LIKE :pat"),
104
+ {"pat": src_key_pattern},
105
+ ).fetchall()
106
+ for row in result:
107
+ old_key = row.cover_s3_key
108
+ new_key = DST_PREFIX + old_key[len(SRC_PREFIX):]
109
+ if apply:
110
+ db.execute(
111
+ text("UPDATE upload_jobs SET cover_s3_key = :new WHERE id = :id"),
112
+ {"new": new_key, "id": row.id},
113
+ )
114
+ print(f" DB [cover_s3_key] job {row.id}: {old_key} -> {new_key}")
115
+ print(f" ({len(result)} upload_job rows with covers/ key)")
116
+ if apply:
117
+ db.commit()
118
+ finally:
119
+ db.close()
120
+
121
+ print(f"\nDone. {'Objects moved and DB patched.' if apply else 'Dry-run complete. Re-run with --apply.'}")
122
+
123
+
124
+ if __name__ == "__main__":
125
+ main()
tests/__init__.py ADDED
File without changes
tests/test_editing_feedback.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for compute_edit_metrics (pure, no I/O)."""
2
+ import math
3
+
4
+ import pytest
5
+
6
+ from app.services.editing_feedback import compute_edit_metrics
7
+
8
+
9
+ def test_empty_cuts():
10
+ """No scene cuts at all (or only 1) β†’ zero metrics."""
11
+ m = compute_edit_metrics([], [1.0, 2.0, 3.0])
12
+ assert m["cut_count"] == 0
13
+ assert m["cut_durations"] == []
14
+ assert m["beat_sync_score"] == 0.0
15
+
16
+ m2 = compute_edit_metrics([0.5], [1.0, 2.0])
17
+ assert m2["cut_count"] == 0
18
+
19
+
20
+ def test_perfect_beat_sync():
21
+ """Every cut lands exactly on a beat β†’ 100% sync."""
22
+ cuts = [0.0, 1.0, 2.0, 3.0, 4.0]
23
+ beats = [0.0, 1.0, 2.0, 3.0, 4.0]
24
+ m = compute_edit_metrics(cuts, beats)
25
+ assert m["cut_count"] == 4
26
+ assert m["beat_sync_score"] == 100.0
27
+ assert all(abs(o) <= 150 for o in m["beat_offsets_ms"])
28
+
29
+
30
+ def test_no_beat_sync():
31
+ """Cuts far from any beat β†’ 0% sync."""
32
+ cuts = [0.0, 5.0, 10.0, 15.0]
33
+ beats = [1.0, 2.0, 3.0] # all far (>150 ms) from 5, 10, 15
34
+ m = compute_edit_metrics(cuts, beats)
35
+ assert m["cut_count"] == 3
36
+ assert m["beat_sync_score"] == 0.0
37
+
38
+
39
+ def test_partial_beat_sync():
40
+ """Half of cuts within tolerance β†’ 50% sync."""
41
+ cuts = [0.0, 1.0, 5.0, 6.0] # cuts at 1.0 and 6.0 are on beats; 0.0 ignored (first), 5.0 is far
42
+ beats = [1.0, 2.0, 6.0, 7.0]
43
+ m = compute_edit_metrics(cuts, beats)
44
+ # cut transitions: 0β†’1 (1.0 is on beat), 1β†’5 (5.0 is ~3s from nearest beat 6.0 β†’ off), 5β†’6 (6.0 is on beat)
45
+ assert m["cut_count"] == 3
46
+ assert m["beat_sync_score"] == 66.7 # 2/3
47
+
48
+
49
+ def test_cut_durations():
50
+ """Basic duration stats."""
51
+ cuts = [0.0, 2.0, 5.0, 9.0] # durations: 2, 3, 4
52
+ m = compute_edit_metrics(cuts, [])
53
+ assert m["cut_durations"] == [2.0, 3.0, 4.0]
54
+ assert m["avg_cut_duration"] == 3.0
55
+ assert m["min_cut_duration"] == 2.0
56
+ assert m["max_cut_duration"] == 4.0
57
+ assert m["total_duration_seconds"] == 9.0
58
+
59
+
60
+ def test_std_dev_single_value():
61
+ """A single cut β†’ std dev is 0 (no variance)."""
62
+ cuts = [0.0, 3.0]
63
+ m = compute_edit_metrics(cuts, [])
64
+ assert m["cut_count"] == 1
65
+ assert m["cut_durations"] == [3.0]
66
+ assert m["std_cut_duration"] == 0.0
67
+
68
+
69
+ def test_std_dev_multiple():
70
+ """Multiple cuts produce non-zero std dev (uses sample std dev, n-1 divisor)."""
71
+ cuts = [0.0, 1.0, 3.0, 7.0] # durations: 1, 2, 4
72
+ m = compute_edit_metrics(cuts, [])
73
+ # statistics.stdev uses sample std dev (n-1 divisor)
74
+ mean = (1 + 2 + 4) / 3 # 7/3 β‰ˆ 2.333
75
+ variance = ((1 - mean)**2 + (2 - mean)**2 + (4 - mean)**2) / (3 - 1)
76
+ expected_std = math.sqrt(variance) # β‰ˆ 1.528
77
+ assert m["std_cut_duration"] == pytest.approx(expected_std, rel=1e-3)
78
+
79
+
80
+ def test_beat_offsets_ms():
81
+ """Verify offset calculation in ms."""
82
+ cuts = [0.0, 1.5, 3.0]
83
+ beats = [1.0, 2.0, 3.0]
84
+ m = compute_edit_metrics(cuts, beats)
85
+ # Cut at 1.5: nearest beat is 1.0 or 2.0 (offset = +500ms or -500ms) β†’ 500ms
86
+ # Cut at 3.0: nearest beat is 3.0 (offset = 0ms)
87
+ offsets = m["beat_offsets_ms"]
88
+ assert len(offsets) == 2
89
+ # first offset: |1.5 - 1.0| = 0.5s vs |1.5 - 2.0| = 0.5s β†’ 0.5s = 500ms
90
+ assert abs(offsets[0]) == 500.0
91
+ assert offsets[1] == 0.0
92
+
93
+
94
+ def test_avg_and_total_duration():
95
+ """Check total duration and average."""
96
+ cuts = [10.0, 15.0, 25.0, 40.0]
97
+ m = compute_edit_metrics(cuts, [])
98
+ assert m["total_duration_seconds"] == 30.0 # 40 - 10
99
+ assert m["avg_cut_duration"] == 10.0 # (5+10+15)/3
100
+ assert m["cut_durations"] == [5.0, 10.0, 15.0]
101
+
102
+
103
+ def test_empty_beats():
104
+ """No beats at all should not crash."""
105
+ cuts = [0.0, 2.0, 4.0]
106
+ m = compute_edit_metrics(cuts, [])
107
+ assert m["cut_count"] == 2
108
+ assert m["beat_sync_score"] == 0.0
109
+ assert m["beat_offsets_ms"] == [0.0, 0.0]
110
+ assert m["total_beats"] == 0