File size: 2,271 Bytes
dc19c4a | 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 | import pandas as pd
import duckdb
from datetime import datetime, timedelta
from typing import Dict, List, Optional
from pydantic import BaseModel
class PopularLesson(BaseModel):
lesson: str
runs: int
class LessonsData(BaseModel):
completed: int
popular: List[PopularLesson]
def format_lessons_data(user_id: str,con) -> Optional[LessonsData]:
try:
try:
year = datetime.now().strftime("%Y")
s3_path = f"s3://learnpython/lessonsrun/{year}/*/*/*.parquet"
print(f"path ", s3_path)
# Create a temporary view for better performance
con.execute(f"""
CREATE OR REPLACE TEMPORARY VIEW yearly_lessons AS
SELECT * FROM read_parquet('{s3_path}')
""")
query = f"""
WITH popular_lessons AS (
SELECT
title as lesson,
COUNT(*) as runs
FROM yearly_lessons
WHERE title IS NOT NULL
GROUP BY title
ORDER BY runs DESC
LIMIT 3
)
SELECT {{
'completed': (SELECT COUNT(DISTINCT title)
FROM yearly_lessons
WHERE user_id = '{user_id}'
AND title IS NOT NULL),
'popular': LIST(struct_pack(lesson, runs))
}} as lessons_data
FROM popular_lessons;
"""
result = con.execute(query).fetchone()
if result and result[0]:
data = result[0]
return LessonsData(
completed=data['completed'],
popular=[PopularLesson(lesson=item['lesson'], runs=item['runs'])
for item in data['popular']]
)
return LessonsData(completed=0, popular=[])
except Exception as e:
print(f"Error querying data: {str(e)}")
return LessonsData(completed=0, popular=[])
except Exception as e:
print(f"Error in format_lessons_data: {str(e)}")
return LessonsData(completed=0, popular=[])
|