ariansyahdedy commited on
Commit
b0f2d3d
·
1 Parent(s): 904f598
app/config.py CHANGED
@@ -1,4 +1,8 @@
1
  import os
 
 
 
 
2
 
3
  # In a real environment, you would secure these properly.
4
  GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID", "50786072753-s9nq1ma3nv44k382b5mcnvmeggt1cvha.apps.googleusercontent.com")
@@ -7,3 +11,7 @@ GOOGLE_REDIRECT_URI = os.environ.get("GOOGLE_REDIRECT_URI", "http://localhost:80
7
 
8
  # For YouTube Data API. The user must consent to at least read their channel info and videos.
9
  YOUTUBE_SCOPES = ["https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/youtube.force-ssl"]
 
 
 
 
 
1
  import os
2
+ from fastapi.templating import Jinja2Templates
3
+
4
+ from app.services.gambling_filter import GamblingFilter
5
+ from app.services.youtube_moderator import YouTubeCommentModerator
6
 
7
  # In a real environment, you would secure these properly.
8
  GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID", "50786072753-s9nq1ma3nv44k382b5mcnvmeggt1cvha.apps.googleusercontent.com")
 
11
 
12
  # For YouTube Data API. The user must consent to at least read their channel info and videos.
13
  YOUTUBE_SCOPES = ["https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/youtube.force-ssl"]
14
+
15
+ templates = Jinja2Templates(directory="templates")
16
+ filter_instance = GamblingFilter()
17
+ user_moderator = YouTubeCommentModerator(gambling_filter=GamblingFilter())
app/main.py CHANGED
@@ -1,7 +1,9 @@
1
  from fastapi import FastAPI, Request
 
2
  from fastapi.templating import Jinja2Templates
3
  from fastapi.responses import HTMLResponse
4
  from starlette.middleware.sessions import SessionMiddleware
 
5
  # from starlette.middleware.proxy_headers import ProxyHeadersMiddleware
6
  import os
7
  # BEFORE creating the FastAPI app
@@ -13,7 +15,7 @@ from app.routes import auth, youtube
13
  templates = Jinja2Templates(directory="app/templates")
14
 
15
  app = FastAPI()
16
-
17
  # Set a secret key for session cookies (Use a strong key in production!)
18
  app.add_middleware(SessionMiddleware, secret_key="CHANGE_THIS_SECRET")
19
 
@@ -21,9 +23,28 @@ app.add_middleware(SessionMiddleware, secret_key="CHANGE_THIS_SECRET")
21
  app.include_router(auth.router)
22
  app.include_router(youtube.router)
23
 
 
24
  @app.get("/", response_class=HTMLResponse)
25
- async def read_root(request: Request):
26
- return templates.TemplateResponse("index.html", {"request": request})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  @app.get("/success", response_class=HTMLResponse)
29
  async def read_success(request: Request):
 
1
  from fastapi import FastAPI, Request
2
+ from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
3
  from fastapi.templating import Jinja2Templates
4
  from fastapi.responses import HTMLResponse
5
  from starlette.middleware.sessions import SessionMiddleware
6
+ from fastapi.staticfiles import StaticFiles
7
  # from starlette.middleware.proxy_headers import ProxyHeadersMiddleware
8
  import os
9
  # BEFORE creating the FastAPI app
 
15
  templates = Jinja2Templates(directory="app/templates")
16
 
17
  app = FastAPI()
18
+ app.mount("/static", StaticFiles(directory="static"), name="static")
19
  # Set a secret key for session cookies (Use a strong key in production!)
20
  app.add_middleware(SessionMiddleware, secret_key="CHANGE_THIS_SECRET")
21
 
 
23
  app.include_router(auth.router)
24
  app.include_router(youtube.router)
25
 
26
+ # 1) Root route => Decide if user is logged in; if not, go to /login
27
  @app.get("/", response_class=HTMLResponse)
28
+ async def root_redirect(request: Request):
29
+ token = request.cookies.get("token")
30
+ if token:
31
+ return RedirectResponse(url="/videos", status_code=303)
32
+ else:
33
+ return RedirectResponse(url="/login", status_code=303)
34
+
35
+ # 2) Show the login form (GET /login)
36
+ @app.get("/login", response_class=HTMLResponse)
37
+ async def login_form(request: Request):
38
+ return templates.TemplateResponse("login.html", {"request": request})
39
+
40
+ @app.get("/logout")
41
+ async def logout():
42
+ response = RedirectResponse(url="/login")
43
+ response.delete_cookie("token")
44
+ return response
45
+ # @app.get("/", response_class=HTMLResponse)
46
+ # async def read_root(request: Request):
47
+ # return templates.TemplateResponse("login.html", {"request": request})
48
 
49
  @app.get("/success", response_class=HTMLResponse)
50
  async def read_success(request: Request):
app/models.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Dict, Optional, Set, Tuple
2
+ from pydantic import BaseModel
3
+
4
+
5
+ class User(BaseModel):
6
+ username: str
7
+ email: Optional[str] = None
8
+ youtube_credentials: Optional[Dict] = None
9
+
10
+ class UserDatabase:
11
+ """
12
+ In-memory user database. In a production app,
13
+ replace with a proper database like SQLAlchemy
14
+ """
15
+ users = {}
16
+
17
+ @classmethod
18
+ def create_user(cls, username: str, credentials: Dict):
19
+ user = User(username=username, youtube_credentials=credentials)
20
+ cls.users[username] = user
21
+ return user
22
+
23
+ @classmethod
24
+ def get_user(cls, username: str):
25
+ return cls.users.get(username)
app/routes/auth.py CHANGED
@@ -2,10 +2,11 @@ from fastapi import APIRouter, Request, Response, status
2
  from fastapi.responses import RedirectResponse, HTMLResponse
3
  from starlette.middleware.sessions import SessionMiddleware
4
  from google_auth_oauthlib.flow import Flow
 
5
  import os
6
 
7
  from app.config import GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URI, YOUTUBE_SCOPES
8
-
9
  router = APIRouter()
10
 
11
 
@@ -23,7 +24,7 @@ def create_flow():
23
  scopes=YOUTUBE_SCOPES,
24
  )
25
 
26
- @router.get("/login")
27
  async def login(request: Request):
28
  flow = create_flow()
29
  flow.redirect_uri = GOOGLE_REDIRECT_URI # must set the redirect_uri separately
@@ -65,5 +66,35 @@ async def auth_callback(request: Request):
65
  "client_secret": credentials.client_secret,
66
  "scopes": credentials.scopes
67
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- return RedirectResponse(url="/success", status_code=status.HTTP_302_FOUND)
 
 
 
 
 
 
 
 
 
 
 
2
  from fastapi.responses import RedirectResponse, HTMLResponse
3
  from starlette.middleware.sessions import SessionMiddleware
4
  from google_auth_oauthlib.flow import Flow
5
+ from googleapiclient.discovery import build
6
  import os
7
 
8
  from app.config import GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URI, YOUTUBE_SCOPES
9
+ from app.models import UserDatabase
10
  router = APIRouter()
11
 
12
 
 
24
  scopes=YOUTUBE_SCOPES,
25
  )
26
 
27
+ @router.get("/auth")
28
  async def login(request: Request):
29
  flow = create_flow()
30
  flow.redirect_uri = GOOGLE_REDIRECT_URI # must set the redirect_uri separately
 
66
  "client_secret": credentials.client_secret,
67
  "scopes": credentials.scopes
68
  }
69
+
70
+ youtube = build("youtube", "v3", credentials=credentials)
71
+ channel_response = youtube.channels().list(part="snippet", mine=True).execute()
72
+ if channel_response.get("items") and len(channel_response["items"]) > 0:
73
+ channel_username = channel_response["items"][0]["snippet"]["title"]
74
+ else:
75
+ channel_username = "unknown_user"
76
+
77
+
78
+ user = UserDatabase.create_user(channel_username, request.session["credentials"])
79
+ response = RedirectResponse(url="/videos", status_code=status.HTTP_302_FOUND)
80
+
81
+ # Set cookie settings based on your environment
82
+ import os
83
+ if os.getenv("HF_SPACE") == "true":
84
+ secure_cookie = True
85
+ samesite_value = "none"
86
+ else:
87
+ secure_cookie = False
88
+ samesite_value = "lax"
89
 
90
+ # Redirect to /videos with a cookie token
91
+ response = RedirectResponse(url="/videos", status_code=303)
92
+ response.set_cookie(
93
+ key="token",
94
+ value=channel_username,
95
+ max_age=1800,
96
+ httponly=True,
97
+ secure=secure_cookie,
98
+ samesite=samesite_value
99
+ )
100
+ return response
app/routes/youtube.py CHANGED
@@ -1,7 +1,32 @@
1
- from fastapi import APIRouter, Request, HTTPException
 
 
2
  from google.oauth2.credentials import Credentials
3
  from googleapiclient.discovery import build
 
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  router = APIRouter()
6
 
7
  def get_credentials_from_session(session) -> Credentials:
@@ -18,6 +43,15 @@ def get_credentials_from_session(session) -> Credentials:
18
  scopes=creds_data["scopes"]
19
  )
20
 
 
 
 
 
 
 
 
 
 
21
  @router.get("/list-channels")
22
  async def list_channels(request: Request):
23
  """Return the user’s list of YouTube channels."""
@@ -75,3 +109,184 @@ async def list_videos(request: Request, channel_id: str):
75
  })
76
 
77
  return {"videos": videos}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Request, HTTPException, Depends
