Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save chirag-shinde/7163b020f6f75a0ebc144dbd04144586 to your computer and use it in GitHub Desktop.

Select an option

Save chirag-shinde/7163b020f6f75a0ebc144dbd04144586 to your computer and use it in GitHub Desktop.
test pdf summary
import chokidar from 'chokidar';
import fs from 'fs';
import path from 'path';
import dotenv from 'dotenv';
dotenv.config();
const OPENROUTER_API_KEY = process.env.OPENROUTER_API_KEY;
const PROMPTS = [
"Summarize this document in 3 concise bullet points.",
"What are the key conclusions or recommendations in this document?",
"Identify any risks, limitations, or caveats mentioned in this document.",
];
const MODEL = "qwen/qwen3.6-plus:free";
chokidar.watch('./data').on('all', async (event, filePath) => {
console.log(event, filePath);
if (event === 'add' && filePath.endsWith('.pdf')) {
try {
if (!fs.existsSync(filePath)) {
console.error(`Error: PDF not found at "${filePath}"`);
return;
}
const pdfBase64 = fs.readFileSync(filePath).toString("base64");
const results = await Promise.allSettled(
PROMPTS.map((prompt, i) => summarize(pdfBase64, prompt, i, filePath))
);
results.forEach((result, i) => {
console.log(`--- Prompt ${i + 1} ---`);
console.log(`Q: ${PROMPTS[i]}\n`);
if (result.status === "fulfilled") {
console.log(result.value);
} else {
console.error(`Error: ${result.reason.message}`);
}
console.log();
});
} catch (err) {
console.error(`Unhandled error processing ${filePath}:`, err);
}
}
});
async function summarize(pdfBase64, prompt, index, pdfPath) {
const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${OPENROUTER_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: MODEL,
messages: [
{
role: "user",
content: [
{
type: "file",
file: {
filename: path.basename(pdfPath),
file_data: `data:application/pdf;base64,${pdfBase64}`,
},
},
{
type: "text",
text: prompt,
},
],
},
],
}),
});
if (!response.ok) {
const err = await response.text();
throw new Error(`Prompt ${index + 1} failed [${response.status}]: ${err}`);
}
const data = await response.json();
return data.choices[0].message.content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment