diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..167ec597ecf3c695269e28ea34f5a92726367f3b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +FROM python:3.9-slim + +RUN apt-get update && apt-get install -y \ + ffmpeg \ + git \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . + +RUN chmod -R 777 /app + +ENV PORT=7860 +CMD ["python", "run.py", "server"] \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..743b1637698ac918d5914bdf2c1dacbb4987a503 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,24 @@ +yt-dlp==2024.12.23 +pydub==0.25.1 +openai-whisper==20231117 +torch +torchaudio +google-generativeai==0.3.2 +langchain==0.1.0 +langchain-google-genai==0.0.5 +fastapi==0.109.0 +uvicorn[standard]==0.27.0 +pydantic==2.5.3 +pydantic-settings==2.1.0 +python-multipart==0.0.6 +python-dotenv==1.0.0 +httpx==0.26.0 +aiofiles==23.2.1 +sqlmodel==0.0.14 +asyncpg==0.29.0 +greenlet==3.0.3 +passlib[bcrypt]==1.7.4 +python-jose[cryptography]==3.3.0 +bcrypt==4.1.2 +pytest==8.0.0 +pytest-asyncio==0.23.3 \ No newline at end of file diff --git a/run.py b/run.py new file mode 100644 index 0000000000000000000000000000000000000000..880bade67f02008b22163d3f1334243e2541bb18 --- /dev/null +++ b/run.py @@ -0,0 +1,137 @@ +""" +Main entry point for YouTube Study Notes AI. +Provides CLI interface and server startup. +""" + +import sys +import argparse +from pathlib import Path + +# Import necessary modules for server and middleware +from src.utils.logger import setup_logger +from src.utils.config import settings + +logger = setup_logger(__name__) + + +def run_server(): + """Start the FastAPI server with CORS enabled for Flutter Web.""" + import uvicorn + from fastapi.middleware.cors import CORSMiddleware + from src.api.main import app # Import the app instance directly + + logger.info("Configuring CORS for Flutter Web...") + + # Add CORS Middleware to allow requests from Chrome/Flutter + app.add_middleware( + CORSMiddleware, + allow_origins=["*"], # Allows all origins + allow_credentials=True, + allow_methods=["*"], # Allows all methods + allow_headers=["*"], # Allows all headers + ) + + logger.info("Starting YouTube Study Notes AI server...") + logger.info( + f"Server will be available at http://{settings.api_host}:{settings.api_port}" + ) + logger.info( + f"API Documentation: http://{settings.api_host}:{settings.api_port}/docs" + ) + + # Run the server using the app object directly + # Note: reload is disabled here to ensure CORS settings are applied correctly from this script + uvicorn.run(app, host=settings.api_host, port=settings.api_port, log_level="info") + + +def run_cli(youtube_url: str, output_file: str = None): + """ + Run note generation from command line. + + Args: + youtube_url: YouTube video URL + output_file: Optional output file path + """ + from src.audio.downloader import YouTubeDownloader + from src.transcription.whisper_transcriber import WhisperTranscriber + from src.summarization.note_generator import NoteGenerator + + logger.info("Starting CLI mode") + logger.info(f"Processing URL: {youtube_url}") + + try: + # Step 1: Download audio + logger.info("Step 1/3: Downloading audio...") + downloader = YouTubeDownloader() + video_info = downloader.get_video_info(youtube_url) + audio_file = downloader.download_audio(youtube_url) + + # Step 2: Transcribe + logger.info("Step 2/3: Transcribing audio...") + transcriber = WhisperTranscriber() + transcript_data = transcriber.transcribe(audio_file) + + # Step 3: Generate notes + logger.info("Step 3/3: Generating notes...") + note_gen = NoteGenerator() + notes = note_gen.generate_notes_from_full_transcript( + transcript_data["text"], video_info["title"] + ) + + # Format and save + final_notes = note_gen.format_final_notes( + notes, video_info["title"], youtube_url, video_info["duration"] + ) + + if output_file: + output_path = Path(output_file) + else: + output_path = settings.output_dir / f"{video_info['title'][:50]}_notes.md" + + output_path.write_text(final_notes, encoding="utf-8") + + logger.info(f"āœ… Notes saved to: {output_path}") + print(f"\nāœ… Success! Notes saved to: {output_path}") + + # Cleanup + downloader.cleanup(audio_file) + + except Exception as e: + logger.error(f"Failed: {e}") + print(f"\nāŒ Error: {e}") + sys.exit(1) + + +def main(): + """Main entry point with argument parsing.""" + parser = argparse.ArgumentParser( + description="YouTube Study Notes AI - Generate structured notes from educational videos" + ) + + parser.add_argument( + "mode", + choices=["server", "cli"], + help="Run mode: server (API + web UI) or cli (direct processing)", + ) + + parser.add_argument( + "--url", type=str, help="YouTube video URL (required for cli mode)" + ) + + parser.add_argument( + "--output", type=str, help="Output file path (optional for cli mode)" + ) + + args = parser.parse_args() + + if args.mode == "server": + run_server() + elif args.mode == "cli": + if not args.url: + print("Error: --url is required for cli mode") + sys.exit(1) + run_cli(args.url, args.output) + + +if __name__ == "__main__": + main() diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/__pycache__/__init__.cpython-312.pyc b/src/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..458cefe41e8e02e82d043ffce82612cc8eb26fa2 Binary files /dev/null and b/src/__pycache__/__init__.cpython-312.pyc differ diff --git a/src/api/__init__.py b/src/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/api/__pycache__/__init__.cpython-312.pyc b/src/api/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3db1f4535dcc311340a1ad9ccbee277853c2eef Binary files /dev/null and b/src/api/__pycache__/__init__.cpython-312.pyc differ diff --git a/src/api/__pycache__/analytics_routes.cpython-312.pyc b/src/api/__pycache__/analytics_routes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..172d1562bffa4157bb6be82cf11134c30483d83b Binary files /dev/null and b/src/api/__pycache__/analytics_routes.cpython-312.pyc differ diff --git a/src/api/__pycache__/auth_routes.cpython-312.pyc b/src/api/__pycache__/auth_routes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e76f59560847f1f9147677d47f6d87868b83044 Binary files /dev/null and b/src/api/__pycache__/auth_routes.cpython-312.pyc differ diff --git a/src/api/__pycache__/main.cpython-312.pyc b/src/api/__pycache__/main.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f237e2c1076ed8d63ac9e8f60ad0e99ade6219ad Binary files /dev/null and b/src/api/__pycache__/main.cpython-312.pyc differ diff --git a/src/api/__pycache__/notes_routes.cpython-312.pyc b/src/api/__pycache__/notes_routes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edd23b5049093234a5227b6be82aa1d578cc306a Binary files /dev/null and b/src/api/__pycache__/notes_routes.cpython-312.pyc differ diff --git a/src/api/analytics_routes.py b/src/api/analytics_routes.py new file mode 100644 index 0000000000000000000000000000000000000000..66b301cc8141ec75c2a2e1a56263e4575aa690b2 --- /dev/null +++ b/src/api/analytics_routes.py @@ -0,0 +1,139 @@ +""" +Analytics API endpoints for user statistics. +""" + +from typing import Dict, List +from fastapi import APIRouter, Depends +from pydantic import BaseModel, Field +from sqlmodel import Session, select, func +from datetime import datetime + +from src.db.database import get_session +from src.db.models import User, Note +from src.auth.dependencies import get_current_user +from src.utils.logger import setup_logger + +logger = setup_logger(__name__) + +router = APIRouter(prefix="/analytics", tags=["Analytics"]) + + +# Response Models +class AnalyticsResponse(BaseModel): + """Response model for user analytics.""" + total_videos_processed: int = Field(..., description="Total number of videos processed") + total_study_time_seconds: int = Field(..., description="Total study time in seconds") + total_study_time_formatted: str = Field(..., description="Total study time formatted (HH:MM:SS)") + total_notes: int = Field(..., description="Total number of notes generated") + average_video_duration: float = Field(..., description="Average video duration in seconds") + languages_used: List[str] = Field(..., description="List of languages used") + recent_activity: List[Dict] = Field(..., description="Recent notes (last 5)") + + class Config: + json_schema_extra = { + "example": { + "total_videos_processed": 15, + "total_study_time_seconds": 18000, + "total_study_time_formatted": "5:00:00", + "total_notes": 15, + "average_video_duration": 1200.0, + "languages_used": ["en", "es"], + "recent_activity": [ + { + "video_title": "Python Basics", + "created_at": "2024-01-27T05:00:00", + "duration": 1800 + } + ] + } + } + + +def format_duration(seconds: int) -> str: + """ + Format duration in seconds to HH:MM:SS format. + + Args: + seconds: Duration in seconds + + Returns: + Formatted duration string + """ + if seconds is None or seconds == 0: + return "0:00:00" + + hours = seconds // 3600 + minutes = (seconds % 3600) // 60 + secs = seconds % 60 + + return f"{hours}:{minutes:02d}:{secs:02d}" + + +@router.get("", response_model=AnalyticsResponse) +async def get_analytics( + current_user: User = Depends(get_current_user), + session: Session = Depends(get_session) +): + """ + Get user statistics and analytics. + + **Protected Route**: Requires authentication + + Returns comprehensive statistics including: + - Total videos processed + - Total study time (sum of video durations) + - Average video duration + - Languages used + - Recent activity + """ + # Get all notes for the user + statement = select(Note).where(Note.user_id == current_user.id) + notes = session.exec(statement).all() + + total_notes = len(notes) + + # Calculate total study time (sum of video durations) + total_study_time = 0 + durations = [] + for note in notes: + if note.video_duration: + total_study_time += note.video_duration + durations.append(note.video_duration) + + # Calculate average duration + average_duration = sum(durations) / len(durations) if durations else 0 + + # Get unique languages + languages = list(set(note.language for note in notes if note.language)) + + # Get recent activity (last 5 notes) + recent_statement = ( + select(Note) + .where(Note.user_id == current_user.id) + .order_by(Note.created_at.desc()) + .limit(5) + ) + recent_notes = session.exec(recent_statement).all() + + recent_activity = [ + { + "video_title": note.video_title, + "video_url": note.video_url, + "created_at": str(note.created_at), + "duration": note.video_duration, + "duration_formatted": format_duration(note.video_duration) if note.video_duration else "N/A" + } + for note in recent_notes + ] + + logger.info(f"Analytics retrieved for user {current_user.email}") + + return AnalyticsResponse( + total_videos_processed=total_notes, + total_study_time_seconds=total_study_time, + total_study_time_formatted=format_duration(total_study_time), + total_notes=total_notes, + average_video_duration=round(average_duration, 2), + languages_used=languages, + recent_activity=recent_activity + ) diff --git a/src/api/auth_routes.py b/src/api/auth_routes.py new file mode 100644 index 0000000000000000000000000000000000000000..d3d0ba4eefdcfc9b63d3fa0d3428e568b164e33d --- /dev/null +++ b/src/api/auth_routes.py @@ -0,0 +1,162 @@ +""" +Authentication API endpoints for user signup and login. +""" + +from datetime import timedelta +from fastapi import APIRouter, Depends, HTTPException, status +from fastapi.security import OAuth2PasswordRequestForm +from pydantic import BaseModel, EmailStr, Field +from sqlmodel import select +from sqlmodel.ext.asyncio.session import AsyncSession + +from src.db.database import get_session +from src.db.models import User +from src.auth.security import hash_password, verify_password, create_access_token +from src.utils.logger import setup_logger +from src.utils.config import settings + +logger = setup_logger(__name__) + +router = APIRouter(prefix="/auth", tags=["Authentication"]) + + +# Request/Response Models +class SignupRequest(BaseModel): + """Request model for user signup.""" + email: EmailStr = Field(..., description="User email address") + username: str = Field(..., min_length=3, max_length=50, description="Username") + password: str = Field(..., min_length=6, description="Password (min 6 characters)") + + class Config: + json_schema_extra = { + "example": { + "email": "student@example.com", + "username": "Student123", + "password": "secure_password" + } + } + + +class UserResponse(BaseModel): + """Response model for user data (without password).""" + id: int + email: str + username: str + role: str + created_at: str + + class Config: + json_schema_extra = { + "example": { + "id": 1, + "email": "student@example.com", + "username": "Student123", + "role": "user", + "created_at": "2024-01-27T05:00:00" + } + } + + +class TokenResponse(BaseModel): + """Response model for login token.""" + access_token: str = Field(..., description="JWT access token") + token_type: str = Field(default="bearer", description="Token type") + expires_in: int = Field(..., description="Token expiration time in minutes") + + class Config: + json_schema_extra = { + "example": { + "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", + "token_type": "bearer", + "expires_in": 60 + } + } + + +@router.post("/signup", response_model=UserResponse, status_code=status.HTTP_201_CREATED) +async def signup( + signup_data: SignupRequest, + session: AsyncSession = Depends(get_session) +): + """ + Register a new user. + """ + # Check if email or username already exists + statement = select(User).where( + (User.email == signup_data.email) | (User.username == signup_data.username) + ) + result = await session.exec(statement) + existing_user = result.first() + + if existing_user: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="Email or Username already registered" + ) + + # Create new user with hashed password + hashed_password_value = hash_password(signup_data.password) + + new_user = User( + email=signup_data.email, + username=signup_data.username, + password_hash=hashed_password_value, + role="user" + ) + + session.add(new_user) + await session.commit() + await session.refresh(new_user) + + logger.info(f"New user registered: {new_user.email}") + + return UserResponse( + id=new_user.id, + email=new_user.email, + username=new_user.username, + role=new_user.role, + created_at=str(new_user.created_at) + ) + + +@router.post("/login", response_model=TokenResponse) +async def login( + form_data: OAuth2PasswordRequestForm = Depends(), + session: AsyncSession = Depends(get_session) +): + """ + Authenticate user and return JWT access token. + """ + # Find user by username + statement = select(User).where(User.username == form_data.username) + result = await session.exec(statement) + user = result.first() + + # If not found by username, try finding by email + if not user: + statement = select(User).where(User.email == form_data.username) + result = await session.exec(statement) + user = result.first() + + # Verify user exists and password is correct + if not user or not verify_password(form_data.password, user.password_hash): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect username or password", + headers={"WWW-Authenticate": "Bearer"}, + ) + + # Create access token + access_token_expires = timedelta(minutes=settings.access_token_expire_minutes) + access_token = create_access_token( + data={"sub": user.username}, + expires_delta=access_token_expires + ) + + logger.info(f"User logged in: {user.username}") + + return TokenResponse( + access_token=access_token, + token_type="bearer", + expires_in=settings.access_token_expire_minutes + ) \ No newline at end of file diff --git a/src/api/main.py b/src/api/main.py new file mode 100644 index 0000000000000000000000000000000000000000..b8797988e93776a6e23ae195cdbf4396d0c46cdf --- /dev/null +++ b/src/api/main.py @@ -0,0 +1,365 @@ +""" +FastAPI application for YouTube study notes generation. +Provides REST API endpoints for note generation and status tracking. +""" + +import asyncio +import uuid +from datetime import datetime +from pathlib import Path +from typing import Dict, Optional +from enum import Enum +from contextlib import asynccontextmanager + +from fastapi import FastAPI, HTTPException, BackgroundTasks +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import FileResponse +from pydantic import BaseModel, HttpUrl, Field + +from src.audio.downloader import YouTubeDownloader +from src.audio.processor import AudioProcessor +from src.transcription.whisper_transcriber import WhisperTranscriber +from src.summarization.segmenter import TranscriptSegmenter +from src.summarization.note_generator import NoteGenerator +from src.utils.logger import setup_logger +from src.utils.config import settings +from src.db.database import create_db_and_tables + +logger = setup_logger(__name__) + + +# Pydantic Models +class TaskStatus(str, Enum): + """Task processing status.""" + + PENDING = "pending" + DOWNLOADING = "downloading" + TRANSCRIBING = "transcribing" + GENERATING_NOTES = "generating_notes" + COMPLETED = "completed" + FAILED = "failed" + + +class GenerateNotesRequest(BaseModel): + """Request model for note generation.""" + + youtube_url: HttpUrl = Field(..., description="YouTube video URL") + language: str = Field(default="en", description="Video language code") + + class Config: + json_schema_extra = { + "example": { + "youtube_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ", + "language": "en", + } + } + + +class TaskResponse(BaseModel): + """Response model for task creation.""" + + task_id: str = Field(..., description="Unique task identifier") + status: TaskStatus = Field(..., description="Current task status") + message: str = Field(..., description="Status message") + + +class TaskStatusResponse(BaseModel): + """Response model for task status queries.""" + + task_id: str + status: TaskStatus + message: str + video_title: Optional[str] = None + progress: Optional[int] = Field(None, description="Progress percentage (0-100)") + notes_file: Optional[str] = None + created_at: datetime + updated_at: datetime + + +# Global task storage (in production, use a database) +tasks: Dict[str, Dict] = {} + + +# --- Lifespan Event Handler (Fixes Windows Event Loop Issue) --- +@asynccontextmanager +async def lifespan(app: FastAPI): + """ + Handle startup and shutdown events. + Initializes the database tables when the server starts. + """ + logger.info("Lifespan: Initializing database tables...") + await create_db_and_tables() + logger.info("Lifespan: Database tables initialized successfully") + yield + logger.info("Lifespan: Server shutting down...") + + +# FastAPI app +app = FastAPI( + title="YouTube Study Notes AI", + description="Generate structured study notes from YouTube educational videos", + version="1.0.0", + lifespan=lifespan, +) + +# CORS middleware +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], # In production, specify allowed origins + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# Include routers +from src.api.auth_routes import router as auth_router +from src.api.notes_routes import router as notes_router +from src.api.analytics_routes import router as analytics_router + +app.include_router(auth_router) +app.include_router(notes_router) +app.include_router(analytics_router) + + +@app.get("/") +async def root(): + """Root endpoint with API information.""" + return { + "name": "YouTube Study Notes AI", + "version": "1.0.0", + "description": "Generate structured study notes from YouTube videos with user management", + "endpoints": { + "authentication": { + "signup": "POST /auth/signup", + "login": "POST /auth/login", + }, + "notes": { + "create": "POST /notes", + "list": "GET /notes", + "get": "GET /notes/{note_id}", + "delete": "DELETE /notes/{note_id}", + }, + "analytics": {"user_stats": "GET /analytics"}, + "generation": { + "generate_notes": "POST /generate-notes", + "check_status": "GET /status/{task_id}", + "download_notes": "GET /download/{task_id}", + }, + }, + "documentation": {"swagger_ui": "/docs", "redoc": "/redoc"}, + } + + +@app.post("/generate-notes", response_model=TaskResponse) +async def generate_notes( + request: GenerateNotesRequest, background_tasks: BackgroundTasks +): + """ + Generate study notes from a YouTube video. + + This endpoint starts an async task to process the video. + Use the returned task_id to check status and download results. + """ + try: + # Generate unique task ID + task_id = str(uuid.uuid4()) + + # Initialize task + tasks[task_id] = { + "status": TaskStatus.PENDING, + "message": "Task created, starting processing...", + "youtube_url": str(request.youtube_url), + "language": request.language, + "video_title": None, + "progress": 0, + "notes_file": None, + "created_at": datetime.now(), + "updated_at": datetime.now(), + } + + # Start background processing + background_tasks.add_task( + process_video, task_id, str(request.youtube_url), request.language + ) + + logger.info(f"Created task {task_id} for URL: {request.youtube_url}") + + return TaskResponse( + task_id=task_id, + status=TaskStatus.PENDING, + message="Processing started. Use task_id to check status.", + ) + + except Exception as e: + logger.error(f"Failed to create task: {e}") + raise HTTPException(status_code=500, detail=str(e)) + + +@app.get("/status/{task_id}", response_model=TaskStatusResponse) +async def get_status(task_id: str): + """Get the current status of a processing task.""" + if task_id not in tasks: + raise HTTPException(status_code=404, detail="Task not found") + + task = tasks[task_id] + + return TaskStatusResponse( + task_id=task_id, + status=task["status"], + message=task["message"], + video_title=task.get("video_title"), + progress=task.get("progress"), + notes_file=task.get("notes_file"), + created_at=task["created_at"], + updated_at=task["updated_at"], + ) + + +@app.get("/download/{task_id}") +async def download_notes(task_id: str): + """Download the generated notes file.""" + if task_id not in tasks: + raise HTTPException(status_code=404, detail="Task not found") + + task = tasks[task_id] + + if task["status"] != TaskStatus.COMPLETED: + raise HTTPException( + status_code=400, detail=f"Notes not ready. Current status: {task['status']}" + ) + + notes_file = task.get("notes_file") + if not notes_file or not Path(notes_file).exists(): + raise HTTPException(status_code=404, detail="Notes file not found") + + return FileResponse( + notes_file, media_type="text/markdown", filename=Path(notes_file).name + ) + + +async def process_video(task_id: str, youtube_url: str, language: str): + """ + Background task to process video and generate notes. + + Args: + task_id: Unique task identifier + youtube_url: YouTube video URL + language: Video language code + """ + audio_file = None + + try: + # Update status: Downloading + update_task(task_id, TaskStatus.DOWNLOADING, "Downloading video...", 10) + + # Download video and extract audio + downloader = YouTubeDownloader() + + # Get video info + video_info = downloader.get_video_info(youtube_url) + video_title = video_info["title"] + video_duration = video_info["duration"] + + update_task( + task_id, + TaskStatus.DOWNLOADING, + f"Downloading: {video_title}", + 20, + video_title=video_title, + ) + + audio_file = downloader.download_audio(youtube_url, task_id) + + # Validate audio + processor = AudioProcessor() + if not processor.validate_audio_file(audio_file): + raise ValueError("Invalid audio file") + + # Update status: Transcribing + update_task(task_id, TaskStatus.TRANSCRIBING, "Transcribing audio...", 40) + + # Transcribe audio + transcriber = WhisperTranscriber() + transcript_data = transcriber.transcribe(audio_file, language=language) + + update_task(task_id, TaskStatus.TRANSCRIBING, "Transcription complete", 60) + + # Update status: Generating notes + update_task( + task_id, TaskStatus.GENERATING_NOTES, "Generating structured notes...", 70 + ) + + # Segment transcript + segmenter = TranscriptSegmenter() + + # For shorter transcripts, process as a whole + # For longer ones, segment first + word_count = len(transcript_data["text"].split()) + + if word_count < 2000: + # Short video: process full transcript + logger.info("Processing short video (full transcript)") + note_gen = NoteGenerator() + notes = note_gen.generate_notes_from_full_transcript( + transcript_data["text"], video_title + ) + else: + # Long video: segment and process + logger.info("Processing long video (segmented)") + segments = segmenter.segment_transcript(transcript_data, method="time") + + note_gen = NoteGenerator() + notes = note_gen.generate_notes_from_segments(segments) + + # Add title + notes = f"# {video_title}\n\n{notes}" + + update_task(task_id, TaskStatus.GENERATING_NOTES, "Formatting notes...", 90) + + # Format final notes with metadata + final_notes = note_gen.format_final_notes( + notes, video_title, youtube_url, video_duration + ) + + # Save notes to file + notes_file = settings.output_dir / f"{task_id}_notes.md" + notes_file.write_text(final_notes, encoding="utf-8") + + # Update status: Completed + update_task( + task_id, + TaskStatus.COMPLETED, + "Notes generated successfully!", + 100, + notes_file=str(notes_file), + ) + + logger.info(f"Task {task_id} completed successfully") + + except Exception as e: + logger.error(f"Task {task_id} failed: {e}") + update_task(task_id, TaskStatus.FAILED, f"Processing failed: {str(e)}", 0) + + finally: + # Cleanup audio file + if audio_file and audio_file.exists(): + try: + downloader.cleanup(audio_file) + except Exception as e: + logger.warning(f"Cleanup failed: {e}") + + +def update_task( + task_id: str, status: TaskStatus, message: str, progress: int, **kwargs +): + """Update task status and metadata.""" + if task_id in tasks: + tasks[task_id].update( + { + "status": status, + "message": message, + "progress": progress, + "updated_at": datetime.now(), + **kwargs, + } + ) diff --git a/src/api/notes_routes.py b/src/api/notes_routes.py new file mode 100644 index 0000000000000000000000000000000000000000..6892366df187acbccfeed84b8fc505139d491d23 --- /dev/null +++ b/src/api/notes_routes.py @@ -0,0 +1,155 @@ +""" +Notes management API endpoints. +""" + +from typing import List, Optional +from pathlib import Path +import os + +from fastapi import APIRouter, Depends, HTTPException, status, Query +from fastapi.responses import FileResponse, JSONResponse +from pydantic import BaseModel, HttpUrl, Field +from sqlmodel import Session, select + +from src.db.database import get_session +from src.db.models import User, Note +from src.auth.dependencies import get_current_user +from src.utils.logger import setup_logger +from src.utils.config import settings + +logger = setup_logger(__name__) + +router = APIRouter(prefix="/notes", tags=["Notes"]) + + +# --- New Models for File-based Notes --- +class GeneratedNoteFile(BaseModel): + filename: str + title: str + created_at: float + size: int + + +# --- Existing Models --- +class CreateNoteRequest(BaseModel): + video_url: HttpUrl = Field(..., description="YouTube video URL") + video_title: str = Field(..., max_length=500, description="Video title") + summary_text: str = Field(..., description="Generated study notes in markdown") + video_duration: Optional[int] = Field(None, description="Video duration in seconds") + language: str = Field( + default="en", max_length=10, description="Video language code" + ) + + +class NoteResponse(BaseModel): + id: int + video_url: str + video_title: str + summary_text: str + video_duration: Optional[int] + language: str + user_id: int + created_at: str + + +# ========================================== +# āœ… NEW ENDPOINTS: Read from 'outputs' folder +# ========================================== + + +@router.get("/generated", response_model=List[GeneratedNoteFile]) +async def list_generated_notes(): + """ + List all markdown files found in the 'outputs' directory. + This bypasses the database to show files directly. + """ + notes = [] + output_dir = settings.output_dir + + # Create directory if it doesn't exist + if not output_dir.exists(): + return [] + + # Scan for .md files + # We look for files ending with _notes.md + for file_path in output_dir.glob("*_notes.md"): + try: + # Try to read the first line to get a clean title + content = file_path.read_text(encoding="utf-8") + lines = content.split("\n") + # Usually the first line is "# Title" + title = lines[0].replace("#", "").strip() if lines else file_path.name + + stats = file_path.stat() + + notes.append( + GeneratedNoteFile( + filename=file_path.name, + title=title if title else file_path.name, + created_at=stats.st_mtime, + size=stats.st_size, + ) + ) + except Exception as e: + logger.error(f"Error reading file {file_path}: {e}") + continue + + # Sort by newest first + notes.sort(key=lambda x: x.created_at, reverse=True) + return notes + + +@router.get("/generated/{filename}") +async def get_generated_note_content(filename: str): + """ + Get the full content of a specific markdown file. + """ + # Security check: prevent directory traversal + if ".." in filename or "/" in filename: + raise HTTPException(status_code=400, detail="Invalid filename") + + file_path = settings.output_dir / filename + + if not file_path.exists(): + raise HTTPException(status_code=404, detail="Note file not found") + + content = file_path.read_text(encoding="utf-8") + return {"content": content, "filename": filename} + + +# ========================================== +# End of New Endpoints +# ========================================== + +# ... (Database endpoints kept for compatibility if needed later) ... +# You can leave the rest of the file as is, or I can include it below just in case. +# For brevity, I'll include the standard DB create/get just to not break anything. + + +@router.post("", response_model=NoteResponse, status_code=status.HTTP_201_CREATED) +async def create_note( + note_data: CreateNoteRequest, + current_user: User = Depends(get_current_user), + session: Session = Depends(get_session), +): + new_note = Note( + video_url=str(note_data.video_url), + video_title=note_data.video_title, + summary_text=note_data.summary_text, + video_duration=note_data.video_duration, + language=note_data.language, + user_id=current_user.id, + ) + session.add(new_note) + session.commit() + session.refresh(new_note) + return NoteResponse( + id=new_note.id, + video_url=new_note.video_url, + video_title=new_note.video_title, + summary_text=new_note.summary_text, + video_duration=new_note.video_duration, + language=new_note.language, + user_id=new_note.user_id, + created_at=str(new_note.created_at), + ) diff --git a/src/audio/__init__.py b/src/audio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/audio/__pycache__/__init__.cpython-312.pyc b/src/audio/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24ca028ecb24afacb2e2942265ba796b2bead5c5 Binary files /dev/null and b/src/audio/__pycache__/__init__.cpython-312.pyc differ diff --git a/src/audio/__pycache__/downloader.cpython-312.pyc b/src/audio/__pycache__/downloader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4b3a240a25b7cb4bcefe42b85da5925e325c202 Binary files /dev/null and b/src/audio/__pycache__/downloader.cpython-312.pyc differ diff --git a/src/audio/__pycache__/processor.cpython-312.pyc b/src/audio/__pycache__/processor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05e85ac6e726d0ed311bbc5e879ae31de9c8c679 Binary files /dev/null and b/src/audio/__pycache__/processor.cpython-312.pyc differ diff --git a/src/audio/downloader.py b/src/audio/downloader.py new file mode 100644 index 0000000000000000000000000000000000000000..c2b9b66fd89b34b58f46a865a5009bd3c5dec1c8 --- /dev/null +++ b/src/audio/downloader.py @@ -0,0 +1,171 @@ +""" +YouTube video downloader and audio extraction module. +Uses yt-dlp for robust YouTube video handling. +""" + +import re +from pathlib import Path +from typing import Dict, Optional +import yt_dlp + +from src.utils.logger import setup_logger +from src.utils.config import settings + +logger = setup_logger(__name__) + + +class YouTubeDownloader: + """Handles YouTube video downloading and audio extraction.""" + + def __init__(self, output_dir: Optional[Path] = None): + """ + Initialize the YouTube downloader. + + Args: + output_dir: Directory to save downloaded audio files + """ + self.output_dir = output_dir or settings.temp_dir + self.output_dir.mkdir(parents=True, exist_ok=True) + + @staticmethod + def is_valid_youtube_url(url: str) -> bool: + """ + Validate if the URL is a valid YouTube link. + + Args: + url: YouTube URL to validate + + Returns: + True if valid YouTube URL, False otherwise + """ + youtube_regex = ( + r'(https?://)?(www\.)?' + r'(youtube|youtu|youtube-nocookie)\.(com|be)/' + r'(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})' + ) + + match = re.match(youtube_regex, url) + return bool(match) + + def get_video_info(self, url: str) -> Dict[str, any]: + """ + Get video information without downloading. + + Args: + url: YouTube video URL + + Returns: + Dictionary containing video metadata + + Raises: + ValueError: If URL is invalid or video is unavailable + """ + if not self.is_valid_youtube_url(url): + raise ValueError(f"Invalid YouTube URL: {url}") + + ydl_opts = { + 'quiet': True, + 'no_warnings': True, + } + + try: + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + info = ydl.extract_info(url, download=False) + + return { + 'title': info.get('title', 'Unknown'), + 'duration': info.get('duration', 0), + 'uploader': info.get('uploader', 'Unknown'), + 'description': info.get('description', ''), + 'thumbnail': info.get('thumbnail', ''), + 'upload_date': info.get('upload_date', ''), + } + except Exception as e: + logger.error(f"Failed to get video info: {e}") + raise ValueError(f"Could not access video: {str(e)}") + + def download_audio(self, url: str, video_id: Optional[str] = None) -> Path: + """ + Download YouTube video and extract audio. + + Args: + url: YouTube video URL + video_id: Optional custom identifier for the output file + + Returns: + Path to the downloaded audio file + + Raises: + ValueError: If URL is invalid or download fails + RuntimeError: If video exceeds maximum duration + """ + if not self.is_valid_youtube_url(url): + raise ValueError(f"Invalid YouTube URL: {url}") + + # Get video info to check duration + info = self.get_video_info(url) + duration = info['duration'] + + if duration > settings.max_video_duration: + raise RuntimeError( + f"Video duration ({duration}s) exceeds maximum allowed " + f"({settings.max_video_duration}s)" + ) + + # Generate output filename + if video_id: + output_template = str(self.output_dir / f"{video_id}.%(ext)s") + else: + output_template = str(self.output_dir / "%(id)s.%(ext)s") + + # yt-dlp options for audio extraction + ydl_opts = { + 'format': 'bestaudio/best', + 'postprocessors': [{ + 'key': 'FFmpegExtractAudio', + 'preferredcodec': 'wav', + 'preferredquality': '192', + }], + 'outtmpl': output_template, + 'quiet': False, + 'no_warnings': False, + 'extract_flat': False, + } + + try: + logger.info(f"Downloading audio from: {url}") + logger.info(f"Video title: {info['title']}") + logger.info(f"Duration: {duration}s ({duration/60:.1f} minutes)") + + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + result = ydl.extract_info(url, download=True) + + # Get the output filename + if video_id: + audio_file = self.output_dir / f"{video_id}.wav" + else: + audio_file = self.output_dir / f"{result['id']}.wav" + + if not audio_file.exists(): + raise RuntimeError("Audio file was not created") + + logger.info(f"Audio downloaded successfully: {audio_file}") + return audio_file + + except Exception as e: + logger.error(f"Failed to download audio: {e}") + raise ValueError(f"Download failed: {str(e)}") + + def cleanup(self, file_path: Path) -> None: + """ + Remove downloaded audio file. + + Args: + file_path: Path to the file to remove + """ + try: + if file_path.exists(): + file_path.unlink() + logger.info(f"Cleaned up file: {file_path}") + except Exception as e: + logger.warning(f"Failed to cleanup file {file_path}: {e}") diff --git a/src/audio/processor.py b/src/audio/processor.py new file mode 100644 index 0000000000000000000000000000000000000000..61c4d3a9e225479d1926431cb7e91b6ba2a48519 --- /dev/null +++ b/src/audio/processor.py @@ -0,0 +1,102 @@ +""" +Audio preprocessing utilities. +Handles noise reduction, normalization, and format validation. +""" + +from pathlib import Path +from typing import Optional +import wave + +from src.utils.logger import setup_logger + +logger = setup_logger(__name__) + + +class AudioProcessor: + """Handles audio preprocessing and validation.""" + + @staticmethod + def get_audio_duration(audio_path: Path) -> float: + """ + Get the duration of an audio file in seconds. + + Args: + audio_path: Path to the audio file + + Returns: + Duration in seconds + """ + try: + with wave.open(str(audio_path), 'r') as audio_file: + frames = audio_file.getnframes() + rate = audio_file.getframerate() + duration = frames / float(rate) + return duration + except Exception as e: + logger.warning(f"Could not get audio duration: {e}") + return 0.0 + + @staticmethod + def validate_audio_file(audio_path: Path) -> bool: + """ + Validate that the audio file is readable and properly formatted. + + Args: + audio_path: Path to the audio file + + Returns: + True if valid, False otherwise + """ + if not audio_path.exists(): + logger.error(f"Audio file does not exist: {audio_path}") + return False + + if audio_path.stat().st_size == 0: + logger.error(f"Audio file is empty: {audio_path}") + return False + + try: + with wave.open(str(audio_path), 'r') as audio_file: + # Check basic properties + channels = audio_file.getnchannels() + sample_width = audio_file.getsampwidth() + framerate = audio_file.getframerate() + + logger.info( + f"Audio validation: {channels} channels, " + f"{sample_width} bytes/sample, {framerate} Hz" + ) + + return True + except Exception as e: + logger.error(f"Audio file validation failed: {e}") + return False + + @staticmethod + def get_audio_info(audio_path: Path) -> dict: + """ + Get detailed information about an audio file. + + Args: + audio_path: Path to the audio file + + Returns: + Dictionary with audio properties + """ + try: + with wave.open(str(audio_path), 'r') as audio_file: + frames = audio_file.getnframes() + rate = audio_file.getframerate() + duration = frames / float(rate) + + return { + 'channels': audio_file.getnchannels(), + 'sample_width': audio_file.getsampwidth(), + 'framerate': rate, + 'frames': frames, + 'duration': duration, + 'file_size': audio_path.stat().st_size, + } + except Exception as e: + logger.error(f"Failed to get audio info: {e}") + return {} diff --git a/src/auth/__init__.py b/src/auth/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5cb2f1dffbcc937f0dc929e6f798631f732ce64f --- /dev/null +++ b/src/auth/__init__.py @@ -0,0 +1,24 @@ +""" +Authentication module for YouTube Study Notes AI. +Provides secure password hashing and JWT token management. +""" + +from .security import ( + hash_password, + verify_password, + create_access_token, + decode_access_token, +) +from .dependencies import ( + get_current_user, + get_current_active_user, +) + +__all__ = [ + "hash_password", + "verify_password", + "create_access_token", + "decode_access_token", + "get_current_user", + "get_current_active_user", +] diff --git a/src/auth/__pycache__/__init__.cpython-312.pyc b/src/auth/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..477651f377e255eeccf15fc98967cd3ad8c0b92d Binary files /dev/null and b/src/auth/__pycache__/__init__.cpython-312.pyc differ diff --git a/src/auth/__pycache__/dependencies.cpython-312.pyc b/src/auth/__pycache__/dependencies.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7fb4813e164bf5d5729aff344fcfaebf47c8864 Binary files /dev/null and b/src/auth/__pycache__/dependencies.cpython-312.pyc differ diff --git a/src/auth/__pycache__/security.cpython-312.pyc b/src/auth/__pycache__/security.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b98200fd2785321a6b66db1e9817368e62dd24f2 Binary files /dev/null and b/src/auth/__pycache__/security.cpython-312.pyc differ diff --git a/src/auth/dependencies.py b/src/auth/dependencies.py new file mode 100644 index 0000000000000000000000000000000000000000..cba750c3abad23070a56b943d6810c0bf51cc4d1 --- /dev/null +++ b/src/auth/dependencies.py @@ -0,0 +1,96 @@ +""" +FastAPI dependencies for authentication and authorization. +""" + +from typing import Optional +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from sqlmodel import Session, select + +from src.db.database import get_session +from src.db.models import User +from src.auth.security import decode_access_token + +# OAuth2 scheme for extracting bearer tokens from Authorization header +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login") + + +async def get_current_user( + token: str = Depends(oauth2_scheme), + session: Session = Depends(get_session) +) -> User: + """ + Get the currently authenticated user from JWT token. + + This dependency extracts the JWT token from the Authorization header, + validates it, and retrieves the corresponding user from the database. + + Args: + token: JWT token from Authorization header + session: Database session + + Returns: + User object if authentication is successful + + Raises: + HTTPException: 401 Unauthorized if token is invalid or user not found + + Usage: + @app.get("/protected") + async def protected_route(current_user: User = Depends(get_current_user)): + return {"message": f"Hello {current_user.username}"} + """ + credentials_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + + # Decode the token + payload = decode_access_token(token) + if payload is None: + raise credentials_exception + + # Extract user email from token + email: Optional[str] = payload.get("sub") + if email is None: + raise credentials_exception + + # Retrieve user from database + statement = select(User).where(User.email == email) + user = session.exec(statement).first() + + if user is None: + raise credentials_exception + + return user + + +async def get_current_active_user( + current_user: User = Depends(get_current_user) +) -> User: + """ + Get the current active user (for future soft-delete support). + + Currently returns the user as-is, but can be extended to check + for account status, email verification, banned users, etc. + + Args: + current_user: User from get_current_user dependency + + Returns: + User object if user is active + + Raises: + HTTPException: 400 Bad Request if user is inactive + + Usage: + @app.get("/protected") + async def protected_route(user: User = Depends(get_current_active_user)): + return {"message": f"Hello active user {user.username}"} + """ + # Future: Check if user.is_active, user.is_verified, etc. + # if not current_user.is_active: + # raise HTTPException(status_code=400, detail="Inactive user") + + return current_user diff --git a/src/auth/security.py b/src/auth/security.py new file mode 100644 index 0000000000000000000000000000000000000000..07e547fe7cfd9074d32ead0cb5c907ffad9db44e --- /dev/null +++ b/src/auth/security.py @@ -0,0 +1,113 @@ +""" +Security utilities for password hashing and JWT token management. +""" + +from datetime import datetime, timedelta +from typing import Optional +from jose import JWTError, jwt +from passlib.context import CryptContext + +from src.utils.config import settings + +# Password hashing context using bcrypt +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + + +def hash_password(password: str) -> str: + """ + Hash a plain-text password using bcrypt. + + Args: + password: Plain-text password to hash + + Returns: + Hashed password string + + Example: + >>> hashed = hash_password("my_secret_password") + >>> print(hashed) + $2b$12$... + """ + return pwd_context.hash(password) + + +def verify_password(plain_password: str, hashed_password: str) -> bool: + """ + Verify a plain-text password against a hashed password. + + Args: + plain_password: Plain-text password to verify + hashed_password: Hashed password to compare against + + Returns: + True if password matches, False otherwise + + Example: + >>> hashed = hash_password("my_password") + >>> verify_password("my_password", hashed) + True + >>> verify_password("wrong_password", hashed) + False + """ + return pwd_context.verify(plain_password, hashed_password) + + +def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str: + """ + Create a JWT access token. + + Args: + data: Dictionary of claims to encode in the token (e.g., {"sub": "user@example.com"}) + expires_delta: Optional custom expiration time + + Returns: + Encoded JWT token string + + Example: + >>> token = create_access_token({"sub": "user@example.com"}) + >>> print(token) + eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... + """ + to_encode = data.copy() + + if expires_delta: + expire = datetime.utcnow() + expires_delta + else: + expire = datetime.utcnow() + timedelta(minutes=settings.access_token_expire_minutes) + + to_encode.update({"exp": expire}) + + encoded_jwt = jwt.encode( + to_encode, + settings.secret_key, + algorithm=settings.algorithm + ) + + return encoded_jwt + + +def decode_access_token(token: str) -> Optional[dict]: + """ + Decode and verify a JWT access token. + + Args: + token: JWT token string to decode + + Returns: + Dictionary of claims if token is valid, None otherwise + + Example: + >>> token = create_access_token({"sub": "user@example.com"}) + >>> payload = decode_access_token(token) + >>> print(payload["sub"]) + user@example.com + """ + try: + payload = jwt.decode( + token, + settings.secret_key, + algorithms=[settings.algorithm] + ) + return payload + except JWTError: + return None diff --git a/src/db/__init__.py b/src/db/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..501d6dff7c64e6c8e935bbe614715fcedeeb548f --- /dev/null +++ b/src/db/__init__.py @@ -0,0 +1,14 @@ +""" +Database module for YouTube Study Notes AI. +Provides ORM models and database connection management. +""" + +from .models import User, Note +from .database import create_db_and_tables, get_session + +__all__ = [ + "User", + "Note", + "create_db_and_tables", + "get_session", +] diff --git a/src/db/__pycache__/__init__.cpython-312.pyc b/src/db/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1de07e60a566963278f7461b694ec4b78bb66ce1 Binary files /dev/null and b/src/db/__pycache__/__init__.cpython-312.pyc differ diff --git a/src/db/__pycache__/database.cpython-312.pyc b/src/db/__pycache__/database.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f685af65fe96699c6b127f8609a4b168ec2d623 Binary files /dev/null and b/src/db/__pycache__/database.cpython-312.pyc differ diff --git a/src/db/__pycache__/models.cpython-312.pyc b/src/db/__pycache__/models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bb00da634d67590cff2a5819a32f59c48fd4a1d Binary files /dev/null and b/src/db/__pycache__/models.cpython-312.pyc differ diff --git a/src/db/database.py b/src/db/database.py new file mode 100644 index 0000000000000000000000000000000000000000..cae00de68c06d8056242c49fdce60823fe19891f --- /dev/null +++ b/src/db/database.py @@ -0,0 +1,37 @@ +""" +Database connection and session management. +""" + +from typing import AsyncGenerator +from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine +from sqlalchemy.orm import sessionmaker +from sqlmodel import SQLModel +from sqlmodel.ext.asyncio.session import AsyncSession + +from src.utils.config import settings + +async_engine: AsyncEngine = create_async_engine( + settings.database_url, + echo=False, + future=True, + connect_args={"statement_cache_size": 0} +) + +async def create_db_and_tables(): + """Create database tables defined in SQLModel models.""" + async with async_engine.begin() as conn: + await conn.run_sync(SQLModel.metadata.create_all) + +async def get_session() -> AsyncGenerator[AsyncSession, None]: + """ + Dependency to provide async database session. + Yields: + AsyncSession: Database session + """ + async_session = sessionmaker( + bind=async_engine, + class_=AsyncSession, + expire_on_commit=False + ) + async with async_session() as session: + yield session \ No newline at end of file diff --git a/src/db/models.py b/src/db/models.py new file mode 100644 index 0000000000000000000000000000000000000000..0acbe470ad00006aa15f8e9b0298b1f04cbba275 --- /dev/null +++ b/src/db/models.py @@ -0,0 +1,81 @@ +""" +SQLModel database models for PostgreSQL (Supabase). +Optimized for cloud deployment and mobile app integration. +""" + +from datetime import datetime +from typing import Optional, List +from sqlmodel import SQLModel, Field, Relationship + + +class User(SQLModel, table=True): + """ + User model for authentication and note ownership. + + Attributes: + id: Primary key, auto-incremented + email: Unique email address for login + username: Display name for the user + password_hash: Bcrypt hashed password + role: User role (default: "user") + created_at: Account creation timestamp + notes: Relationship to user's notes + """ + __tablename__ = "users" + + id: Optional[int] = Field(default=None, primary_key=True) + email: str = Field(unique=True, index=True, max_length=255, nullable=False) + username: str = Field(max_length=100, nullable=False) + password_hash: str = Field(max_length=255, nullable=False) + role: str = Field(default="user", max_length=50, nullable=False) + created_at: datetime = Field(default_factory=datetime.utcnow, nullable=False) + + # Relationship to notes + notes: List["Note"] = Relationship(back_populates="owner") + + class Config: + """Pydantic configuration.""" + json_schema_extra = { + "example": { + "email": "student@example.com", + "username": "Student123", + "role": "user" + } + } + + +class Note(SQLModel, table=True): + """ + Note model for storing generated study notes. + + Attributes: + id: Primary key, auto-incremented + user_id: Foreign key to the user who generated this note + video_url: YouTube video URL + video_title: Title of the processed video + summary_content: Generated study notes content (markdown) + created_at: Note generation timestamp + owner: Relationship to the user who owns this note + """ + __tablename__ = "notes" + + id: Optional[int] = Field(default=None, primary_key=True) + user_id: int = Field(foreign_key="users.id", index=True, nullable=False) + video_url: str = Field(index=True, max_length=500, nullable=False) + video_title: str = Field(max_length=500, nullable=False) + summary_content: str = Field(nullable=False) # Full markdown content + created_at: datetime = Field(default_factory=datetime.utcnow, nullable=False) + + # Relationship to user + owner: Optional[User] = Relationship(back_populates="notes") + + class Config: + """Pydantic configuration.""" + json_schema_extra = { + "example": { + "user_id": 1, + "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ", + "video_title": "Introduction to Python Programming", + "summary_content": "# Study Notes\\n\\n## Key Concepts..." + } + } diff --git a/src/summarization/__init__.py b/src/summarization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/summarization/__pycache__/__init__.cpython-312.pyc b/src/summarization/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..654b6614902e25ecee82434db6077e47fdb5e440 Binary files /dev/null and b/src/summarization/__pycache__/__init__.cpython-312.pyc differ diff --git a/src/summarization/__pycache__/note_generator.cpython-312.pyc b/src/summarization/__pycache__/note_generator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fe0ef30bea728bca9efb43623955b85beec0195 Binary files /dev/null and b/src/summarization/__pycache__/note_generator.cpython-312.pyc differ diff --git a/src/summarization/__pycache__/segmenter.cpython-312.pyc b/src/summarization/__pycache__/segmenter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..961261770305444087c57e4818ef393287fc5905 Binary files /dev/null and b/src/summarization/__pycache__/segmenter.cpython-312.pyc differ diff --git a/src/summarization/note_generator.py b/src/summarization/note_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..14ee101d14a0d5eed895b0bc7322fbaf29af8df9 --- /dev/null +++ b/src/summarization/note_generator.py @@ -0,0 +1,239 @@ +""" +LLM-based note generation module. +Uses Google Gemini to generate structured study notes from transcripts. +""" + +from typing import Dict, List, Optional +import google.generativeai as genai + +from src.utils.logger import setup_logger +from src.utils.config import settings + +logger = setup_logger(__name__) + + +class NoteGenerator: + """Generates structured study notes using LLM.""" + + # System prompt for note generation + SYSTEM_PROMPT = """You are an expert educational note-taker. Your task is to convert video transcripts into clear, structured study notes. + +Follow these guidelines: +1. Create a clear hierarchical structure with section titles +2. Use bullet points for key information +3. Highlight important concepts and definitions +4. Extract key terms and explain them +5. Be concise but comprehensive +6. Focus on educational content, skip irrelevant parts +7. Use proper Markdown formatting + +Format the output as follows: +# [Main Topic/Title] + +## [Section 1 Title] +- Key point 1 +- Key point 2 + - Sub-point if needed +- **Important term**: Definition or explanation + +## [Section 2 Title] +... + +## Key Concepts +- **Concept 1**: Explanation +- **Concept 2**: Explanation +""" + + def __init__(self, api_key: Optional[str] = None, model_name: str = "gemini-2.5-flash"): + """ + Initialize the note generator. + + Args: + api_key: Google Gemini API key (defaults to config) + model_name: Gemini model to use + """ + self.api_key = api_key or settings.google_api_key + self.model_name = model_name + + # Configure Gemini + genai.configure(api_key=self.api_key) + self.model = genai.GenerativeModel(model_name) + + logger.info(f"Initialized NoteGenerator with model: {model_name}") + + def generate_notes_from_segment(self, segment_text: str) -> str: + """ + Generate notes from a single transcript segment. + + Args: + segment_text: Text segment to process + + Returns: + Generated notes in Markdown format + """ + try: + prompt = f"{self.SYSTEM_PROMPT}\n\nTranscript:\n{segment_text}\n\nGenerate structured study notes:" + + logger.debug(f"Generating notes for segment ({len(segment_text)} chars)") + + response = self.model.generate_content(prompt) + notes = response.text + + logger.debug(f"Generated {len(notes)} characters of notes") + + return notes.strip() + + except Exception as e: + logger.error(f"Failed to generate notes: {e}") + return f"## Error\nFailed to generate notes for this segment: {str(e)}" + + def generate_notes_from_segments(self, segments: List[Dict]) -> str: + """ + Generate notes from multiple transcript segments. + + Args: + segments: List of transcript segments + + Returns: + Combined notes in Markdown format + """ + all_notes = [] + + logger.info(f"Generating notes from {len(segments)} segments") + + for i, segment in enumerate(segments, 1): + logger.info(f"Processing segment {i}/{len(segments)}") + + segment_text = segment.get('text', '') + if not segment_text: + continue + + # Add timestamp if available + if 'start' in segment: + timestamp = self._format_timestamp(segment['start']) + all_notes.append(f"\n---\n**Timestamp: {timestamp}**\n") + + # Generate notes for this segment + notes = self.generate_notes_from_segment(segment_text) + all_notes.append(notes) + + # Combine all notes + combined_notes = "\n\n".join(all_notes) + + logger.info(f"Generated total of {len(combined_notes)} characters") + + return combined_notes + + def generate_notes_from_full_transcript( + self, + transcript_text: str, + video_title: str = "Educational Video" + ) -> str: + """ + Generate notes from full transcript (for shorter videos). + + Args: + transcript_text: Full transcript text + video_title: Title of the video + + Returns: + Generated notes in Markdown format + """ + try: + prompt = f"""{self.SYSTEM_PROMPT} + +Video Title: {video_title} + +Transcript: +{transcript_text} + +Generate comprehensive structured study notes:""" + + logger.info(f"Generating notes from full transcript ({len(transcript_text)} chars)") + + response = self.model.generate_content(prompt) + notes = response.text + + # Add header with video title + final_notes = f"# {video_title}\n\n{notes.strip()}" + + logger.info(f"Generated {len(final_notes)} characters of notes") + + return final_notes + + except Exception as e: + logger.error(f"Failed to generate notes from full transcript: {e}") + raise RuntimeError(f"Note generation failed: {str(e)}") + + def generate_summary(self, notes: str) -> str: + """ + Generate a brief summary of the notes. + + Args: + notes: Generated study notes + + Returns: + Brief summary + """ + try: + prompt = f"""Provide a brief 2-3 sentence summary of these study notes: + +{notes} + +Summary:""" + + response = self.model.generate_content(prompt) + summary = response.text.strip() + + return summary + + except Exception as e: + logger.error(f"Failed to generate summary: {e}") + return "Summary generation failed." + + @staticmethod + def _format_timestamp(seconds: float) -> str: + """Format seconds into MM:SS or HH:MM:SS.""" + hours = int(seconds // 3600) + minutes = int((seconds % 3600) // 60) + secs = int(seconds % 60) + + if hours > 0: + return f"{hours:02d}:{minutes:02d}:{secs:02d}" + else: + return f"{minutes:02d}:{secs:02d}" + + def format_final_notes( + self, + notes: str, + video_title: str, + video_url: str, + duration: int + ) -> str: + """ + Format final notes with metadata. + + Args: + notes: Generated notes + video_title: Video title + video_url: Original YouTube URL + duration: Video duration in seconds + + Returns: + Formatted notes with metadata header + """ + duration_str = self._format_timestamp(duration) + + header = f"""# {video_title} + +--- + +**Source:** [{video_url}]({video_url}) +**Duration:** {duration_str} +**Generated:** AI Study Notes + +--- + +""" + + return header + notes diff --git a/src/summarization/segmenter.py b/src/summarization/segmenter.py new file mode 100644 index 0000000000000000000000000000000000000000..a0bcdaec2d8c717fc3512408281de2338aa70777 --- /dev/null +++ b/src/summarization/segmenter.py @@ -0,0 +1,173 @@ +""" +Transcript segmentation module. +Splits long transcripts into logical sections for better processing. +""" + +import re +from typing import List, Dict + +from src.utils.logger import setup_logger + +logger = setup_logger(__name__) + + +class TranscriptSegmenter: + """Handles intelligent segmentation of transcripts.""" + + # Common filler words to remove + FILLER_WORDS = { + 'um', 'uh', 'like', 'you know', 'i mean', 'sort of', 'kind of', + 'basically', 'actually', 'literally', 'right', 'okay', 'so yeah' + } + + def __init__(self, max_segment_words: int = 500): + """ + Initialize the segmenter. + + Args: + max_segment_words: Maximum words per segment + """ + self.max_segment_words = max_segment_words + + def clean_text(self, text: str) -> str: + """ + Clean transcript by removing filler words and normalizing. + + Args: + text: Raw transcript text + + Returns: + Cleaned text + """ + # Convert to lowercase for processing + cleaned = text.lower() + + # Remove filler words + for filler in self.FILLER_WORDS: + # Use word boundaries to avoid partial matches + pattern = r'\b' + re.escape(filler) + r'\b' + cleaned = re.sub(pattern, '', cleaned, flags=re.IGNORECASE) + + # Remove multiple spaces + cleaned = re.sub(r'\s+', ' ', cleaned) + + # Remove leading/trailing whitespace + cleaned = cleaned.strip() + + # Capitalize first letter of sentences + cleaned = '. '.join(s.capitalize() for s in cleaned.split('. ')) + + logger.debug(f"Cleaned text: reduced from {len(text)} to {len(cleaned)} characters") + + return cleaned + + def segment_by_time( + self, + segments: List[Dict], + interval_seconds: int = 300 + ) -> List[Dict]: + """ + Segment transcript by time intervals. + + Args: + segments: List of timestamped segments from Whisper + interval_seconds: Time interval for each segment (default: 5 minutes) + + Returns: + List of combined segments grouped by time + """ + if not segments: + return [] + + time_segments = [] + current_segment = { + 'start': segments[0]['start'], + 'text': '' + } + + for seg in segments: + # Check if we should start a new time segment + if seg['start'] - current_segment['start'] >= interval_seconds: + # Save current segment + current_segment['end'] = seg['start'] + time_segments.append(current_segment) + + # Start new segment + current_segment = { + 'start': seg['start'], + 'text': seg['text'] + } + else: + # Add to current segment + current_segment['text'] += ' ' + seg['text'] + + # Add the last segment + if current_segment['text']: + current_segment['end'] = segments[-1]['end'] + time_segments.append(current_segment) + + logger.info(f"Segmented transcript into {len(time_segments)} time-based segments") + + return time_segments + + def segment_by_topic(self, text: str) -> List[str]: + """ + Segment text by detecting topic transitions. + Simple heuristic: Split on paragraph breaks and large sentences. + + Args: + text: Full transcript text + + Returns: + List of text segments + """ + # Split by double newlines (paragraphs) + paragraphs = [p.strip() for p in text.split('\n\n') if p.strip()] + + segments = [] + current_segment = [] + current_word_count = 0 + + for para in paragraphs: + words = para.split() + word_count = len(words) + + # If adding this paragraph exceeds max words, start new segment + if current_word_count + word_count > self.max_segment_words and current_segment: + segments.append(' '.join(current_segment)) + current_segment = [para] + current_word_count = word_count + else: + current_segment.append(para) + current_word_count += word_count + + # Add the last segment + if current_segment: + segments.append(' '.join(current_segment)) + + logger.info(f"Segmented text into {len(segments)} topic-based segments") + + return segments + + def segment_transcript( + self, + transcript_data: Dict, + method: str = "time" + ) -> List[Dict]: + """ + Segment transcript using specified method. + + Args: + transcript_data: Full transcript data with text and segments + method: Segmentation method ("time" or "topic") + + Returns: + List of segmented chunks + """ + if method == "time" and 'segments' in transcript_data: + # Use timestamped segments + return self.segment_by_time(transcript_data['segments']) + else: + # Use topic-based segmentation on full text + text_segments = self.segment_by_topic(transcript_data['text']) + return [{'text': seg} for seg in text_segments] diff --git a/src/transcription/__init__.py b/src/transcription/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/transcription/__pycache__/__init__.cpython-312.pyc b/src/transcription/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d89dc507ca024d00d519e047e8403b876aa72b1d Binary files /dev/null and b/src/transcription/__pycache__/__init__.cpython-312.pyc differ diff --git a/src/transcription/__pycache__/whisper_transcriber.cpython-312.pyc b/src/transcription/__pycache__/whisper_transcriber.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c7acdeb226ec8d160c11489e0d34a6e2c954a66 Binary files /dev/null and b/src/transcription/__pycache__/whisper_transcriber.cpython-312.pyc differ diff --git a/src/transcription/whisper_transcriber.py b/src/transcription/whisper_transcriber.py new file mode 100644 index 0000000000000000000000000000000000000000..aa5e135b01cc20c94afe92b9089827119df1dd6d --- /dev/null +++ b/src/transcription/whisper_transcriber.py @@ -0,0 +1,186 @@ +""" +Whisper-based speech-to-text transcription module. +Converts audio files to text using OpenAI's Whisper model. +""" + +from pathlib import Path +from typing import Dict, List, Optional +import whisper +import torch + +from src.utils.logger import setup_logger +from src.utils.config import settings + +logger = setup_logger(__name__) + + +class WhisperTranscriber: + """Handles audio transcription using Whisper ASR model.""" + + def __init__(self, model_size: Optional[str] = None): + """ + Initialize the Whisper transcriber. + + Args: + model_size: Whisper model size (tiny, base, small, medium, large) + Defaults to config setting + """ + self.model_size = model_size or settings.whisper_model_size + self.model = None + self.device = "cuda" if torch.cuda.is_available() else "cpu" + + logger.info(f"Initializing Whisper transcriber with model: {self.model_size}") + logger.info(f"Using device: {self.device}") + + def load_model(self) -> None: + """Load the Whisper model into memory.""" + if self.model is not None: + logger.info("Model already loaded") + return + + try: + logger.info(f"Loading Whisper {self.model_size} model...") + self.model = whisper.load_model(self.model_size, device=self.device) + logger.info("Model loaded successfully") + except Exception as e: + logger.error(f"Failed to load Whisper model: {e}") + raise RuntimeError(f"Model loading failed: {str(e)}") + + def transcribe( + self, + audio_path: Path, + language: str = "en", + verbose: bool = True + ) -> Dict[str, any]: + """ + Transcribe audio file to text. + + Args: + audio_path: Path to the audio file + language: Language code (default: "en" for English) + verbose: Whether to show progress during transcription + + Returns: + Dictionary containing: + - text: Full transcript + - segments: List of timestamped segments + - language: Detected/specified language + + Raises: + FileNotFoundError: If audio file doesn't exist + RuntimeError: If transcription fails + """ + if not audio_path.exists(): + raise FileNotFoundError(f"Audio file not found: {audio_path}") + + # Load model if not already loaded + self.load_model() + + try: + logger.info(f"Starting transcription of: {audio_path}") + logger.info(f"Language: {language}") + + # Transcribe with Whisper + result = self.model.transcribe( + str(audio_path), + language=language, + verbose=verbose, + task="transcribe", + fp16=torch.cuda.is_available() # Use FP16 on GPU for speed + ) + + # Extract relevant information + transcript_data = { + 'text': result['text'].strip(), + 'segments': self._process_segments(result['segments']), + 'language': result['language'], + } + + logger.info(f"Transcription complete. Length: {len(transcript_data['text'])} characters") + logger.info(f"Number of segments: {len(transcript_data['segments'])}") + + return transcript_data + + except Exception as e: + logger.error(f"Transcription failed: {e}") + raise RuntimeError(f"Transcription error: {str(e)}") + + def _process_segments(self, raw_segments: List[Dict]) -> List[Dict]: + """ + Process raw Whisper segments into a cleaner format. + + Args: + raw_segments: Raw segment data from Whisper + + Returns: + List of processed segments with timestamps and text + """ + processed = [] + + for segment in raw_segments: + processed.append({ + 'id': segment['id'], + 'start': segment['start'], + 'end': segment['end'], + 'text': segment['text'].strip(), + }) + + return processed + + def transcribe_with_timestamps( + self, + audio_path: Path, + language: str = "en" + ) -> str: + """ + Transcribe audio and format with timestamps. + + Args: + audio_path: Path to the audio file + language: Language code + + Returns: + Formatted transcript with timestamps + """ + result = self.transcribe(audio_path, language, verbose=False) + + formatted_lines = [] + for segment in result['segments']: + timestamp = self._format_timestamp(segment['start']) + formatted_lines.append(f"[{timestamp}] {segment['text']}") + + return "\n".join(formatted_lines) + + @staticmethod + def _format_timestamp(seconds: float) -> str: + """ + Format seconds into MM:SS or HH:MM:SS. + + Args: + seconds: Time in seconds + + Returns: + Formatted timestamp string + """ + hours = int(seconds // 3600) + minutes = int((seconds % 3600) // 60) + secs = int(seconds % 60) + + if hours > 0: + return f"{hours:02d}:{minutes:02d}:{secs:02d}" + else: + return f"{minutes:02d}:{secs:02d}" + + def get_plain_text(self, audio_path: Path, language: str = "en") -> str: + """ + Get plain text transcript without timestamps. + + Args: + audio_path: Path to the audio file + language: Language code + + Returns: + Plain text transcript + """ + result = self.transcribe(audio_path, language, verbose=False) + return result['text'] diff --git a/src/ui/__init__.py b/src/ui/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/ui/app.html b/src/ui/app.html new file mode 100644 index 0000000000000000000000000000000000000000..d37479f600a49adffa1edde12ed4713861d20389 --- /dev/null +++ b/src/ui/app.html @@ -0,0 +1,461 @@ + + + + + + YouTube Study Notes AI + + + + +
+
+