2
+ from fastapi import FastAPI, Request, Form, File, UploadFile, HTTPException, Depends
3
+ from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
4
  from google.oauth2.credentials import Credentials
5
  from googleapiclient.discovery import build
6
+ from typing import List, Dict, Optional, Set, Tuple
7
 
8
+ from app.services.gambling_filter import GamblingFilter
9
+ from app.models import User, UserDatabase
10
+
11
+ from app.config import templates, user_moderator, filter_instance
12
+
13
+ import googleapiclient.discovery
14
+ import logging
15
+
16
+ # Configure logging at the top of the file
17
+ logging.basicConfig(
18
+ level=logging.INFO,
19
+ format='%(asctime)s - %(name)s - [%(levelname)s] %(message)s',
20
+ datefmt='%Y-%m-%d %H:%M:%S'
21
+ )
22
+ logger = logging.getLogger(__name__)
23
+
24
+ manual_overrides = {}
25
+ def keep_comment(comment_id: str, video_id: str):
26
+ # Mark this comment as manually kept
27
+ manual_overrides[(video_id, comment_id)] = "safe"
28
+
29
+
30
  router = APIRouter()
31
 
32
  def get_credentials_from_session(session) -> Credentials:
 
43
  scopes=creds_data["scopes"]
44
  )
45
 
46
+ def get_current_user_from_cookie(request: Request):
47
+ token = request.cookies.get("token")
48
+ if not token:
49
+ raise HTTPException(status_code=401, detail="Not authenticated")
50
+ user = UserDatabase.get_user(token)
51
+ if not user:
52
+ raise HTTPException(status_code=401, detail="Invalid authentication credentials")
53
+ return user
54
+
55
  @router.get("/list-channels")
56
  async def list_channels(request: Request):
57
  """Return the user’s list of YouTube channels."""
 
109
  })
110
 
111
  return {"videos": videos}
