Upload 2 files
Browse filesFiles changed (2)
- lessonsdata.pyAdded+97
- stats.pyAdded+106
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697import 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) -> 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=[])
if __name__ == "__main__":
# Example usage with a specific user_id
user_id = "18eee92a-9c14-4484-b3c0-25d75a840d77"
result = format_lessons_data(user_id)
print(result.model_dump())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106import pandas as pd
import duckdb
from datetime import datetime, timedelta
from typing import Dict, List, TypedDict
from supabase import create_client
class DailyRun(TypedDict):
date: str
runs: int
class TotalTimeRun(TypedDict):
total: int
avgExecutionTime: str
overTime: List[DailyRun]
def format_code_run_data(user_id: str) -> TotalTimeRun:
try:
over_time: List[DailyRun] = []
total_runs = 0
total_execution_time = 0
# Generate dates for the last 5 days
current_date = datetime.now()
dates = [(current_date - timedelta(days=i)).date() for i in range(4, -1, -1)]
# 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:
for date in dates:
year = date.strftime("%Y")
month = date.strftime("%m")
day = date.strftime("%d")
date_str = date.isoformat()
try:
query = f"""
SELECT
COUNT(*) as run_count,
COALESCE(SUM(execution_time), 0) as total_exec_time
FROM read_parquet('s3://learnpython/coderuns/{year}/{month}/{day}/{user_id}/{user_id}.parquet')
WHERE user_id = '{user_id}'
"""
results = con.execute(query).fetchall()
if results and len(results) > 0:
run_count = int(results[0][0])
total_runs += run_count
total_execution_time += float(results[0][1] or 0)
over_time.append({
"date": date_str,
"runs": run_count
})
else:
over_time.append({
"date": date_str,
"runs": 0
})
except Exception as e:
print(f"Error for {date_str}:", e)
over_time.append({
"date": date_str,
"runs": 0
})
finally:
con.close()
avg_execution_time = f"{(total_execution_time / total_runs):.2f}s" if total_runs > 0 else "0.00s"
return {
"total": total_runs,
"avgExecutionTime": avg_execution_time,
"overTime": over_time
}
except Exception as e:
print("Error in format_code_run_data:", e)
return {
"total": 0,
"avgExecutionTime": "0.00s",
"overTime": []
}
# Example usage:
if __name__ == "__main__":
result = format_code_run_data("18eee92a-9c14-4484-b3c0-25d75a840d77")
print(result)lessonsdata.pyAdded+97
stats.pyAdded+106