šŸ“š YouTube Study Notes AI

+

Transform educational videos into structured study notes

+
+ +
+ +
+
+ + +
+ +
+ +
+
+
+
Processing...
+
+
+
+
+ +
+ +
+
+ +
+
+ + + + + diff --git a/src/utils/__init__.py b/src/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/utils/__pycache__/__init__.cpython-312.pyc b/src/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7311214de952a16c4c50d45dcbb543d660278b64 Binary files /dev/null and b/src/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/src/utils/__pycache__/config.cpython-312.pyc b/src/utils/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29765524d2ef3df43c25dbc378c3bf8527423761 Binary files /dev/null and b/src/utils/__pycache__/config.cpython-312.pyc differ diff --git a/src/utils/__pycache__/logger.cpython-312.pyc b/src/utils/__pycache__/logger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..746da85406883f522b85dbbd0b88eb25f477a9e9 Binary files /dev/null and b/src/utils/__pycache__/logger.cpython-312.pyc differ diff --git a/src/utils/config.py b/src/utils/config.py new file mode 100644 index 0000000000000000000000000000000000000000..bacc271f50946e2f723febd98e81d48ee21bfd0e --- /dev/null +++ b/src/utils/config.py @@ -0,0 +1,107 @@ +""" +Configuration management for the YouTube Notes AI application. +Uses Pydantic Settings for type-safe environment variable loading. +""" + +import os +from pathlib import Path +from typing import Literal + +from pydantic import Field +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + """Application configuration settings loaded from environment variables.""" + + # Google Gemini API Configuration + google_api_key: str = Field( + ..., + description="Google Gemini API key for note generation" + ) + + # Whisper Model Configuration + whisper_model_size: Literal["tiny", "base", "small", "medium", "large"] = Field( + default="base", + description="Whisper model size (larger = more accurate but slower)" + ) + + # Processing Limits + max_video_duration: int = Field( + default=7200, + description="Maximum video duration in seconds (2 hours default)" + ) + + # Output Configuration + output_format: Literal["markdown", "json"] = Field( + default="markdown", + description="Output format for generated notes" + ) + output_dir: Path = Field( + default=Path("outputs"), + description="Directory for saving generated notes" + ) + + # Logging Configuration + log_level: str = Field( + default="INFO", + description="Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)" + ) + log_file: str = Field( + default="app.log", + description="Log file path" + ) + + # API Configuration + api_host: str = Field( + default="0.0.0.0", + description="FastAPI host address" + ) + api_port: int = Field( + default=8000, + description="FastAPI port number" + ) + + # Database Configuration + database_url: str = Field( + default="postgresql+asyncpg://postgres:password@localhost:5432/studynotes", + description="PostgreSQL database connection URL (use asyncpg driver)" + ) + + # Authentication Configuration + secret_key: str = Field( + default="your-secret-key-change-this-in-production-min-32-chars", + description="JWT secret key for token signing (MUST be changed in production)" + ) + access_token_expire_minutes: int = Field( + default=60, + description="JWT token expiration time in minutes" + ) + algorithm: str = Field( + default="HS256", + description="JWT signing algorithm" + ) + + # Temporary Files + temp_dir: Path = Field( + default=Path("temp"), + description="Directory for temporary files (audio, video)" + ) + + model_config = SettingsConfigDict( + env_file=".env", + env_file_encoding="utf-8", + case_sensitive=False + ) + + def __init__(self, **kwargs): + """Initialize settings and create necessary directories.""" + super().__init__(**kwargs) + + # Create directories if they don't exist + self.output_dir.mkdir(parents=True, exist_ok=True) + self.temp_dir.mkdir(parents=True, exist_ok=True) + + +# Global settings instance +settings = Settings() diff --git a/src/utils/logger.py b/src/utils/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..a5a27abc2feda6aeef3fc34b64f802cc219d7086 --- /dev/null +++ b/src/utils/logger.py @@ -0,0 +1,68 @@ +""" +Logging utilities for the YouTube Notes AI application. +Provides structured logging with both file and console output. +""" + +import logging +import sys +from pathlib import Path +from typing import Optional + +from src.utils.config import settings + + +def setup_logger( + name: str, + log_file: Optional[str] = None, + level: Optional[str] = None +) -> logging.Logger: + """ + Set up a logger with both file and console handlers. + + Args: + name: Logger name (typically __name__) + log_file: Optional custom log file path + level: Optional custom log level + + Returns: + Configured logger instance + """ + # Create logger + logger = logging.getLogger(name) + + # Set level from config or parameter + log_level = level or settings.log_level + logger.setLevel(getattr(logging, log_level.upper())) + + # Avoid duplicate handlers + if logger.handlers: + return logger + + # Create formatters + detailed_formatter = logging.Formatter( + fmt="%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s", + datefmt="%Y-%m-%d %H:%M:%S" + ) + + simple_formatter = logging.Formatter( + fmt="%(levelname)s - %(message)s" + ) + + # Console handler (simple format) + console_handler = logging.StreamHandler(sys.stdout) + console_handler.setLevel(logging.INFO) + console_handler.setFormatter(simple_formatter) + logger.addHandler(console_handler) + + # File handler (detailed format) + file_path = log_file or settings.log_file + file_handler = logging.FileHandler(file_path, encoding="utf-8") + file_handler.setLevel(logging.DEBUG) + file_handler.setFormatter(detailed_formatter) + logger.addHandler(file_handler) + + return logger + + +# Default application logger +logger = setup_logger("youtube_notes_ai")