112
+
113
+ @router.post("/api/comments/keep/{comment_id}")
114
+ async def api_keep_comment(
115
+ request: Request,
116
+ comment_id: str,
117
+ video_id: str
118
+ ):
119
+ try:
120
+ logging.debug(f"Received keep request for comment_id: {comment_id}, video_id: {video_id}")
121
+
122
+ # Get current user's credentials
123
+ current_user = get_current_user_from_cookie(request)
124
+ logging.debug(f"Current user: {current_user.username}")
125
+ user_creds = Credentials.from_authorized_user_info(current_user.youtube_credentials)
126
+
127
+ # Create a moderator instance with user credentials
128
+
129
+ user_moderator.youtube_service = googleapiclient.discovery.build(
130
+ "youtube", "v3",
131
+ credentials=user_creds
132
+ )
133
+
134
+ logging.debug("Setting moderation status to 'published' on YouTube...")
135
+ # Mark comment as approved on YouTube
136
+ result = user_moderator.youtube_service.comments().setModerationStatus(
137
+ id=comment_id,
138
+ moderationStatus="published" # This marks the comment as approved
139
+ ).execute()
140
+ logging.debug(f"YouTube API response: {result}")
141
+
142
+ # Add the comment ID to the manual overrides so it won't be reflagged
143
+ keep_comment(comment_id, video_id) # Ensure this function is defined and working
144
+ logging.debug("Manual override saved for comment.")
145
+
146
+ return {"success": True, "message": "Comment kept successfully"}
147
+
148
+ except Exception as e:
149
+ logging.error(f"Error keeping comment: {e}", exc_info=True)
150
+ return {"success": False, "error": str(e)}
151
+
152
+
153
+ @router.get("/videos", response_class=HTMLResponse)
154
+ async def list_videos(request: Request, current_user: User = Depends(get_current_user_from_cookie)):
155
+ # Reconstruct the credentials from the stored dictionary
156
+ user_creds = Credentials.from_authorized_user_info(current_user.youtube_credentials)
157
+ user_moderator.youtube_service = googleapiclient.discovery.build(
158
+ "youtube", "v3", credentials=user_creds
159
+ )
160
+
161
+ videos = user_moderator.get_channel_videos()
162
+
163
+ return templates.TemplateResponse("videos.html", {
164
+ "request": request,
165
+ "current_user": current_user,
166
+ "videos": videos
167
+ })
168
+
169
+
170
+ @router.get("/refresh_comments/{video_id}")
171
+ async def refresh_video_comments(
172
+ request: Request,
173
+ video_id: str,
174
+ threshold: float = 0.55
175
+ ):
176
+ """
177
+ Refresh comments for a specific video, reapplying moderation.
178
+
179
+ :param request: Request object
180
+ :param video_id: ID of the video to refresh comments for
181
+ :param threshold: Gambling confidence threshold
182
+ :return: Rendered template with updated comments
183
+ """
184
+ # Get current user's credentials
185
+ current_user = get_current_user_from_cookie(request)
186
+
187
+ if not current_user:
188
+ return RedirectResponse(url="/login", status_code=303)
189
+
190
+ try:
191
+ # Recreate moderator with current user's credentials
192
+ user_creds = Credentials.from_authorized_user_info(current_user.youtube_credentials)
193
+
194
+
195
+ user_moderator.youtube_service = googleapiclient.discovery.build(
196
+ "youtube", "v3",
197
+ credentials=user_creds
198
+ )
199
+
200
+ # Moderate comments for the video
201
+ result = user_moderator.moderate_video_comments(video_id, threshold)
202
+
203
+ # Fetch video details to pass to template
204
+ youtube_service = googleapiclient.discovery.build(
205
+ "youtube", "v3",
206
+ credentials=user_creds
207
+ )
208
+ video_request = youtube_service.videos().list(
209
+ part="snippet",
210
+ id=video_id
211
+ )
212
+ video_response = video_request.execute()
213
+ video_info = video_response['items'][0]['snippet'] if video_response['items'] else {}
214
+
215
+ return templates.TemplateResponse("video_comments.html", {
216
+ "request": request,
217
+ "video": {
218
+ "id": video_id,
219
+ "title": video_info.get('title', 'Unknown Video')
220
+ },
221
+ "safe_comments": result.get('safe_comments', []),
222
+ "flagged_comments": result.get('gambling_comments', []),
223
+ "total_comments": result.get('total_comments', 0)
224
+ })
225
+
226
+ except Exception as e:
227
+ logging.error(f"Error refreshing comments: {e}")
228
+ return templates.TemplateResponse("error.html", {
229
+ "request": request,
230
+ "error": f"Failed to refresh comments: {str(e)}"
231
+ })
232
+
233
+
234
+ @router.post("/moderate_video")
235
+ async def moderate_video(request: Request, video_id: str = Form(...), threshold: float = Form(0.55)):
236
+ if not user_moderator.youtube_service:
237
+ result = {"error": "YouTube service not authenticated. Please authenticate first."}
238
+ else:
239
+ result = user_moderator.moderate_video_comments(video_id, threshold)
240
+
241
+ return templates.TemplateResponse("index.html", {
242
+ "request": request,
243
+ "result": result,
244
+ "video_id": video_id,
245
+ "rules": {
246
+ "platform": sorted(list(filter_instance._platform_names)),
247
+ "gambling_term": sorted(list(filter_instance._gambling_terms)),
248
+ "safe_indicator": sorted(list(filter_instance._safe_indicators)),
249
+ "gambling_context": sorted(list(filter_instance._gambling_contexts)),
250
+ "ambiguous_term": sorted(list(filter_instance._ambiguous_terms))
251
+ }
252
+ })
253
+
254
+ @router.delete("/api/comments/{comment_id}")
255
+ async def api_delete_comment(
256
+ request: Request,
257
+ comment_id: str,
258
+ video_id: str
259
+ ):
260
+ current_user = get_current_user_from_cookie(request)
261
+ user_creds = Credentials.from_authorized_user_info(current_user.youtube_credentials)
262
+
263
+ user_moderator.youtube_service = googleapiclient.discovery.build(
264
+ "youtube", "v3",
265
+ credentials=user_creds
266
+ )
267
+ success = user_moderator.delete_comment(comment_id)
268
+ return {"success": success}
269
+
270
+ @router.get("/video/{video_id}", response_class=HTMLResponse)
271
+ async def moderate_video_comments(
272
+ request: Request,
273
+ video_id: str,
274
+ current_user: User = Depends(get_current_user_from_cookie)
275
+ ):
276
+ # Reconstruct the Credentials object from the stored dict
277
+ user_creds = Credentials.from_authorized_user_info(current_user.youtube_credentials)
278
+
279
+ user_moderator.youtube_service = googleapiclient.discovery.build(
280
+ "youtube", "v3",
281
+ credentials=user_creds
282
+ )
283
+
284
+ moderation_results = user_moderator.moderate_video_comments(video_id)
285
+
286
+ return templates.TemplateResponse("video_comments.html", {
287
+ "request": request,
288
+ "current_user": current_user,
289
+ "video": {"id": video_id, "title": "Sample Video Title"}, # Optionally fetch actual title
290
+ "safe_comments": moderation_results.get('safe_comments', []),
291
+ "flagged_comments": moderation_results.get('gambling_comments', [])
292
+ })
app/services/__init__.py ADDED
File without changes
app/services/gambling_filter.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import re
3
+ import time
4
+ import os
5
+ import logging
6
+ from typing import List, Dict, Optional, Set, Tuple
7
+
8
+ import unicodedata
9
+ import unidecode
10
+
11
+ import io
12
+ import pandas as pd
13
+ import json
14
+
15
+ # Configure logging at the top of the file
16
+ logging.basicConfig(
17
+ level=logging.INFO,
18
+ format='%(asctime)s - %(name)s - [%(levelname)s] %(message)s',
19
+ datefmt='%Y-%m-%d %H:%M:%S'
20
+ )
21
+ logger = logging.getLogger(__name__)
22
+
23
+ VISUAL_MAP = {
24
+ 'А': 'A','В': 'B','С': 'C','Е': 'E','Н': 'H','К': 'K','М': 'M','О': 'O','Р': 'P','Т': 'T','Х': 'X',
25
+ 'а': 'a','в': 'b','с': 'c','е': 'e','о': 'o','р': 'p','х': 'x','у': 'y',
26
+ 'Я': 'R','я': 'r',
27
+ 'ρ': 'p',
28
+ 'Π': 'P',
29
+ # etc...
30
+ }
31
+
32
+
33
+ # --- GamblingFilter class (with rule updates) ---
34
+ class GamblingFilter:
35
+ """
36
+ A high-performance filter for detecting online gambling-related comments.
37
+ Features include aggressive Unicode normalization, keyword matching, and pattern detection.
38
+ """
39
+
40
+ def __init__(self):
41
+ logger.info("Initializing GamblingFilter")
42
+ self._platform_names: Set[str] = {
43
+ 'agustoto', 'aero', 'aero88', 'dora', 'dora77', 'dewadora', 'pulau777', 'pulau', '777',
44
+ 'jptogel', 'mandalika', 'cnd88', 'axl', 'berkah99', 'weton88', 'garuda', 'hoki'
45
+ }
46
+
47
+ self._gambling_terms: Set[str] = {
48
+ 'jackpot', 'jp', 'wd', 'depo', 'cuan', 'gacor', 'gacir', 'jekpot', 'sultan',
49
+ 'rezeki nomplok', 'rezeki', 'menang', 'nomplok', 'deposit', 'withdraw', 'maxwin',
50
+ 'auto sultan', 'jepe', 'jepee', 'bikin nagih', 'berkah'
51
+ }
52
+
53
+ self._ambiguous_terms: Set[str] = {
54
+ 'auto', 'main', 'bermain', 'hasil', 'dapat', 'dapet', 'berkat'
55
+ }
56
+
57
+ self._safe_indicators: Set[str] = {
58
+ 'tidak mengandung', 'bukan perjudian', 'tanpa perjudian',
59
+ 'dokumentasi', 'profesional', 'pembelajaran'
60
+ }
61
+
62
+ self._gambling_contexts: List[str] = [
63
+ r'(main|bermain|coba).{1,30}(dapat|dapet|pro|jadi|langsung|menang|jp|cuan)',
64
+ r'(modal|depo).{1,30}(jadi|langsung|wd|cuan)',
65
+ r'(jp|jackpot|jekpot).{1,30}(gede|besar|pecah)',
66
+ r'(berkat|dari).{1,30}(rezeki|menang|cuan|sultan)',
67
+ r'(gacor|gacir).{1,30}(terus|parah|tiap|hari)',
68
+ r'(rezeki|cuan).{1,30}(nomplok|datang|mengalir|lancar)',
69
+ r'(hari ini).{1,30}(menang|cuan|rezeki|berkat)',
70
+ r'(malah|eh).{1,30}(jadi|dapat|dapet|rezeki)',
71
+ r'(auto).{1,30}(sultan|cuan|rezeki|kaya)',
72
+ r'(0\d:[0-5]\d).{1,30}(menang|rezeki|cuan|gacor)',
73
+ r'(iseng|coba).{1,30}(malah|jadi|eh|pro)',
74
+ r'(deposit|depo|wd).{1,30}(jadi|langsung)',
75
+ r'(langsung|auto).{1,30}(jp|cuan|sultan|rezeki)',
76
+ r'bikin\s+nagih',
77
+ r'gak\s+ada\s+duanya',
78
+ r'berkah.{0,20}rezeki',
79
+ r'puji\s+syukur'
80
+ ]
81
+
82
+ self._compiled_gambling_contexts = [
83
+ re.compile(pattern, re.IGNORECASE | re.DOTALL)
84
+ for pattern in self._gambling_contexts
85
+ ]
86
+
87
+ self._update_platform_pattern()
88
+
89
+ self._number_pattern = re.compile(r'(88|777|77|99|7+)')
90
+
91
+ def _update_platform_pattern(self):
92
+ """Recompile the platform name regex based on current _platform_names."""
93
+ platform_patterns = []
94
+ for platform in self._platform_names:
95
+ # chars = list(platform)
96
+ # strict = ''.join(f'[{c.upper()}{c.lower()}][^a-zA-Z0-9]*' for c in chars[:-1]) + f'[{chars[-1].upper()}{chars[-1].lower()}]'
97
+ # flexible = '.*?'.join(re.escape(c) for c in chars)
98
+ # platform_patterns.append(f'({strict})')
99
+ # platform_patterns.append(f'({flexible})')
100
+ chars = list(platform) # e.g. ['p', 'u', 'l', 'a', 'u']
101
+ # Each letter can be followed by up to 3 non-alphanumeric chars:
102
+ # (or fewer if you want to be more strict)
103
+ segments = [
104
+ f'[{c.upper()}{c.lower()}][^a-zA-Z0-9]{{0,3}}'
105
+ for c in chars[:-1]
106
+ ]
107
+ # Then the last char without trailing non-alphanumerics
108
+ segments.append(f'[{chars[-1].upper()}{chars[-1].lower()}]')
109
+ strict = ''.join(segments)
110
+ platform_patterns.append(strict)
111
+
112
+ self._platform_pattern = re.compile('|'.join(platform_patterns), re.DOTALL)
113
+
114
+ def add_rule(self, rule_type: str, rule_value: str):
115
+ """
116
+ Add a new rule based on the rule type.
117
+ Allowed types: 'platform', 'gambling_term', 'safe_indicator', 'gambling_context', 'ambiguous_term'
118
+ """
119
+ rule_type = rule_type.lower()
120
+ if rule_type == 'platform':
121
+ self._platform_names.add(rule_value)
122
+ self._update_platform_pattern()
123
+ elif rule_type == 'gambling_term':
124
+ self._gambling_terms.add(rule_value)
125
+ elif rule_type == 'safe_indicator':
126
+ self._safe_indicators.add(rule_value)
127
+ elif rule_type == 'gambling_context':
128
+ self._gambling_contexts.append(rule_value)
129
+ self._compiled_gambling_contexts.append(re.compile(rule_value, re.IGNORECASE | re.DOTALL))
130
+ elif rule_type == 'ambiguous_term':
131
+ self._ambiguous_terms.add(rule_value)
132
+ else:
133
+ raise ValueError("Unsupported rule type")
134
+
135
+ def _strip_all_formatting(self, text: str) -> str:
136
+ result = []
137
+ for c in text:
138
+ if c.isalnum() or c.isspace():
139
+ result.append(c.lower())
140
+ return ''.join(result)
141
+
142
+ def _aggressive_normalize_text(self, text: str) -> str:
143
+ normalized = unicodedata.normalize('NFKD', text)
144
+ ascii_text = ''.join(c for c in normalized if ord(c) < 128)
145
+ return ascii_text.lower()
146
+
147
+
148
+
149
+ def _robust_normalize(self, text: str) -> str:
150
+ """
151
+ 1) Replace visually-similar letters (Cyrillic/Greek) with Latin equivalents.
152
+ 2) Then use unidecode to handle bold/italic forms, fullwidth, etc.
153
+ 3) Lowercase the result.
154
+ """
155
+ # Step 1: custom pass for visual lookalikes
156
+ mapped_chars = []
157
+ for ch in text:
158
+ if ch in VISUAL_MAP:
159
+ mapped_chars.append(VISUAL_MAP[ch])
160
+ else:
161
+ mapped_chars.append(ch)
162
+ mapped_text = ''.join(mapped_chars)
163
+
164
+ # Step 2: apply normal Unicode decomposition + unidecode
165
+ # This handles bold/italic/mathematical letters, fullwidth forms, etc.
166
+ decomposed = unicodedata.normalize('NFKD', mapped_text)
167
+ ascii_equiv = unidecode.unidecode(decomposed)
168
+
169
+ # Step 3: lowercase the result
170
+ return ascii_equiv.lower()
171
+
172
+
173
+ def _extract_platform_names(self, text: str) -> List[str]:
174
+ matches = []
175
+ pattern_matches = self._platform_pattern.findall(text)
176
+ if pattern_matches:
177
+ pattern_matches = [m for sublist in pattern_matches for m in sublist if m]
178
+ matches.extend(pattern_matches)
179
+ normalized = self._robust_normalize(text)
180
+ stripped = self._strip_all_formatting(text)
181
+ for platform in self._platform_names:
182
+ if platform in normalized or platform in stripped:
183
+ if not any(platform in m.lower() for m in matches):
184
+ matches.append(platform)
185
+ if '88' in text or '88' in normalized:
186
+ if not any('88' in m for m in matches):
187
+ matches.append('88')
188
+ if '777' in text or '777' in normalized:
189
+ if not any('777' in m for m in matches):
190
+ matches.append('777')
191
+ return matches
192
+
193
+ def normalize_text(self, text: str) -> str:
194
+ normalized = unicodedata.normalize('NFKD', text)
195
+ normalized = ''.join(c for c in normalized if ord(c) < 128 or c.isspace())
196
+ return normalized.lower()
197
+
198
+ def is_gambling_comment(self, text: str, threshold: float = 0.55) -> Tuple[bool, Dict]:
199
+ start_time = time.time()
200
+ logger.info(f"Analyzing comment for gambling content: {text[:100]}...")
201
+ metrics = {
202
+ 'platform_matches': [],
203
+ 'gambling_term_matches': [],
204
+ 'context_matches': [],
205
+ 'safe_indicators': [],
206
+ 'has_numbers': False,
207
+ 'confidence_score': 0.0,
208
+ 'processing_time_ms': 0
209
+ }
210
+
211
+ normalized_text = self.normalize_text(text)
212
+ stripped_text = self._strip_all_formatting(text)
213
+ aggressive_text = self._robust_normalize(text)
214
+
215
+ for indicator in self._safe_indicators:
216
+ if indicator in normalized_text.lower():
217
+ metrics['safe_indicators'].append(indicator)
218
+
219
+ if len(metrics['safe_indicators']) > 0:
220
+ metrics['confidence_score'] = 0.0
221
+ metrics['processing_time_ms'] = (time.time() - start_time) * 1000
222
+ return False, metrics
223
+
224
+ platform_matches = self._extract_platform_names(text)
225
+ if platform_matches:
226
+ metrics['platform_matches'] = platform_matches
227
+
228
+ for term in self._gambling_terms:
229
+ if (term in normalized_text.lower() or
230
+ term in stripped_text.lower() or
231
+ term in aggressive_text.lower()):
232
+ metrics['gambling_term_matches'].append(term)
233
+
234
+ if self._number_pattern.search(normalized_text):
235
+ metrics['has_numbers'] = True
236
+
237
+ for pattern in self._compiled_gambling_contexts:
238
+ match = pattern.search(normalized_text)
239
+ if match:
240
+ metrics['context_matches'].append(match.group(0))
241
+ match = pattern.search(aggressive_text)
242
+ if match and match.group(0) not in metrics['context_matches']:
243
+ metrics['context_matches'].append(match.group(0))
244
+
245
+ platform_score = min(len(metrics['platform_matches']) * 1.0, 1)
246
+ term_score = min(len(metrics['gambling_term_matches']) * 0.2, 0.4)
247
+ context_score = min(len(metrics['context_matches']) * 0.2, 0.4)
248
+ number_score = 0.1 if metrics['has_numbers'] else 0
249
+
250
+ if platform_score > 0 and (term_score > 0 or context_score > 0):
251
+ total_score = platform_score + term_score + context_score + number_score
252
+ elif context_score > 0.2 and term_score > 0:
253
+ total_score = context_score + term_score + number_score
254
+ else:
255
+ total_score = max(platform_score, term_score, context_score) * 0.8
256
+
257
+ metrics['confidence_score'] = min(total_score, 1.0)
258
+
259
+ if ("berkah" in normalized_text.lower() or "berkah" in aggressive_text.lower()) and \
260
+ ("rezeki" in normalized_text.lower() or "rezeki" in aggressive_text.lower()) and \
261
+ len(metrics['platform_matches']) > 0:
262
+ metrics['confidence_score'] = max(metrics['confidence_score'], 0.7)
263
+ if "Special case: berkah+rezeki+platform" not in metrics['context_matches']:
264
+ metrics['context_matches'].append("Special case: berkah+rezeki+platform")
265
+
266
+ elif ("puji" in normalized_text.lower() or "puji" in aggressive_text.lower()) and \
267
+ ("syukur" in normalized_text.lower() or "syukur" in aggressive_text.lower()) and \
268
+ len(metrics['platform_matches']) > 0:
269
+ metrics['confidence_score'] = max(metrics['confidence_score'], 0.7)
270
+ if "Special case: puji+syukur+platform" not in metrics['context_matches']:
271
+ metrics['context_matches'].append("Special case: puji+syukur+platform")
272
+
273
+ metrics['processing_time_ms'] = (time.time() - start_time) * 1000
274
+ is_gambling = metrics['confidence_score'] >= threshold
275
+ return is_gambling, metrics
276
+
277
+ def filter_comments(self, comments: List[str], threshold: float = 0.55) -> Dict[str, List]:
278
+ result = {
279
+ 'gambling_comments': [],
280
+ 'safe_comments': [],
281
+ 'metrics': []
282
+ }
283
+
284
+ for comment in comments:
285
+ is_gambling, metrics = self.is_gambling_comment(comment, threshold)
286
+ if is_gambling:
287
+ result['gambling_comments'].append(comment)
288
+ else:
289
+ result['safe_comments'].append(comment)
290
+ metrics['original_text'] = comment
291
+ result['metrics'].append(metrics)
292
+ return result
293
+
app/services/youtube_moderator.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import time
3
+ import os
4
+ import logging
5
+ from typing import List, Dict, Optional, Set, Tuple
6
+
7
+ import google_auth_oauthlib.flow
8
+ import googleapiclient.discovery
9
+ import googleapiclient.errors
10
+ from google_auth_oauthlib.flow import Flow
11
+ from google.oauth2.credentials import Credentials
12
+ from googleapiclient.discovery import build
13
+ from fastapi import FastAPI, Request, Form, File, UploadFile, HTTPException, Depends
14
+ from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
15
+ from fastapi.templating import Jinja2Templates
16
+ from fastapi.staticfiles import StaticFiles
17
+ from fastapi.security import OAuth2PasswordBearer
18
+ from google.oauth2.credentials import Credentials
19
+ from pydantic import BaseModel
20
+
21
+
22
+ from app.services.gambling_filter import GamblingFilter
23
+
24
+ def get_credentials_from_session(session) -> Credentials:
25
+ """Utility to build a Credentials object from stored session data."""
26
+ creds_data = session.get("credentials")
27
+ if not creds_data:
28
+ return None
29
+ return Credentials(
30
+ token=creds_data["token"],
31
+ refresh_token=creds_data["refresh_token"],
32
+ token_uri=creds_data["token_uri"],
33
+ client_id=creds_data["client_id"],
34
+ client_secret=creds_data["client_secret"],
35
+ scopes=creds_data["scopes"]
36
+ )
37
+
38
+ class YouTubeCommentModerator:
39
+ def __init__(self,
40
+ client_secrets_path: str = "./app/client_secret.json",
41
+ gambling_filter: Optional[GamblingFilter] = None):
42
+ """
43
+ Initialize the YouTube Comment Moderator with configurable settings.
44
+
45
+ :param client_secrets_path: Path to OAuth 2.0 client secrets file
46
+ :param gambling_filter: Optional pre-configured GamblingFilter instance
47
+ """
48
+ # Setup logging
49
+ logging.basicConfig(
50
+ level=logging.INFO,
51
+ format='%(asctime)s - [%(levelname)s] %(message)s',
52
+ datefmt='%Y-%m-%d %H:%M:%S'
53
+ )
54
+ self.logger = logging.getLogger(__name__)
55
+
56
+
57
+ # YouTube service
58
+ self.youtube_service = None
59
+
60
+ # Gambling Filter
61
+ self.gambling_filter = gambling_filter or GamblingFilter()
62
+
63
+
64
+ def moderate_video_comments(self, video_id: str, threshold: float = 0.55) -> Dict:
65
+ if not self.youtube_service:
66
+ self.logger.error("YouTube service not authenticated.")
67
+ return {"error": "Not authenticated"}
68
+
69
+ try:
70
+ comments = []
71
+ request = self.youtube_service.commentThreads().list(
72
+ part="snippet",
73
+ videoId=video_id,
74
+ maxResults=100,
75
+ textFormat="plainText"
76
+ )
77
+ response = request.execute()
78
+
79
+ moderation_results = {
80
+ "total_comments": 0,
81
+ "gambling_comments": [],
82
+ "safe_comments": [],
83
+ "moderation_metrics": []
84
+ }
85
+
86
+ while request is not None:
87
+ for item in response.get("items", []):
88
+ comment_id = item["snippet"]["topLevelComment"]["id"]
89
+ comment_snippet = item["snippet"]["topLevelComment"]["snippet"]
90
+ comment_text = comment_snippet["textDisplay"]
91
+
92
+ # Check for manual override first
93
+ if manual_overrides.get((video_id, comment_id)) == "safe":
94
+ # The user previously pressed "Keep" - skip the gambling filter
95
+ is_gambling = False
96
+ metrics = {"confidence_score": 0.0}
97
+ else:
98
+ # Normal path - filter it
99
+ is_gambling, metrics = self.gambling_filter.is_gambling_comment(comment_text, threshold)
100
+
101
+ comment_info = {
102
+ "id": comment_id,
103
+ "text": comment_text,
104
+ "author": comment_snippet["authorDisplayName"],
105
+ "is_gambling": is_gambling,
106
+ "metrics": metrics
107
+ }
108
+
109
+ moderation_results["total_comments"] += 1
110
+
111
+ if is_gambling:
112
+ moderation_results["gambling_comments"].append(comment_info)
113
+ else:
114
+ moderation_results["safe_comments"].append(comment_info)
115
+
116
+ metrics["original_text"] = comment_text
117
+ moderation_results["moderation_metrics"].append(metrics)
118
+
119
+ # Handle pagination if available
120
+ request = self.youtube_service.commentThreads().list_next(request, response)
121
+ if request:
122
+ response = request.execute()
123
+ else:
124
+ break
125
+
126
+ return moderation_results
127
+
128
+ except Exception as e:
129
+ self.logger.error(f"Error moderating comments: {e}")
130
+ return {"error": str(e)}
131
+
132
+
133
+ def delete_comment(self, comment_id: str) -> bool:
134
+ """
135
+ Delete a specific comment.
136
+
137
+ :param comment_id: YouTube comment ID
138
+ :return: Boolean indicating successful deletion
139
+ """
140
+ try:
141
+
142
+ # self.youtube_service.comments().delete(id=comment_id).execute()
143
+ self.youtube_service.comments().setModerationStatus(
144
+ id=comment_id,
145
+ moderationStatus="rejected"
146
+ ).execute()
147
+ self.logger.info(f"Comment {comment_id} deleted successfully.")
148
+ return True
149
+ except Exception as e:
150
+ self.logger.error(f"Failed to delete comment {comment_id}: {e}")
151
+ return False
152
+
153
+ def get_channel_videos(self, max_results: int = 50) -> List[Dict]:
154
+ """
155
+ Retrieve videos from authenticated user's channel.
156
+
157
+ :param max_results: Maximum number of videos to retrieve
158
+ :return: List of video details
159
+ """
160
+ if not self.youtube_service:
161
+ self.logger.error("YouTube service not authenticated.")
162
+ return []
163
+
164
+ try:
165
+ request = self.youtube_service.search().list(
166
+ part="snippet",
167
+ channelId=self._get_channel_id(),
168
+ maxResults=max_results,
169
+ type="video"
170
+ )
171
+ response = request.execute()
172
+
173
+ videos = []
174
+ for item in response.get("items", []):
175
+ video_info = {
176
+ "id": item["id"]["videoId"],
177
+ "title": item["snippet"]["title"],
178
+ "thumbnail": item["snippet"]["thumbnails"]["default"]["url"]
179
+ }
180
+ videos.append(video_info)
181
+
182
+ return videos
183
+ except Exception as e:
184
+ self.logger.error(f"Error retrieving videos: {e}")
185
+ return []
186
+
187
+ def _get_channel_id(self) -> Optional[str]:
188
+ """
189
+ Retrieve the authenticated user's channel ID.
190
+
191
+ :return: Channel ID or None
192
+ """
193
+ try:
194
+ request = self.youtube_service.channels().list(part="id", mine=True)
195
+ response = request.execute()
196
+ return response["items"][0]["id"]
197
+ except Exception as e:
198
+ self.logger.error(f"Error retrieving channel ID: {e}")
199
+ return None
200
+
app/templates/base.html ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ <!DOCTYPE html>
3
+ <html lang="en">
4
+ <head>
5
+ <meta charset="UTF-8">
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
+ <title>{% block title %}YouTube Comment Moderator{% endblock %}</title>
8
+ <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet">
9
+ <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
10
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js" defer></script>
11
+ </head>
12
+ <body class="bg-gray-100 min-h-screen flex flex-col">
13
+ <nav class="bg-blue-600 text-white p-4 shadow-md">
14
+ <div class="container mx-auto flex justify-between items-center">
15
+ <a href="/" class="text-2xl font-bold">
16
+ <i class="fas fa-shield-alt mr-2"></i>YouTube Comment Guard
17
+ </a>
18
+ {% if current_user %}
19
+ <div class="flex items-center space-x-4">
20
+ <span>Welcome, {{ current_user.username }}</span>
21
+ <a href="/logout" class="bg-red-500 hover:bg-red-600 px-3 py-2 rounded">
22
+ Logout
23
+ </a>
24
+ </div>
25
+ {% else %}
26
+ <a href="/login" class="bg-green-500 hover:bg-green-600 px-4 py-2 rounded">
27
+ Login
28
+ </a>
29
+ {% endif %}
30
+ </div>
31
+ </nav>
32
+
33
+ <main class="container mx-auto px-4 py-8 flex-grow">
34
+ {% block content %}{% endblock %}
35
+ </main>
36
+
37
+ <footer class="bg-gray-800 text-white py-4 text-center">
38
+ <p>&copy; 2024 YouTube Comment Guard. All rights reserved.</p>
39
+ </footer>
40
+
41
+ {% block scripts %}{% endblock %}
42
+ </body>
43
+ </html>
app/templates/index.html CHANGED
@@ -1,10 +1,519 @@
1
  <!DOCTYPE html>
