#!/usr/bin/env python3
"""
async_extract_questions.py
Scan a folder of images, send each to Groq (primary) or Sambanova (fallback)
via streaming chat-completions, extract only the questions, and write them
in alphabetical order to a single text file.
Requirements:
- Python 3.8+
- aiohttp
- tqdm
"""
import os
import glob
import mimetypes
import base64
import json
import asyncio
import logging
from typing import List, Optional
import aiohttp
from aiohttp import ClientResponse, ClientError, ClientTimeout
from tqdm import tqdm
# ========== CONFIGURATION ==========
# === API KEYS ===
GROQ_API_KEY = "your_groq_key_here"
SAMBANOVA_API_KEY = "your_sambanova_key_here"
# === Endpoints & Models ===
GROQ_ENDPOINT = "https://api.groq.com/openai/v1/chat/completions"
GROQ_MODELS = [
"meta-llama/llama-4-scout-17b-16e-instruct",
"meta-llama/llama-4-maverick-17b-128e-instruct",
]
SAMBANOVA_ENDPOINT = "https://api.sambanova.ai/v1/chat/completions"
SAMBANOVA_MODEL = "Llama-4-Maverick-17B-128E-Instruct"
# === Prompt ===
PROMPT_TEXT = "Give only the questions as text, DO NOT CHANGE THEIR CONTENT"
# === I/O ===
IMAGE_FOLDER = "images" # Path to your images folder
OUTPUT_FILE = "extracted.txt" # Final text file
# === Concurrency & Retries ===
MAX_CONCURRENT_REQUESTS = 5
MAX_RETRIES = 2
INITIAL_BACKOFF = 1.0 # seconds
# ====================================
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] %(levelname)s:%(name)s: %(message)s"
)
logger = logging.getLogger("extract_questions")
def encode_image_to_data_url(path: str) -> str:
"""
Read image file and encode to Base64 data URL.
"""
mime_type, _ = mimetypes.guess_type(path)
if not mime_type:
raise ValueError(f"Cannot determine MIME type for {path}")
with open(path, "rb") as f:
raw = f.read()
b64 = base64.b64encode(raw).decode("utf-8")
return f"data:{mime_type};base64,{b64}"
async def parse_sse_stream(response: ClientResponse) -> str:
"""
Parse a streaming SSE response and concatenate all delta.content pieces.
"""
text_parts: List[str] = []
async for raw_line in response.content:
line = raw_line.decode("utf-8").strip()
if not line.startswith("data:"):
continue
payload = line[len("data:"):].strip()
if payload in ("[DONE]", ""):
break
try:
data = json.loads(payload)
except json.JSONDecodeError:
continue
# Groq and Sambanova have slightly different shapes
choices = data.get("choices", [])
if not choices:
continue
delta = choices[0].get("delta", {})
content = delta.get("content")
if content:
text_parts.append(content)
# Some streams use finish_reason instead of explicit [DONE]
if choices[0].get("finish_reason") == "stop":
break
return "".join(text_parts).strip()
async def call_groq(
session: aiohttp.ClientSession,
data_url: str,
model: str
) -> str:
"""
Send image to Groq streaming API using given model.
Raises on non-200 or other errors.
"""
headers = {
"Authorization": f"Bearer {GROQ_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"temperature": 1,
"max_completion_tokens": 1024,
"top_p": 1,
"stream": True,
"stop": None,
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": PROMPT_TEXT},
{"type": "image_url", "image_url": {"url": data_url}}
]
}
]
}
async with session.post(
GROQ_ENDPOINT,
headers=headers,
json=payload,
timeout=ClientTimeout(total=60)
) as resp:
if resp.status == 429:
raise aiohttp.ClientResponseError(
status=429, request_info=resp.request_info,
history=resp.history, message="Rate limit"
)
resp.raise_for_status()
return await parse_sse_stream(resp)
async def call_sambanova(
session: aiohttp.ClientSession,
data_url: str
) -> str:
"""
Send image to Sambanova streaming API.
Raises on non-200 or other errors.
"""
headers = {
"Authorization": f"Bearer {SAMBANOVA_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": SAMBANOVA_MODEL,
"stream": True,
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": PROMPT_TEXT},
{"type": "image_url", "image_url": {"url": data_url}}
]
}
]
}
async with session.post(
SAMBANOVA_ENDPOINT,
headers=headers,
json=payload,
timeout=ClientTimeout(total=60)
) as resp:
if resp.status == 429:
raise aiohttp.ClientResponseError(
status=429, request_info=resp.request_info,
history=resp.history, message="Rate limit"
)
resp.raise_for_status()
return await parse_sse_stream(resp)
async def process_image(
idx: int,
path: str,
session: aiohttp.ClientSession,
sem: asyncio.Semaphore,
results: List[Optional[str]],
pbar: tqdm
):
"""
Encode image, try Groq models then fallback to Sambanova,
with retry logic and exponential backoff.
Store result in results[idx]. Always update progress bar.
"""
fname = os.path.basename(path)
data_url = None
try:
data_url = encode_image_to_data_url(path)
except Exception as e:
logger.error(f"[{fname}] Failed to encode image: {e}")
results[idx] = ""
pbar.update(1)
return
# Acquire semaphore to limit concurrent API calls
async with sem:
backoff = INITIAL_BACKOFF
for attempt in range(1, MAX_RETRIES + 1):
try:
# Try each Groq model in turn
for model in GROQ_MODELS:
try:
logger.info(f"[{fname}] Attempt {attempt} on Groq model {model}")
text = await call_groq(session, data_url, model)
logger.info(f"[{fname}] Success with Groq model {model}")
results[idx] = text
pbar.update(1)
return
except ClientResponseError as e:
if e.status == 429:
logger.warning(f"[{fname}] Groq model {model} rate-limited.")
continue # try next Groq model
else:
logger.error(f"[{fname}] Groq model {model} error: {e}")
raise
# If both Groq models rate-limited or failed with 429, try Sambanova
logger.info(f"[{fname}] Falling back to Sambanova (attempt {attempt})")
text = await call_sambanova(session, data_url)
logger.info(f"[{fname}] Success with Sambanova")
results[idx] = text
pbar.update(1)
return
except (ClientResponseError, ClientError, asyncio.TimeoutError) as e:
logger.error(f"[{fname}] Attempt {attempt} failed: {e}")
if attempt < MAX_RETRIES:
await asyncio.sleep(backoff)
backoff *= 2
else:
logger.error(f"[{fname}] All retries exhausted. Skipping.")
results[idx] = ""
pbar.update(1)
return
async def main():
# 1. Gather image paths sorted alphabetically
pattern = os.path.join(IMAGE_FOLDER, "*")
image_paths = sorted([p for p in glob.glob(pattern)
if os.path.isfile(p) and
mimetypes.guess_type(p)[0] and
mimetypes.guess_type(p)[0].startswith("image/")])
total = len(image_paths)
if total == 0:
logger.error(f"No images found in {IMAGE_FOLDER}.")
return
logger.info(f"Found {total} images. Starting processing...")
# Prepare shared structures
results: List[Optional[str]] = [None] * total
sem = asyncio.Semaphore(MAX_CONCURRENT_REQUESTS)
timeout = ClientTimeout(total=None) # we set per-request timeouts earlier
# Start session
async with aiohttp.ClientSession(timeout=timeout) as session:
# Progress bar
with tqdm(total=total, desc="Images processed") as pbar:
tasks = [
process_image(i, path, session, sem, results, pbar)
for i, path in enumerate(image_paths)
]
await asyncio.gather(*tasks)
logger.info("All tasks completed. Writing output file...")
# 2. Write results in original alphabetical order
with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
for text in results:
# Even if text == "", we write a blank line to preserve count/order
f.write((text or "").strip() + "\n\n")
logger.info(f"Done! Extracted questions are in {OUTPUT_FILE}")
if __name__ == "__main__":
asyncio.run(main())