Shubhi324 commited on
Commit
f767df6
·
verified ·
1 Parent(s): 32ca500

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -118
app.py CHANGED
@@ -1,118 +1,121 @@
1
- from fastapi import FastAPI, Depends, HTTPException
2
- from fastapi.middleware.cors import CORSMiddleware
3
- from sqlalchemy.orm import Session
4
- from typing import List
5
- import database, schemas, moderator
6
-
7
- # Init DB
8
- database.init_db()
9
-
10
- app = FastAPI(title="SafeStream API")
11
-
12
- # Allow all origins for dev
13
- app.add_middleware(
14
- CORSMiddleware,
15
- allow_origins=["*"],
16
- allow_credentials=True,
17
- allow_methods=["*"],
18
- allow_headers=["*"],
19
- )
20
-
21
- def get_db():
22
- db = database.SessionLocal()
23
- try:
24
- yield db
25
- finally:
26
- db.close()
27
-
28
- @app.on_event("startup")
29
- def startup_event():
30
- # Seed data if empty
31
- db = database.SessionLocal()
32
- if db.query(database.Video).count() == 0:
33
- # Using real YouTube IDs for the iframe
34
- seed_videos = [
35
- database.Video(title="Daily Vlog #102", url="dQw4w9WgXcQ", description="Just another day in the life. Comment below!"),
36
- database.Video(title="Gaming Highlights", url="jNQXAC9IVRw", description="Insane plays from last night."),
37
- database.Video(title="Relaxing Rain Sounds", url="q76bMs-NwRk", description="Sleep aid.")
38
- ]
39
- db.add_all(seed_videos)
40
- db.commit()
41
- db.close()
42
-
43
- @app.get("/videos", response_model=List[schemas.Video])
44
- def get_videos(db: Session = Depends(get_db)):
45
- return db.query(database.Video).all()
46
-
47
- @app.get("/videos/{video_id}", response_model=schemas.Video)
48
- def get_video(video_id: int, db: Session = Depends(get_db)):
49
- video = db.query(database.Video).filter(database.Video.id == video_id).first()
50
- if not video:
51
- raise HTTPException(status_code=404, detail="Video not found")
52
- return video
53
-
54
-
55
- @app.get("/videos/{video_id}/comments", response_model=List[schemas.Comment])
56
- def get_comments(video_id: int, db: Session = Depends(get_db)):
57
- return db.query(database.Comment).filter(database.Comment.video_id == video_id).all()
58
-
59
- @app.post("/comments", response_model=schemas.Comment)
60
- def create_comment(comment: schemas.CommentCreate, db: Session = Depends(get_db)):
61
- # 1. Analyze for toxicity
62
- analysis = moderator.moderator.analyze(comment.text)
63
-
64
- # 2. Save to DB
65
- db_comment = database.Comment(
66
- video_id=comment.video_id,
67
- user=comment.user,
68
- text=comment.text,
69
- timestamp=comment.timestamp,
70
- is_toxic=analysis["is_toxic"],
71
- toxicity_score=analysis["score"],
72
- flagged_reason=analysis["reason"]
73
- )
74
- db.add(db_comment)
75
- db.commit()
76
- db.refresh(db_comment)
77
- return db_comment
78
-
79
- @app.delete("/comments")
80
- def clear_comments(db: Session = Depends(get_db)):
81
- db.query(database.Comment).delete()
82
- db.commit()
83
- return {"message": "All comments cleared"}
84
-
85
- @app.get("/stats")
86
- def get_stats(db: Session = Depends(get_db)):
87
- comments = db.query(database.Comment).all()
88
- total = len(comments)
89
- toxic_comments = [c for c in comments if c.is_toxic]
90
- toxic_count = len(toxic_comments)
91
-
92
- # Custom Classification Logic for Demo
93
- types = {
94
- "Insult": 0,
95
- "Identity Hate": 0,
96
- "Threat": 0,
97
- "Online Harassment": 0
98
- }
99
-
100
- for c in toxic_comments:
101
- text = c.text.lower()
102
- if any(w in text for w in ["kill", "die", "hurt", "attack", "gun", "shoot", "murder"]):
103
- types["Threat"] += 1
104
- elif any(w in text for w in ["hate", "racist", "gay", "lesbian", "black", "white", "jew", "muslim", "women", "men", "trans"]):
105
- types["Identity Hate"] += 1
106
- elif any(w in text for w in ["stupid", "idiot", "dumb", "ugly", "fat", "loser", "moron", "coward"]):
107
- types["Insult"] += 1
108
- else:
109
- # Catch-all for other toxic comments
110
- types["Online Harassment"] += 1
111
-
112
- return {
113
- "total_comments": total,
114
- "toxic_comments": toxic_count,
115
- "toxic_ratio": (toxic_count/total) if total > 0 else 0,
116
- "types_breakdown": [{"name": k, "value": v} for k, v in types.items()]
117
- }
118
-
 
 
 
 
1
+ import uvicorn
2
+ from fastapi import FastAPI, Depends, HTTPException
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from sqlalchemy.orm import Session
5
+ from typing import List
6
+
7
+ # Import your local files
8
+ import database
9
+ import schemas
10
+ import moderator
11
+
12
+ # Initialize Database
13
+ database.init_db()
14
+
15
+ app = FastAPI(title="SafeStream API")
16
+
17
+ # Allow all origins for development
18
+ app.add_middleware(
19
+ CORSMiddleware,
20
+ allow_origins=["*"],
21
+ allow_credentials=True,
22
+ allow_methods=["*"],
23
+ allow_headers=["*"],
24
+ )
25
+
26
+ def get_db():
27
+ db = database.SessionLocal()
28
+ try:
29
+ yield db
30
+ finally:
31
+ db.close()
32
+
33
+ @app.on_event("startup")
34
+ def startup_event():
35
+ # Seed data if empty
36
+ db = database.SessionLocal()
37
+ if db.query(database.Video).count() == 0:
38
+ seed_videos = [
39
+ database.Video(title="Daily Vlog #102", url="dQw4w9WgXcQ", description="Just another day in the life. Comment below!"),
40
+ database.Video(title="Gaming Highlights", url="jNQXAC9IVRw", description="Insane plays from last night."),
41
+ database.Video(title="Relaxing Rain Sounds", url="q76bMs-NwRk", description="Sleep aid.")
42
+ ]
43
+ db.add_all(seed_videos)
44
+ db.commit()
45
+ db.close()
46
+
47
+ @app.get("/")
48
+ def read_root():
49
+ return {"message": "SafeStream API is running. Visit /docs for documentation."}
50
+
51
+ @app.get("/videos", response_model=List[schemas.Video])
52
+ def get_videos(db: Session = Depends(get_db)):
53
+ return db.query(database.Video).all()
54
+
55
+ @app.get("/videos/{video_id}", response_model=schemas.Video)
56
+ def get_video(video_id: int, db: Session = Depends(get_db)):
57
+ video = db.query(database.Video).filter(database.Video.id == video_id).first()
58
+ if not video:
59
+ raise HTTPException(status_code=404, detail="Video not found")
60
+ return video
61
+
62
+ @app.get("/videos/{video_id}/comments", response_model=List[schemas.Comment])
63
+ def get_comments(video_id: int, db: Session = Depends(get_db)):
64
+ return db.query(database.Comment).filter(database.Comment.video_id == video_id).all()
65
+
66
+ @app.post("/comments", response_model=schemas.Comment)
67
+ def create_comment(comment: schemas.CommentCreate, db: Session = Depends(get_db)):
68
+ # 1. Analyze for toxicity using your moderator tool
69
+ analysis = moderator.moderator.analyze(comment.text)
70
+
71
+ # 2. Save to DB
72
+ db_comment = database.Comment(
73
+ video_id=comment.video_id,
74
+ user=comment.user,
75
+ text=comment.text,
76
+ timestamp=comment.timestamp,
77
+ is_toxic=analysis["is_toxic"],
78
+ toxicity_score=analysis["score"],
79
+ flagged_reason=analysis["reason"]
80
+ )
81
+ db.add(db_comment)
82
+ db.commit()
83
+ db.refresh(db_comment)
84
+ return db_comment
85
+
86
+ @app.delete("/comments")
87
+ def clear_comments(db: Session = Depends(get_db)):
88
+ db.query(database.Comment).delete()
89
+ db.commit()
90
+ return {"message": "All comments cleared"}
91
+
92
+ @app.get("/stats")
93
+ def get_stats(db: Session = Depends(get_db)):
94
+ comments = db.query(database.Comment).all()
95
+ total = len(comments)
96
+ toxic_comments = [c for c in comments if c.is_toxic]
97
+ toxic_count = len(toxic_comments)
98
+
99
+ types = {"Insult": 0, "Identity Hate": 0, "Threat": 0, "Online Harassment": 0}
100
+
101
+ for c in toxic_comments:
102
+ text = c.text.lower()
103
+ if any(w in text for w in ["kill", "die", "hurt", "attack", "gun", "shoot", "murder"]):
104
+ types["Threat"] += 1
105
+ elif any(w in text for w in ["hate", "racist", "gay", "lesbian", "black", "white", "jew", "muslim", "women", "men", "trans"]):
106
+ types["Identity Hate"] += 1
107
+ elif any(w in text for w in ["stupid", "idiot", "dumb", "ugly", "fat", "loser", "moron", "coward"]):
108
+ types["Insult"] += 1
109
+ else:
110
+ types["Online Harassment"] += 1
111
+
112
+ return {
113
+ "total_comments": total,
114
+ "toxic_comments": toxic_count,
115
+ "toxic_ratio": (toxic_count/total) if total > 0 else 0,
116
+ "types_breakdown": [{"name": k, "value": v} for k, v in types.items()]
117
+ }
118
+
119
+ # CRITICAL: This part runs the server on Hugging Face's port
120
+ if __name__ == "__main__":
121
+ uvicorn.run(app, host="0.0.0.0", port=7860)