File size: 5,716 Bytes
16a4dbd
 
 
66097e1
16a4dbd
 
e099ac1
 
 
 
66097e1
 
16a4dbd
 
 
66097e1
16a4dbd
 
 
 
 
 
 
 
66097e1
 
 
 
 
 
 
16a4dbd
66097e1
 
 
 
 
 
 
16a4dbd
 
 
 
 
 
66097e1
16a4dbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94c2cc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16a4dbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66097e1
16a4dbd
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import { NextRequest, NextResponse } from 'next/server';
import mammoth from 'mammoth';
import ExcelJS from 'exceljs';
import fs from 'fs';
import path from 'path';

// Use /data for Hugging Face Spaces persistent storage
const DATA_DIR = process.env.SPACE_ID
  ? '/data'
  : path.join(process.cwd(), 'public', 'data');
const PUBLIC_DIR = path.join(DATA_DIR, 'public');

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { fileName, isPublic = false, operation = 'read', key } = body;

    if (!fileName) {
      return NextResponse.json(
        { success: false, error: 'File name is required' },
        { status: 400 }
      );
    }

    let targetDir = PUBLIC_DIR;
    if (!isPublic) {
      if (!key) {
        return NextResponse.json(
          { success: false, error: 'Passkey (key) is required for non-public files' },
          { status: 401 }
        );
      }
      const sanitizedKey = key.replace(/[^a-zA-Z0-9_-]/g, '');
      targetDir = path.join(DATA_DIR, sanitizedKey);
    }

    // Get file buffer
    const filePath = path.join(targetDir, fileName);
    if (!fs.existsSync(filePath)) {
      return NextResponse.json(
        { success: false, error: 'File not found' },
        { status: 404 }
      );
    }

    const fileBuffer = fs.readFileSync(filePath);
    const ext = fileName.split('.').pop()?.toLowerCase();
    let content: any = {};

    switch (ext) {
      case 'docx':
        try {
          const result = await mammoth.extractRawText({ buffer: fileBuffer });
          content = {
            type: 'docx',
            text: result.value,
            messages: result.messages
          };

          const htmlResult = await mammoth.convertToHtml({ buffer: fileBuffer });
          content.html = htmlResult.value;
        } catch (error) {
          content = {
            type: 'docx',
            error: 'Failed to process Word document',
            details: error
          };
        }
        break;

      case 'xlsx':
      case 'xls':
        try {
          const workbook = new ExcelJS.Workbook();
          await workbook.xlsx.load(fileBuffer as any);

          const sheets: any[] = [];
          workbook.eachSheet((worksheet) => {
            const sheetData: any = {
              name: worksheet.name,
              rowCount: worksheet.rowCount,
              columnCount: worksheet.columnCount,
              data: []
            };

            worksheet.eachRow((row, rowNumber) => {
              const rowData: any[] = [];
              row.eachCell((cell, colNumber) => {
                rowData.push({
                  value: cell.value,
                  type: cell.type,
                  formula: cell.formula
                });
              });
              sheetData.data.push(rowData);
            });

            sheets.push(sheetData);
          });

          content = {
            type: 'excel',
            sheets,
            sheetCount: sheets.length
          };
        } catch (error) {
          content = {
            type: 'excel',
            error: 'Failed to process Excel spreadsheet',
            details: error
          };
        }
        break;

      case 'pdf':
        try {
          const pdf = require('pdf-parse');
          const data = await pdf(fileBuffer);
          content = {
            type: 'pdf',
            text: data.text,
            info: data.info,
            metadata: data.metadata,
            version: data.version,
            numpages: data.numpages
          };
        } catch (error) {
          content = {
            type: 'pdf',
            error: 'Failed to process PDF document',
            details: error
          };
        }
        break;

      case 'pptx':
      case 'ppt':
        content = {
          type: 'powerpoint',
          fileName,
          size: fileBuffer.length,
          message: 'PowerPoint processing requires additional libraries'
        };
        break;

      case 'txt':
      case 'md':
      case 'json':
      case 'csv':
        content = {
          type: ext,
          text: fileBuffer.toString('utf-8')
        };
        break;

      default:
        content = {
          type: 'unknown',
          fileName,
          size: fileBuffer.length,
          message: 'Unknown file type'
        };
    }

    if (operation === 'analyze' && content.text) {
      const text = content.text || '';
      content.analysis = {
        characterCount: text.length,
        wordCount: text.split(/\s+/).filter(Boolean).length,
        lineCount: text.split('\n').length,
        paragraphCount: text.split('\n\n').filter(Boolean).length
      };
    }

    return NextResponse.json({
      success: true,
      fileName,
      operation,
      content
    });
  } catch (error) {
    console.error('Error processing document:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to process document' },
      { status: 500 }
    );
  }
}

export async function GET() {
  return NextResponse.json({
    message: 'Document processing endpoint',
    endpoint: '/api/documents/process',
    method: 'POST',
    body: {
      fileName: 'Name of the file to process',
      isPublic: 'true/false - whether file is in public folder',
      key: 'Passkey for secure storage (required if not public)',
      operation: 'Operation to perform: read (default), analyze'
    },
    supportedFormats: [
      'docx - Word documents (text extraction)',
      'xlsx/xls - Excel spreadsheets (data extraction)',
      'pdf - PDF files (metadata only)',
      'pptx/ppt - PowerPoint (metadata only)',
      'txt/md/json/csv - Text files (full content)'
    ]
  });
}