lessonsstats
Browse files14 unmodified lines15161718192021222324252627101 unmodified lines12913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321444 unmodified lines25926026126226326426526626726826927027117827227327414 unmodified linesclass User(BaseModel): id:str
class PopularLesson(BaseModel): lesson: str runs: int
class LessonsData(BaseModel): completed: int popular: List[PopularLesson]class DailyRun(TypedDict): date: str runs: int101 unmodified lines
def format_lessons_data(user_id: str) -> Optional[LessonsData]: try: # Initialize DuckDB connection con = duckdb.connect()
# Load the S3 extension con.execute("INSTALL httpfs;") con.execute("LOAD httpfs;")
# Configure S3 settings aws_access_key_id = "c4dfbdd1eff1be49e872d1e1489bf4b7" aws_secret_access_key = "0d4a2371d814b62abe5d0643850e665c"
con.execute(f""" SET s3_endpoint='eu2.contabostorage.com'; SET s3_access_key_id='{aws_access_key_id}'; SET s3_secret_access_key='{aws_secret_access_key}'; SET s3_url_style='path'; SET s3_use_ssl=true; """)
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=[])
finally: # Clean up temporary view and close connection con.execute("DROP VIEW IF EXISTS yearly_lessons") con.close()
except Exception as e: print(f"Error in format_lessons_data: {str(e)}") return LessonsData(completed=0, popular=[])
# @app.post("/create")# async def index(item: Message): 44 unmodified lines return {"result": results}
@app.post("/lessonsstats")async def codestats(user: User): results = format_lessons_data(user_id) return {"result": results}
@app.get("/")async def running():
return {"Hello": f" MamaKuchi Report Generator "} return {"Hello": f" MamaKuchi Report Generator "}
app.py+97-1