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 lines56789101121 unmodified lines3334353637383940414243441 unmodified line4647484950515253545556210 unmodified lines2672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962 unmodified lines299300301302303304568 unmodified lines87387487587687787887988088188288388488588688788888989089189289389489589689789866 unmodified lines9659669679689699709719729739749759769779789799809819829839844 unmodified linesimport base64import hashlibimport secretsimport shutilimport tempfileimport threading21 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")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")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 linesreturn 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 filedef create_file_on_drive(filename: str,content: str,2 unmodified linesfolder_id: str | None = None,make_public: bool = True,) -> dict: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,step_key: str,job_id: str,folder_id: str,creds: Credentials,) -> dict:"""Copy file with video-title name, upload to Drive, clean up."""_set_step(job_id, step_key, "running")try:tmp_path = local_file.parent / drive_nameif 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,)tmp_path.unlink()_set_step(job_id, step_key, "done")return resultexcept 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 βββββββββββββββββββββββββββββββββββββββ_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",job_id, folder_id, creds,)qa_drive = _upload_with_title(QA_FILE, 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",job_id, folder_id, creds,)4 unmodified lines567891021 unmodified lines3233343536373839404142431 unmodified line454647484950210 unmodified lines2612622632642652662 unmodified lines269270271272273274275276277278568 unmodified lines84784884985085185285385485585685785885986086186286386486586686786886987087187287387487566 unmodified lines9429439449459469479489499509519529539549559569579589599609614 unmodified linesimport base64import hashlibimport secretsimport tempfileimport threading21 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")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")SCOPES = ["https://www.googleapis.com/auth/spreadsheets",1 unmodified line"https://www.googleapis.com/auth/drive.file",]SHEETS_HEADERS = ["Timestamp", # A"Job ID", # B210 unmodified linesreturn folder["id"]def create_file_on_drive(filename: str,content: str,2 unmodified linesfolder_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_content(content: str,filename: str,step_key: str,job_id: str,folder_id: str,creds: Credentials,) -> dict:"""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:result = create_file_on_drive(filename=filename,content=content,mimetype="text/plain",creds=creds,folder_id=folder_id,make_public=True,)_set_step(job_id, step_key, "done")return resultexcept 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 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_content(summary, f"{video_title}__summary.txt", "upload_summary",job_id, folder_id, creds,)qa_drive = _upload_content(qa, f"{video_title}__qa.txt", "upload_qa",job_id, folder_id, creds,)transcript_drive = _upload_content(transcript, f"{video_title}__transcript.txt", "upload_transcript",job_id, folder_id, creds,)
7 unmodified lines891011121314151617188 unmodified lines272829303132333435363738117 unmodified lines15615715815916016116216316416516616716816917017117218 unmodified lines19119219319419519619719819920020120220320416 unmodified lines22122222322422522622739 unmodified lines26726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930065 unmodified lines3663673683693703713723733743753763773783793803813823832 unmodified lines3863873883893903914 unmodified lines3963973983994004014027 unmodified linesimport loggingimport timefrom pathlib import Pathfrom typing import Optional, Listfrom urllib.parse import urlparse, parse_qsfrom google import genai # pip install google-genaifrom google.genai import typesfrom 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_MODELS = ["gemini-2.5-flash",117 unmodified lines# ============================================================================class YouTubeTranscriptFetcher:"""Fetches YouTube transcript with polling retry for new uploads."""def __init__(self,youtube_url: str,output_file: Path = TRANSCRIPT_FILE,languages: Optional[List[str]] = None,polling_config: dict = None,):self.youtube_url = youtube_urlself.output_file = Path(output_file)self.languages = languages or ["en", "en-US", "en-GB"]self.polling_config = polling_config or POLLING_CONFIGself.video_id = self._extract_video_id(youtube_url)18 unmodified linestranscript = 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))attempts = list(self.polling_config.items())16 unmodified linestry: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."""MAX_RETRIES = 5BASE_WAIT = 10 # secondsMAX_WAIT = 120 # seconds cap# Errors β retry same model with backoffRETRYABLE = ["503", "502", "500", "UNAVAILABLE", "SERVICE_UNAVAILABLE"]# Errors β skip to next model immediatelySKIP_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,):self.client = genai.Client(api_key=api_key)self.models = models or GEMINI_MODELSself.summary_file = Path(summary_file)self.qa_file = Path(qa_file)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)."""overall_last_error = None65 unmodified linesreturn full_text.strip(), ""def run(self, transcript: str) -> tuple[str, str, str]: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)return summary, qa, model_used2 unmodified lines# ============================================================================class TranscriptSummaryPipeline:def __init__(self,4 unmodified linesself.youtube_url = youtube_urlself.fetcher = YouTubeTranscriptFetcher(youtube_url=youtube_url,output_file=TRANSCRIPT_FILE,languages=languages,polling_config=polling_config,)7 unmodified lines8910111213141516178 unmodified lines26272829303132117 unmodified lines15015115215315415515615715815916016116216316416516616718 unmodified lines18618718818919019119219319419519619719816 unmodified lines21521621721821922039 unmodified lines26026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029165 unmodified lines3573583593603613623633643653663673683692 unmodified lines3723733743753763773783793803814 unmodified lines3863873883893903917 unmodified linesimport loggingimport timefrom typing import Optional, Listfrom urllib.parse import urlparse, parse_qsfrom google import genai # pip install google-genaifrom google.genai import typesfrom youtube_transcript_api import (8 unmodified lines# CONFIG# ============================================================================GEMINI_API_KEY = "AIzaSyCNz5wQAyJ65kNRkwr0-1A-_Z6-lQzdcyc"GEMINI_MODELS = ["gemini-2.5-flash",117 unmodified lines# ============================================================================class YouTubeTranscriptFetcher:"""Fetches a YouTube transcript and returns it as a plain string.No files are written to disk."""def __init__(self,youtube_url: str,languages: Optional[List[str]] = None,polling_config: dict = None,):self.youtube_url = youtube_urlself.languages = languages or ["en", "en-US", "en-GB"]self.polling_config = polling_config or POLLING_CONFIGself.video_id = self._extract_video_id(youtube_url)18 unmodified linestranscript = self.api.fetch(self.video_id, languages=self.languages)return " ".join(item.text for item in transcript)def run(self) -> str:"""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 linestry:text = self._fetch_once()logger.info("[%d/%d] β Transcript fetched β %d characters",idx, len(attempts), len(text),39 unmodified lines# ============================================================================class GeminiSummarizer:"""Sends transcript to Gemini and returns (summary, qa, model_used).No files are written to disk."""MAX_RETRIES = 5BASE_WAIT = 10 # secondsMAX_WAIT = 120 # seconds cap# Errors β retry same model with exponential backoffRETRYABLE = ["503", "502", "500", "UNAVAILABLE", "SERVICE_UNAVAILABLE"]# Errors β skip to next model immediatelySKIP_TO_NEXT = ["429", "RESOURCE_EXHAUSTED", "quota", "404", "NOT_FOUND"]def __init__(self,api_key: str = GEMINI_API_KEY,models: list = None,):self.client = genai.Client(api_key=api_key)self.models = models or GEMINI_MODELSdef _call_api(self, transcript: str) -> tuple[str, str]:"""Try each model in order with per-model retry + backoff.Returns (full_response_text, model_used)."""overall_last_error = None65 unmodified linesreturn 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)logger.info("β Summarization complete β model: %s", model_used)return summary, qa, model_used2 unmodified lines# ============================================================================class TranscriptSummaryPipeline:"""Orchestrates fetch β summarize.All data flows in memory β no disk I/O."""def __init__(self,4 unmodified linesself.youtube_url = youtube_urlself.fetcher = YouTubeTranscriptFetcher(youtube_url=youtube_url,languages=languages,polling_config=polling_config,)
app.py+31-54
gemini_transcript.py+32-43