|
| 1 | +import { OpenAPIHono, createRoute, z } from '@hono/zod-openapi' |
| 2 | +import { Context } from 'hono' |
| 3 | +import { streamSSE } from 'hono/streaming' |
| 4 | +import { pdfTranslatePrompt } from '../../utils/prompts' |
| 5 | +import { handleError } from '../../utils/errorHandler' |
| 6 | +import { pdfTranslateRequestSchema, pdfTranslateResponseSchema, createPdfTranslateResponse } from '../../schemas/v1/pdf-translate' |
| 7 | +import { processTextOutputRequest } from '../../services/ai' |
| 8 | +import { apiVersion } from './versionConfig' |
| 9 | +import { createFinalResponse } from './finalResponse' |
| 10 | +import { writeTextStreamSSE } from './streamUtils' |
| 11 | +import { extractPDF, truncateText } from '../../utils/pdfExtractor' |
| 12 | + |
| 13 | +const router = new OpenAPIHono() |
| 14 | + |
| 15 | +// Maximum text length to send to the LLM (to avoid token limits) |
| 16 | +const MAX_PDF_TEXT_LENGTH = 50000 |
| 17 | + |
| 18 | +async function handlePdfTranslateRequest(c: Context) { |
| 19 | + try { |
| 20 | + const { payload, config } = await c.req.json() |
| 21 | + const provider = config.provider |
| 22 | + const model = config.model |
| 23 | + const isStreaming = config.stream || false |
| 24 | + |
| 25 | + // Extract PDF content |
| 26 | + const pdfData = await extractPDF(payload.url) |
| 27 | + |
| 28 | + if (!pdfData.text || pdfData.text.length === 0) { |
| 29 | + throw new Error('No text content found in the PDF') |
| 30 | + } |
| 31 | + |
| 32 | + // Truncate text if it's too long |
| 33 | + const textToTranslate = truncateText(pdfData.text, MAX_PDF_TEXT_LENGTH) |
| 34 | + |
| 35 | + // Create the prompt |
| 36 | + const prompt = pdfTranslatePrompt(textToTranslate, payload.targetLanguage) |
| 37 | + |
| 38 | + // Handle streaming response |
| 39 | + if (isStreaming) { |
| 40 | + const result = await processTextOutputRequest(prompt, config) |
| 41 | + |
| 42 | + // Set SSE headers |
| 43 | + c.header('Content-Type', 'text/event-stream') |
| 44 | + c.header('Cache-Control', 'no-cache') |
| 45 | + c.header('Connection', 'keep-alive') |
| 46 | + |
| 47 | + return streamSSE(c, async (stream) => { |
| 48 | + try { |
| 49 | + await writeTextStreamSSE( |
| 50 | + stream, |
| 51 | + result, |
| 52 | + { |
| 53 | + provider, |
| 54 | + model, |
| 55 | + version: apiVersion |
| 56 | + }, |
| 57 | + { |
| 58 | + extraDone: { |
| 59 | + pdfMetadata: { |
| 60 | + title: pdfData.title, |
| 61 | + author: pdfData.author, |
| 62 | + pages: pdfData.pages, |
| 63 | + extractedTextLength: pdfData.text.length, |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + ) |
| 68 | + } catch (error) { |
| 69 | + console.error('Streaming error:', error) |
| 70 | + try { |
| 71 | + await stream.writeSSE({ |
| 72 | + data: JSON.stringify({ |
| 73 | + error: error instanceof Error ? error.message : 'Streaming error', |
| 74 | + done: true |
| 75 | + }) |
| 76 | + }) |
| 77 | + } catch (writeError) { |
| 78 | + console.error('Error writing error message to stream:', writeError) |
| 79 | + } |
| 80 | + } finally { |
| 81 | + try { |
| 82 | + await stream.close() |
| 83 | + } catch (closeError) { |
| 84 | + console.error('Error closing stream:', closeError) |
| 85 | + } |
| 86 | + } |
| 87 | + }) |
| 88 | + } |
| 89 | + |
| 90 | + // Handle non-streaming response |
| 91 | + const result = await processTextOutputRequest(prompt, config) |
| 92 | + const finalResponse = createPdfTranslateResponse( |
| 93 | + result.text, |
| 94 | + provider, |
| 95 | + model, |
| 96 | + { |
| 97 | + title: pdfData.title, |
| 98 | + author: pdfData.author, |
| 99 | + pages: pdfData.pages, |
| 100 | + extractedTextLength: pdfData.text.length, |
| 101 | + }, |
| 102 | + { |
| 103 | + input_tokens: result.usage.promptTokens, |
| 104 | + output_tokens: result.usage.completionTokens, |
| 105 | + total_tokens: result.usage.totalTokens, |
| 106 | + } |
| 107 | + ) |
| 108 | + |
| 109 | + const finalResponseWithVersion = createFinalResponse(finalResponse, apiVersion) |
| 110 | + |
| 111 | + return c.json(finalResponseWithVersion, 200) |
| 112 | + } catch (error) { |
| 113 | + return handleError(c, error, 'Failed to translate PDF') |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +router.openapi( |
| 118 | + createRoute({ |
| 119 | + path: '/', |
| 120 | + method: 'post', |
| 121 | + security: [ { BearerAuth: [] } ], |
| 122 | + request: { |
| 123 | + body: { |
| 124 | + content: { |
| 125 | + 'application/json': { |
| 126 | + schema: pdfTranslateRequestSchema |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + }, |
| 131 | + responses: { |
| 132 | + 200: { |
| 133 | + description: 'Returns the translated PDF content.', |
| 134 | + content: { |
| 135 | + 'application/json': { |
| 136 | + schema: pdfTranslateResponseSchema |
| 137 | + } |
| 138 | + } |
| 139 | + }, |
| 140 | + 401: { |
| 141 | + description: 'Unauthorized - Bearer token required', |
| 142 | + content: { |
| 143 | + 'application/json': { |
| 144 | + schema: z.object({ |
| 145 | + error: z.string() |
| 146 | + }) |
| 147 | + } |
| 148 | + } |
| 149 | + }, |
| 150 | + 400: { |
| 151 | + description: 'Bad request - Invalid URL or PDF cannot be processed', |
| 152 | + content: { |
| 153 | + 'application/json': { |
| 154 | + schema: z.object({ |
| 155 | + error: z.string() |
| 156 | + }) |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | + }, |
| 161 | + summary: 'Translate PDF document', |
| 162 | + description: 'This endpoint receives a PDF URL and uses an LLM to translate the document\'s content to the target language.', |
| 163 | + tags: ['API'] |
| 164 | + }), |
| 165 | + handlePdfTranslateRequest as any |
| 166 | +) |
| 167 | + |
| 168 | +export default { |
| 169 | + handler: router, |
| 170 | + mountPath: 'pdf-translate' |
| 171 | +} |
0 commit comments