├── assets
└── sample.pdf
├── resources
└── icon.ico
├── screenshots
├── index.png
├── search.png
└── precheck.png
├── .gitignore
├── main
├── helpers
│ ├── index.ts
│ └── create-window.ts
├── ocr.ts
└── background.ts
├── renderer
├── public
│ └── images
│ │ └── logo.png
├── next.config.js
├── tsconfig.json
├── next-env.d.ts
├── services
│ ├── types.ts
│ ├── const.ts
│ └── util.ts
├── pages
│ ├── _app.tsx
│ ├── home.tsx
│ ├── search.tsx
│ ├── precheck.tsx
│ └── setup.tsx
└── components
│ ├── DirectoryPicker.tsx
│ ├── Overlay.tsx
│ ├── SetupInstructions.tsx
│ ├── DocsScanner.tsx
│ ├── ResultsDisplay.tsx
│ └── PDFViewer.tsx
├── electron-builder.yml
├── tsconfig.json
├── package.json
├── TODO.md
├── README.md
└── LICENSE.md
/assets/sample.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eastrd/ArchivEye/HEAD/assets/sample.pdf
--------------------------------------------------------------------------------
/resources/icon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eastrd/ArchivEye/HEAD/resources/icon.ico
--------------------------------------------------------------------------------
/screenshots/index.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eastrd/ArchivEye/HEAD/screenshots/index.png
--------------------------------------------------------------------------------
/screenshots/search.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eastrd/ArchivEye/HEAD/screenshots/search.png
--------------------------------------------------------------------------------
/screenshots/precheck.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eastrd/ArchivEye/HEAD/screenshots/precheck.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | *.log
3 | .next
4 | app
5 | dist
6 | temp
7 | _index
8 | config.ini
9 | .vscode
--------------------------------------------------------------------------------
/main/helpers/index.ts:
--------------------------------------------------------------------------------
1 | import createWindow from './create-window';
2 |
3 | export {
4 | createWindow,
5 | };
6 |
--------------------------------------------------------------------------------
/renderer/public/images/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eastrd/ArchivEye/HEAD/renderer/public/images/logo.png
--------------------------------------------------------------------------------
/renderer/next.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | webpack: (config, { isServer }) => {
3 | if (!isServer) {
4 | config.target = 'electron-renderer';
5 | }
6 |
7 | return config;
8 | },
9 | };
10 |
--------------------------------------------------------------------------------
/renderer/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "include": [
4 | "next-env.d.ts",
5 | "**/*.ts",
6 | "**/*.tsx"
7 | ],
8 | "exclude": [
9 | "node_modules"
10 | ]
11 | }
12 |
--------------------------------------------------------------------------------
/renderer/next-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 | ///
3 |
4 | // NOTE: This file should not be edited
5 | // see https://nextjs.org/docs/basic-features/typescript for more information.
6 |
--------------------------------------------------------------------------------
/renderer/services/types.ts:
--------------------------------------------------------------------------------
1 | export type SearchResult = {
2 | id: string;
3 | docName: string;
4 | docPath: string;
5 | page: number;
6 | };
7 |
8 | // One row in master.sf file
9 | export type IndexRecord = {
10 | id: string;
11 | docPath: string;
12 | };
13 |
--------------------------------------------------------------------------------
/electron-builder.yml:
--------------------------------------------------------------------------------
1 | appId: com.archiveye.eastrd
2 | productName: ArchivEye
3 | copyright: Copyright © 2023 Eastrd
4 | directories:
5 | output: dist
6 | buildResources: resources
7 | files:
8 | - from: .
9 | filter:
10 | - package.json
11 | - app
12 | publish: null
13 |
--------------------------------------------------------------------------------
/renderer/pages/_app.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | import type { AppProps } from "next/app";
3 | import { ChakraProvider, extendTheme } from "@chakra-ui/react";
4 |
5 | const theme = extendTheme({
6 | config: {
7 | initialColorMode: "dark",
8 | useSystemColorMode: false,
9 | },
10 | });
11 |
12 | function App({ Component, pageProps }: AppProps) {
13 | return (
14 |
15 |
16 |
17 | );
18 | }
19 |
20 | export default App;
21 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "lib": [
5 | "dom",
6 | "dom.iterable",
7 | "esnext"
8 | ],
9 | "allowJs": true,
10 | "skipLibCheck": true,
11 | "strict": false,
12 | "forceConsistentCasingInFileNames": true,
13 | "noEmit": true,
14 | "incremental": true,
15 | "esModuleInterop": true,
16 | "module": "esnext",
17 | "moduleResolution": "node",
18 | "resolveJsonModule": true,
19 | "isolatedModules": true,
20 | "jsx": "preserve"
21 | },
22 | "exclude": [
23 | "node_modules",
24 | "renderer/next.config.js",
25 | "app",
26 | "dist"
27 | ]
28 | }
29 |
--------------------------------------------------------------------------------
/renderer/components/DirectoryPicker.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState } from "react";
2 | import electron from "electron";
3 | import { Button, Text } from "@chakra-ui/react";
4 |
5 | const ipcRenderer: Electron.IpcRenderer = electron.ipcRenderer;
6 |
7 | type Props = {
8 | buttonText: string;
9 | disabled: boolean;
10 | handleOnClick: () => void;
11 | };
12 |
13 | const DirectoryPicker = ({ buttonText, disabled, handleOnClick }: Props) => {
14 | const [selectedDirectory, setSelectedDirectory] = useState("");
15 |
16 | return (
17 |
18 | {selectedDirectory &&
Selected directory: {selectedDirectory}
}
19 |
26 | {selectedDirectory ? (
27 | {buttonText}
28 | ) : (
29 | {buttonText}
30 | )}
31 |
32 |
33 | );
34 | };
35 |
36 | export default DirectoryPicker;
37 |
--------------------------------------------------------------------------------
/renderer/services/const.ts:
--------------------------------------------------------------------------------
1 | export const phrases = [
2 | "Cracking the case of the cryptic PDFs...",
3 | "Hold tight, our digital detectives are on the case!",
4 | "Patience is the key, even Sherlock Holmes had to wait sometimes...",
5 | "Indexing PDFs faster than a caffeine-fueled lawyer!",
6 | "We're searching high and low, just like a journalist on a deadline!",
7 | "Brew another cup of coffee, we're almost there!",
8 | "Sifting through pages like a sleep-deprived investigator!",
9 | "Hang in there, we're chasing the paper trail for you!",
10 | "Our night owl agents are scanning and searching for you!",
11 | "No need to burn the midnight oil, we're doing the heavy lifting for you!",
12 | "It's a PDF party, and we're bringing the OCR!",
13 | "Rest your eyes, while we uncover the textual mysteries!",
14 | "Putting on our reading glasses and digging through the docs!",
15 | "Our digital bloodhounds are sniffing out the hidden text!",
16 | "Don't worry, we're night owls too! Just a bit longer...",
17 | "PDFs and OCR, a match made in document heaven!",
18 | "We're on a text treasure hunt, hold tight!",
19 | "Our virtual magnifying glass is scanning your PDFs!",
20 | "Let's solve this paper puzzle together!",
21 | "Late-night indexing, the unsung hero of document search!",
22 | ];
23 | export const INDEX_DB_FILENAME = "master.sf";
24 | export const SEP = "|||";
25 | export const SamplePDF =
26 | "D:/LibGen/NonFiction/1000/[Article] A Mathematical Theory of Communication_bb0283f61b7a5457d74caa9c791e11eb.pdf";
27 |
--------------------------------------------------------------------------------
/renderer/components/Overlay.tsx:
--------------------------------------------------------------------------------
1 | import { CheckIcon } from "@chakra-ui/icons";
2 | import {
3 | Flex,
4 | Box,
5 | Center,
6 | VStack,
7 | Icon,
8 | Button,
9 | Text,
10 | Link,
11 | } from "@chakra-ui/react";
12 | import React from "react";
13 |
14 | const isProd: boolean = process.env.NODE_ENV === "production";
15 |
16 | type Props = {
17 | link: string;
18 | };
19 |
20 | const Overlay = ({ link }: Props) => {
21 | return (
22 |
31 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 | Indexing Completed!
47 |
48 | Start Searching
49 |
50 |
51 |
52 |
53 |
54 | );
55 | };
56 |
57 | export default Overlay;
58 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "private": true,
3 | "name": "archiveye",
4 | "description": "An GUI offline OCR tool for searching scanned PDF documents on a per-page basis, prioritizing accessibility, privacy, and user experience with Nextron and NodeJS",
5 | "version": "0.3.2",
6 | "author": "Eastrd",
7 | "main": "app/background.js",
8 | "scripts": {
9 | "dev": "nextron",
10 | "build": "nextron build",
11 | "postinstall": "electron-builder install-app-deps"
12 | },
13 | "build": {
14 | "productName": "Archiveye",
15 | "win": {
16 | "target": "nsis"
17 | },
18 | "nsis": {
19 | "createDesktopShortcut": true,
20 | "createStartMenuShortcut": true
21 | },
22 | "extraResources": [
23 | {
24 | "from": "assets",
25 | "to": "assets"
26 | }
27 | ]
28 | },
29 | "dependencies": {
30 | "@chakra-ui/core": "^0.8.0",
31 | "@chakra-ui/icons": "^2.0.18",
32 | "@chakra-ui/react": "^2.5.5",
33 | "@emotion/react": "^11.10.6",
34 | "@emotion/styled": "^11.10.6",
35 | "@types/ini": "^1.3.31",
36 | "dotenv": "^16.0.3",
37 | "electron-serve": "^1.1.0",
38 | "electron-store": "^8.1.0",
39 | "framer-motion": "^10.12.0",
40 | "ini": "^4.1.0",
41 | "pdfjs-dist": "^3.5.141",
42 | "uuid": "^9.0.0"
43 | },
44 | "devDependencies": {
45 | "@types/node": "^18.11.18",
46 | "@types/react": "^18.0.26",
47 | "electron": "^21.3.3",
48 | "electron-builder": "^23.6.0",
49 | "next": "^12.3.4",
50 | "nextron": "^8.5.0",
51 | "react": "^18.2.0",
52 | "react-dom": "^18.2.0",
53 | "typescript": "^4.9.4"
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/renderer/services/util.ts:
--------------------------------------------------------------------------------
1 | import fsp from "fs/promises";
2 | import fs from "fs";
3 | import path from "path";
4 |
5 | export const getDir = (p) => {
6 | // We want a proper folder to store configs, this function is intended for packaged electron app where it would always return app.asar as its path
7 | if (path.basename(p) === "app.asar") {
8 | return path.join(p, "..");
9 | }
10 | return p;
11 | };
12 |
13 | export const createFolderIfNotExists = async (folderPath) => {
14 | try {
15 | await fsp.access(folderPath);
16 | console.log("Folder already exists:", folderPath);
17 | } catch (err) {
18 | if (err.code === "ENOENT") {
19 | try {
20 | await fsp.mkdir(folderPath, { recursive: true });
21 | console.log("Folder created:", folderPath);
22 | } catch (mkdirErr) {
23 | console.error("Error creating folder:", mkdirErr);
24 | }
25 | } else {
26 | console.error("Error checking folder existence:", err);
27 | }
28 | }
29 | };
30 |
31 | export const searchTextInFile = async (filePath, searchText) => {
32 | try {
33 | const data = await fsp.readFile(filePath, "utf-8");
34 | const regex = new RegExp(searchText, "gi"); // ignore case
35 | const matches = data.match(regex);
36 |
37 | if (matches) {
38 | return {
39 | success: true,
40 | matches: matches.length,
41 | error: false,
42 | };
43 | } else {
44 | return {
45 | success: false,
46 | matches: 0,
47 | error: "",
48 | };
49 | }
50 | } catch (error) {
51 | console.error("Error reading file:", error);
52 | return {
53 | success: false,
54 | matches: 0,
55 | error: true,
56 | };
57 | }
58 | };
59 |
--------------------------------------------------------------------------------
/renderer/pages/home.tsx:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from "react";
2 | import Head from "next/head";
3 | import { Button, Text, Heading, VStack } from "@chakra-ui/react";
4 | import Link from "next/link";
5 | import { ipcRenderer } from "electron";
6 |
7 | const isProd: boolean = process.env.NODE_ENV === "production";
8 |
9 | function Home() {
10 | const [needInit, setNeedInit] = useState(true);
11 |
12 | useEffect(() => {
13 | // Check if config.ini exists, if exists then proceed to setup page, otherwise go to precheck page
14 | ipcRenderer
15 | .invoke("exists-config")
16 | .then((ifExists) => setNeedInit(!ifExists));
17 |
18 | ipcRenderer.invoke("get-env").then((p) => console.log("AppDir: ", p));
19 | }, []);
20 |
21 | return (
22 |
23 |
24 | ArchivEye
25 |
26 |
32 |
33 | {needInit && "Welcome To "} ArchivEye
34 |
35 |
36 | Easily search through your scanned PDF documents with OCR capabilities
37 |
38 |
39 | {needInit ? (
40 |
41 | Get Started
42 |
43 | ) : (
44 |
45 | Welcome Back
46 |
47 | )}
48 |
49 |
50 | );
51 | }
52 |
53 | export default Home;
54 |
--------------------------------------------------------------------------------
/main/helpers/create-window.ts:
--------------------------------------------------------------------------------
1 | import {
2 | screen,
3 | BrowserWindow,
4 | BrowserWindowConstructorOptions,
5 | } from 'electron';
6 | import Store from 'electron-store';
7 |
8 | export default (windowName: string, options: BrowserWindowConstructorOptions): BrowserWindow => {
9 | const key = 'window-state';
10 | const name = `window-state-${windowName}`;
11 | const store = new Store({ name });
12 | const defaultSize = {
13 | width: options.width,
14 | height: options.height,
15 | };
16 | let state = {};
17 | let win;
18 |
19 | const restore = () => store.get(key, defaultSize);
20 |
21 | const getCurrentPosition = () => {
22 | const position = win.getPosition();
23 | const size = win.getSize();
24 | return {
25 | x: position[0],
26 | y: position[1],
27 | width: size[0],
28 | height: size[1],
29 | };
30 | };
31 |
32 | const windowWithinBounds = (windowState, bounds) => {
33 | return (
34 | windowState.x >= bounds.x &&
35 | windowState.y >= bounds.y &&
36 | windowState.x + windowState.width <= bounds.x + bounds.width &&
37 | windowState.y + windowState.height <= bounds.y + bounds.height
38 | );
39 | };
40 |
41 | const resetToDefaults = () => {
42 | const bounds = screen.getPrimaryDisplay().bounds;
43 | return Object.assign({}, defaultSize, {
44 | x: (bounds.width - defaultSize.width) / 2,
45 | y: (bounds.height - defaultSize.height) / 2,
46 | });
47 | };
48 |
49 | const ensureVisibleOnSomeDisplay = windowState => {
50 | const visible = screen.getAllDisplays().some(display => {
51 | return windowWithinBounds(windowState, display.bounds);
52 | });
53 | if (!visible) {
54 | // Window is partially or fully not visible now.
55 | // Reset it to safe defaults.
56 | return resetToDefaults();
57 | }
58 | return windowState;
59 | };
60 |
61 | const saveState = () => {
62 | if (!win.isMinimized() && !win.isMaximized()) {
63 | Object.assign(state, getCurrentPosition());
64 | }
65 | store.set(key, state);
66 | };
67 |
68 | state = ensureVisibleOnSomeDisplay(restore());
69 |
70 | const browserOptions: BrowserWindowConstructorOptions = {
71 | ...state,
72 | ...options,
73 | webPreferences: {
74 | nodeIntegration: true,
75 | contextIsolation: false,
76 | ...options.webPreferences,
77 | },
78 | };
79 | win = new BrowserWindow(browserOptions);
80 |
81 | win.on('close', saveState);
82 |
83 | return win;
84 | };
85 |
--------------------------------------------------------------------------------
/renderer/components/SetupInstructions.tsx:
--------------------------------------------------------------------------------
1 | import { Box, Code, Heading, Link, Text } from "@chakra-ui/react";
2 | import { ipcRenderer } from "electron";
3 |
4 | const SetupInstructions = () => (
5 |
6 |
7 | Required Third Party Tools
8 |
9 |
10 | 1. Install Tesseract
11 |
12 |
13 | Tesseract is an integral part of ArchivEye, providing powerful OCR
14 | capabilities that convert extracted individual pages into searchable text.
15 |
16 |
17 | Download and install the latest version 5.3.1 from
18 | {
23 | ipcRenderer.send(
24 | "open-link-external-browser",
25 | "https://digi.bib.uni-mannheim.de/tesseract/tesseract-ocr-w64-setup-5.3.1.20230401.exe"
26 | );
27 | }}
28 | >
29 | uni-mannheim
30 |
31 |
32 |
33 | 2. Install GhostScript
34 |
35 |
36 | GhostScript is used to extract individual pages from the PDF file as
37 | images for Tesseract to OCR.
38 |
39 |
40 | Go to
41 | {
46 | ipcRenderer.send(
47 | "open-link-external-browser",
48 | "https://github.com/ArtifexSoftware/ghostpdl-downloads/releases"
49 | );
50 | }}
51 | >
52 | this Github release page
53 |
54 | and download gs10011w64.exe
55 |
56 |
57 | 2. Select Paths Below
58 |
59 |
60 | For Tesseract, select the folder Tesseract-OCR
61 |
62 |
63 | For GhostScript, be sure to select the folder that is inside{" "}
64 | gs but not gs itself, in the time of releasing
65 | this version of ArchivEye, mine would be gs10.01.1
66 |
67 |
68 | Don't worry if you accidentally select the wrong paths, the{" "}
69 | Validate & Proceed button below will validate the paths to
70 | make sure the paths are correct before we start indexing PDFs
71 |
72 |
73 | );
74 |
75 | export default SetupInstructions;
76 |
--------------------------------------------------------------------------------
/TODO.md:
--------------------------------------------------------------------------------
1 | # TODO
2 |
3 | ## Backend
4 |
5 | - [x] Add indexing system
6 | - [x] Add progress feedback
7 | - [x] Set index path to be at app path by default
8 | - [x] Add search system
9 | - [x] Fix app path bug
10 |
11 | ## Frontend
12 |
13 | - [x] DARK THEME MYSELF PLZZZZ! IT'S HURTING MY OWN EYES
14 | - [x] Fix inconsistent dark mode
15 | - [x] Setup Page: Index Folder & PDF Document Folder setter
16 | - [x] Receive backend's OCR progress and display it on a horizontal progress bar
17 | - [x] Cross out (1) button after selection, cross out (2) button after indexing starts
18 | - [x] Make both of buttons disabled after indexing starts
19 | - [x] Add relevant random wait phrases
20 | - [x] When OCR is completed, show an overlay with a button that proceeds to search page
21 | - [x] Check if index DB already exists, if so provide an option to go straight to search
22 | - [x] Add option to index more documents
23 | - [x] Filter only PDF files
24 | - [x] For index found users, disable the "Start Search" button when they are indexing
25 | - [x] Prompt a previous-index-db deletion confirmation if user wants to index on top of already indexed databases
26 | - [x] Refactor out index path setting
27 | - [x] Search Page
28 | - [x] Update search result continuously
29 | - [x] Display on a results table (Fix partial state issue)
30 | - [x] Tooltip on hover of the pdf document name
31 | - [x] Implement view to the side
32 | - [x] Fix bug where substring highlight is case-sensitive
33 | - [x] Implement PDF Viewer
34 | - [ ] Add color invert (My EYES!!)
35 | - [x] Add Zoom in / out (My EYES!)
36 | - [x] Pagination of search result display
37 | - [x] Show text with highlights of where the search query appears
38 | - Pre-Check Page
39 | - [x] Check if config.ini is present, if not create one and ask user to set up
40 | - [x] Fix race condition between state update and config save
41 | - [x] If config.ini is present, validate that the binaries/folders in the paths exist
42 | - [x] Populate paths settings from config if exists
43 | - [x] Fix Blank page routing bug
44 | - [x] Fix command path has space and wasn't escaped
45 |
46 | ## Meta
47 |
48 | - [x] Add setup instructions & Test if it works
49 | - [x] Test Electron packaging
50 | - [x] Fix the shitty canvas bug
51 | - [x] Figure out how to get environment variables to work for users
52 | - [x] Move third-party software installation instructions inside the precheck page for more clarity
53 | - [x] Add descriptions of what GhostScript and Tesseract does
54 | - [x] Indexing new data will delete old indexed data
55 | - [ ] Need better descriptions about ArchivEye on home page
56 | - [ ] Speed up indexing efficiency
57 | - [x] Add tests to ensure both binaries are installed and can be executed, use sample image and pdf to validate these
58 | - [x] Add settings button that goes to precheck page to validate paths and binaries
59 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # ArchivEye
3 |
4 | Article and Demo Video [available here](https://ipyt.info/archiveye.html) thanks to [ATroubledMaker](https://ipyt.info/)
5 |
6 | ## Description
7 |
8 | ArchivEye is an offline PDF OCR tool developed to safeguard the privacy and confidentiality of sensitive documents.
9 |
10 | This user-friendly GUI application is designed for professionals like lawyers, OSINT researchers, journalists, and others who often work with PDF documents.
11 |
12 | ArchivEye's OCR technology enables users to search through scanned and non-searchable PDF files without uploading them to the cloud, offering added privacy and security.
13 |
14 | The software prioritizes ease of use, allowing even those without technical expertise to navigate and use it smoothly. By offering a unified interface for searching and indexing multiple PDF documents within a folder, ArchivEye streamlines tasks such as opening numerous PDFs, reading, manual note-taking, and cross-referencing information, saving users valuable time.
15 |
16 | ---
17 |
18 | ## Installation
19 |
20 | ### Prerequisites
21 |
22 | ArchivEye requires `Tesseract` and `GhostScript` to be installed on your system.
23 |
24 | Follow the steps below to install these third-party tools
25 |
26 | #### Install Tesseract
27 |
28 | `Tesseract` is an integral part of ArchivEye, providing powerful OCR capabilities that convert extracted individual pages into searchable text.
29 |
30 | Download and install the latest version 5.3.1 from [uni-mannheim](https://digi.bib.uni-mannheim.de/tesseract/tesseract-ocr-w64-setup-5.3.1.20230401.exe)
31 |
32 | #### Install GhostScript
33 |
34 | GhostScript is used to extract individual pages from the PDF file as images for Tesseract to OCR.
35 |
36 | Go to [this page](https://github.com/ArtifexSoftware/ghostpdl-downloads/releases) and download and install `gs10011w64.exe`
37 |
38 | ## Download ArchivEye
39 |
40 | Simply go to the [`Release`](https://github.com/eastrd/ArchivEye/releases/tag/v0.2.1) section of this Github page and download the `.exe` file, double click and it will install automatically
41 |
42 | ---
43 |
44 | ## Usage
45 |
46 | ### First Time Setup
47 |
48 | During the first-time setup, you will need to configure the tool by specifying the paths to the installed Tesseract and GhostScript tools. Use the Select buttons for `Tesseract` and `GhostScript`:
49 |
50 | - For `Tesseract`, select the folder `Tesseract-OCR`
51 |
52 | - For `GhostScript`, be sure to select the folder that is inside `gs` but not `gs` itself, in the time of releasing this version of ArchivEye, mine would be `gs10.01.1`
53 |
54 | Don't worry if you accidentally select the wrong paths, the `Validate & Proceed` button will validate the paths to make sure the paths are correct before we start indexing PDFs. It will also automatically run both the `Ghostscript` and `Tesseract` binaries on a dummy PDF to make sure these third party tools are working as expected
55 |
56 | 
57 |
58 | ### Indexing
59 |
60 | 
61 |
62 |
63 | ### Search
64 |
65 | 
66 |
67 |
68 | ## Future Roadmap
69 |
70 | - [ ] Make OCR index process faster
71 | - [ ] Support more languages
--------------------------------------------------------------------------------
/renderer/components/DocsScanner.tsx:
--------------------------------------------------------------------------------
1 | import { SetStateAction, useState } from "react";
2 | import {
3 | Box,
4 | Button,
5 | FormControl,
6 | FormLabel,
7 | Input,
8 | Text,
9 | } from "@chakra-ui/react";
10 | import React from "react";
11 |
12 | type Props = {
13 | onSubmitFiles: (files: Array) => void;
14 | label: string | null;
15 | disabled: boolean;
16 | hintText: string;
17 | files: Array;
18 | setFiles: React.Dispatch>>;
19 | };
20 |
21 | const DocsPicker = ({
22 | onSubmitFiles,
23 | hintText,
24 | label,
25 | files,
26 | disabled,
27 | setFiles,
28 | }: Props) => {
29 | const [dragging, setDragging] = useState(false);
30 |
31 | const handlePathChange = (event: React.ChangeEvent) => {
32 | if (event.target.files) {
33 | setFiles(Array.from(event.target.files).map((f) => f.path));
34 | }
35 | };
36 |
37 | const handleDragOver = (event: React.DragEvent) => {
38 | event.preventDefault();
39 | setDragging(true);
40 | };
41 |
42 | const handleDragLeave = () => {
43 | setDragging(false);
44 | };
45 |
46 | const handleDrop = (event: React.DragEvent) => {
47 | event.preventDefault();
48 | if (event.dataTransfer.files) {
49 | setFiles(Array.from(event.dataTransfer.files).map((f) => f.path));
50 | }
51 | setDragging(false);
52 | };
53 |
54 | const handleSubmit = (event: React.FormEvent) => {
55 | event.preventDefault();
56 | onSubmitFiles(files);
57 | };
58 |
59 | return (
60 |
69 |
79 | {label && {label} }
80 |
81 |
89 | document.getElementById("file-input")?.click()}
94 | border="1px dashed"
95 | borderColor={dragging ? "gray.400" : "gray.200"}
96 | borderRadius="lg"
97 | transition="border-color 0.2s"
98 | _hover={{ borderColor: "gray.400" }}
99 | bg="gray.50"
100 | >
101 |
102 | {files.length ? `Found ${files.length} PDF Files` : hintText}
103 |
104 |
105 |
106 |
107 | );
108 | };
109 |
110 | export default DocsPicker;
111 |
--------------------------------------------------------------------------------
/renderer/components/ResultsDisplay.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState } from "react";
2 | import {
3 | Table,
4 | Thead,
5 | Tbody,
6 | Tr,
7 | Th,
8 | Td,
9 | TableContainer,
10 | Tooltip,
11 | Button,
12 | Flex,
13 | Box,
14 | } from "@chakra-ui/react";
15 | import { SearchResult } from "../services/types";
16 |
17 | type Props = {
18 | results: Array;
19 | handleOnView: (result: SearchResult) => void;
20 | itemsPerPage?: number;
21 | };
22 |
23 | const ResultsDisplay = ({ results, handleOnView, itemsPerPage = 5 }: Props) => {
24 | const [currentPage, setCurrentPage] = useState(1);
25 |
26 | const totalPages = Math.max(Math.ceil(results.length / itemsPerPage), 1);
27 |
28 | const paginatedResults = results
29 | .sort((a, b) => {
30 | // Sort by doc name then page number
31 | const nameComparison = a.docName.localeCompare(b.docName);
32 | if (nameComparison === 0) {
33 | return a.page - b.page;
34 | }
35 | return nameComparison;
36 | })
37 | .slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage);
38 |
39 | const nextPage = () => {
40 | setCurrentPage((prevPage) => Math.min(prevPage + 1, totalPages));
41 | };
42 |
43 | const prevPage = () => {
44 | setCurrentPage((prevPage) => Math.max(prevPage - 1, 1));
45 | };
46 |
47 | return (
48 | <>
49 |
50 |
51 |
52 |
53 | PDF Document
54 | Page
55 | Action
56 |
57 |
58 |
59 | {paginatedResults.map((result: SearchResult) => {
60 | return (
61 |
62 |
63 |
64 |
65 | {result.docName}
66 |
67 |
68 |
69 | {result.page}
70 |
71 | {
74 | handleOnView(result);
75 | }}
76 | >
77 | View
78 |
79 |
80 |
81 | );
82 | })}
83 |
84 |
85 |
86 |
87 |
94 | Previous
95 |
96 |
97 | Page {currentPage} of {totalPages}
98 |
99 |
106 | Next
107 |
108 |
109 | >
110 | );
111 | };
112 |
113 | export default ResultsDisplay;
114 |
--------------------------------------------------------------------------------
/renderer/components/PDFViewer.tsx:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useRef, useState } from "react";
2 | import { ipcRenderer } from "electron";
3 | import { Box, Button } from "@chakra-ui/react";
4 |
5 | type Props = {
6 | pdfPath: string;
7 | page: number;
8 | };
9 |
10 | const PDFViewer = ({ pdfPath, page }: Props) => {
11 | const pdfCanvasRef = useRef(null);
12 | const [zoomLevel, setZoomLevel] = useState(0.95);
13 | const [panOffset, setPanOffset] = useState({ x: 0, y: 0 });
14 |
15 | const handleMouseDown = (event) => {
16 | const startX = event.clientX;
17 | const startY = event.clientY;
18 |
19 | const handleMouseMove = (event) => {
20 | const dragSensitivity = 0.02; // Adjust the sensitivity (0.5 means half the mouse movement)
21 | const dx = (event.clientX - startX) * dragSensitivity;
22 | const dy = (event.clientY - startY) * dragSensitivity;
23 |
24 | setPanOffset((prevOffset) => {
25 | const container = pdfCanvasRef.current.parentElement;
26 | const containerWidth = container.clientWidth;
27 | const containerHeight = container.clientHeight;
28 | const canvasWidth = pdfCanvasRef.current.clientWidth * zoomLevel;
29 | const canvasHeight = pdfCanvasRef.current.clientHeight * zoomLevel;
30 |
31 | const minX = Math.min(0, containerWidth - canvasWidth);
32 | const minY = Math.min(0, containerHeight - canvasHeight);
33 | const maxX = Math.max(0, containerWidth);
34 | const maxY = Math.max(0, containerHeight);
35 |
36 | const newX = Math.min(maxX, Math.max(minX, prevOffset.x + dx));
37 | const newY = Math.min(maxY, Math.max(minY, prevOffset.y + dy));
38 |
39 | return { x: newX, y: newY };
40 | });
41 | };
42 |
43 | const handleMouseUp = () => {
44 | window.removeEventListener("mousemove", handleMouseMove);
45 | window.removeEventListener("mouseup", handleMouseUp);
46 | };
47 |
48 | window.addEventListener("mousemove", handleMouseMove);
49 | window.addEventListener("mouseup", handleMouseUp);
50 | };
51 |
52 | const handleZoomIn = () => {
53 | setZoomLevel((prevZoomLevel) => prevZoomLevel + 0.1);
54 | };
55 |
56 | const handleZoomOut = () => {
57 | setZoomLevel((prevZoomLevel) => prevZoomLevel - 0.1);
58 | };
59 |
60 | useEffect(() => {
61 | (async function () {
62 | // We import this here so that it's only loaded during client-side rendering.
63 | const pdfJS = await import("pdfjs-dist/build/pdf");
64 | pdfJS.GlobalWorkerOptions.workerSrc =
65 | window.location.origin + "/pdf.worker.min.js";
66 |
67 | // Request the ArrayBuffer of the PDF file from the main process
68 | const arrayBuffer = await ipcRenderer.invoke("read-pdf-file", pdfPath);
69 |
70 | if (arrayBuffer) {
71 | const pdf = await pdfJS.getDocument({ data: arrayBuffer }).promise;
72 | const pageObj = await pdf.getPage(page);
73 | const viewport = pageObj.getViewport({ scale: zoomLevel });
74 |
75 | // Prepare canvas using PDF page dimensions.
76 | const canvas = pdfCanvasRef.current;
77 | const canvasContext = canvas.getContext("2d");
78 | canvas.height = viewport.height;
79 | canvas.width = viewport.width;
80 |
81 | // Render PDF page into canvas context.
82 | const renderContext = { canvasContext, viewport };
83 | await pageObj.render(renderContext);
84 | } else {
85 | console.error("Error loading PDF file");
86 | }
87 | })();
88 | }, [pdfPath, page, zoomLevel]);
89 |
90 | return (
91 |
92 |
93 | 1.5} onClick={handleZoomIn} mr={2}>
94 | Zoom In
95 |
96 |
97 | Zoom Out
98 |
99 |
100 |
112 |
121 |
122 |
123 | );
124 | };
125 |
126 | export default PDFViewer;
127 |
--------------------------------------------------------------------------------
/renderer/pages/search.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Box,
3 | Button,
4 | Divider,
5 | Flex,
6 | FormControl,
7 | Heading,
8 | Highlight,
9 | Input,
10 | Text,
11 | Tooltip,
12 | VStack,
13 | } from "@chakra-ui/react";
14 | import electron from "electron";
15 | import { useCallback, useEffect, useState } from "react";
16 | import { SearchResult } from "../services/types";
17 | import ResultsDisplay from "../components/ResultsDisplay";
18 | import PDFViewer from "../components/PDFViewer";
19 | import Link from "next/link";
20 |
21 | const ipcRenderer: Electron.IpcRenderer = electron.ipcRenderer;
22 | const isProd: boolean = process.env.NODE_ENV === "production";
23 |
24 | const Search = () => {
25 | const [selectedResult, setSelectedResult] = useState();
26 | const [searchQuery, setSearchQuery] = useState("");
27 | const [searchResults, setSearchResults] = useState>([]);
28 | const [resultContext, setResultContext] = useState("");
29 |
30 | // Prevent stale search results being used
31 | const handleSearchResult = useCallback((event, result: SearchResult) => {
32 | setSearchResults((prevSearchResults) => [result, ...prevSearchResults]);
33 | }, []);
34 |
35 | useEffect(() => {
36 | ipcRenderer.on("search-result", handleSearchResult);
37 | return () => {
38 | ipcRenderer.removeListener("search-result", handleSearchResult);
39 | };
40 | }, [handleSearchResult]);
41 |
42 | const handleSearchInputChange = (e) => {
43 | setSearchQuery(e.target.value);
44 | };
45 |
46 | const handleSearchSubmit = (e) => {
47 | e.preventDefault();
48 | setSearchResults([]);
49 | console.log("[+] Search", searchQuery);
50 | // Reset PDF viewer and context UI
51 | setResultContext("");
52 | setSelectedResult(null);
53 |
54 | ipcRenderer.send("search-request", searchQuery);
55 | };
56 |
57 | return (
58 |
59 |
65 |
66 |
67 | Back
68 |
69 |
70 |
71 |
72 | ArchivEye
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
88 |
89 | Search
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 | Search Results
99 |
100 | {
102 | setSelectedResult(result);
103 |
104 | ipcRenderer
105 | .invoke("in-page-text-search", result, searchQuery, 40)
106 | .then((res: { chunk: string; index: number }) => {
107 | setResultContext(res.chunk);
108 | });
109 | }}
110 | results={searchResults}
111 | />
112 | {resultContext && (
113 | <>
114 |
115 | Context
116 |
117 |
118 | {`${resultContext}`}
122 |
123 | >
124 | )}
125 |
126 |
133 |
134 |
135 | {selectedResult ? `${selectedResult.docName}` : "PDF Viewer"}
136 |
137 | {selectedResult && (
138 |
142 | )}
143 |
144 |
145 |
146 | );
147 | };
148 |
149 | export default Search;
150 |
--------------------------------------------------------------------------------
/main/ocr.ts:
--------------------------------------------------------------------------------
1 | import { exec } from "child_process";
2 | import { readdir } from "fs/promises";
3 | import path from "path";
4 | import { promisify } from "util";
5 | import fs from "fs";
6 | import fsp from "fs/promises";
7 | import { SEP } from "../renderer/services/const";
8 | import { IndexRecord } from "../renderer/services/types";
9 | import * as ini from "ini";
10 | import { app } from "electron";
11 | import { getDir } from "../renderer/services/util";
12 |
13 | export const execAsync = promisify(exec);
14 | export const appDir = getDir(app.getAppPath());
15 |
16 | console.log("AppDir: ", appDir);
17 |
18 | export const parseIndexDB = async (
19 | dbPath: string
20 | ): Promise> => {
21 | try {
22 | const data = await fsp.readFile(dbPath, "utf-8");
23 | const lines = data.split("\n");
24 |
25 | const parsed: Array = lines
26 | .map((line) => {
27 | const [id, path] = line.split(SEP);
28 | return { id, docPath: path };
29 | })
30 | .filter((item: IndexRecord) => item.id && item.docPath);
31 | return parsed;
32 | } catch (error) {
33 | console.error("Error reading file:", error);
34 | throw error;
35 | }
36 | };
37 |
38 | export const execute = async (cmd: string) => {
39 | try {
40 | console.log("Executing command ", cmd);
41 | const { stdout, stderr } = await execAsync(cmd);
42 | if (stderr) {
43 | throw new Error(`Error: ${stderr}`);
44 | }
45 | return stdout;
46 | } catch (error) {
47 | throw error;
48 | }
49 | };
50 |
51 | export const pdfToImgs = async (
52 | inPDF: string,
53 | outDir: string
54 | ): Promise => {
55 | // Convert PDF to images, return list of image names
56 | try {
57 | const result = await gsCMD(inPDF, outDir);
58 | // Scan the output dir and return all filenames
59 | return readdir(outDir);
60 | } catch (error) {
61 | console.error("error converting PDF to images: ", error);
62 | return [];
63 | }
64 | };
65 |
66 | export const gsCMD = async (inPDF: string, outDir: string): Promise => {
67 | const cfg = ini.parse(
68 | fs.readFileSync(path.join(appDir, "config.ini"), "utf-8")
69 | );
70 | return execute(
71 | `"${cfg.OCR.GHOSTSCRIPT}/gswin64c.exe" -sDEVICE=pngalpha -o "${outDir}/%04d.png" -r300 "${inPDF}"`
72 | );
73 | };
74 |
75 | export const tessCMD = async (
76 | inImg: string,
77 | outDir: string
78 | ): Promise => {
79 | // Extract image name as output text name
80 | const baseName = path.basename(inImg);
81 |
82 | const cfg = ini.parse(
83 | fs.readFileSync(path.join(appDir, "config.ini"), "utf-8")
84 | );
85 |
86 | return execute(
87 | `"${cfg.OCR.TESSERACT}/tesseract.exe" "${inImg}" "${path.join(
88 | outDir,
89 | baseName.split(".")[0]
90 | )}"`
91 | );
92 | };
93 |
94 | export const writeOrAppendToFile = (
95 | filePath: string,
96 | content: string
97 | ): void => {
98 | if (fs.existsSync(filePath)) {
99 | fs.appendFileSync(filePath, content);
100 | } else {
101 | fs.writeFileSync(filePath, content);
102 | }
103 | };
104 |
105 | export const createFolder = (folderPath: string): void => {
106 | if (!fs.existsSync(folderPath)) {
107 | fs.mkdirSync(folderPath);
108 | }
109 | };
110 |
111 | export const deletePathSync = (pathToDelete: string): void => {
112 | if (fs.existsSync(pathToDelete)) {
113 | if (fs.lstatSync(pathToDelete).isFile()) {
114 | fs.unlinkSync(pathToDelete);
115 | } else {
116 | fs.readdirSync(pathToDelete).forEach((file) => {
117 | const filePath = path.join(pathToDelete, file);
118 | if (fs.lstatSync(filePath).isDirectory()) {
119 | deletePathSync(filePath);
120 | } else {
121 | fs.unlinkSync(filePath);
122 | }
123 | });
124 | fs.rmdirSync(pathToDelete);
125 | }
126 | }
127 | };
128 |
129 | // Deprecated and not used
130 | export const findStrPercByLines = (filePath: string, searchString: string) => {
131 | const fileContent = fs.readFileSync(filePath, "utf-8").toLowerCase();
132 | const searchStringIndex = fileContent.indexOf(searchString.toLowerCase());
133 | if (searchStringIndex === -1) {
134 | return -1;
135 | }
136 | const totalNewlines = (fileContent.match(/\n/g) || []).length;
137 | const newlinesBeforeSearchString = (
138 | fileContent.slice(0, searchStringIndex).match(/\n/g) || []
139 | ).length;
140 |
141 | if (totalNewlines === 0) {
142 | return 0;
143 | }
144 | const percentagePosition = (newlinesBeforeSearchString / totalNewlines) * 100;
145 | return percentagePosition;
146 | };
147 |
148 | export const getSubstringWithContext = (
149 | filePath: string,
150 | searchString: string,
151 | wordRange: number
152 | ) => {
153 | const fileContent = fs.readFileSync(filePath, "utf-8");
154 | const searchStringIndex = fileContent
155 | .toLowerCase()
156 | .indexOf(searchString.toLowerCase());
157 |
158 | if (searchStringIndex === -1) {
159 | return { chunk: "Substring not found.", index: -1 };
160 | }
161 |
162 | const words = fileContent.split(/\s+/);
163 | const wordIndex = words.findIndex((word) =>
164 | word.toLowerCase().includes(searchString.toLowerCase())
165 | );
166 |
167 | const startWordIndex = Math.max(0, wordIndex - wordRange);
168 | const endWordIndex = Math.min(words.length, wordIndex + 1 + wordRange);
169 |
170 | const contextWords = words.slice(startWordIndex, endWordIndex);
171 | const textChunk = contextWords.join(" ");
172 | const substringIndexInChunk = textChunk
173 | .toLowerCase()
174 | .indexOf(searchString.toLowerCase());
175 |
176 | return { chunk: textChunk, index: substringIndexInChunk };
177 | };
178 |
--------------------------------------------------------------------------------
/renderer/pages/precheck.tsx:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from "react";
2 | import {
3 | Button,
4 | VStack,
5 | Box,
6 | FormControl,
7 | Flex,
8 | FormLabel,
9 | useToast,
10 | } from "@chakra-ui/react";
11 | import DirectoryPicker from "../components/DirectoryPicker";
12 | import { Heading } from "@chakra-ui/react";
13 | import { ipcRenderer } from "electron";
14 | import SetupInstructions from "../components/SetupInstructions";
15 |
16 | const isProd: boolean = process.env.NODE_ENV === "production";
17 |
18 | function PreCheck() {
19 | const toast = useToast();
20 |
21 | const [tessPath, setTessPath] = useState("");
22 | const [gsPath, setGsPath] = useState("");
23 | const [isValidating, setIsValidating] = useState(false);
24 |
25 | const makeErrorToast = (title: string, description: string) => {
26 | toast({
27 | title,
28 | description,
29 | status: "error",
30 | duration: 9000,
31 | isClosable: true,
32 | });
33 | };
34 |
35 | useEffect(() => {
36 | ipcRenderer.invoke("load-config").then((cfg) => {
37 | console.log(cfg);
38 | if (cfg.Tess && cfg.Gs) {
39 | setTessPath(cfg.Tess);
40 | setGsPath(cfg.Gs);
41 | }
42 | });
43 | }, []);
44 |
45 | return (
46 |
47 |
48 | First-time Setup
49 |
50 |
51 |
52 |
53 |
54 | Tesseract Path
55 | {tessPath}
56 | {
58 | ipcRenderer.invoke("directory-pick").then(setTessPath);
59 | }}
60 | buttonText="Select"
61 | disabled={isValidating}
62 | />
63 |
64 |
65 |
66 |
67 | GhostScript Path
68 | {gsPath}
69 | {
71 | ipcRenderer.invoke("directory-pick").then(setGsPath);
72 | }}
73 | buttonText="Select"
74 | disabled={isValidating}
75 | />
76 |
77 |
78 |
79 |
87 | ipcRenderer
88 | .invoke("check-env", {
89 | Tess: tessPath,
90 | Gs: gsPath,
91 | })
92 | .then(
93 | (res: {
94 | TessExists: Boolean;
95 | TessDataExists: Boolean;
96 | GsBinExists: Boolean;
97 | }) => {
98 | setIsValidating(true);
99 | if (!res.TessDataExists || !res.TessExists) {
100 | makeErrorToast(
101 | "Wrong Tesseract Path",
102 | "Unable to find `tesseract.exe` in your provided Tesseract path above, please double check you have installed Tesseract on your system and have selected its root path"
103 | );
104 | setIsValidating(false);
105 | } else if (!res.GsBinExists) {
106 | makeErrorToast(
107 | "Wrong GhostScript Path",
108 | "Unable to find the `bin` folder in your provided GhostScript path above, please double check you have installed GhostScript on your system and have selected its root path"
109 | );
110 | setIsValidating(false);
111 | } else {
112 | ipcRenderer
113 | .invoke("save-config", {
114 | Tess: tessPath,
115 | Gs: gsPath,
116 | })
117 | .then(() => {
118 | ipcRenderer
119 | .invoke("test-ocr")
120 | .then((res: { error: boolean; reason: string }) => {
121 | if (res.error) {
122 | makeErrorToast(
123 | "There's an issue when testing if OCR works",
124 | res.reason
125 | );
126 | } else {
127 | window.location.href = isProd
128 | ? `app://./setup.html`
129 | : `/setup`;
130 | }
131 | setIsValidating(false);
132 | });
133 | });
134 | }
135 | }
136 | )
137 | }
138 | >
139 | {isValidating
140 | ? "Validating... Please Wait..."
141 | : "Validate & Proceed"}
142 |
143 |
144 |
145 |
146 | );
147 | }
148 |
149 | export default PreCheck;
150 |
--------------------------------------------------------------------------------
/renderer/pages/setup.tsx:
--------------------------------------------------------------------------------
1 | // components/SetupScreen.js
2 | import {
3 | Button,
4 | Divider,
5 | Flex,
6 | Heading,
7 | Link,
8 | Modal,
9 | ModalBody,
10 | ModalCloseButton,
11 | ModalContent,
12 | ModalFooter,
13 | ModalHeader,
14 | ModalOverlay,
15 | Progress,
16 | Text,
17 | VStack,
18 | useDisclosure,
19 | } from "@chakra-ui/react";
20 | import { useEffect, useState } from "react";
21 | import DocsPicker from "../components/DocsScanner";
22 | import electron from "electron";
23 | import { phrases } from "../services/const";
24 | import Overlay from "../components/Overlay";
25 | import path from "path";
26 |
27 | const ipcRenderer: Electron.IpcRenderer = electron.ipcRenderer;
28 | const isProd: boolean = process.env.NODE_ENV === "production";
29 |
30 | const randomWaitingPhrase = () => {
31 | return phrases[Math.floor(Math.random() * phrases.length)];
32 | };
33 |
34 | enum PgType {
35 | Standby,
36 | Indexing,
37 | Complete,
38 | }
39 |
40 | const SetupScreen = () => {
41 | const [paths, setPaths] = useState>([]);
42 | const [progressPerc, setProgressPerc] = useState(0.0);
43 | const [progressType, setProgressType] = useState(PgType.Standby);
44 | const [waitPhrase, setWaitPhrase] = useState("");
45 | const [alreadyHasIndexDB, setAlreadyHasIndexDB] = useState(false);
46 | const { isOpen, onOpen, onClose } = useDisclosure();
47 |
48 | useEffect(() => {
49 | const interval = setInterval(() => {
50 | // Get OCR progress update via IPC bridge
51 | ipcRenderer.invoke("get-ocr-progress").then(setProgressPerc);
52 | }, 1000);
53 | return () => {
54 | clearInterval(interval);
55 | };
56 | }, []);
57 |
58 | useEffect(() => {
59 | ipcRenderer.invoke("if-index-exists").then(setAlreadyHasIndexDB);
60 | }, []);
61 |
62 | useEffect(() => {
63 | let intervalId: NodeJS.Timeout;
64 | if (progressType == PgType.Indexing) {
65 | intervalId = setInterval(() => {
66 | setWaitPhrase(randomWaitingPhrase());
67 | }, 4000);
68 | }
69 | return () => {
70 | clearInterval(intervalId);
71 | };
72 | }, [progressType]);
73 |
74 | return (
75 |
76 | {progressType === PgType.Complete && }
77 |
78 |
79 | Setup
80 |
81 |
82 | {
84 | window.location.href = isProd
85 | ? `app://./precheck.html`
86 | : `/precheck`;
87 | }}
88 | isDisabled={progressType === PgType.Indexing}
89 | >
90 | Settings
91 |
92 |
93 |
94 | PDF Documents Path
95 |
96 | ) => {
102 | setPaths(paths.filter((p) => path.extname(p) === ".pdf"));
103 | }}
104 | onSubmitFiles={(paths) => {
105 | ipcRenderer.send("file-list", paths);
106 | }}
107 | />
108 |
109 |
116 |
117 | {progressType === PgType.Indexing && "Indexing... Please Wait..."}
118 |
119 |
{waitPhrase}
120 |
{
126 | onOpen();
127 | }}
128 | >
129 | Start Indexing
130 |
131 |
132 |
133 |
134 | Delete Your Previously Indexed Data?
135 |
136 |
137 | Generating new indexed data will erase all of your previous index
138 | database (if any). This will NOT affect your original PDF
139 | documents.
140 |
141 |
142 | Would you like to continue?
143 |
144 |
145 |
146 | {
150 | onClose();
151 | console.log(paths);
152 | ipcRenderer.invoke("delete-index").then(() => {
153 | ipcRenderer.send("file-list", paths);
154 | setProgressType(PgType.Indexing);
155 |
156 | ipcRenderer.invoke("done-ocr").then(() => {
157 | setProgressType(PgType.Complete);
158 | });
159 | });
160 | }}
161 | >
162 | Proceed
163 |
164 | Cancel
165 |
166 |
167 |
168 |
169 |
170 | {alreadyHasIndexDB && (
171 | <>
172 | Looks like you already have a indexed database
173 |
174 | You could resume searching with the previously indexed documents
175 |
176 |
180 |
185 | Start Search
186 |
187 |
188 | >
189 | )}
190 |
191 |
192 | );
193 | };
194 |
195 | export default SetupScreen;
196 |
--------------------------------------------------------------------------------
/main/background.ts:
--------------------------------------------------------------------------------
1 | import { app, dialog, ipcMain, shell } from "electron";
2 | import serve from "electron-serve";
3 | import { createWindow } from "./helpers";
4 | import path from "path";
5 | import {
6 | createFolder,
7 | deletePathSync,
8 | getSubstringWithContext,
9 | gsCMD,
10 | parseIndexDB,
11 | pdfToImgs,
12 | tessCMD,
13 | writeOrAppendToFile,
14 | } from "./ocr";
15 | import { v4 as uuidv4 } from "uuid";
16 | import {
17 | createFolderIfNotExists,
18 | getDir,
19 | searchTextInFile,
20 | } from "../renderer/services/util";
21 | import { IndexRecord, SearchResult } from "../renderer/services/types";
22 | import { INDEX_DB_FILENAME, SEP } from "../renderer/services/const";
23 | import fsp from "fs/promises";
24 | import fs from "fs";
25 | import * as ini from "ini";
26 |
27 | let mainWindow: Electron.CrossProcessExports.BrowserWindow;
28 | export const isProd: boolean = process.env.NODE_ENV === "production";
29 | const appDir = getDir(app.getAppPath());
30 |
31 | if (isProd) {
32 | serve({ directory: "app" });
33 | } else {
34 | app.setPath("userData", `${app.getPath("userData")} (development)`);
35 | }
36 |
37 | (async () => {
38 | await app.whenReady();
39 |
40 | mainWindow = createWindow("main", {
41 | width: 1100,
42 | height: 1100,
43 | autoHideMenuBar: true,
44 | });
45 |
46 | if (isProd) {
47 | await mainWindow.loadURL("app://./home.html");
48 | } else {
49 | const port = process.argv[2];
50 | await mainWindow.loadURL(`http://localhost:${port}/home`);
51 | mainWindow.webContents.openDevTools();
52 | }
53 | })();
54 |
55 | app.on("window-all-closed", () => {
56 | app.quit();
57 | });
58 |
59 | // Create `_index` folder if not exist
60 | const indexPath: string = path.join(appDir, "_index");
61 |
62 | createFolderIfNotExists(indexPath);
63 |
64 | let ocrProgress: number = 0;
65 |
66 | console.log("indexPath is ", indexPath);
67 |
68 | ipcMain.on("file-list", async (_event, paths) => {
69 | let counter = 0;
70 | for (const p of paths) {
71 | // For now, only index PDF files
72 | if (path.extname(p) !== ".pdf") {
73 | continue;
74 | }
75 |
76 | const uid = uuidv4();
77 | // Append the "UUID to book path relation" to a master CSV
78 | const dbPath = path.join(indexPath, INDEX_DB_FILENAME);
79 | const record = `${uid}${SEP}${p}`;
80 | writeOrAppendToFile(dbPath, record + "\n");
81 |
82 | // Create a temp folder to contain all extracted page images from the PDF
83 | const pageImgDir = path.join(indexPath, `tmp_${uid}`);
84 | createFolder(pageImgDir);
85 |
86 | // Create a folder for OCR'd texts
87 | const txtDir = path.join(indexPath, `${uid}`);
88 | createFolder(txtDir);
89 |
90 | const pageImgNames = await pdfToImgs(p, pageImgDir);
91 | for (const pageImgName of pageImgNames) {
92 | const pageImgPath = path.join(pageImgDir, pageImgName);
93 |
94 | await tessCMD(pageImgPath, txtDir).catch((err) =>
95 | console.log(`Tesseract error when ocr ${p}: ${err}`)
96 | );
97 | console.log(`OCR'd Page ${pageImgName}`);
98 | }
99 | console.log(`Finish OCR ${p}`);
100 | deletePathSync(pageImgDir);
101 |
102 | counter++;
103 | ocrProgress = (counter / paths.length) * 100;
104 | }
105 | });
106 |
107 | ipcMain.handle("get-ocr-progress", (event) => {
108 | return ocrProgress;
109 | });
110 |
111 | ipcMain.handle("if-index-exists", (event) => {
112 | const indexDBPath = path.join(indexPath, INDEX_DB_FILENAME);
113 | return fs.existsSync(indexDBPath);
114 | });
115 |
116 | ipcMain.handle("done-ocr", async () => {
117 | ocrProgress = 0.0;
118 | return new Promise((resolve) => {
119 | const checkProgress = () => {
120 | if (ocrProgress === 100) {
121 | clearInterval(interval);
122 | resolve();
123 | }
124 | };
125 | const interval = setInterval(checkProgress, 1000); // Check every second
126 | });
127 | });
128 |
129 | ipcMain.on("search-request", (event, searchQuery: SearchResult) => {
130 | // Use master index db to go through all text files
131 | parseIndexDB(path.join(indexPath, INDEX_DB_FILENAME)).then(
132 | (records: Array) => {
133 | for (const record of records) {
134 | const { id, docPath } = record;
135 | // Recursively search the index folder that contains text
136 | const indexDocPath = path.join(indexPath, id);
137 | fsp.readdir(indexDocPath).then((files) => {
138 | for (const file of files) {
139 | // file is just the page text file name, not full path
140 | const p = path.join(indexDocPath, file);
141 | searchTextInFile(p, searchQuery).then((res) => {
142 | if (res.success && res.matches > 0) {
143 | console.log(`Found at page ${file} of ${docPath}`);
144 | const result: SearchResult = {
145 | docName: path.basename(docPath),
146 | docPath: docPath,
147 | id,
148 | page: parseInt(file.replace(".txt", ""), 10),
149 | };
150 | event.sender.send("search-result", result);
151 | }
152 | });
153 | }
154 | });
155 | }
156 | }
157 | );
158 | });
159 |
160 | ipcMain.handle("read-pdf-file", async (event, filePath) => {
161 | try {
162 | const data = await fsp.readFile(filePath);
163 | return new Uint8Array(data).buffer;
164 | } catch (error) {
165 | console.error("Error reading PDF file:", error);
166 | return null;
167 | }
168 | });
169 |
170 | ipcMain.handle("directory-pick", async (event) => {
171 | const result = await dialog.showOpenDialog(mainWindow, {
172 | properties: ["openDirectory"],
173 | });
174 | return !result.canceled ? result.filePaths[0] : "";
175 | });
176 |
177 | ipcMain.handle("load-config", (event) => {
178 | return getConfigINI();
179 | });
180 |
181 | ipcMain.handle("save-config", (event, cfg: { Tess: string; Gs: string }) => {
182 | console.log("Received settings: ", cfg);
183 | // Save config.ini
184 | fs.writeFileSync(
185 | path.join(appDir, "config.ini"),
186 | /*
187 | Example:
188 | TESSDATA_PREFIX = S:\Apps\Tesseract-OCR\tessdata\
189 | TESSERACT = S:\Apps\Tesseract-OCR\
190 | GHOSTSCRIPT = S:\Apps\gs\gs10.01.1\bin\
191 | */
192 | ini.stringify(
193 | {
194 | TESSERACT: cfg.Tess,
195 | TESSDATA_PREFIX: path.join(cfg.Tess, "tessdata/"),
196 | GHOSTSCRIPT: path.join(cfg.Gs, "bin/"),
197 | },
198 | { section: "OCR" }
199 | )
200 | );
201 | return;
202 | });
203 |
204 | ipcMain.handle("exists-config", (event) => {
205 | return fs.existsSync(path.join(appDir, "config.ini"));
206 | });
207 |
208 | ipcMain.handle("get-env", (event) => {
209 | return appDir;
210 | });
211 |
212 | ipcMain.handle("check-env", async (event, cfg) => {
213 | const { Tess, Gs } = cfg;
214 | // Check if `tesseract.exe` exists in Tess
215 | const tesseractExists = fs.existsSync(path.join(Tess, "tesseract.exe"));
216 | // Check if folder `tessdata` exists in Tess
217 | const tessdataExists = fs.existsSync(path.join(Tess, "tessdata"));
218 | // Check if folder `bin` exists in Gs
219 | const binExists = fs.existsSync(path.join(Gs, "bin"));
220 | return {
221 | TessExists: tesseractExists,
222 | TessDataExists: tessdataExists,
223 | GsBinExists: binExists,
224 | };
225 | });
226 |
227 | ipcMain.handle("delete-index", (event) => {
228 | deletePathSync(indexPath);
229 | createFolderIfNotExists(indexPath);
230 | });
231 |
232 | ipcMain.handle(
233 | "in-page-text-search",
234 | (event, result: SearchResult, searchQuery: string, contextRange: number) => {
235 | const { id, page } = result;
236 | const pageFilename = page.toString().padStart(4, "0") + ".txt";
237 | const pagePath = path.join(indexPath, id, pageFilename);
238 | return getSubstringWithContext(pagePath, searchQuery, contextRange);
239 | }
240 | );
241 |
242 | ipcMain.on("open-link-external-browser", (event, url) => {
243 | console.log(url);
244 | shell.openExternal(url);
245 | // mainWindow.webContents.setWindowOpenHandler(({ url }) => {
246 | // shell.openExternal(url);
247 | // return { action: "deny" };
248 | // });
249 | });
250 |
251 | ipcMain.handle("test-ocr", async (event) => {
252 | try {
253 | const result = await testOCR();
254 | return result;
255 | } catch (error) {
256 | return error;
257 | }
258 | });
259 |
260 | function testOCR() {
261 | return new Promise((resolve, reject) => {
262 | const pdfPath = getTestPDFFilePath("sample.pdf");
263 | const testPath = path.join(appDir, "tests");
264 |
265 | // Run ghostscript command to ensure image extraction is working
266 | createFolderIfNotExists(testPath)
267 | .then(() => gsCMD(pdfPath, testPath))
268 | .then(() => {
269 | const numImages = getNumberOfFiles(testPath);
270 | // Check if test directory contain exactly 2 images (2 pages)
271 | if (numImages !== 2) {
272 | deletePathSync(testPath);
273 | reject({
274 | error: true,
275 | reason: `Ghostscript error: number of image mismatch, expected 2 images extracted but got ${numImages}`,
276 | });
277 | }
278 |
279 | const pngPath = path.join(testPath, "0001.png");
280 | return tessCMD(pngPath, testPath);
281 | })
282 | .then(() => {
283 | // Check if 0001.txt exists
284 | const ocrTxtPath = path.join(testPath, "0001.txt");
285 | if (!fs.existsSync(ocrTxtPath)) {
286 | deletePathSync(testPath);
287 | reject({
288 | error: true,
289 | reason: `Tesseract error: 0001.txt does not exist`,
290 | });
291 | }
292 | deletePathSync(testPath);
293 | resolve({
294 | error: false,
295 | reason: "",
296 | });
297 | })
298 | .catch((err) => {
299 | deletePathSync(testPath);
300 | reject({
301 | error: true,
302 | reason: `An error occurred during the OCR test: ${err.message}`,
303 | });
304 | });
305 | });
306 | }
307 |
308 | const getNumberOfFiles = (directoryPath: string) => {
309 | const files = fs.readdirSync(directoryPath);
310 | return files.length;
311 | };
312 |
313 | const getTestPDFFilePath = (filename: string) => {
314 | const isDev = process.env.NODE_ENV === "development";
315 | if (isDev) {
316 | return path.join(__dirname, "..", "assets", filename);
317 | } else {
318 | return path.join(app.getAppPath(), "..", "assets", filename);
319 | }
320 | };
321 |
322 | const getConfigINI = () => {
323 | if (!fs.existsSync(path.join(appDir, "config.ini"))) {
324 | return {
325 | Tess: "",
326 | Gs: "",
327 | };
328 | }
329 | const cfg = ini.parse(
330 | fs.readFileSync(path.join(appDir, "config.ini"), "utf-8")
331 | );
332 | return {
333 | Tess: cfg.OCR.TESSERACT,
334 | Gs: cfg.OCR.GHOSTSCRIPT.replace(/bin\\$/, "").replace(/bin\/$/, ""),
335 | };
336 | };
337 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright © 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
6 |
7 | Preamble
8 | The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
9 |
10 | The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
11 |
12 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
13 |
14 | Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
15 |
16 | A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
17 |
18 | The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
19 |
20 | An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
21 |
22 | The precise terms and conditions for copying, distribution and modification follow.
23 |
24 | TERMS AND CONDITIONS
25 | 0. Definitions.
26 | "This License" refers to version 3 of the GNU Affero General Public License.
27 |
28 | "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
29 |
30 | "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
31 |
32 | To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
33 |
34 | A "covered work" means either the unmodified Program or a work based on the Program.
35 |
36 | To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
37 |
38 | To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
39 |
40 | An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
41 |
42 | 1. Source Code.
43 | The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
44 |
45 | A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
46 |
47 | The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
48 |
49 | The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
50 |
51 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
52 |
53 | The Corresponding Source for a work in source code form is that same work.
54 |
55 | 2. Basic Permissions.
56 | All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
57 |
58 | You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
59 |
60 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
61 |
62 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
63 | No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
64 |
65 | When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
66 |
67 | 4. Conveying Verbatim Copies.
68 | You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
69 |
70 | You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
71 |
72 | 5. Conveying Modified Source Versions.
73 | You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
74 |
75 | a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
76 | b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
77 | c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
78 | d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
79 | A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
80 |
81 | 6. Conveying Non-Source Forms.
82 | You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
83 |
84 | a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
85 | b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
86 | c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
87 | d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
88 | e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
89 | A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
90 |
91 | A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
92 |
93 | "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
94 |
95 | If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
96 |
97 | The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
98 |
99 | Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
100 |
101 | 7. Additional Terms.
102 | "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
103 |
104 | When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
105 |
106 | Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
107 |
108 | a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
109 | b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
110 | c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
111 | d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
112 | e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
113 | f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
114 | All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
115 |
116 | If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
117 |
118 | Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
119 |
120 | 8. Termination.
121 | You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
122 |
123 | However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
124 |
125 | Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
126 |
127 | Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
128 |
129 | 9. Acceptance Not Required for Having Copies.
130 | You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
131 |
132 | 10. Automatic Licensing of Downstream Recipients.
133 | Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
134 |
135 | An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
136 |
137 | You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
138 |
139 | 11. Patents.
140 | A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
141 |
142 | A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
143 |
144 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
145 |
146 | In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
147 |
148 | If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
149 |
150 | If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
151 |
152 | A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
153 |
154 | Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
155 |
156 | 12. No Surrender of Others' Freedom.
157 | If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
158 |
159 | 13. Remote Network Interaction; Use with the GNU General Public License.
160 | Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
161 |
162 | Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
163 |
164 | 14. Revised Versions of this License.
165 | The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
166 |
167 | Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
168 |
169 | If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
170 |
171 | Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
172 |
173 | 15. Disclaimer of Warranty.
174 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
175 |
176 | 16. Limitation of Liability.
177 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
178 |
179 | 17. Interpretation of Sections 15 and 16.
180 | If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
181 |
182 | END OF TERMS AND CONDITIONS
183 |
184 | How to Apply These Terms to Your New Programs
185 | If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
186 |
187 | To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
188 |
189 |
190 | Copyright (C)
191 |
192 | This program is free software: you can redistribute it and/or modify
193 | it under the terms of the GNU Affero General Public License as
194 | published by the Free Software Foundation, either version 3 of the
195 | License, or (at your option) any later version.
196 |
197 | This program is distributed in the hope that it will be useful,
198 | but WITHOUT ANY WARRANTY; without even the implied warranty of
199 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
200 | GNU Affero General Public License for more details.
201 |
202 | You should have received a copy of the GNU Affero General Public License
203 | along with this program. If not, see .
204 | Also add information on how to contact you by electronic and paper mail.
205 |
206 | If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
207 |
208 | You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see .
--------------------------------------------------------------------------------