-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.py
More file actions
1815 lines (1550 loc) · 72.1 KB
/
test.py
File metadata and controls
1815 lines (1550 loc) · 72.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
from datetime import datetime, timedelta
from flask import Flask, render_template, request, redirect, url_for, flash, send_from_directory, abort, jsonify, Blueprint
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import inspect, text, func
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
from jinja2 import DictLoader
import cv2
import random
from collections import Counter, defaultdict
import math
import voice
import speech_recognition as sr
import static_ffmpeg
import uuid
import shutil
import subprocess
import json
import threading
from vosk import Model, KaldiRecognizer
import wave
import markdown
import bleach
__version__ = '1.0.1'
# ==========================================
# CONFIGURATION
# ==========================================
# file system and app configuration
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
UPLOAD_FOLDER = os.path.join(BASE_DIR, 'uploads')
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('VIEWFLOW_SECRET', 'dev-secret-key-gautham-deepak')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(BASE_DIR, 'viewflow.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 * 1024 # 16GB max
# Markdown Filter
@app.template_filter('markdown')
def markdown_filter(text):
if not text:
return ""
# Convert markdown to HTML
html = markdown.markdown(text)
# Sanitize HTML
allowed_tags = ['p', 'strong', 'em', 'ul', 'ol', 'li', 'a', 'br', 'h1', 'h2', 'h3', 'blockquote', 'code', 'pre']
allowed_attrs = {'a': ['href', 'title', 'target']}
clean_html = bleach.clean(html, tags=allowed_tags, attributes=allowed_attrs, strip=True)
return clean_html
app.config['VOSK_MODEL_PATH'] = os.environ.get('VOSK_MODEL_PATH', os.path.join(UPLOAD_FOLDER, 'models', 'vosk-model-small-en-us-0.15'))
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'auth.login'
ALLOWED_VIDEO_EXTENSIONS = {'mp4', 'avi', 'mov', 'mkv'}
ALLOWED_IMAGE_EXTENSIONS = {'jpg', 'jpeg', 'png', 'gif', 'webp'}
# Use filesystem templates from the `templates/` directory so edits there are reflected.
# If you prefer the in-memory templates for tests, uncomment the DictLoader block below.
# app.jinja_loader = DictLoader({
# 'base.html': BASE_HTML,
# 'home.html': HOME_HTML,
# 'watch.html': WATCH_HTML,
# 'login.html': LOGIN_HTML,
# 'register.html': REGISTER_HTML,
# 'upload.html': UPLOAD_HTML
# })
# ==========================================
# DATABASE MODELS
# ==========================================
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(150), unique=True, nullable=False)
email = db.Column(db.String(150), unique=True, nullable=False)
password = db.Column(db.String(200), nullable=False)
display_name = db.Column(db.String(150), nullable=True)
date_joined = db.Column(db.DateTime, default=datetime.utcnow)
location = db.Column(db.String(200), nullable=True)
date_of_birth = db.Column(db.Date, nullable=True)
gender = db.Column(db.String(50), nullable=True)
profile_pic = db.Column(db.String(300), nullable=True)
bio = db.Column(db.Text, nullable=True)
notifications_enabled = db.Column(db.Boolean, default=True)
videos = db.relationship('Video', backref='uploader', lazy=True)
@property
def age(self):
if not self.date_of_birth:
return None
today = datetime.utcnow().date()
return today.year - self.date_of_birth.year - ((today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day))
class Video(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
description = db.Column(db.Text, nullable=True)
filename = db.Column(db.String(100), nullable=False)
thumbnail = db.Column(db.String(200), nullable=True)
category = db.Column(db.String(100), nullable=True)
tags = db.Column(db.String(500), nullable=True)
views = db.Column(db.Integer, default=0)
upload_date = db.Column(db.DateTime, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
is_public = db.Column(db.Boolean, default=True)
resolutions = db.Column(db.String(200), nullable=True) # JSON string: ["720p", "480p"]
height = db.Column(db.Integer, nullable=True)
status = db.Column(db.String(20), default='ready')
heatmap = db.Column(db.Text, default='[]')
preview_images = db.Column(db.Text, nullable=True)
captions = db.Column(db.String(300), nullable=True)
is_short = db.Column(db.Boolean, default=False)
class Playlist(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
is_public = db.Column(db.Boolean, default=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
user = db.relationship('User', backref='playlists', lazy=True)
videos = db.relationship('PlaylistVideo', backref='playlist', lazy=True, cascade="all, delete-orphan")
class PlaylistVideo(db.Model):
id = db.Column(db.Integer, primary_key=True)
playlist_id = db.Column(db.Integer, db.ForeignKey('playlist.id'), nullable=False)
video_id = db.Column(db.Integer, db.ForeignKey('video.id'), nullable=False)
added_at = db.Column(db.DateTime, default=datetime.utcnow)
video = db.relationship('Video', lazy=True)
class WatchLater(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
video_id = db.Column(db.Integer, db.ForeignKey('video.id'), nullable=False)
added_at = db.Column(db.DateTime, default=datetime.utcnow)
user = db.relationship('User', backref='watch_later', lazy=True)
video = db.relationship('Video', lazy=True)
class Subscription(db.Model):
id = db.Column(db.Integer, primary_key=True)
subscriber_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
channel_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
class Reaction(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
video_id = db.Column(db.Integer, db.ForeignKey('video.id'), nullable=False)
# type: 1 = like, -1 = dislike
type = db.Column(db.Integer, nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.Text, nullable=False)
date_posted = db.Column(db.DateTime, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
video_id = db.Column(db.Integer, db.ForeignKey('video.id'), nullable=False)
user = db.relationship('User', backref='comments', lazy=True)
video = db.relationship('Video', backref=db.backref('comments', lazy=True, cascade="all, delete-orphan"))
class ViewHistory(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
video_id = db.Column(db.Integer, db.ForeignKey('video.id'), nullable=False)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
user = db.relationship('User', backref='view_history', lazy=True)
video = db.relationship('Video', backref='view_events', lazy=True)
class Notification(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
message = db.Column(db.String(500), nullable=False)
link = db.Column(db.String(500), nullable=True)
is_read = db.Column(db.Boolean, default=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
user = db.relationship('User', backref='notifications', lazy=True)
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
# ==========================================
# UTILITIES
# ==========================================
def allowed_file(filename, file_type='video'):
"""Check if file extension is allowed.
file_type can be 'video' or 'image'
"""
if not filename or '.' not in filename:
return False
ext = filename.rsplit('.', 1)[1].lower()
if file_type == 'video':
return ext in ALLOWED_VIDEO_EXTENSIONS
elif file_type == 'image':
return ext in ALLOWED_IMAGE_EXTENSIONS
return False
def generate_thumbnail(video_path, output_path):
"""Generate a thumbnail from a random frame in the video"""
try:
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
return None
# Get total frames
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if total_frames <= 0:
cap.release()
return None
# Pick a random frame (avoid first and last 10%)
start_frame = int(total_frames * 0.1)
end_frame = int(total_frames * 0.9)
random_frame = random.randint(start_frame, end_frame) if end_frame > start_frame else total_frames // 2
# Set frame position
cap.set(cv2.CAP_PROP_POS_FRAMES, random_frame)
ret, frame = cap.read()
cap.release()
if ret:
# Resize to standard thumbnail size (320x180)
thumbnail = cv2.resize(frame, (320, 180))
cv2.imwrite(output_path, thumbnail)
return True
return None
except Exception as e:
print(f"Error generating thumbnail: {e}")
return None
# ==========================================
# RECOMMENDATION ENGINE
# ==========================================
def get_user_profile_vector(user_id):
"""
Builds a weighted feature vector for the user based on watch history.
Features: Categories, Tags, Channels.
Weights: Recency (Decay), Frequency (Replays), Context (Last 2 videos).
"""
# Get last 50 views for long-term profile
history = ViewHistory.query.filter_by(user_id=user_id).order_by(ViewHistory.timestamp.desc()).limit(50).all()
if not history:
return None
# 1. Analyze Replays (Frequency)
video_counts = Counter([h.video_id for h in history])
# 2. Build User Profile Vector
user_vector = defaultdict(float)
# Hyperparameters
WEIGHT_CATEGORY = 3.0
WEIGHT_TAG = 1.0
WEIGHT_CHANNEL = 2.0
DECAY_FACTOR = 0.95 # 5% decay per step back in history
# Short-term context (Last 2 videos) - "Current Mood"
last_2_ids = [h.video_id for h in history[:2]]
for idx, h in enumerate(history):
if not h.video:
continue
# Time Decay: Recent views have higher weight
recency_weight = pow(DECAY_FACTOR, idx)
# Replay Multiplier: Boost if watched multiple times
# Logarithmic scaling to prevent spamming from dominating
replay_count = video_counts[h.video_id]
replay_mult = 1.0 + math.log(replay_count) if replay_count > 1 else 1.0
# Short-term Context Boost: Massive boost for the immediate previous videos
context_boost = 2.5 if h.video_id in last_2_ids else 1.0
# Final Event Weight
final_weight = recency_weight * replay_mult * context_boost
# Feature Extraction & Weighting
if h.video.category:
user_vector[f"cat:{h.video.category}"] += WEIGHT_CATEGORY * final_weight
if h.video.tags:
# tags are comma separated
t_list = [t.strip().lower() for t in h.video.tags.split(',') if t.strip()]
for tag in t_list:
user_vector[f"tag:{tag}"] += WEIGHT_TAG * final_weight
user_vector[f"chan:{h.video.user_id}"] += WEIGHT_CHANNEL * final_weight
return user_vector
def get_recommendations(user_id, limit=4, exclude_video_ids=None):
if not user_id:
return []
user_vector = get_user_profile_vector(user_id)
if not user_vector:
return []
# Fetch candidate videos (public videos)
query = Video.query.filter_by(is_public=True)
if exclude_video_ids:
query = query.filter(~Video.id.in_(exclude_video_ids))
candidates = query.all()
scored_videos = []
for vid in candidates:
score = 0
# Dot Product: User Vector • Video Feature Vector
# Category Match
if vid.category:
score += user_vector.get(f"cat:{vid.category}", 0)
# Tag Match
if vid.tags:
v_tags = [t.strip().lower() for t in vid.tags.split(',') if t.strip()]
for t in v_tags:
score += user_vector.get(f"tag:{t}", 0)
# Channel Match
score += user_vector.get(f"chan:{vid.user_id}", 0)
if score > 0:
# Add a tiny random noise to break ties and add serendipity
score += random.uniform(0, 0.5)
scored_videos.append((score, vid))
# Sort by score desc
scored_videos.sort(key=lambda x: x[0], reverse=True)
return [v for s, v in scored_videos[:limit]]
def get_channel_recommendation(user_id):
user_vector = get_user_profile_vector(user_id)
if not user_vector:
return None, []
# Extract channel scores from the vector
channel_scores = {}
for key, score in user_vector.items():
if key.startswith("chan:"):
chan_id = int(key.split(":")[1])
channel_scores[chan_id] = score
if not channel_scores:
return None, []
# Get top channel by score
top_channel_id = max(channel_scores, key=channel_scores.get)
channel = User.query.get(top_channel_id)
if not channel:
return None, []
# Get videos from this channel
videos = Video.query.filter_by(user_id=top_channel_id, is_public=True).order_by(Video.upload_date.desc()).limit(4).all()
return channel, videos
# ==========================================
# BLUEPRINTS
# ==========================================
auth_bp = Blueprint('auth', __name__)
main_bp = Blueprint('main', __name__)
@main_bp.app_template_filter('format_date')
def format_date(date):
if not date:
return 'Unknown'
return date.strftime('%b %d, %Y')
# --------------------------
# Database / Uploads Init
# --------------------------
def init_db():
"""Create uploads directory, database tables, and run best-effort migrations.
This is executed on app import so the test server can start even if the DB
file does not yet exist.
"""
# ensure uploads dir exists
try:
os.makedirs(app.config.get('UPLOAD_FOLDER', UPLOAD_FOLDER), exist_ok=True)
except Exception:
pass
with app.app_context():
try:
db.create_all()
print("Database initialized.")
except Exception:
# continue even if create_all fails
pass
# best-effort sqlite ALTER TABLE migrations for test environment
try:
inspector = inspect(db.engine)
# video table columns
try:
video_cols = [c['name'] for c in inspector.get_columns('video')]
except Exception:
video_cols = []
with db.engine.connect() as conn:
if 'is_public' not in video_cols:
try:
conn.execute(text("ALTER TABLE video ADD COLUMN is_public BOOLEAN DEFAULT 1"))
conn.commit()
except Exception:
pass
if 'thumbnail' not in video_cols:
try:
conn.execute(text("ALTER TABLE video ADD COLUMN thumbnail VARCHAR(200)"))
conn.commit()
except Exception:
pass
if 'category' not in video_cols:
try:
conn.execute(text("ALTER TABLE video ADD COLUMN category VARCHAR(100)"))
conn.commit()
except Exception:
pass
if 'tags' not in video_cols:
try:
conn.execute(text("ALTER TABLE video ADD COLUMN tags VARCHAR(500)"))
conn.commit()
except Exception:
pass
if 'resolutions' not in video_cols:
try:
conn.execute(text("ALTER TABLE video ADD COLUMN resolutions VARCHAR(200)"))
conn.commit()
except Exception:
pass
if 'height' not in video_cols:
try:
conn.execute(text("ALTER TABLE video ADD COLUMN height INTEGER"))
conn.commit()
except Exception:
pass
if 'status' not in video_cols:
try:
conn.execute(text("ALTER TABLE video ADD COLUMN status VARCHAR(20) DEFAULT 'ready'"))
conn.commit()
except Exception:
pass
if 'heatmap' not in video_cols:
try:
conn.execute(text("ALTER TABLE video ADD COLUMN heatmap TEXT DEFAULT '[]'"))
conn.commit()
except Exception:
pass
if 'preview_images' not in video_cols:
try:
conn.execute(text("ALTER TABLE video ADD COLUMN preview_images TEXT"))
conn.commit()
except Exception:
pass
if 'captions' not in video_cols:
try:
conn.execute(text("ALTER TABLE video ADD COLUMN captions VARCHAR(300)"))
conn.commit()
except Exception:
pass
if 'is_short' not in video_cols:
try:
conn.execute(text("ALTER TABLE video ADD COLUMN is_short BOOLEAN DEFAULT 0"))
conn.commit()
except Exception:
pass
# user table columns
try:
user_cols = [c['name'] for c in inspector.get_columns('user')]
except Exception:
user_cols = []
with db.engine.connect() as conn:
if 'display_name' not in user_cols:
try:
conn.execute(text("ALTER TABLE user ADD COLUMN display_name VARCHAR(150)"))
conn.commit()
except Exception:
pass
if 'location' not in user_cols:
try:
conn.execute(text("ALTER TABLE user ADD COLUMN location VARCHAR(200)"))
conn.commit()
except Exception:
pass
if 'age' not in user_cols:
try:
conn.execute(text("ALTER TABLE user ADD COLUMN age INTEGER"))
conn.commit()
except Exception:
pass
if 'date_joined' not in user_cols:
try:
conn.execute(text("ALTER TABLE user ADD COLUMN date_joined DATETIME"))
conn.commit()
except Exception:
pass
if 'gender' not in user_cols:
try:
conn.execute(text("ALTER TABLE user ADD COLUMN gender VARCHAR(50)"))
conn.commit()
except Exception:
pass
if 'profile_pic' not in user_cols:
try:
conn.execute(text("ALTER TABLE user ADD COLUMN profile_pic VARCHAR(300)"))
conn.commit()
except Exception:
pass
if 'bio' not in user_cols:
try:
conn.execute(text("ALTER TABLE user ADD COLUMN bio TEXT"))
conn.commit()
except Exception:
pass
if 'notifications_enabled' not in user_cols:
try:
conn.execute(text("ALTER TABLE user ADD COLUMN notifications_enabled BOOLEAN DEFAULT 1"))
conn.commit()
except Exception:
pass
except Exception:
# if inspector or engine access fails, just continue
pass
# Initialize DB and uploads at import time so the app is ready on start
init_db()
@main_bp.route('/')
def home():
# Base query for visible videos
base_query = Video.query.filter_by(status='ready')
if current_user.is_authenticated:
base_query = base_query.filter((Video.is_public == True) | (Video.user_id == current_user.id))
else:
base_query = base_query.filter_by(is_public=True)
# 1. Latest (Sort by date)
latest = base_query.order_by(Video.upload_date.desc()).limit(4).all()
# 2. Trending (Sort by views)
trending = base_query.order_by(Video.views.desc()).limit(4).all()
# 3. For You & 4. From Channel (Personalized)
for_you = []
featured_channel = None
channel_videos = []
show_extra_sections = False
if current_user.is_authenticated:
try:
# Check if user has any history
has_history = ViewHistory.query.filter_by(user_id=current_user.id).count() > 0
if has_history:
for_you = get_recommendations(current_user.id, limit=4)
featured_channel, channel_videos = get_channel_recommendation(current_user.id)
show_extra_sections = True
else:
# New user: Fill For You with random/trending, hide others
all_public = Video.query.filter_by(is_public=True).all()
for_you = random.sample(all_public, min(len(all_public), 4)) if all_public else []
show_extra_sections = False
except Exception as e:
print(f"Recommendation error: {e}")
# Fallback on error
all_public = Video.query.filter_by(is_public=True).all()
for_you = random.sample(all_public, min(len(all_public), 4)) if all_public else []
else:
# Guest: Fill For You with random, hide others
all_public = Video.query.filter_by(is_public=True).all()
for_you = random.sample(all_public, min(len(all_public), 4)) if all_public else []
show_extra_sections = False
# If we are hiding extra sections, clear them
if not show_extra_sections:
latest = []
trending = []
featured_channel = None
channel_videos = []
return render_template('home.html', title='Home',
for_you=for_you,
latest=latest,
trending=trending,
featured_channel=featured_channel,
channel_videos=channel_videos)
@main_bp.route('/playlists')
@login_required
def playlists():
user_playlists = Playlist.query.filter_by(user_id=current_user.id).order_by(Playlist.created_at.desc()).all()
return render_template('playlists.html', title='My Playlists', playlists=user_playlists)
@main_bp.route('/playlist/create', methods=['POST'])
@login_required
def create_playlist():
name = request.form.get('name')
if name:
p = Playlist(name=name, user_id=current_user.id)
db.session.add(p)
db.session.commit()
flash('Playlist created')
return redirect(url_for('main.playlists'))
@main_bp.route('/playlist/<int:playlist_id>')
def view_playlist(playlist_id):
playlist = Playlist.query.get_or_404(playlist_id)
if not playlist.is_public and (not current_user.is_authenticated or current_user.id != playlist.user_id):
abort(403)
videos = [pv.video for pv in playlist.videos]
return render_template('playlist.html', title=playlist.name, playlist=playlist, videos=videos)
@main_bp.route('/playlist/<int:playlist_id>/add/<int:video_id>', methods=['POST'])
@login_required
def add_to_playlist(playlist_id, video_id):
playlist = Playlist.query.get_or_404(playlist_id)
if playlist.user_id != current_user.id:
abort(403)
exists = PlaylistVideo.query.filter_by(playlist_id=playlist_id, video_id=video_id).first()
if not exists:
pv = PlaylistVideo(playlist_id=playlist_id, video_id=video_id)
db.session.add(pv)
db.session.commit()
if is_ajax(request):
return jsonify({'success': True, 'is_saved_in_any': True})
flash('Added to playlist')
else:
if is_ajax(request):
return jsonify({'success': False, 'message': 'Already in playlist', 'is_saved_in_any': True})
return redirect(url_for('main.watch', video_id=video_id))
@main_bp.route('/playlist/<int:playlist_id>/remove/<int:video_id>', methods=['POST'])
@login_required
def remove_from_playlist(playlist_id, video_id):
playlist = Playlist.query.get_or_404(playlist_id)
if playlist.user_id != current_user.id:
abort(403)
pv = PlaylistVideo.query.filter_by(playlist_id=playlist_id, video_id=video_id).first()
if pv:
db.session.delete(pv)
db.session.commit()
# Check if saved in any other playlist
user_playlists = Playlist.query.filter_by(user_id=current_user.id).all()
is_saved_in_any = False
if user_playlists:
p_ids = [p.id for p in user_playlists]
is_saved_in_any = PlaylistVideo.query.filter(PlaylistVideo.playlist_id.in_(p_ids), PlaylistVideo.video_id == video_id).first() is not None
if is_ajax(request):
return jsonify({'success': True, 'is_saved_in_any': is_saved_in_any})
flash('Removed from playlist')
return redirect(url_for('main.view_playlist', playlist_id=playlist_id))
@main_bp.route('/watch-later')
@login_required
def watch_later():
wl_items = WatchLater.query.filter_by(user_id=current_user.id).order_by(WatchLater.added_at.desc()).all()
videos = [item.video for item in wl_items]
return render_template('watch_later.html', title='Watch Later', videos=videos)
@main_bp.route('/watch-later/add/<int:video_id>', methods=['POST'])
@login_required
def add_to_watch_later(video_id):
exists = WatchLater.query.filter_by(user_id=current_user.id, video_id=video_id).first()
if not exists:
wl = WatchLater(user_id=current_user.id, video_id=video_id)
db.session.add(wl)
db.session.commit()
if is_ajax(request):
return jsonify({'success': True, 'in_watch_later': True})
flash('Added to Watch Later')
else:
if is_ajax(request):
return jsonify({'success': False, 'message': 'Already in Watch Later', 'in_watch_later': True})
return redirect(url_for('main.watch', video_id=video_id))
@main_bp.route('/watch-later/remove/<int:video_id>', methods=['POST'])
@login_required
def remove_from_watch_later(video_id):
wl = WatchLater.query.filter_by(user_id=current_user.id, video_id=video_id).first()
if wl:
db.session.delete(wl)
db.session.commit()
if is_ajax(request):
return jsonify({'success': True, 'in_watch_later': False})
flash('Removed from Watch Later')
else:
if is_ajax(request):
return jsonify({'success': False, 'in_watch_later': False})
return redirect(url_for('main.watch_later'))
@main_bp.route('/search')
def search():
query = request.args.get('q', '').strip()
if not query:
return redirect(url_for('main.home'))
# Process natural language/voice commands
clean_query = voice.process_command(query)
# Search in video title, description, and uploader name
search_pattern = f"%{clean_query}%"
videos = Video.query.join(Video.uploader).filter(
(Video.is_public == True) &
(
(Video.title.ilike(search_pattern)) |
(Video.description.ilike(search_pattern)) |
(User.username.ilike(search_pattern)) |
(User.display_name.ilike(search_pattern))
)
).order_by(Video.upload_date.desc()).all()
return render_template('search.html', title=f"Search: {clean_query}", query=clean_query, videos=videos)
@main_bp.route('/search/suggestions')
def search_suggestions():
query = request.args.get('q', '').strip()
suggestions = []
if query:
# Search for videos matching the query
# Use ilike for case-insensitive search if supported, or just contains
videos = Video.query.filter(Video.title.contains(query)).filter_by(is_public=True).limit(5).all()
suggestions = [{'text': v.title, 'type': 'video'} for v in videos]
else:
# Return trending (most viewed videos) as a proxy for trending searches
trending = Video.query.filter_by(is_public=True).order_by(Video.views.desc()).limit(5).all()
suggestions = [{'text': v.title, 'type': 'trending'} for v in trending]
return jsonify(suggestions)
@main_bp.route('/voice_search', methods=['POST'])
def voice_search_api():
if 'audio' not in request.files:
return jsonify({'error': 'No audio file provided'}), 400
audio_file = request.files['audio']
if audio_file.filename == '':
return jsonify({'error': 'No selected file'}), 400
try:
static_ffmpeg.add_paths()
except Exception:
pass
# Save temporary file
unique_id = str(uuid.uuid4())
temp_webm = os.path.join(app.config['UPLOAD_FOLDER'], f'temp_voice_{unique_id}.webm')
temp_wav = os.path.join(app.config['UPLOAD_FOLDER'], f'temp_voice_{unique_id}.wav')
try:
if not shutil.which('ffmpeg'):
# Fallback: try to find it in static_ffmpeg location manually if add_paths failed
import sys
bin_path = os.path.join(sys.prefix, 'bin')
if os.path.exists(os.path.join(bin_path, 'ffmpeg')):
os.environ["PATH"] += os.pathsep + bin_path
if not shutil.which('ffmpeg'):
return jsonify({'error': 'Server Error: ffmpeg binary not found'}), 500
audio_file.save(temp_webm)
# Convert WebM to WAV using ffmpeg (SpeechRecognition needs WAV/AIFF/FLAC)
# -y to overwrite, -ac 1 for mono (optional but good for SR)
cmd = ['ffmpeg', '-i', temp_webm, '-ac', '1', '-ar', '16000', temp_wav, '-y']
subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
# Try Offline (Vosk) first if model exists
model_path = app.config.get('VOSK_MODEL_PATH')
if model_path and os.path.exists(model_path):
try:
model = Model(model_path)
wf = wave.open(temp_wav, "rb")
rec = KaldiRecognizer(model, wf.getframerate())
rec.SetWords(True)
result_text = ""
while True:
data = wf.readframes(4000)
if len(data) == 0:
break
if rec.AcceptWaveform(data):
pass
else:
pass
final_res = json.loads(rec.FinalResult())
text = final_res.get('text', '')
wf.close()
if text:
return jsonify({'text': text})
except Exception as e:
print(f"Vosk error: {e}")
# Fallback to Google if Vosk fails
r = sr.Recognizer()
with sr.AudioFile(temp_wav) as source:
audio_data = r.record(source)
# Try Google first (high accuracy, requires internet on server)
try:
text = r.recognize_google(audio_data)
return jsonify({'text': text})
except sr.UnknownValueError:
return jsonify({'error': 'Could not understand audio'}), 400
except sr.RequestError as e:
print(f"Speech service error: {e}")
return jsonify({'error': 'Speech service unavailable'}), 503
except subprocess.CalledProcessError as e:
err_msg = e.stderr.decode() if e.stderr else str(e)
print(f"FFmpeg error: {err_msg}")
return jsonify({'error': 'Audio conversion failed'}), 500
except Exception as e:
print(f"Voice search error: {e}")
import traceback
traceback.print_exc()
return jsonify({'error': 'Voice processing failed'}), 500
finally:
# Cleanup
if os.path.exists(temp_webm):
os.remove(temp_webm)
if os.path.exists(temp_wav):
os.remove(temp_wav)
@main_bp.route('/test-async')
@login_required
def test_async():
return render_template('test_async.html')
@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form.get('email')
password = request.form.get('password')
user = User.query.filter_by(email=email).first()
if user and check_password_hash(user.password, password):
login_user(user)
return redirect(url_for('main.home'))
flash('Login failed. Check your email and password.')
return render_template('login.html', title="Login")
@auth_bp.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form.get('username')
display_name = request.form.get('display_name') or username
email = request.form.get('email')
password = request.form.get('password')
dob_str = request.form.get('date_of_birth')
gender = request.form.get('gender')
location = request.form.get('location')
bio = request.form.get('bio')
if User.query.filter_by(email=email).first():
flash('Email already exists.')
return redirect(url_for('auth.register'))
if User.query.filter_by(username=username).first():
flash('Username already taken.')
return redirect(url_for('auth.register'))
# Parse DOB
date_of_birth = None
if dob_str:
try:
date_of_birth = datetime.strptime(dob_str, '%Y-%m-%d').date()
except ValueError:
pass
# Handle profile picture upload
profile_pic_path = None
if 'profile_pic' in request.files:
file = request.files['profile_pic']
if file and file.filename:
if allowed_file(file.filename, 'image'):
filename = secure_filename(file.filename)
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
save_name = f"profile_{timestamp}_{filename}"
# Create profiles directory if it doesn't exist
profiles_dir = os.path.join(app.config['UPLOAD_FOLDER'], 'profiles')
os.makedirs(profiles_dir, exist_ok=True)
save_path = os.path.join(profiles_dir, save_name)
file.save(save_path)
# Force forward slash for database path to ensure URL compatibility
profile_pic_path = f"profiles/{save_name}"
print(f"[REGISTER] Saved profile picture: {save_name}")
else:
flash('Invalid image file type. Allowed: jpg, jpeg, png, gif, webp')
else:
if file.filename:
print(f"[REGISTER] Profile picture rejected: {file.filename} (invalid format)")
new_user = User(
username=username,
display_name=display_name,
email=email,
password=generate_password_hash(password, method='pbkdf2:sha256'),
date_of_birth=date_of_birth,
gender=gender if gender else None,
location=location if location else None,
bio=bio if bio else None,
profile_pic=profile_pic_path,
date_joined=datetime.utcnow()
)
db.session.add(new_user)
db.session.commit()
login_user(new_user)
flash('Account created successfully!')
return redirect(url_for('main.home'))
return render_template('register.html', title="Register")
@auth_bp.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('main.home'))
@main_bp.route('/settings', methods=['GET', 'POST'])
@login_required
def settings():
if request.method == 'POST':
current_user.username = request.form.get('username')
current_user.display_name = request.form.get('display_name')
current_user.email = request.form.get('email')
current_user.gender = request.form.get('gender')
current_user.location = request.form.get('location')
current_user.bio = request.form.get('bio')
current_user.notifications_enabled = 'notifications_enabled' in request.form
dob_str = request.form.get('date_of_birth')
if dob_str:
try:
current_user.date_of_birth = datetime.strptime(dob_str, '%Y-%m-%d').date()
except ValueError:
pass
if 'profile_pic' in request.files:
file = request.files['profile_pic']
if file and file.filename:
if allowed_file(file.filename, 'image'):
filename = secure_filename(file.filename)
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
save_name = f"profile_{timestamp}_{filename}"
profiles_dir = os.path.join(app.config['UPLOAD_FOLDER'], 'profiles')