Here's a Python script that meets the specified requirements:
import asyncio
import aiohttp
import os
import glob
import base64
import json
import mimetypes
from tqdm import tqdm
import logging
# Define API keys as constants
GROQ_API_KEY = "your_groq_key_here"
SAMBANOVA_API_KEY = "your_sambanova_key_here"
# Define API endpoints and 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"
# Define prompt text
PROMPT_TEXT = "Give only the questions as text, DO NOT CHANGE THEIR CONTENT"
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
async def encode_image(image_path):
"""Encode an image file to a Base64 data URL."""
mime_type, _ = mimetypes.guess_type(image_path)
if mime_type is None:
mime_type = "image/jpeg" # Default to JPEG if type is unknown
with open(image_path, "rb") as image_file:
encoded_image = base64.b64encode(image_file.read()).decode("utf-8")
return f"data:{mime_type};base64,{encoded_image}"
async def make_api_call(session, endpoint, api_key, model, image_url):
"""Make an API call to the specified endpoint with the given image URL."""
payload = {
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": PROMPT_TEXT},
{"type": "image_url", "image_url": {"url": image_url}}
]
}
],
"model": model,
"temperature": 1,
"max_completion_tokens": 1024,
"top_p": 1,
"stream": True,
"stop": None
}
if endpoint == SAMBANOVA_ENDPOINT:
payload = {
"stream": True,
"model": model,
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": PROMPT_TEXT},
{"type": "image_url", "image_url": {"url": image_url}}
]
}
]
}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
async with session.post(endpoint, json=payload, headers=headers) as response:
if response.status == 429: # Rate limit exceeded
return None, response.status
response.raise_for_status() # Raise an exception for bad status codes
return await response.text(), response.status
async def parse_response(response_text):
"""Parse the streaming response from the API."""
content = ""
for line in response_text.splitlines():
if line.startswith("data: "):
line = line[6:] # Remove "data: " prefix
if line == "[DONE]":
break
try:
chunk = json.loads(line)
if "choices" in chunk and chunk["choices"]:
delta = chunk["choices"][0].get("delta", {})
content += delta.get("content", "")
except json.JSONDecodeError:
logging.error(f"Failed to parse JSON: {line}")
return content.strip()
async def process_image(session, image_path):
"""Process an image by making API calls and parsing the response."""
image_url = await encode_image(image_path)
filename = os.path.basename(image_path)
logging.info(f"Processing {filename}...")
# Try Groq models first
for model in GROQ_MODELS:
logging.info(f"Trying Groq model {model} for {filename}...")
response_text, status = await make_api_call(session, GROQ_ENDPOINT, GROQ_API_KEY, model, image_url)
if status == 429: # Rate limit exceeded, try the next Groq model
logging.warning(f"Groq rate limit exceeded for {filename} with model {model}. Trying the next model...")
continue
if response_text is not None:
content = await parse_response(response_text)
logging.info(f"Successfully processed {filename} with Groq model {model}.")
return content
# If all Groq models fail, try Sambanova
logging.info(f"Trying Sambanova for {filename}...")
response_text, status = await make_api_call(session, SAMBANOVA_ENDPOINT, SAMBANOVA_API_KEY, SAMBANOVA_MODEL, image_url)
if response_text is not None:
content = await parse_response(response_text)
logging.info(f"Successfully processed {filename} with Sambanova.")
return content
logging.error(f"Failed to process {filename}.")
return None
async def main():
image_folder = "path_to_your_image_folder" # Update this path
output_file = "extracted_questions.txt"
image_paths = sorted(glob.glob(os.path.join(image_folder, "*.*")))
async with aiohttp.ClientSession() as session:
tasks = []
for image_path in image_paths:
task = asyncio.create_task(process_image(session, image_path))
tasks.append((image_path, task))
results = {}
for image_path, task in tqdm(tasks, desc="Processing images"):
filename = os.path.basename(image_path)
try:
content = await task
results[filename] = content
except Exception as e:
logging.error(f"Error processing {filename}: {e}")
results[filename] = None
# Write results to the output file in the correct order
with open(output_file, "w") as f:
for image_path in sorted(image_paths):
filename = os.path.basename(image_path)
content = results[filename]
if content is not None:
f.write(content + "\n")
if __name__ == "__main__":
asyncio.run(main())