2
- <html>
3
  <head>
4
- <title>FastAPI + Google OAuth2 Example</title>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  </head>
6
  <body>
7
- <h1>Welcome to the FastAPI + Google OAuth2 Example</h1>
8
- <p>Please <a href="/login">Login with Google</a> to see your YouTube channels.</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  </body>
10
- </html>
 
1
  <!DOCTYPE html>
2
+ <html lang="en">
3
  <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Gambling Comment Filter</title>
7
+ <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
8
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
9
+ <style>
10
+ :root {
11
+ --primary: #4361ee;
12
+ --secondary: #3a0ca3;
13
+ --light: #f8f9fa;
14
+ --dark: #212529;
15
+ --success: #2dc653;
16
+ --danger: #e63946;
17
+ --warning: #ff9f1c;
18
+ --info: #90e0ef;
19
+ --border-radius: 0.5rem;
20
+ --box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
21
+ --transition: all 0.3s ease;
22
+ }
23
+
24
+ body {
25
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
26
+ background-color: #f5f7fa;
27
+ color: #333;
28
+ line-height: 1.6;
29
+ padding: 0;
30
+ margin: 0;
31
+ }
32
+
33
+ .navbar {
34
+ background-color: var(--primary);
35
+ box-shadow: var(--box-shadow);
36
+ padding: 1rem 0;
37
+ }
38
+
39
+ .navbar-brand {
40
+ color: white;
41
+ font-weight: 700;
42
+ font-size: 1.5rem;
43
+ padding-left: 1rem;
44
+ }
45
+
46
+ .app-container {
47
+ max-width: 1200px;
48
+ margin: 2rem auto;
49
+ padding: 0 1rem;
50
+ }
51
+
52
+ .card {
53
+ border: none;
54
+ border-radius: var(--border-radius);
55
+ box-shadow: var(--box-shadow);
56
+ margin-bottom: 2rem;
57
+ overflow: hidden;
58
+ transition: var(--transition);
59
+ }
60
+
61
+ .card:hover {
62
+ box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
63
+ }
64
+
65
+ .card-header {
66
+ background-color: white;
67
+ border-bottom: 1px solid rgba(0, 0, 0, 0.1);
68
+ font-weight: 600;
69
+ padding: 1.25rem 1.5rem;
70
+ }
71
+
72
+ .card-body {
73
+ padding: 1.5rem;
74
+ }
75
+
76
+ .form-label {
77
+ font-weight: 500;
78
+ margin-bottom: 0.5rem;
79
+ color: #495057;
80
+ }
81
+
82
+ .form-control {
83
+ border-radius: var(--border-radius);
84
+ padding: 0.75rem 1rem;
85
+ border: 1px solid #ced4da;
86
+ transition: var(--transition);
87
+ }
88
+
89
+ .form-control:focus {
90
+ border-color: var(--primary);
91
+ box-shadow: 0 0 0 0.2rem rgba(67, 97, 238, 0.25);
92
+ }
93
+
94
+ .btn {
95
+ border-radius: var(--border-radius);
96
+ padding: 0.75rem 1.5rem;
97
+ font-weight: 500;
98
+ transition: var(--transition);
99
+ }
100
+
101
+ .btn-primary {
102
+ background-color: var(--primary);
103
+ border-color: var(--primary);
104
+ }
105
+
106
+ .btn-primary:hover {
107
+ background-color: var(--secondary);
108
+ border-color: var(--secondary);
109
+ }
110
+
111
+ .result {
112
+ background-color: #f8f9fa;
113
+ border-radius: var(--border-radius);
114
+ padding: 1.5rem;
115
+ margin-bottom: 2rem;
116
+ }
117
+
118
+ .result-header {
119
+ display: flex;
120
+ align-items: center;
121
+ margin-bottom: 1rem;
122
+ }
123
+
124
+ .result-icon {
125
+ font-size: 1.5rem;
126
+ margin-right: 0.75rem;
127
+ }
128
+
129
+ .result-title {
130
+ font-size: 1.25rem;
131
+ font-weight: 600;
132
+ margin: 0;
133
+ }
134
+
135
+ .badge {
136
+ font-size: 0.85rem;
137
+ padding: 0.5rem 0.75rem;
138
+ border-radius: 50px;
139
+ font-weight: 500;
140
+ }
141
+
142
+ .rules-container {
143
+ background-color: white;
144
+ border-radius: var(--border-radius);
145
+ box-shadow: var(--box-shadow);
146
+ padding: 1.5rem;
147
+ }
148
+
149
+ .rules-category {
150
+ margin-bottom: 2rem;
151
+ }
152
+
153
+ .rules-category h3 {
154
+ font-size: 1.1rem;
155
+ font-weight: 600;
156
+ margin-bottom: 1rem;
157
+ padding-bottom: 0.5rem;
158
+ border-bottom: 2px solid var(--primary);
159
+ color: var(--primary);
160
+ }
161
+
162
+ .rules-list {
163
+ list-style-type: none;
164
+ padding: 0;
165
+ margin: 0;
166
+ max-height: 200px;
167
+ overflow-y: auto;
168
+ }
169
+
170
+ .rules-list li {
171
+ padding: 0.5rem 0.75rem;
172
+ background-color: #f8f9fa;
173
+ margin-bottom: 0.5rem;
174
+ border-radius: var(--border-radius);
175
+ font-size: 0.9rem;
176
+ display: flex;
177
+ align-items: center;
178
+ }
179
+
180
+ .rules-list li:before {
181
+ content: "•";
182
+ color: var(--primary);
183
+ font-weight: bold;
184
+ margin-right: 0.5rem;
185
+ }
186
+
187
+ pre {
188
+ background-color: #f8f9fa;
189
+ padding: 1rem;
190
+ border-radius: var(--border-radius);
191
+ white-space: pre-wrap;
192
+ }
193
+
194
+ .tabs {
195
+ display: flex;
196
+ background-color: white;
197
+ border-radius: var(--border-radius);
198
+ box-shadow: var(--box-shadow);
199
+ margin-bottom: 2rem;
200
+ overflow: hidden;
201
+ }
202
+
203
+ .tab {
204
+ flex: 1;
205
+ text-align: center;
206
+ padding: 1rem;
207
+ cursor: pointer;
208
+ transition: var(--transition);
209
+ border-bottom: 3px solid transparent;
210
+ font-weight: 500;
211
+ }
212
+
213
+ .tab.active {
214
+ background-color: white;
215
+ color: var(--primary);
216
+ border-bottom: 3px solid var(--primary);
217
+ }
218
+
219
+ .tab-icon {
220
+ margin-right: 0.5rem;
221
+ }
222
+
223
+ .tab-content {
224
+ display: none;
225
+ }
226
+
227
+ .tab-content.active {
228
+ display: block;
229
+ }
230
+
231
+ .footer {
232
+ text-align: center;
233
+ padding: 2rem 0;
234
+ margin-top: 2rem;
235
+ background-color: white;
236
+ border-top: 1px solid rgba(0, 0, 0, 0.1);
237
+ }
238
+ </style>
239
  </head>
