Download lessonsdata.py from testser2/mzlessons: direct link, hf CLI and curl.
- Browser
- Download file 2.27 kB
-
https://huggingface.co/spaces/testser2/mzlessons/resolve/main/lessonsdata.py
- Command line
-
hf download hf://spaces/testser2/mzlessons/lessonsdata.py
-
curl -L -o lessonsdata.py https://huggingface.co/spaces/testser2/mzlessons/resolve/main/lessonsdata.py
2.27 kB
| 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=[]) | |