CoolFace
Apppublic

sanjaymalladi/AI_Document_Chat_Assistant

sourceHugging Faceotherupdated 2y agoView on Hugging Face
1likes
server.js107 linesDownload Raw Back to root
1require('dotenv').config();2const express = require('express');3const multer = require('multer');4const cors = require('cors');5const path = require('path');6const fs = require('fs');7const pdfParse = require('pdf-parse');8const pptxParser = require('pptx-parser');9const { GoogleGenerativeAI } = require('@google/generative-ai');10 11const app = express();12const port = process.env.PORT || 3000;13 14// Middleware15app.use(cors());16app.use(express.json());17app.use(express.static('public'));18 19// Configure multer for file upload20const storage = multer.diskStorage({21  destination: function (req, file, cb) {22    const uploadDir = 'uploads';23    if (!fs.existsSync(uploadDir)) {24      fs.mkdirSync(uploadDir);25    }26    cb(null, uploadDir);27  },28  filename: function (req, file, cb) {29    cb(null, Date.now() + path.extname(file.originalname));30  }31});32 33const upload = multer({34  storage: storage,35  fileFilter: function (req, file, cb) {36    const allowedTypes = ['.pdf', '.pptx'];37    const ext = path.extname(file.originalname).toLowerCase();38    if (allowedTypes.includes(ext)) {39      cb(null, true);40    } else {41      cb(new Error('Only PDF and PPTX files are allowed'));42    }43  }44});45 46// Initialize Gemini AI47const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);48 49// Extract text from PDF50async function extractTextFromPDF(filePath) {51  const dataBuffer = fs.readFileSync(filePath);52  const data = await pdfParse(dataBuffer);53  return data.text;54}55 56// Extract text from PPTX57async function extractTextFromPPTX(filePath) {58  const result = await pptxParser.parseFile(filePath);59  let text = '';60  result.slides.forEach(slide => {61    text += slide.text + '\n';62  });63  return text;64}65 66// Generate notes using Gemini AI67async function generateNotes(text) {68  const model = genAI.getGenerativeModel({ model: 'gemini-pro' });69  const prompt = `Please create well-structured, comprehensive notes from the following content. Include main points, key concepts, and important details:\n\n${text}`;70  71  const result = await model.generateContent(prompt);72  const response = await result.response;73  return response.text();74}75 76// File upload and processing endpoint77app.post('/upload', upload.single('file'), async (req, res) => {78  try {79    if (!req.file) {80      return res.status(400).json({ error: 'No file uploaded' });81    }82 83    const filePath = req.file.path;84    const fileExt = path.extname(req.file.originalname).toLowerCase();85    86    let extractedText = '';87    if (fileExt === '.pdf') {88      extractedText = await extractTextFromPDF(filePath);89    } else if (fileExt === '.pptx') {90      extractedText = await extractTextFromPPTX(filePath);91    }92 93    const notes = await generateNotes(extractedText);94 95    // Clean up uploaded file96    fs.unlinkSync(filePath);97 98    res.json({ notes });99  } catch (error) {100    console.error('Error processing file:', error);101    res.status(500).json({ error: 'Error processing file' });102  }103});104 105app.listen(port, () => {106  console.log(`Server is running on port ${port}`);107});