240
  <body>
241
+ <!-- Navbar -->
242
+ <nav class="navbar navbar-dark">
243
+ <div class="container">
244
+ <span class="navbar-brand">
245
+ <i class="fas fa-shield-alt me-2"></i>
246
+ Gambling Comment Filter
247
+ </span>
248
+ </div>
249
+ </nav>
250
+
251
+ <div class="app-container">
252
+ <!-- Results Section (if available) -->
253
+ {% if result %}
254
+ <div class="card mb-4">
255
+ <div class="card-header d-flex align-items-center">
256
+ <i class="fas fa-chart-bar me-2"></i>
257
+ Analysis Results
258
+ </div>
259
+ <div class="card-body">
260
+ {% if result.message %}
261
+ <div class="alert alert-success">
262
+ <i class="fas fa-check-circle me-2"></i>
263
+ {{ result.message }}
264
+ </div>
265
+ {% elif result.upload_result %}
266
+ <div class="result">
267
+ <div class="result-header">
268
+ <div class="result-icon text-primary">
269
+ <i class="fas fa-file-alt"></i>
270
+ </div>
271
+ <h5 class="result-title">File Upload Results</h5>
272
+ </div>
273
+ <div class="row mb-3">
274
+ <div class="col-md-6">
275
+ <div class="card bg-light">
276
+ <div class="card-body text-center">
277
+ <h3 class="text-danger mb-1">{{ result.upload_result.gambling_comments | length }}</h3>
278
+ <p class="mb-0">Gambling Comments Found</p>
279
+ </div>
280
+ </div>
281
+ </div>
282
+ <div class="col-md-6">
283
+ <div class="card bg-light">
284
+ <div class="card-body text-center">
285
+ <h3 class="text-success mb-1">{{ result.upload_result.safe_comments | length }}</h3>
286
+ <p class="mb-0">Safe Comments Found</p>
287
+ </div>
288
+ </div>
289
+ </div>
290
+ </div>
291
+ <details>
292
+ <summary class="mb-2 btn btn-sm btn-outline-secondary">View Detailed Results</summary>
293
+ <pre>{{ result.upload_result | pretty_json | safe }}</pre>
294
+ </details>
295
+ </div>
296
+ {% else %}
297
+ <div class="result">
298
+ <div class="result-header">
299
+ <div class="result-icon {% if result.is_gambling %}text-danger{% else %}text-success{% endif %}">
300
+ <i class="fas {% if result.is_gambling %}fa-exclamation-triangle{% else %}fa-check-circle{% endif %}"></i>
301
+ </div>
302
+ <h5 class="result-title">Classification Result</h5>
303
+ </div>
304
+ <div class="mb-3">
305
+ <span class="badge {% if result.is_gambling %}bg-danger{% else %}bg-success{% endif %} me-2">
306
+ <i class="fas {% if result.is_gambling %}fa-times{% else %}fa-check{% endif %} me-1"></i>
307
+ {{ "Gambling Comment" if result.is_gambling else "Safe Comment" }}
308
+ </span>
309
+ <span class="badge bg-info text-dark">
310
+ <i class="fas fa-chart-line me-1"></i>
311
+ Confidence: {{ result.metrics.confidence_score }}
312
+ </span>
313
+ </div>
314
+ <details>
315
+ <summary class="mb-2 btn btn-sm btn-outline-secondary">View Analysis Details</summary>
316
+ <pre>{{ result.upload_result | pretty_json | safe }}</pre>
317
+ </details>
318
+ </div>
319
+ {% endif %}
320
+ </div>
321
+ </div>
322
+ {% endif %}
323
+
324
+ <!-- Tabs for Different Functions -->
325
+ <div class="tabs">
326
+ <div class="tab active" data-tab="classify">
327
+ <i class="fas fa-search tab-icon"></i>
328
+ Classify Comment
329
+ </div>
330
+ <div class="tab" data-tab="upload">
331
+ <i class="fas fa-upload tab-icon"></i>
332
+ Batch Upload
333
+ </div>
334
+ <div class="tab" data-tab="rules">
335
+ <i class="fas fa-cogs tab-icon"></i>
336
+ Manage Rules
337
+ </div>
338
+ </div>
339
+
340
+ <!-- Tab Contents -->
341
+ <div class="tab-content active" id="classify-tab">
342
+ <div class="card">
343
+ <div class="card-header">
344
+ <i class="fas fa-search me-2"></i>
345
+ Classify Single Comment
346
+ </div>
347
+ <div class="card-body">
348
+ <form action="/classify" method="post">
349
+ <div class="form-group mb-3">
350
+ <label for="comment" class="form-label">Enter your comment:</label>
351
+ <textarea class="form-control" name="comment" id="comment" rows="4" placeholder="Type or paste the comment here...">{{ comment }}</textarea>
352
+ </div>
353
+ <button type="submit" class="btn btn-primary">
354
+ <i class="fas fa-check-circle me-2"></i>
355
+ Analyze Comment
356
+ </button>
357
+ </form>
358
+ </div>
359
+ </div>
360
+ </div>
361
+
362
+ <div class="tab-content" id="upload-tab">
363
+ <div class="card">
364
+ <div class="card-header">
365
+ <i class="fas fa-upload me-2"></i>
366
+ Batch Upload &amp; Process
367
+ </div>
368
+ <div class="card-body">
369
+ <form action="/upload" method="post" enctype="multipart/form-data">
370
+ <div class="form-group mb-3">
371
+ <label for="file" class="form-label">Select File for Analysis:</label>
372
+ <input type="file" class="form-control" name="file" id="file">
373
+ <small class="form-text text-muted">Supported formats: CSV, JSON, Excel</small>
374
+ </div>
375
+ <div class="form-group mb-3">
376
+ <label for="column" class="form-label">Column Name:</label>
377
+ <input type="text" class="form-control" name="column" id="column" value="comment" placeholder="Column containing comments">
378
+ <small class="form-text text-muted">Default is "comment"</small>
379
+ </div>
380
+ <button type="submit" class="btn btn-primary">
381
+ <i class="fas fa-file-import me-2"></i>
382
+ Upload &amp; Process File
383
+ </button>
384
+ </form>
385
+ </div>
386
+ </div>
387
+ </div>
388
+
389
+ <div class="tab-content" id="rules-tab">
390
+ <div class="card mb-4">
391
+ <div class="card-header">
392
+ <i class="fas fa-plus-circle me-2"></i>
393
+ Add New Rule
394
+ </div>
395
+ <div class="card-body">
396
+ <form action="/add_rule" method="post">
397
+ <div class="row">
398
+ <div class="col-md-6">
399
+ <div class="form-group mb-3">
400
+ <label for="rule_type" class="form-label">Rule Type:</label>
401
+ <select name="rule_type" id="rule_type" class="form-control">
402
+ <option value="platform">Platform Name</option>
403
+ <option value="gambling_term">Gambling Term</option>
404
+ <option value="safe_indicator">Safe Indicator</option>
405
+ <option value="gambling_context">Gambling Context</option>
406
+ <option value="ambiguous_term">Ambiguous Term</option>
407
+ </select>
408
+ </div>
409
+ </div>
410
+ <div class="col-md-6">
411
+ <div class="form-group mb-3">
412
+ <label for="rule_value" class="form-label">Rule Value:</label>
413
+ <input type="text" class="form-control" name="rule_value" id="rule_value" placeholder="Enter new rule value">
414
+ </div>
415
+ </div>
416
+ </div>
417
+ <button type="submit" class="btn btn-primary">
418
+ <i class="fas fa-plus me-2"></i>
419
+ Add Rule
420
+ </button>
421
+ </form>
422
+ </div>
423
+ </div>
424
+
425
+ <div class="rules-container">
426
+ <h2 class="mb-4">Current Rules</h2>
427
+ <div class="row">
428
+ <div class="col-md-4">
429
+ <div class="rules-category">
430
+ <h3><i class="fas fa-dice me-2"></i>Platform Names</h3>
431
+ <ul class="rules-list">
432
+ {% for rule in rules.platform %}
433
+ <li>{{ rule }}</li>
434
+ {% endfor %}
435
+ </ul>
436
+ </div>
437
+ </div>
438
+ <div class="col-md-4">
439
+ <div class="rules-category">
440
+ <h3><i class="fas fa-coins me-2"></i>Gambling Terms</h3>
441
+ <ul class="rules-list">
442
+ {% for rule in rules.gambling_term %}
443
+ <li>{{ rule }}</li>
444
+ {% endfor %}
445
+ </ul>
446
+ </div>
447
+ </div>
448
+ <div class="col-md-4">
449
+ <div class="rules-category">
450
+ <h3><i class="fas fa-shield-alt me-2"></i>Safe Indicators</h3>
451
+ <ul class="rules-list">
452
+ {% for rule in rules.safe_indicator %}
453
+ <li>{{ rule }}</li>
454
+ {% endfor %}
455
+ </ul>
456
+ </div>
457
+ </div>
458
+ </div>
459
+ <div class="row">
460
+ <div class="col-md-6">
461
+ <div class="rules-category">
462
+ <h3><i class="fas fa-comment-alt me-2"></i>Gambling Contexts</h3>
463
+ <ul class="rules-list">
464
+ {% for rule in rules.gambling_context %}
465
+ <li>{{ rule }}</li>
466
+ {% endfor %}
467
+ </ul>
468
+ </div>
469
+ </div>
470
+ <div class="col-md-6">
471
+ <div class="rules-category">
472
+ <h3><i class="fas fa-question-circle me-2"></i>Ambiguous Terms</h3>
473
+ <ul class="rules-list">
474
+ {% for rule in rules.ambiguous_term %}
475
+ <li>{{ rule }}</li>
476
+ {% endfor %}
477
+ </ul>
478
+ </div>
479
+ </div>
480
+ </div>
481
+ </div>
482
+ </div>
483
+ </div>
484
+
485
+ <footer class="footer">
486
+ <div class="container">
487
+ <p class="mb-0">Gambling Comment Filter &copy; 2025 | All Rights Reserved</p>
488
+ </div>
489
+ </footer>
490
+
491
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
492
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
493
+ <script>
494
+ // Tab functionality
495
+ document.addEventListener('DOMContentLoaded', function() {
496
+ const tabs = document.querySelectorAll('.tab');
497
+
498
+ tabs.forEach(tab => {
499
+ tab.addEventListener('click', function() {
500
+ // Remove active class from all tabs
501
+ tabs.forEach(t => t.classList.remove('active'));
502
+
503
+ // Add active class to clicked tab
504
+ this.classList.add('active');
505
+
506
+ // Hide all tab contents
507
+ document.querySelectorAll('.tab-content').forEach(content => {
508
+ content.classList.remove('active');
509
+ });
510
+
511
+ // Show the corresponding tab content
512
+ const tabId = this.getAttribute('data-tab') + '-tab';
513
+ document.getElementById(tabId).classList.add('active');
514
+ });
515
+ });
516
+ });
517
+ </script>
518
  </body>
