-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdb4.py
More file actions
55 lines (48 loc) · 1.81 KB
/
db4.py
File metadata and controls
55 lines (48 loc) · 1.81 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
import json
from app.db.database import Base, engine, SessionLocal
from app.models.album import Album
from app.models.rating import Rating
from app.models.user import User
from app.models.list import List
from app.models.list_item import ListItem
from sqlalchemy import func
from app.utils.hash import hash_password
# Drop and recreate tables
Base.metadata.drop_all(bind=engine)
Base.metadata.create_all(bind=engine)
print("Tables dropped and recreated.")
sample_users = [
User(username="shanthony_mantano99", email="[email protected]", hashed_password=hash_password("fantano420")),
User(username="particlegardener", email="[email protected]", hashed_password=hash_password("jalapeno12")),
User(username="paul_mcartney", email="[email protected]", hashed_password=hash_password("herethereand")),
User(username="jessemoras", email="[email protected]", hashed_password=hash_password("schwartzschwartzschwartz")),
]
# Load scraped albums
with open("scraped_albums.json", "r", encoding="utf-8") as f:
scraped_data = json.load(f)
# Convert JSON to Album instances
albums_to_add = [
Album(
title=item["title"],
artist=item["artist"],
year=item["year"],
genre=item.get("genre"),
cover_url=item["cover_url"]
)
for item in scraped_data
]
# Commit to database
db = SessionLocal()
db.add_all(sample_users)
try:
db.add_all(albums_to_add)
db.commit()
print(f"✅ Inserted {len(albums_to_add)} albums from scraped_albums.json")
# Backfill average scores to None (explicitly)
for album in db.query(Album).all():
avg = db.query(func.avg(Rating.score)).filter(Rating.album_id == album.id).scalar()
album.average_score = round(avg, 2) if avg is not None else None
db.commit()
print("✅ Backfilled average scores.")
finally:
db.close()