-
Notifications
You must be signed in to change notification settings - Fork 36
/
zoteroocr.js
224 lines (207 loc) · 7.75 KB
/
zoteroocr.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// zoteroocr.js
// See https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules.
Components.utils.import("resource://gre/modules/FileUtils.jsm");
Components.utils.import("resource://gre/modules/osfile.jsm");
Zotero.OCR = new function() {
this.openPreferenceWindow = function(paneID, action) {
var io = {pane: paneID, action: action};
window.openDialog(
'chrome://zoteroocr/content/preferences.xul',
'zoteroocr-preferences-windowname',
'chrome,titlebar,toolbar,centerscreen' + Zotero.Prefs.get('browser.preferences.instantApply', true) ? 'dialog=no' : 'modal', io
);
};
// disable or enable the nested option to overwrite PDF
this.updatePDFOverwritePref = function () {
setTimeout(() => {
document.getElementById('checkbox-zoteroocr-overwrite-pdf').disabled = !document.getElementById('checkbox-zoteroocr-output-pdf').checked;
});
};
this.recognize = Zotero.Promise.coroutine(function* () {
// Look for the tesseract executable in the settings and at commonly used locations.
// If it is found, the settings are updated.
// Otherwise abort with an alert.
let ocrEngine = Zotero.Prefs.get("zoteroocr.ocrPath");
let found = false;
if (ocrEngine) {
found = yield OS.File.exists(ocrEngine);
}
else {
let path = ["/usr/local/bin/", "/usr/bin/", "C:\\Program Files\\Tesseract-OCR\\", ""];
for (ocrEngine of path) {
ocrEngine += "tesseract";
if (Zotero.isWin) {
ocrEngine += ".exe";
}
if (yield OS.File.exists(ocrEngine)) {
found = true;
Zotero.debug("Found " + ocrEngine);
Zotero.Prefs.set("zoteroocr.ocrPath", ocrEngine);
break;
}
Zotero.debug("No " + ocrEngine);
}
}
if (!found) {
alert("No " + ocrEngine + " executable found.");
return;
}
// Use the special pdfinfo variant in the zotero directory (which comes along Zotero)
// See https://developer.mozilla.org/en-US/docs/Archive/Add-ons/Code_snippets/File_I_O#Getting_special_files
// and https://dxr.mozilla.org/mozilla-central/source/xpcom/io/nsDirectoryServiceDefs.h.
let zdir = FileUtils.getDir('GreBinD', []);
let pdfinfo = zdir.clone();
pdfinfo.append("pdfinfo");
pdfinfo = pdfinfo.path;
if (Zotero.isWin) {
pdfinfo = pdfinfo + ".exe";
}
if (!(yield OS.File.exists(pdfinfo))) {
alert("No " + pdfinfo + " executable found.");
return;
}
// Look for a specific path in the preferences for pdftoppm
let pdftoppm = Zotero.Prefs.get("zoteroocr.pdftoppmPath");
if (!pdftoppm) {
// alternatively use the also the Zotero directory to look for pdftoppm
pdftoppm = zdir.clone();
pdftoppm.append("pdftoppm");
pdftoppm = pdftoppm.path;
}
if (Zotero.isWin && !(pdftoppm.endsWith(".exe"))) {
pdftoppm = pdftoppm + ".exe";
}
if (!(yield OS.File.exists(pdftoppm))) {
alert("No " + pdftoppm + " executable found.");
return;
}
let items = Zotero.getActiveZoteroPane().getSelectedItems();
for (let item of items) {
// find the PDF
let pdfItem;
if (item.isAttachment()) {
if (item.isFileAttachment() && item.attachmentContentType == 'application/pdf') {
pdfItem = item;
item = Zotero.Items.get(item.parentItemID);
}
else {
alert("Item is attachment but not PDF and will be ignored.");
continue;
}
}
else {
let pdfAttachments = item.getAttachments(false)
.map(itemID => Zotero.Items.get(itemID))
.filter(att => att.isFileAttachment() && att.attachmentContentType == 'application/pdf');
if (pdfAttachments.length == 0) {
alert("No PDF found for the selected item.");
continue;
}
if (pdfAttachments.length > 1) {
alert("There are several PDFs attached to this item. Only the first one will be processed.");
}
pdfItem = pdfAttachments[0];
}
let pdf = pdfItem.getFilePath();
let base = pdf.replace(/\.pdf$/, '');
let dir = OS.Path.dirname(pdf);
let infofile = dir + '/pdfinfo.txt';
let ocrbase = Zotero.Prefs.get("zoteroocr.overwritePDF") ? base : base + '.ocr';
// TODO filter out PDFs which have already a text layer
// extract images from PDF
let imageList = OS.Path.join(dir, 'image-list.txt');
if (!(yield OS.File.exists(imageList))) {
try {
Zotero.debug("Running " + pdfinfo + ' ' + pdf + ' ' + infofile);
yield Zotero.Utilities.Internal.exec(pdfinfo, [pdf, infofile]);
Zotero.debug("Running " + pdftoppm + ' -png -r 300 ' + pdf + ' ' + dir + '/page');
yield Zotero.Utilities.Internal.exec(pdftoppm, ['-png', '-r', 300, pdf, dir + '/page']);
}
catch (e) {
Zotero.logError(e);
}
// save the list of images in a separate file
let info = yield Zotero.File.getContentsAsync(infofile);
let numPages = info.match('Pages:[^0-9]+([0-9]+)')[1];
var imageListArray = [];
for (let i = 1; i <= parseInt(numPages, 10); i++) {
let paddedIndex = "0".repeat(numPages.length) + i;
imageListArray.push(dir + '/page-' + paddedIndex.substr(-numPages.length) + '.png');
}
Zotero.File.putContents(Zotero.File.pathToFile(imageList), imageListArray.join('\n'));
}
let parameters = [dir + '/image-list.txt'];
parameters.push(ocrbase);
if (Zotero.Prefs.get("zoteroocr.language")) {
parameters.push('-l');
parameters.push(Zotero.Prefs.get("zoteroocr.language"));
}
parameters.push('txt');
if (Zotero.Prefs.get("zoteroocr.outputPDF")) {
parameters.push('pdf');
}
if (Zotero.Prefs.get("zoteroocr.outputHocr")) {
parameters.push('hocr');
}
try {
Zotero.debug("Running " + ocrEngine + ' ' + parameters.join(' '));
yield Zotero.Utilities.Internal.exec(ocrEngine, parameters);
}
catch (e) {
Zotero.logError(e);
}
if (Zotero.Prefs.get("zoteroocr.outputNote")) {
let contents = yield Zotero.File.getContentsAsync(ocrbase + '.txt');
contents = contents.replace(/(?:\r\n|\r|\n)/g, '<br />');
let newNote = new Zotero.Item('note');
newNote.setNote(contents);
newNote.parentID = item.id;
yield newNote.saveTx();
}
if (Zotero.Prefs.get("zoteroocr.outputHocr")) {
let contents = yield Zotero.File.getContentsAsync(ocrbase + '.hocr');
// replace the absolute paths of images with relative ones
escapedDir = dir.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
let regexp = new RegExp(escapedDir + "/", 'g');
contents = contents.replace(regexp, '');
// split content into the preamble and pages
contents = contents.replace("</body>\n</html>", '');
parts = contents.split("<div class='ocr_page'");
preamble = parts[0];
// create new html attachments including hocrjs for individual pages
maximumPagesAsHtml = parseInt(Zotero.Prefs.get("zoteroocr.maximumPagesAsHtml"));
if (isNaN(maximumPagesAsHtml)) {
upperLimit = parts.length;
} else {
upperLimit = Math.min(parts.length, maximumPagesAsHtml + 1)
}
for (let i = 1; i < upperLimit; i++) {
let pagename = 'page-' + i + '.html';
let htmlfile = Zotero.File.pathToFile(OS.Path.join(dir, pagename));
let pagecontent = preamble + "<div class='ocr_page'" + parts[i] + '<script src="https://unpkg.com/hocrjs"></script>\n</body>\n</html>';
Zotero.File.putContents(htmlfile, pagecontent);
yield Zotero.Attachments.linkFromFile({
file: OS.Path.join(dir, pagename),
contentType: "text/html",
parentItemID: item.id
});
}
}
// attach PDF if it is a new one
if (Zotero.Prefs.get("zoteroocr.outputPDF") && !(Zotero.Prefs.get("zoteroocr.overwritePDF"))) {
yield Zotero.Attachments.linkFromFile({
file: ocrbase + '.pdf',
parentItemID: item.id
});
}
if (!Zotero.Prefs.get("zoteroocr.outputPNG") && imageListArray) {
// delete image list
yield Zotero.File.removeIfExists(imageList);
// delete PNGs
for (let imageName of imageListArray) {
yield Zotero.File.removeIfExists(imageName);
}
}
}
});
};