519
+ </html>
app/templates/login.html ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>YouTube Comment Moderator</title>
7
+ <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
8
+ <style>
9
+ body {
10
+ background-color: #f4f4f4;
11
+ display: flex;
12
+ align-items: center;
13
+ justify-content: center;
14
+ min-height: 100vh;
15
+ font-family: 'Arial', sans-serif;
16
+ }
17
+ .login-container {
18
+ max-width: 400px;
19
+ width: 100%;
20
+ padding: 2rem;
21
+ background-color: white;
22
+ border-radius: 12px;
23
+ box-shadow: 0 10px 25px rgba(0,0,0,0.1);
24
+ }
25
+ .login-header {
26
+ text-align: center;
27
+ margin-bottom: 2rem;
28
+ }
29
+ .login-header img {
30
+ width: 80px;
31
+ margin-bottom: 1rem;
32
+ }
33
+ .btn-youtube {
34
+ background-color: #FF0000;
35
+ color: white;
36
+ display: flex;
37
+ align-items: center;
38
+ justify-content: center;
39
+ gap: 10px;
40
+ transition: background-color 0.3s ease;
41
+ }
42
+ .btn-youtube:hover {
43
+ background-color: #CC0000;
44
+ color: white;
45
+ }
46
+ .login-footer {
47
+ text-align: center;
48
+ margin-top: 1rem;
49
+ color: #6c757d;
50
+ font-size: 0.8rem;
51
+ }
52
+ </style>
53
+ </head>
54
+ <body>
55
+ <div class="login-container">
56
+ <div class="login-header">
57
+ <img src="../static/logo.png" alt="YouTube Comment Moderator">
58
+ <h2>YouTube Comment Moderator</h2>
59
+ <p class="text-muted">Simplify your comment management</p>
60
+ </div>
61
+
62
+ {% if error %}
63
+ <div class="alert alert-danger mb-3">{{ error }}</div>
64
+ {% endif %}
65
+
66
+ <form action="/auth" method="get">
67
+ <button type="submit" class="btn btn-youtube w-100 py-2">
68
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="white">
69
+ <path d="M19.615 3.184c-3.604-.246-11.631-.245-15.23 0-3.897.266-4.356 2.62-4.385 8.816.029 6.185.484 8.549 4.385 8.816 3.6.246 11.626.246 15.23 0 3.897-.266 4.356-2.62 4.385-8.816-.029-6.185-.484-8.549-4.385-8.816zm-10.615 12.816v-8l8 3.993-8 4.007z"/>
70
+ </svg>
71
+ Login with YouTube
72
+ </button>
73
+ </form>
74
+
75
+ <div class="login-footer">
76
+ <p>Securely powered by Google OAuth</p>
77
+ </div>
78
+ </div>
79
+
80
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
81
+ </body>
82
+ </html>
app/templates/video_comments.html ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}
4
+ Moderate Comments - {{ video.title }}
5
+ {% endblock %}
6
+
7
+ {% block content %}
8
+ <div class="container mx-auto px-4 py-8">
9
+ <!-- Outer container with card styling -->
10
+ <div class="bg-white shadow-xl rounded-lg overflow-visible">
11
+ <!-- Header section with video title and controls -->
12
+ <div class="bg-gradient-to-r from-blue-500 to-purple-600 p-6">
13
+ <div class="flex justify-between items-center">
14
+ <h1 class="text-3xl font-bold text-white flex items-center">
15
+ <i class="fab fa-youtube mr-4 text-red-500"></i>
16
+ {{ video.title }}
17
+ </h1>
18
+ <div class="flex space-x-4">
19
+ <button id="refreshCommentsBtn" class="bg-white text-blue-600 px-4 py-2 rounded-lg hover:bg-blue-50 transition duration-300 flex items-center shadow-md">
20
+ <i class="fas fa-sync mr-2"></i>Refresh Comments
21
+ </button>
22
+ <div x-data="{ showSettings: false, saveSettings() {
23
+ // Add your save logic here, e.g., update a model or call an API
24
+ alert('Settings saved!');
25
+ this.showSettings = false; // Optionally hide the settings box after saving
26
+ } }" class="relative">
27
+ <button @click="showSettings = !showSettings" class="bg-white text-purple-600 px-4 py-2 rounded-lg hover:bg-purple-50 transition duration-300 flex items-center shadow-md">
28
+ <i class="fas fa-cog mr-2"></i>Moderation Settings
29
+ </button>
30
+ <div x-show="showSettings" x-transition class="absolute right-0 mt-2 w-72 bg-white rounded-lg shadow-2xl p-6 z-20 border border-gray-100">
31
+ <h3 class="text-xl font-semibold mb-4 text-gray-800">Moderation Settings</h3>
32
+ <div class="space-y-4">
33
+ <div class="flex items-center">
34
+ <input type="checkbox" id="auto-delete" class="mr-3 rounded text-blue-500 focus:ring-blue-400">
35
+ <label for="auto-delete" class="text-gray-700">Auto-delete flagged comments</label>
36
+ </div>
37
+ <div>
38
+ <label class="block mb-2 text-gray-700">Gambling Confidence Threshold</label>
39
+ <input type="range" min="0" max="1" step="0.05" class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer" x-model="threshold" value="0.55">
40
+ </div>
41
+ <button @click="saveSettings" class="w-full bg-gradient-to-r from-blue-500 to-purple-600 text-white py-2 rounded-lg hover:opacity-90 transition duration-300">
42
+ Save Settings
43
+ </button>
44
+ </div>
45
+ </div>
46
+ </div>
47
+
48
+ </div>
49
+ </div>
50
+ </div>
51
+
52
+ <!-- Comments Section -->
53
+ <div class="grid md:grid-cols-2 gap-6 p-6">
54
+ <!-- Safe Comments Column -->
55
+ <div>
56
+ <h2 class="text-2xl font-semibold mb-4 flex items-center text-green-600">
57
+ <i class="fas fa-check-circle mr-3"></i>Safe Comments
58
+ <span class="text-sm text-gray-500 ml-2">({{ safe_comments|length }})</span>
59
+ </h2>
60
+ <div class="space-y-4">
61
+ {% for comment in safe_comments %}
62
+ <div class="bg-white p-4 rounded-lg shadow-md border border-gray-100">
63
+ <p class="mb-2 text-gray-800">{{ comment.text }}</p>
64
+ <div class="text-sm text-gray-600 flex justify-between items-center">
65
+ <span class="font-medium">{{ comment.author }}</span>
66
+ <span class="text-xs text-green-600">Safe</span>
67
+ </div>
68
+ </div>
69
+ {% endfor %}
70
+ </div>
71
+ </div>
72
+ <!-- Flagged Comments Column -->
73
+ <div>
74
+ <h2 class="text-2xl font-semibold mb-4 flex items-center text-red-600">
75
+ <i class="fas fa-exclamation-triangle mr-3"></i>Flagged Comments
76
+ <span id="flaggedCount" class="text-sm text-gray-500 ml-2">({{ flagged_comments|length }})</span>
77
+
78
+ </h2>
79
+ <div class="space-y-4">
80
+ {% for comment in flagged_comments %}
81
+ <div class="comment-card bg-red-50 p-4 rounded-lg shadow-md border border-red-200 relative">
82
+ <p class="mb-2 text-gray-800">{{ comment.text }}</p>
83
+ <div class="text-sm text-gray-600 flex justify-between items-center">
84
+ <span class="font-medium">{{ comment.author }}</span>
85
+ <div class="flex space-x-2">
86
+ <button data-comment-id="{{ comment.id }}" data-video-id="{{ video.id }}" class="delete-comment-btn bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600 transition duration-300">
87
+ Delete
88
+ </button>
89
+ <button data-comment-id="{{ comment.id }}" data-video-id="{{ video.id }}"class="keep-comment-btn bg-green-500 text-white px-3 py-1 rounded hover:bg-green-600 transition duration-300">
90
+ Keep
91
+ </button>
92
+ </div>
93
+ </div>
94
+ <div class="mt-2 text-xs text-gray-500">
95
+ <strong>Gambling Confidence:</strong> {{ comment.metrics.confidence_score }}
96
+ </div>
97
+ </div>
98
+ {% endfor %}
99
+ </div>
100
+ </div>
101
+ </div>
102
+ </div>
103
+ </div>
104
+ {% endblock %}
105
+
106
+ {% block scripts %}
107
+ <script>
108
+ document.addEventListener('DOMContentLoaded', function() {
109
+ // Delete Comment Functionality
110
+ document.querySelectorAll('.delete-comment-btn').forEach(button => {
111
+ button.addEventListener('click', async function(e) {
112
+ e.stopPropagation(); // Ensure this click doesn't affect other handlers
113
+ const commentId = this.getAttribute('data-comment-id');
114
+ const videoId = this.getAttribute('data-video-id');
115
+ const commentCard = this.closest('.comment-card');
116
+
117
+ try {
118
+ const response = await fetch(`/api/comments/${commentId}?video_id=${videoId}`, {
119
+ method: 'DELETE'
120
+ });
121
+ const data = await response.json();
122
+
123
+ if (data.success) {
124
+ // Remove the comment from the DOM
125
+ commentCard.remove();
126
+
127
+ // Optionally, update the flagged comments count
128
+ const flaggedCommentsCount = document.querySelector('h2 span');
129
+ const currentCount = parseInt(flaggedCommentsCount.textContent.replace(/[()]/g, ''));
130
+ flaggedCommentsCount.textContent = `(${currentCount - 1})`;
131
+ } else {
132
+ alert("Failed to delete comment. Please refresh and try again.");
133
+ }
134
+ } catch (err) {
135
+ console.error(err);
136
+ alert("Error deleting comment.");
137
+ }
138
+ });
139
+ });
140
+
141
+ // Keep Comment Functionality with added debug logging
142
+ document.querySelectorAll('.keep-comment-btn').forEach(button => {
143
+ button.addEventListener('click', async function(e) {
144
+ e.stopPropagation();
145
+ const commentId = this.getAttribute('data-comment-id');
146
+ const videoId = this.getAttribute('data-video-id');
147
+ const commentCard = this.closest('.comment-card');
148
+ console.log(`Keep button clicked for commentId: ${commentId}, videoId: ${videoId}`);
149
+
150
+ try {
151
+ // Make the API call to keep the comment on YouTube
152
+ const response = await fetch(`/api/comments/keep/${commentId}?video_id=${videoId}`, {
153
+ method: 'POST'
154
+ });
155
+ console.log("Response received from API:", response);
156
+ const data = await response.json();
157
+ console.log("Parsed response data:", data);
158
+
159
+ if (data.success) {
160
+ // If successful, remove from DOM and update the flagged count
161
+ commentCard.remove();
162
+ const flaggedCommentsCount = document.querySelector('#flaggedCount');
163
+ const currentCount = parseInt(flaggedCommentsCount.textContent);
164
+ flaggedCommentsCount.textContent = currentCount - 1;
165
+ console.log(`Comment ${commentId} removed, flagged count updated to ${currentCount - 1}`);
166
+ } else {
167
+ console.error(`API reported error for comment ${commentId}:`, data.error);
168
+ alert("Failed to keep comment: " + (data.error || 'Unknown error'));
169
+ }
170
+ } catch (err) {
171
+ console.error(`Error keeping comment ${commentId}:`, err);
172
+ alert("Error keeping comment.");
173
+ }
174
+ });
175
+ });
176
+
177
+
178
+ // Refresh Comments Functionality
179
+ document.getElementById('refreshCommentsBtn').addEventListener('click', function(e) {
180
+ e.stopPropagation(); // Prevent any unwanted event bubbling
181
+ const videoId = "{{ video.id }}";
182
+ window.location.href = `/video/${videoId}`;
183
+ });
184
+ });
185
+ </script>
186
+ {% endblock %}
app/templates/videos.html ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Your YouTube Videos{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="container mx-auto px-4 py-8">
7
+ <div class="flex items-center justify-between mb-8">
8
+ <h1 class="text-4xl font-extrabold text-gray-800 flex items-center">
9
+ <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10 mr-4 text-red-600" viewBox="0 0 20 20" fill="currentColor">
10
+ <path fill-rule="evenodd" d="M3 5a2 2 0 012-2h10a2 2 0 012 2v10a2 2 0 01-2 2H5a2 2 0 01-2-2V5zm12 1V5H5v1h10zm-5 8.5a3.5 3.5 0 100-7 3.5 3.5 0 000 7z" clip-rule="evenodd" />
11
+ </svg>
12
+ YouTube Video Management
13
+ </h1>
14
+ <button class="bg-green-500 text-white px-5 py-2 rounded-lg shadow-md hover:bg-green-600 transition duration-300 flex items-center">
15
+ <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
16
+ <path fill-rule="evenodd" d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z" clip-rule="evenodd" />
17
+ </svg>
18
+ Refresh Videos
19
+ </button>
20
+ </div>
21
+
22
+ {% if videos %}
23
+ <div class="grid md:grid-cols-3 gap-6">
24
+ {% for video in videos %}
25
+ <div class="bg-white rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 transform hover:-translate-y-2 border border-gray-100">
26
+ <div class="relative">
27
+ <img src="{{ video.thumbnail }}" alt="{{ video.title }}" class="w-full h-56 object-cover rounded-t-xl">
28
+ <div class="absolute top-2 right-2 bg-black bg-opacity-50 text-white px-3 py-1 rounded-full text-sm">
29
+ {{ video.duration }}
30
+ </div>
31
+ </div>
32
+ <div class="p-5">
33
+ <h3 class="font-bold text-xl mb-3 text-gray-800 line-clamp-2">{{ video.title }}</h3>
34
+ <div class="flex justify-between items-center">
35
+ <div class="flex items-center space-x-3">
36
+ <span class="text-sm text-gray-600 flex items-center">
37
+ <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2 text-gray-400" viewBox="0 0 20 20" fill="currentColor">
38
+ <path d="M2 5a2 2 0 012-2h12a2 2 0 012 2v10a2 2 0 01-2 2H4a2 2 0 01-2-2V5zm3.5 1a.5.5 0 00-.5.5v1a.5.5 0 00.5.5h2a.5.5 0 00.5-.5v-1a.5.5 0 00-.5-.5h-2zm5 0a.5.5 0 00-.5.5v1a.5.5 0 00.5.5h2a.5.5 0 00.5-.5v-1a.5.5 0 00-.5-.5h-2zM6 9.5a.5.5 0 01.5-.5h2a.5.5 0 01.5.5v1a.5.5 0 01-.5.5h-2a.5.5 0 01-.5-.5v-1zm5 0a.5.5 0 01.5-.5h2a.5.5 0 01.5.5v1a.5.5 0 01-.5.5h-2a.5.5 0 01-.5-.5v-1z" />
39
+ </svg>
40
+ {{ video.comments_count }} Comments
41
+ </span>
42
+ </div>
43
+ <a href="/video/{{ video.id }}" class="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 transition duration-300 shadow-md">
44
+ Moderate
45
+ </a>
46
+ </div>
47
+ </div>
48
+ </div>
49
+ {% endfor %}
50
+ </div>
51
+ {% else %}
52
+ <div class="bg-white rounded-xl shadow-lg p-12 text-center">
53
+ <div class="flex justify-center mb-6">
54
+ <svg xmlns="http://www.w3.org/2000/svg" class="h-24 w-24 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
55
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
56
+ </svg>
57
+ </div>
58
+ <h2 class="text-2xl font-semibold text-gray-700 mb-4">No Videos Found</h2>
59
+ <p class="text-gray-500 mb-6">It looks like there are no videos to moderate at the moment.</p>
60
+ <button class="bg-blue-500 text-white px-6 py-3 rounded-lg hover:bg-blue-600 transition duration-300 shadow-md">
61
+ Refresh Channel
62
+ </button>
63
+ </div>
64
+ {% endif %}
65
+ </div>
66
+ {% endblock %}