Spaces:
Sleeping
Sleeping
rsnarsna commited on
Commit Β·
7b71216
1
Parent(s): ee74594
refactor: Remove unused variables and functions in app.py and gemini_transcript.py; streamline file handling and improve memory usage
Browse filesFiles changed (2)
- app.py+31-54
- gemini_transcript.py+32-43
4 unmodified lines5678891021 unmodified lines32333436373835363738404139404142431 unmodified line4546474950515253484950210 unmodified lines2612622632702712722732742752762772782792802812822832842852862872882892902912922932642652662 unmodified lines269270271272273274275276277278568 unmodified lines84784884987687787885085185285385485585685788485885986086186286386488788888989089189289386586686786886987087187289587387487566 unmodified lines9429439449689459469479489729739499509519529769779539549559569809819579589599609614 unmodified linesimport base64import hashlibimport secretsimport shutilimport tempfileimport threading
21 unmodified linesos.environ.setdefault("OAUTHLIB_INSECURE_TRANSPORT", "1")
BASE_DIR = Path(__file__).resolve().parentCLIENT_SECRETS = os.getenv("CLIENT_SECRETS", str(BASE_DIR / "client_secret.json"))TOKEN_PATH = os.getenv("GOOGLE_OAUTH_TOKEN_PATH", str(BASE_DIR / "Google_oauth_token.json"))REDIRECT_URI = os.getenv("REDIRECT_URI", "http://localhost:8000/auth/callback")CLIENT_SECRETS = os.getenv("CLIENT_SECRETS", str(BASE_DIR / "client_secret.json"))TOKEN_PATH = os.getenv("GOOGLE_OAUTH_TOKEN_PATH", str(BASE_DIR / "Google_oauth_token.json"))REDIRECT_URI = os.getenv("REDIRECT_URI", "http://localhost:8000/auth/callback")STATE_FILE = BASE_DIR / "oauth_states.json"DEFAULT_SPREADSHEET_ID = os.getenv("DEFAULT_SPREADSHEET_ID", "1XA3vW_guHBT-ktkYvhktmUqcquECBe8exGZAoSQS3Ag")DEFAULT_DRIVE_FOLDER_ID = os.getenv("DEFAULT_DRIVE_FOLDER_ID", "1hI6dNXysR_2p9gHkDpsI-iwMExmy2hhR")DEFAULT_SPREADSHEET_ID = os.getenv("DEFAULT_SPREADSHEET_ID", "1XA3vW_guHBT-ktkYvhktmUqcquECBe8exGZAoSQS3Ag")DEFAULT_DRIVE_FOLDER_ID = os.getenv("DEFAULT_DRIVE_FOLDER_ID", "1hI6dNXysR_2p9gHkDpsI-iwMExmy2hhR")
SCOPES = [ "https://www.googleapis.com/auth/spreadsheets",1 unmodified line "https://www.googleapis.com/auth/drive.file",]
OUTPUT_DIR = Path(".") / "output"TRANSCRIPT_FILE = OUTPUT_DIR / "transcript.txt"SUMMARY_FILE = OUTPUT_DIR / "summary.txt"QA_FILE = OUTPUT_DIR / "qa.txt"
SHEETS_HEADERS = [ "Timestamp", # A "Job ID", # B210 unmodified lines return folder["id"]
def upload_file_to_drive( filepath: str, creds: Credentials = None, folder_id: str | None = None, make_public: bool = True,) -> dict: if creds is None: creds = require_credentials() svc = _drive(creds) meta = {"name": os.path.basename(filepath)} if folder_id: meta["parents"] = [folder_id] media = MediaFileUpload(filepath, resumable=True) file = svc.files().create( body=meta, media_body=media, fields="id,name,webViewLink,webContentLink,mimeType,size", ).execute() file_id = file["id"] if make_public: file = _make_public(svc, file_id) file["direct_download_link"] = _direct_link(file_id) return file
def create_file_on_drive( filename: str, content: str,2 unmodified lines folder_id: str | None = None, make_public: bool = True,) -> dict: """ Upload a string as a Drive file via a temporary file. No permanent local files are created. """ if creds is None: creds = require_credentials() svc = _drive(creds)568 unmodified lines# PIPELINE BACKGROUND WORKER# ============================================================================
def _upload_with_title( local_file: Path, drive_name: str,def _upload_content( content: str, filename: str, step_key: str, job_id: str, folder_id: str, creds: Credentials,) -> dict: """Copy file with video-title name, upload to Drive, clean up.""" """ Upload a string directly to Drive as a text file. Uses create_file_on_drive which handles its own temp file internally. No permanent local files are created. """ _set_step(job_id, step_key, "running") try: tmp_path = local_file.parent / drive_name if tmp_path.exists(): tmp_path.unlink() shutil.copy2(local_file, tmp_path) result = upload_file_to_drive( str(tmp_path), creds=creds, folder_id=folder_id, make_public=True, result = create_file_on_drive( filename=filename, content=content, mimetype="text/plain", creds=creds, folder_id=folder_id, make_public=True, ) tmp_path.unlink() _set_step(job_id, step_key, "done") return result except Exception as exc:66 unmodified lines _set_step(job_id, "create_drive_folder", "failed") raise RuntimeError(f"Drive folder creation failed: {exc}")
# ββ STEP 4β6: Upload files βββββββββββββββββββββββββββββββββββββββ # ββ STEP 4β6: Upload content strings directly to Drive βββββββββββ _update_job(job_id, status="uploading_drive") _update_sheet_record(job_id, creds, status="uploading_to_drive")
summary_drive = _upload_with_title( SUMMARY_FILE, f"{video_title}__summary.txt", "upload_summary", summary_drive = _upload_content( summary, f"{video_title}__summary.txt", "upload_summary", job_id, folder_id, creds, ) qa_drive = _upload_with_title( QA_FILE, f"{video_title}__qa.txt", "upload_qa", qa_drive = _upload_content( qa, f"{video_title}__qa.txt", "upload_qa", job_id, folder_id, creds, ) transcript_drive = _upload_with_title( TRANSCRIPT_FILE, f"{video_title}__transcript.txt", "upload_transcript", transcript_drive = _upload_content( transcript, f"{video_title}__transcript.txt", "upload_transcript", job_id, folder_id, creds, )
7 unmodified lines89101111121315141516178 unmodified lines26272830313233343529303132117 unmodified lines15015115215915315415515615715815916016416116216316416916516616718 unmodified lines18618718819419519619718919920020119019119219319419519619719816 unmodified lines21521621722421821922039 unmodified lines26026126227026326426526626726826927027127627227327427527627727828328428528627928028128828929029128228328428528629529629728728828929029165 unmodified lines3573583593603613623633643653713723733743753763773783793803663673683692 unmodified lines3723733743753763773783793803814 unmodified lines3863873883993893903917 unmodified linesimport loggingimport time
from pathlib import Pathfrom typing import Optional, Listfrom urllib.parse import urlparse, parse_qs
from google import genai # pip install google-genaifrom google import genai # pip install google-genaifrom google.genai import types
from youtube_transcript_api import (8 unmodified lines# CONFIG# ============================================================================
BASE_DIR = Path(".")TRANSCRIPT_FILE = BASE_DIR / "output" / "transcript.txt"SUMMARY_FILE = BASE_DIR / "output" / "summary.txt"QA_FILE = BASE_DIR / "output" / "qa.txt"
GEMINI_API_KEY = "AIzaSyCNz5wQAyJ65kNRkwr0-1A-_Z6-lQzdcyc"GEMINI_API_KEY = "AIzaSyCNz5wQAyJ65kNRkwr0-1A-_Z6-lQzdcyc"
GEMINI_MODELS = [ "gemini-2.5-flash",117 unmodified lines# ============================================================================
class YouTubeTranscriptFetcher: """Fetches YouTube transcript with polling retry for new uploads.""" """ Fetches a YouTube transcript and returns it as a plain string. No files are written to disk. """
def __init__( self, youtube_url: str, output_file: Path = TRANSCRIPT_FILE, languages: Optional[List[str]] = None, polling_config: dict = None, ): self.youtube_url = youtube_url self.output_file = Path(output_file) self.languages = languages or ["en", "en-US", "en-GB"] self.polling_config = polling_config or POLLING_CONFIG self.video_id = self._extract_video_id(youtube_url)18 unmodified lines transcript = self.api.fetch(self.video_id, languages=self.languages) return " ".join(item.text for item in transcript)
def _save(self, text: str) -> None: self.output_file.parent.mkdir(parents=True, exist_ok=True) self.output_file.write_text(text, encoding="utf-8")
def run(self) -> str: logger.info("Video ID : %s", self.video_id) logger.info("Output file : %s", self.output_file) logger.info("Total polling attempts: %d", len(self.polling_config)) """ Fetch transcript with polling retry. Returns transcript as a string β nothing is written to disk. """ logger.info("Video ID : %s", self.video_id) logger.info("Polling attempts : %d", len(self.polling_config))
attempts = list(self.polling_config.items())
16 unmodified lines
try: text = self._fetch_once() self._save(text) logger.info( "[%d/%d] β
Transcript fetched β %d characters", idx, len(attempts), len(text),39 unmodified lines# ============================================================================
class GeminiSummarizer: """Sends transcript to Gemini with model fallback + per-model retry.""" """ Sends transcript to Gemini and returns (summary, qa, model_used). No files are written to disk. """
MAX_RETRIES = 5 BASE_WAIT = 10 # seconds MAX_WAIT = 120 # seconds cap
# Errors β retry same model with backoff # Errors β retry same model with exponential backoff RETRYABLE = ["503", "502", "500", "UNAVAILABLE", "SERVICE_UNAVAILABLE"] # Errors β skip to next model immediately SKIP_TO_NEXT = ["429", "RESOURCE_EXHAUSTED", "quota", "404", "NOT_FOUND"]
def __init__( self, api_key: str = GEMINI_API_KEY, models: list = None, summary_file: Path = SUMMARY_FILE, qa_file: Path = QA_FILE, api_key: str = GEMINI_API_KEY, models: list = None, ): self.client = genai.Client(api_key=api_key) self.models = models or GEMINI_MODELS self.summary_file = Path(summary_file) self.qa_file = Path(qa_file) self.client = genai.Client(api_key=api_key) self.models = models or GEMINI_MODELS
def _call_api(self, transcript: str) -> tuple[str, str]: """ Try each model in order. Per model: retry up to MAX_RETRIES on transient errors with backoff. Returns (response_text, model_used). Try each model in order with per-model retry + backoff. Returns (full_response_text, model_used). """ overall_last_error = None
65 unmodified lines return full_text.strip(), ""
def run(self, transcript: str) -> tuple[str, str, str]: """ Summarize transcript. Returns (summary, qa, model_used) β nothing is written to disk. """ full, model_used = self._call_api(transcript) summary, qa = self._split(full)
self.summary_file.parent.mkdir(parents=True, exist_ok=True) self.qa_file.parent.mkdir(parents=True, exist_ok=True)
self.summary_file.write_text(summary, encoding="utf-8") self.qa_file.write_text(qa, encoding="utf-8")
logger.info("Summary saved β %s", self.summary_file) logger.info("Q&A saved β %s", self.qa_file)
logger.info("β
Summarization complete β model: %s", model_used) return summary, qa, model_used
2 unmodified lines# ============================================================================
class TranscriptSummaryPipeline: """ Orchestrates fetch β summarize. All data flows in memory β no disk I/O. """
def __init__( self,4 unmodified lines self.youtube_url = youtube_url self.fetcher = YouTubeTranscriptFetcher( youtube_url=youtube_url, output_file=TRANSCRIPT_FILE, languages=languages, polling_config=polling_config, )app.py+31-54
gemini_transcript.py+32-43