├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── app ├── api │ ├── extract │ │ └── route.ts │ └── schema │ │ └── route.ts ├── favicon.ico ├── globals.css ├── layout.tsx └── page.tsx ├── components.json ├── components ├── FileUpload.tsx ├── PdfViewer.tsx ├── PromptInput.tsx ├── ResultDisplay.tsx ├── providers.tsx └── ui │ ├── button.tsx │ ├── card.tsx │ ├── input.tsx │ ├── popover.tsx │ ├── sheet.tsx │ └── textarea.tsx ├── empty-module.ts ├── eslint.config.mjs ├── lib └── utils.ts ├── next.config.ts ├── package-lock.json ├── package.json ├── postcss.config.mjs ├── public ├── file.svg ├── globe.svg ├── next.svg ├── vercel.svg └── window.svg ├── tailwind.config.ts └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.* 7 | .yarn/* 8 | !.yarn/patches 9 | !.yarn/plugins 10 | !.yarn/releases 11 | !.yarn/versions 12 | 13 | # testing 14 | /coverage 15 | 16 | # next.js 17 | /.next/ 18 | /out/ 19 | 20 | # production 21 | /build 22 | 23 | # misc 24 | .DS_Store 25 | *.pem 26 | 27 | # debug 28 | npm-debug.log* 29 | yarn-debug.log* 30 | yarn-error.log* 31 | .pnpm-debug.log* 32 | 33 | # env files (can opt-in for committing if needed) 34 | .env* 35 | 36 | # vercel 37 | .vercel 38 | 39 | # typescript 40 | *.tsbuildinfo 41 | next-env.d.ts 42 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # syntax=docker.io/docker/dockerfile:1 2 | 3 | FROM node:22-alpine AS base 4 | 5 | # Install dependencies only when needed 6 | FROM base AS deps 7 | # Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed. 8 | RUN apk add --no-cache libc6-compat 9 | WORKDIR /app 10 | 11 | # Install dependencies based on the preferred package manager 12 | COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* .npmrc* ./ 13 | RUN \ 14 | if [ -f yarn.lock ]; then yarn --frozen-lockfile; \ 15 | elif [ -f package-lock.json ]; then npm ci; \ 16 | elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm i --frozen-lockfile; \ 17 | else echo "Lockfile not found." && exit 1; \ 18 | fi 19 | 20 | 21 | # Rebuild the source code only when needed 22 | FROM base AS builder 23 | WORKDIR /app 24 | COPY --from=deps /app/node_modules ./node_modules 25 | COPY . . 26 | 27 | # Next.js collects completely anonymous telemetry data about general usage. 28 | # Learn more here: https://nextjs.org/telemetry 29 | # Uncomment the following line in case you want to disable telemetry during the build. 30 | # ENV NEXT_TELEMETRY_DISABLED=1 31 | 32 | RUN \ 33 | if [ -f yarn.lock ]; then yarn run build; \ 34 | elif [ -f package-lock.json ]; then npm run build; \ 35 | elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm run build; \ 36 | else echo "Lockfile not found." && exit 1; \ 37 | fi 38 | 39 | # Production image, copy all the files and run next 40 | FROM base AS runner 41 | WORKDIR /app 42 | 43 | ENV NODE_ENV=production 44 | # Uncomment the following line in case you want to disable telemetry during runtime. 45 | # ENV NEXT_TELEMETRY_DISABLED=1 46 | 47 | RUN addgroup --system --gid 1001 nodejs 48 | RUN adduser --system --uid 1001 nextjs 49 | 50 | COPY --from=builder /app/public ./public 51 | 52 | # Automatically leverage output traces to reduce image size 53 | # https://nextjs.org/docs/advanced-features/output-file-tracing 54 | COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ 55 | COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static 56 | 57 | USER nextjs 58 | 59 | EXPOSE 3000 60 | 61 | ENV PORT=3000 62 | 63 | # server.js is created by next build from the standalone output 64 | # https://nextjs.org/docs/pages/api-reference/config/next-config-js/output 65 | ENV HOSTNAME="0.0.0.0" 66 | CMD ["node", "server.js"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PDF to Structured Data with Next.js and Gemini 2.0 2 | 3 | This project demonstrates how to extract structured data from PDFs using Google's Gemini 2.0 AI model in a Next.js web application. It allows users to upload PDFs and dynamically generate JSON schemas based on user prompts, which are then used to extract structured information from the documents. 4 | 5 | **How It Works:** 6 | 7 | 1. **Upload PDF**: Users can upload their PDF documents through the web interface 8 | 2. **Define Schema**: Users provide a natural language prompt describing the data they want to extract 9 | 3. **Schema Generation**: Gemini 2.0 generates a JSON schema based on the user's prompt 10 | 4. **Data Extraction**: The Schema is used to extract structured data from the PDF using structured output from Gemini 2.0 11 | 5. **Results**: Extracted data is presented in a clean, organized format 12 | 13 | ## Features 14 | 15 | - 📄 PDF file upload and preview 16 | - 🤖 Dynamic JSON schema generation using Gemini 2.0 17 | - 🔍 Structured Outputs using Gemini 2.0 18 | - ⚡ Next.js frontend with shadcn/ui 19 | - 🎨 Uses Gemini 2.0 Javascript SDK 20 | 21 | ## Getting Started 22 | 23 | ### Local Development 24 | 25 | First, set up your environment variables: 26 | 27 | ```bash 28 | cp .env.example .env 29 | ``` 30 | 31 | Add your Google AI Studio API key to the `.env` file: 32 | 33 | ``` 34 | GEMINI_API_KEY=your_google_api_key 35 | ``` 36 | 37 | Then, install dependencies and run the development server: 38 | 39 | ```bash 40 | npm install 41 | npm run dev 42 | ``` 43 | 44 | Open [http://localhost:3000](http://localhost:3000) with your browser to see the application. 45 | 46 | ### Docker Deployment 47 | 48 | 1. Build the Docker image: 49 | 50 | ```bash 51 | docker build -t pdf-structured-data . 52 | ``` 53 | 54 | 2. Run the container with your Google API key: 55 | 56 | ```bash 57 | docker run -p 3000:3000 -e GEMINI_API_KEY=your_google_api_key pdf-structured-data 58 | ``` 59 | 60 | Or using an environment file: 61 | 62 | ```bash 63 | # Run container with env file 64 | docker run -p 3000:3000 --env-file .env pdf-structured-data 65 | ``` 66 | 67 | Open [http://localhost:3000](http://localhost:3000) with your browser to see the application. 68 | 69 | ## Technologies Used 70 | 71 | - [Next.js](https://nextjs.org/) - React framework for the web application 72 | - [Google Gemini 2.0](https://deepmind.google/technologies/gemini/) - AI model for schema generation and data extraction 73 | - [shadcn/ui](https://ui.shadcn.com/) - Re-usable components built using Radix UI and Tailwind CSS 74 | 75 | 76 | ## License 77 | 78 | This project is licensed under the Apache License 2.0 - see the [LICENSE](./LICENSE) file for details. 79 | -------------------------------------------------------------------------------- /app/api/extract/route.ts: -------------------------------------------------------------------------------- 1 | import { NextResponse } from "next/server"; 2 | import { GoogleGenerativeAI } from "@google/generative-ai"; 3 | 4 | const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!); 5 | const MODEL_ID = "gemini-2.0-flash"; 6 | 7 | export async function POST(request: Request) { 8 | try { 9 | const formData = await request.formData(); 10 | const file = formData.get("file") as File; 11 | const schema = JSON.parse(formData.get("schema") as string); 12 | 13 | // Convert PDF to base64 14 | const buffer = await file.arrayBuffer(); 15 | const base64 = Buffer.from(buffer).toString("base64"); 16 | 17 | const model = genAI.getGenerativeModel({ 18 | model: MODEL_ID, 19 | generationConfig: { 20 | responseMimeType: "application/json", 21 | responseSchema: schema, 22 | }, 23 | }); 24 | 25 | const prompt = "Extract the structured data from the following PDF file"; 26 | 27 | const result = await model.generateContent([ 28 | prompt, 29 | { 30 | inlineData: { 31 | mimeType: "application/pdf", 32 | data: base64, 33 | }, 34 | }, 35 | ]); 36 | 37 | const response = await result.response; 38 | const extractedData = JSON.parse(response.text()); 39 | 40 | return NextResponse.json(extractedData); 41 | } catch (error) { 42 | console.error("Error extracting data:", error); 43 | return NextResponse.json( 44 | { error: "Failed to extract data" }, 45 | { status: 500 } 46 | ); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /app/api/schema/route.ts: -------------------------------------------------------------------------------- 1 | import { NextResponse } from "next/server"; 2 | import { GoogleGenerativeAI } from "@google/generative-ai"; 3 | 4 | const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!); 5 | const MODEL_ID = "gemini-2.0-flash"; 6 | 7 | const META_PROMPT = ` 8 | You are a JSON Schema expert. Your task is to create JSON schema based on the user input. The schema will be used for extra data. 9 | 10 | You must also make sure: 11 | - All fields in an object are set as required 12 | - All objects must have properties defined 13 | - Order matters! If the values are dependent or would require additional information, make sure to include the additional information in the description. Same counts for "reasoning" or "thinking" should come before the conclusion. 14 | - $defs must be defined under the schema param 15 | - Return only the schema JSON not more, use \`\`\`json to start and \`\`\` to end the JSON schema 16 | 17 | Restrictions: 18 | - You cannot use examples, if you think examples are helpful include them in the description. 19 | - You cannot use default values, If you think default are helpful include them in the description. 20 | - Top level cannot have a "title" property only "description" 21 | - You cannot use $defs, directly in the schema, don't use any $defs and $ref in the schema. Directly define the schema in the properties. 22 | - Never include a $schema 23 | - The "type" needs to be a single value, no arrays 24 | 25 | Guidelines: 26 | - If the user prompt is short define a single object schema and fields based on your knowledge. 27 | - If the user prompt is in detail about the data only use the data in the schema. Don't add more fields than the user asked for. 28 | 29 | Examples: 30 | 31 | Input: Cookie Recipes 32 | Output: \`\`\`json 33 | { 34 | "description": "Schema for a cookie recipe, including ingredients and quantities. The 'ingredients' array lists each ingredient along with its corresponding quantity and unit of measurement. The 'instructions' array provides a step-by-step guide to preparing the cookies. The order of instructions is important.", 35 | "type": "object", 36 | "properties": { 37 | "name": { 38 | "type": "string", 39 | "description": "The name of the cookie recipe." 40 | }, 41 | "description": { 42 | "type": "string", 43 | "description": "A short description of the cookie, including taste and textures." 44 | }, 45 | "ingredients": { 46 | "type": "array", 47 | "description": "A list of ingredients required for the recipe.", 48 | "items": { 49 | "type": "object", 50 | "description": "An ingredient with its quantity and unit.", 51 | "properties": { 52 | "name": { 53 | "type": "string", 54 | "description": "The name of the ingredient (e.g., flour, sugar, butter)." 55 | }, 56 | "quantity": { 57 | "type": "number", 58 | "description": "The amount of the ingredient needed." 59 | }, 60 | "unit": { 61 | "type": "string", 62 | "description": "The unit of measurement for the ingredient (e.g., cups, grams, teaspoons). Use abbreviations like 'tsp' for teaspoon and 'tbsp' for tablespoon." 63 | } 64 | }, 65 | "required": [ 66 | "name", 67 | "quantity", 68 | "unit" 69 | ] 70 | } 71 | }, 72 | "instructions": { 73 | "type": "array", 74 | "description": "A sequence of steps to prepare the cookie recipe. The order of instructions matters.", 75 | "items": { 76 | "type": "string", 77 | "description": "A single instruction step." 78 | } 79 | } 80 | }, 81 | "required": [ 82 | "name", 83 | "description", 84 | "ingredients", 85 | "instructions" 86 | ] 87 | } 88 | \`\`\` 89 | 90 | Input: Book with title, author, and publication year. 91 | Output: \`\`\`json 92 | { 93 | "type": "object", 94 | "properties": { 95 | "title": { 96 | "type": "string", 97 | "description": "The title of the book." 98 | }, 99 | "author": { 100 | "type": "string", 101 | "description": "The author of the book." 102 | }, 103 | "publicationYear": { 104 | "type": "integer", 105 | "description": "The year the book was published." 106 | } 107 | }, 108 | "required": [ 109 | "title", 110 | "author", 111 | "publicationYear" 112 | ], 113 | } 114 | \`\`\` 115 | 116 | Input: {USER_PROMPT}`.trim(); 117 | 118 | export async function POST(request: Request) { 119 | try { 120 | // Get the prompt from the request body 121 | const { prompt } = await request.json(); 122 | // Get the model 123 | const model = genAI.getGenerativeModel({ model: MODEL_ID }); 124 | // Generate the content 125 | const result = await model.generateContent( 126 | META_PROMPT.replace("{USER_PROMPT}", prompt) 127 | ); 128 | // Get the response 129 | const response = await result.response; 130 | // Remove markdown code block markers if present 131 | const jsonString = response 132 | .text() 133 | .replace(/^```json\n?/, "") 134 | .replace(/\n?```$/, ""); 135 | // Return the schema 136 | return NextResponse.json({ schema: JSON.parse(jsonString) }); 137 | } catch (error) { 138 | console.error("Error generating schema:", error); 139 | return NextResponse.json( 140 | { error: "Failed to generate schema" }, 141 | { status: 500 } 142 | ); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /app/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philschmid/nextjs-gemini-2-0-pdf-structured-data/5e453c5b3d831f5e98503dd5a06521dfc52ca6b2/app/favicon.ico -------------------------------------------------------------------------------- /app/globals.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | 5 | body { 6 | font-family: Arial, Helvetica, sans-serif; 7 | } 8 | 9 | @layer utilities { 10 | .text-balance { 11 | text-wrap: balance; 12 | } 13 | } 14 | 15 | @layer base { 16 | :root { 17 | --background: 0 0% 100%; 18 | --foreground: 240, 3%, 12%; 19 | --card: 0 0% 100%; 20 | --card-foreground: 240, 3%, 12%; 21 | --popover: 0 0% 100%; 22 | --popover-foreground: 240, 3%, 12%; 23 | --primary: 214, 82%, 51%; 24 | --primary-foreground: 0 0% 98%; 25 | --secondary: 240 4.8% 95.9%; 26 | --secondary-foreground: 214, 82%, 51%; 27 | --muted: 240 4.8% 95.9%; 28 | --muted-foreground: 240 3.8% 46.1%; 29 | --accent: 240 4.8% 95.9%; 30 | --accent-foreground: 214, 82%, 51%; 31 | --destructive: 0 84.2% 60.2%; 32 | --destructive-foreground: 0 0% 98%; 33 | --border: 240 5.9% 90%; 34 | --input: 240 5.9% 90%; 35 | --ring: 214, 82%, 51%; 36 | --radius: 0.5rem; 37 | --chart-1: 12 76% 61%; 38 | --chart-2: 173 58% 39%; 39 | --chart-3: 197 37% 24%; 40 | --chart-4: 43 74% 66%; 41 | --chart-5: 27 87% 67%; 42 | } 43 | 44 | .dark { 45 | --background: 240 3% 12%; 46 | --foreground: 0 0% 98%; 47 | --card: 220 7% 8%; 48 | --card-foreground: 0 0% 98%; 49 | --popover: 220 7% 8%; 50 | --popover-foreground: 0 0% 98%; 51 | --primary: 217 91% 60%; 52 | --primary-foreground: 0 0% 98%; 53 | --secondary: 240 3% 12%; 54 | --secondary-foreground: 0 0% 98%; 55 | --muted: 240 3% 12%; 56 | --muted-foreground: 215 20.2% 65.1%; 57 | --accent: 240 3% 12%; 58 | --accent-foreground: 0 0% 98%; 59 | --destructive: 0 62.8% 30.6%; 60 | --destructive-foreground: 0 0% 98%; 61 | --border: 225 9% 15%; 62 | --input: 225 9% 15%; 63 | --ring: 224 76.3% 48%; 64 | --chart-1: 220 70% 50%; 65 | --chart-2: 160 60% 45%; 66 | --chart-3: 30 80% 55%; 67 | --chart-4: 280 65% 60%; 68 | --chart-5: 340 75% 55%; 69 | } 70 | } 71 | 72 | @layer base { 73 | * { 74 | @apply border-border; 75 | } 76 | body { 77 | @apply bg-background text-foreground; 78 | } 79 | } 80 | 81 | h1,h2,h3,h4,h5,h6 { 82 | @apply text-foreground dark:text-foreground; 83 | } 84 | 85 | -------------------------------------------------------------------------------- /app/layout.tsx: -------------------------------------------------------------------------------- 1 | import type { Metadata, Viewport } from "next"; 2 | import { Open_Sans } from "next/font/google"; 3 | import "./globals.css"; 4 | import { ThemeProviders } from "@/components/providers"; 5 | 6 | const openSans = Open_Sans({ 7 | weight: ["400", "500", "700"], 8 | style: ["normal", "italic"], 9 | subsets: ["latin"], 10 | variable: "--font-open-sans", 11 | }); 12 | 13 | export const metadata: Metadata = { 14 | title: "PDF Extractor", 15 | description: "Extract data from PDFs using Google DeepMind Gemini 2.0", 16 | }; 17 | 18 | export const viewport: Viewport = { 19 | themeColor: [ 20 | { media: "(prefers-color-scheme: light)", color: "white" }, 21 | { media: "(prefers-color-scheme: dark)", color: "black" }, 22 | ], 23 | }; 24 | 25 | export default function RootLayout({ 26 | children, 27 | }: Readonly<{ 28 | children: React.ReactNode; 29 | }>) { 30 | return ( 31 | 32 | 35 | {children} 36 | 37 | 38 | ); 39 | } 40 | -------------------------------------------------------------------------------- /app/page.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | import { useState } from "react"; 3 | import { FileUpload } from "@/components/FileUpload"; 4 | import { PromptInput } from "@/components/PromptInput"; 5 | import { ResultDisplay } from "@/components/ResultDisplay"; 6 | import { FileIcon, FileText } from "lucide-react"; 7 | import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; 8 | 9 | export default function Home() { 10 | const [schema, setSchema] = useState(null); 11 | const [file, setFile] = useState(null); 12 | const [result, setResult] = useState(null); 13 | const [loading, setLoading] = useState(false); 14 | 15 | const handleFileSelect = (selectedFile: File) => { 16 | setFile(selectedFile); 17 | }; 18 | 19 | const handlePromptSubmit = async (prompt: string) => { 20 | try { 21 | setLoading(true); 22 | // First, get the JSON schema 23 | const schemaResponse = await fetch("/api/schema", { 24 | method: "POST", 25 | headers: { 26 | "Content-Type": "application/json", 27 | }, 28 | body: JSON.stringify({ prompt }), 29 | }); 30 | 31 | const { schema } = await schemaResponse.json(); 32 | 33 | setSchema(schema); 34 | // Then, process the PDF with the schema 35 | const formData = new FormData(); 36 | formData.append("file", file!); 37 | formData.append("schema", JSON.stringify(schema)); 38 | 39 | const extractResponse = await fetch("/api/extract", { 40 | method: "POST", 41 | body: formData, 42 | }); 43 | 44 | const data = await extractResponse.json(); 45 | setResult(data); 46 | } catch (error) { 47 | console.error("Error processing request:", error); 48 | } finally { 49 | setLoading(false); 50 | } 51 | }; 52 | 53 | const handleReset = () => { 54 | setFile(null); 55 | setResult(null); 56 | setSchema(null); 57 | setLoading(false); 58 | }; 59 | 60 | return ( 61 |
62 | 63 | 64 | 65 | 66 | PDF to Structured Data 67 | 68 | 69 | powered by Google DeepMind Gemini 2.0 Flash 70 | 71 | 72 | 73 | {!result && !loading ? ( 74 | <> 75 | 76 | 77 | 78 | ) : loading ? ( 79 |
83 | 84 | 85 | Processing... 86 | 87 |
88 | ) : ( 89 | 94 | )} 95 |
96 |
97 |
98 | ); 99 | } 100 | -------------------------------------------------------------------------------- /components.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://ui.shadcn.com/schema.json", 3 | "style": "default", 4 | "rsc": true, 5 | "tsx": true, 6 | "tailwind": { 7 | "config": "tailwind.config.ts", 8 | "css": "app/globals.css", 9 | "baseColor": "slate", 10 | "cssVariables": true, 11 | "prefix": "" 12 | }, 13 | "aliases": { 14 | "components": "@/components", 15 | "utils": "@/lib/utils", 16 | "ui": "@/components/ui", 17 | "lib": "@/lib", 18 | "hooks": "@/hooks" 19 | }, 20 | "iconLibrary": "lucide" 21 | } -------------------------------------------------------------------------------- /components/FileUpload.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { useCallback, useState } from "react"; 4 | import { useDropzone } from "react-dropzone"; 5 | import { Button } from "./ui/button"; 6 | import { Upload as UploadIcon, File as FileIcon, X } from "lucide-react"; 7 | import PdfViewer from "./PdfViewer"; 8 | 9 | interface FileUploadProps { 10 | onFileSelect: (file: File) => void; 11 | } 12 | 13 | export function formatFileSize(bytes: number): string { 14 | if (bytes === 0) return "0 Bytes"; 15 | const k = 1024; 16 | const sizes = ["Bytes", "KB", "MB", "GB", "TB"]; 17 | const i = Math.floor(Math.log(bytes) / Math.log(k)); 18 | return ( 19 | Number.parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i] 20 | ); 21 | } 22 | 23 | export function FileUpload({ onFileSelect }: FileUploadProps) { 24 | const [selectedFile, setSelectedFile] = useState(null); 25 | const [file, setFile] = useState(null); 26 | 27 | const onDrop = useCallback( 28 | (acceptedFiles: File[]) => { 29 | const file = acceptedFiles[0]; 30 | setSelectedFile(file); 31 | onFileSelect(file); 32 | setFile(file); 33 | }, 34 | [onFileSelect] 35 | ); 36 | 37 | const { getRootProps, getInputProps, isDragActive } = useDropzone({ 38 | onDrop, 39 | accept: { 40 | "application/pdf": [".pdf"], 41 | }, 42 | maxSize: 100 * 1024 * 1024, // 100MB 43 | multiple: false, 44 | }); 45 | 46 | return ( 47 |
48 | {!selectedFile ? ( 49 |
58 | 59 |
60 | 61 |
62 |

63 | Drop your PDF here or click to browse 64 |

65 |

66 | Maximum file size: 100MB 67 |

68 |
69 |
70 |
71 | ) : ( 72 |
73 | 74 |
75 |

76 | {selectedFile?.name} 77 |

78 |

79 | {formatFileSize(selectedFile?.size ?? 0)} 80 |

81 |
82 | {file && } 83 | 84 | 93 |
94 | )} 95 |
96 | ); 97 | } 98 | -------------------------------------------------------------------------------- /components/PdfViewer.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { useCallback, useState } from "react"; 4 | import { pdfjs, Document, Page } from "react-pdf"; 5 | import "react-pdf/dist/esm/Page/AnnotationLayer.css"; 6 | import "react-pdf/dist/esm/Page/TextLayer.css"; 7 | import { useResizeObserver } from "@wojtekmaj/react-hooks"; 8 | 9 | import type { PDFDocumentProxy } from "pdfjs-dist"; 10 | import { 11 | Sheet, 12 | SheetContent, 13 | SheetHeader, 14 | SheetTitle, 15 | SheetTrigger, 16 | } from "./ui/sheet"; 17 | 18 | pdfjs.GlobalWorkerOptions.workerSrc = new URL( 19 | "pdfjs-dist/build/pdf.worker.min.mjs", 20 | import.meta.url 21 | ).toString(); 22 | 23 | const options = { 24 | cMapUrl: "/cmaps/", 25 | standardFontDataUrl: "/standard_fonts/", 26 | }; 27 | 28 | export default function PdfViewer({ file }: { file: File }) { 29 | const [numPages, setNumPages] = useState(); 30 | const [containerRef, setContainerRef] = useState(null); 31 | const [containerWidth, setContainerWidth] = useState(); 32 | 33 | // Add resize observer 34 | const onResize = useCallback((entries) => { 35 | const [entry] = entries; 36 | if (entry) { 37 | setContainerWidth(entry.contentRect.width); 38 | } 39 | }, []); 40 | 41 | useResizeObserver(containerRef, {}, onResize); 42 | 43 | async function onDocumentLoadSuccess(page: PDFDocumentProxy): Promise { 44 | setNumPages(page._pdfInfo.numPages); 45 | } 46 | 47 | return ( 48 | 49 | 50 | Preview 51 | 52 | 53 | 54 | {file.name} 55 | 56 |
60 | 65 | {Array.from(new Array(numPages), (_el, index) => ( 66 | 71 | ))} 72 | 73 |
74 |
75 |
76 | ); 77 | } 78 | -------------------------------------------------------------------------------- /components/PromptInput.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { useState } from "react"; 4 | import { Button } from "@/components/ui/button"; 5 | import { Wand2 } from "lucide-react"; 6 | import { Textarea } from "@/components/ui/textarea"; 7 | interface PromptInputProps { 8 | onSubmit: (prompt: string) => void; 9 | file: File | null; 10 | } 11 | 12 | export function PromptInput({ onSubmit, file }: PromptInputProps) { 13 | const [prompt, setPrompt] = useState(""); 14 | 15 | const handleSubmit = (e: React.FormEvent) => { 16 | e.preventDefault(); 17 | if (prompt.trim()) { 18 | onSubmit(prompt.trim()); 19 | } 20 | }; 21 | 22 | return ( 23 |
24 |
25 |

26 | Describe the structure and type of data you want to extract from the 27 | PDF. 28 |

29 |
30 | 31 |