mominah commited on
Commit
67b16fb
Β·
verified Β·
1 Parent(s): 5f6f6f9

Update video_rag_routes.py

Browse files
Files changed (1) hide show
  1. video_rag_routes.py +39 -36
video_rag_routes.py CHANGED
@@ -3,8 +3,7 @@
3
  import os
4
  import uuid
5
  import itertools
6
- from dotenv import load_dotenv
7
- from fastapi import APIRouter, HTTPException, UploadFile, File, Depends
8
  from google import genai
9
  from google.api_core.exceptions import ResourceExhausted
10
  from google.genai import types
@@ -16,32 +15,48 @@ from langchain_core.prompts import ChatPromptTemplate
16
  from langchain.text_splitter import RecursiveCharacterTextSplitter
17
  from langchain_groq import ChatGroq
18
 
19
- load_dotenv() # loads .env into os.environ
20
-
21
- # β€”β€”β€” Rotate Gemini API keys β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
22
- _key_names = os.getenv("GOOGLE_API_KEYS", "")
 
 
 
 
 
 
 
 
23
  if not _key_names:
24
- raise RuntimeError("GOOGLE_API_KEYS must be set in .env (comma-separated)")
 
 
 
 
25
  _key_names = [n.strip() for n in _key_names.split(",") if n.strip()]
26
- _api_keys = [os.getenv(name) for name in _key_names]
27
- missing = [n for n,k in zip(_key_names,_api_keys) if k is None]
28
- if missing:
29
- raise RuntimeError(f"Missing key values for: {missing}")
 
 
 
30
  _key_cycle = itertools.cycle(_api_keys)
31
 
32
  def init_google_client():
33
  """
34
- Grab the next key in our cycle and return a fresh genai.Client.
35
  """
36
- api_key = next(_key_cycle)
37
- return genai.Client(api_key=api_key)
 
38
 
39
  # β€”β€”β€” LLM & Embedding Helpers β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
40
 
41
  def get_llm():
42
- api_key = os.getenv("CHATGROQ_API_KEY", "")
43
  if not api_key:
44
- raise ValueError("CHATGROQ_API_KEY must be set")
45
  return ChatGroq(
46
  model="llama-3.3-70b-versatile",
47
  temperature=0,
@@ -81,7 +96,8 @@ def create_chain(retriever):
81
  verbose=False,
82
  )
83
 
84
- # β€”β€”β€” In-Memory Session Store β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
 
85
  sessions: dict[str, dict] = {}
86
 
87
  def process_transcription(text: str) -> str:
@@ -93,28 +109,27 @@ def process_transcription(text: str) -> str:
93
  sessions[sid] = {"retriever": retr, "history": []}
94
  return sid
95
 
 
96
  # β€”β€”β€” Retry Decorator for Rate-Limits β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
 
97
  def retry_on_rate_limit(fn):
98
  async def wrapper(*args, **kwargs):
99
  last_exc = None
100
- # try as many times as there are keys
101
  for _ in range(len(_api_keys)):
102
  client = init_google_client()
103
  try:
104
- # inject `client` as first arg
105
  return await fn(client, *args, **kwargs)
106
  except ResourceExhausted as e:
107
  last_exc = e
108
- # loop and pick next key
109
  continue
110
- # if we get here, all keys are exhausted
111
  raise HTTPException(
112
  status_code=503,
113
- detail="All Gemini API keys are rate-limited",
114
  )
115
  return wrapper
116
 
117
- # β€”β€”β€” FastAPI Router & Models β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
 
118
  router = APIRouter()
119
 
120
  class URLIn(BaseModel):
@@ -122,13 +137,7 @@ class URLIn(BaseModel):
122
 
123
  @router.post("/transcribe_video")
124
  @retry_on_rate_limit
125
- async def transcribe_url(
126
- client: genai.Client,
127
- body: URLIn
128
- ):
129
- """
130
- Transcribe a YouTube URL via Gemini β†’ process β†’ return session_id
131
- """
132
  try:
133
  resp = client.models.generate_content(
134
  model="models/gemini-2.0-flash",
@@ -150,9 +159,6 @@ async def upload_file(
150
  file: UploadFile = File(...),
151
  prompt: str = "Transcribe the video",
152
  ):
153
- """
154
- Transcribe an uploaded video file via Gemini β†’ process β†’ return session_id
155
- """
156
  data = await file.read()
157
  try:
158
  resp = client.models.generate_content(
@@ -174,9 +180,6 @@ class QueryIn(BaseModel):
174
 
175
  @router.post("/vid_query")
176
  async def query_rag(body: QueryIn):
177
- """
178
- Run a RAG query against the stored transcript session.
179
- """
180
  sess = sessions.get(body.session_id)
181
  if not sess:
182
  raise HTTPException(status_code=404, detail="Session not found")
 
3
  import os
4
  import uuid
5
  import itertools
6
+ from fastapi import APIRouter, HTTPException, UploadFile, File
 
7
  from google import genai
8
  from google.api_core.exceptions import ResourceExhausted
9
  from google.genai import types
 
15
  from langchain.text_splitter import RecursiveCharacterTextSplitter
16
  from langchain_groq import ChatGroq
17
 
18
+ # β€”β€”β€” Rotate Gemini API keys from HF Secrets β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
19
+ #
20
+ # In your Space’s Secrets UI, create a comma-separated list under
21
+ # Key: GOOGLE_API_KEY_NAMES
22
+ # Value: G_API,GO_API,GOO_API,GOOG_API,GOOGL_API,GOOGLE_API
23
+ #
24
+ # Then also define each of those six as individual secrets:
25
+ # G_API=AIzaS…1lLXA
26
+ # GO_API=AIzaS…QtkOT8
27
+ # …etc…
28
+ #
29
+ _key_names = os.environ.get("GOOGLE_API_KEY_NAMES", "")
30
  if not _key_names:
31
+ raise RuntimeError(
32
+ "You must define a HF Secret named GOOGLE_API_KEY_NAMES "
33
+ "(e.g. 'G_API,GO_API,…')"
34
+ )
35
+
36
  _key_names = [n.strip() for n in _key_names.split(",") if n.strip()]
37
+ _api_keys = []
38
+ for name in _key_names:
39
+ val = os.environ.get(name)
40
+ if not val:
41
+ raise RuntimeError(f"Hugging Face Secret `{name}` is not set")
42
+ _api_keys.append(val)
43
+
44
  _key_cycle = itertools.cycle(_api_keys)
45
 
46
  def init_google_client():
47
  """
48
+ Rotate through your HF-stored Gemini keys.
49
  """
50
+ key = next(_key_cycle)
51
+ return genai.Client(api_key=key)
52
+
53
 
54
  # β€”β€”β€” LLM & Embedding Helpers β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
55
 
56
  def get_llm():
57
+ api_key = os.environ.get("CHATGROQ_API_KEY")
58
  if not api_key:
59
+ raise RuntimeError("`CHATGROQ_API_KEY` must be set as a HF Secret")
60
  return ChatGroq(
61
  model="llama-3.3-70b-versatile",
62
  temperature=0,
 
96
  verbose=False,
97
  )
98
 
99
+
100
+ # β€”β€”β€” Session Store & Transcription β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
101
  sessions: dict[str, dict] = {}
102
 
103
  def process_transcription(text: str) -> str:
 
109
  sessions[sid] = {"retriever": retr, "history": []}
110
  return sid
111
 
112
+
113
  # β€”β€”β€” Retry Decorator for Rate-Limits β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
114
+
115
  def retry_on_rate_limit(fn):
116
  async def wrapper(*args, **kwargs):
117
  last_exc = None
 
118
  for _ in range(len(_api_keys)):
119
  client = init_google_client()
120
  try:
 
121
  return await fn(client, *args, **kwargs)
122
  except ResourceExhausted as e:
123
  last_exc = e
 
124
  continue
 
125
  raise HTTPException(
126
  status_code=503,
127
+ detail="All Gemini API keys are rate-limited"
128
  )
129
  return wrapper
130
 
131
+
132
+ # β€”β€”β€” FastAPI Router & Endpoints β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
133
  router = APIRouter()
134
 
135
  class URLIn(BaseModel):
 
137
 
138
  @router.post("/transcribe_video")
139
  @retry_on_rate_limit
140
+ async def transcribe_url(client: genai.Client, body: URLIn):
 
 
 
 
 
 
141
  try:
142
  resp = client.models.generate_content(
143
  model="models/gemini-2.0-flash",
 
159
  file: UploadFile = File(...),
160
  prompt: str = "Transcribe the video",
161
  ):
 
 
 
162
  data = await file.read()
163
  try:
164
  resp = client.models.generate_content(
 
180
 
181
  @router.post("/vid_query")
182
  async def query_rag(body: QueryIn):
 
 
 
183
  sess = sessions.get(body.session_id)
184
  if not sess:
185
  raise HTTPException(status_code=404, detail="Session not found")