Repo for the search and displace ingest module that takes odf, docx and pdf and transforms it into .md to be used with search and displace operations
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

503 lines
14 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. <?php
  2. namespace App\Ingest;
  3. use Illuminate\Support\Facades\Storage;
  4. use Symfony\Component\Process\Exception\ProcessFailedException;
  5. use Symfony\Component\Process\Process;
  6. use League\HTMLToMarkdown\HtmlConverter;
  7. class Convertor
  8. {
  9. /**
  10. * @var \Illuminate\Contracts\Filesystem\Filesystem
  11. */
  12. private $storage;
  13. private $path;
  14. protected $type;
  15. public function __construct($path, $type)
  16. {
  17. $this->storage = Storage::disk('local');
  18. $this->path = $path;
  19. $this->type = $type;
  20. }
  21. /**
  22. * @return mixed
  23. * @throws \Exception
  24. */
  25. public function execute()
  26. {
  27. if ($this->type === 'txt') {
  28. return $this->path;
  29. }
  30. if ($this->type === 'pdf') {
  31. // $this->convertPdfToText();
  32. $this->convertPdfToMD();
  33. // $this->getHtmlContentsFromPdfWithImages();
  34. return $this->path;
  35. }
  36. if ($this->type !== 'docx') {
  37. $this->convertToDocx();
  38. }
  39. $this->convertDocumentToText();
  40. //$this->convertToHtml();
  41. return $this->path;
  42. }
  43. /**
  44. * Convert doc,dot,rtf,odt,pdf,docx to docx
  45. *
  46. *
  47. * @return string|void
  48. */
  49. private function convertToDocx()
  50. {
  51. (new Process(['export HOME=' . env('USER_HOME_PATH')]))->run();
  52. /**
  53. * Convert doc,dot,rtf,odt to docx
  54. */
  55. $process = new Process([
  56. 'soffice',
  57. '--headless',
  58. '--convert-to',
  59. 'docx',
  60. $this->storage->path($this->path),
  61. '--outdir',
  62. $this->storage->path('contracts')
  63. ]);
  64. $process->run();
  65. if (!$process->isSuccessful()) {
  66. throw new ProcessFailedException($process);
  67. }
  68. $this->storage->delete($this->path);
  69. $this->path = str_replace(".$this->type", '.docx', $this->path);
  70. }
  71. /**
  72. * Convert docx file to text
  73. *
  74. * @return void
  75. */
  76. private function convertDocumentToText()
  77. {
  78. (new Process(['export HOME=' . env('USER_HOME_PATH')]))->run();
  79. $process = new Process([
  80. 'soffice',
  81. '--headless',
  82. '--convert-to',
  83. 'txt',
  84. $this->storage->path($this->path),
  85. '--outdir',
  86. $this->storage->path('contracts')
  87. ]);
  88. $process->run();
  89. if (!$process->isSuccessful()) {
  90. throw new ProcessFailedException($process);
  91. }
  92. $this->storage->delete($this->path);
  93. $this->path = str_replace(['.docx', '.bin'], '.txt', $this->path);
  94. }
  95. protected function convertPdfToText()
  96. {
  97. $this->prepareForConvertPDF();
  98. $images = $this->getImagesFromPDF();
  99. $contents = $this->getTextContentsFromPDF();
  100. if (!$contents && count($images) === 0) {
  101. throw new \Exception('Could not read from file.');
  102. }
  103. // Handle images and image contents.
  104. if (count($images) > 0) {
  105. foreach ($images as $image) {
  106. try {
  107. $ocr = new OCR($this->storage->path($image));
  108. $imageContents = $ocr->execute();
  109. $contents = $contents . "\n" . $imageContents;
  110. } catch (\Exception $exception) {
  111. \Illuminate\Support\Facades\Log::info('something wrong: ' . $exception->getMessage());
  112. }
  113. }
  114. $dir = str_replace('.pdf', '', $this->path);
  115. $this->storage->deleteDirectory($dir);
  116. }
  117. $this->storage->delete($this->path);
  118. $this->path = str_replace('.pdf', '.txt', $this->path);
  119. $this->storage->put($this->path, $contents);
  120. }
  121. protected function convertPdfToMD()
  122. {
  123. // $this->prepareForConvertPDF();
  124. $result = $this->getContentsFromPdf();
  125. if ( ! $result['has_images'] && ! $result['has_text']) {
  126. throw new \Exception('Cannot get pdf file contents.');
  127. }
  128. if ($result['has_text']) {
  129. if ($result['has_images']) {
  130. // Both text and images.
  131. throw new \Exception('Not supported for now.');
  132. }
  133. // Delete directory because the contents are in the '$result' variable.
  134. $this->storage->deleteDirectory($this->path);
  135. $mdContents = '';
  136. foreach ($result['htmls'] as $html) {
  137. $converter = new HtmlConverter();
  138. $converter->getConfig()->setOption('strip_tags', true);
  139. $contents = $converter->convert($html);
  140. $mdContents = $mdContents . $contents;
  141. }
  142. $this->path = "$this->path.md";
  143. $this->storage->put($this->path, $mdContents);
  144. return;
  145. }
  146. // Only contains images.
  147. $imagesContent = '';
  148. $files = $this->storage->allFiles($this->path);
  149. foreach ($files as $file) {
  150. // Only get the image files from the directory, it may contain some empty html files too.
  151. if (in_array(pathinfo($file, PATHINFO_EXTENSION), ['jpg', 'png'])) {
  152. $ocr = new OCR($this->storage->path($file));
  153. $imagesContent = $imagesContent . $ocr->execute();
  154. }
  155. }
  156. // We are done with the images processing, delete directory.
  157. $this->storage->deleteDirectory($this->path);
  158. $this->path = "$this->path.md";
  159. $this->storage->put($this->path, $imagesContent);
  160. }
  161. private function convertToHtml()
  162. {
  163. (new Process(['export HOME=' . env('USER_HOME_PATH')]))->run();
  164. $process = new Process([
  165. 'soffice',
  166. '--headless',
  167. '--convert-to',
  168. 'html:HTML:EmbedImages',
  169. $this->storage->path($this->path),
  170. '--outdir',
  171. $this->storage->path('contracts')
  172. ]);
  173. $process->run();
  174. if (!$process->isSuccessful()) {
  175. throw new ProcessFailedException($process);
  176. }
  177. $this->storage->delete($this->path);
  178. $this->path = str_replace(".$this->type", '.html', $this->path);
  179. }
  180. private function convertToXML()
  181. {
  182. //Convert the file to xml using pdftohtml to xml and run a python scrypt to fix the paragraphs
  183. $process = new Process([
  184. 'pdftohtml',
  185. '-xml',
  186. '-i',
  187. $this->storage->path($this->path)
  188. ]);
  189. $process->run();
  190. if (!$process->isSuccessful()) {
  191. throw new ProcessFailedException($process);
  192. }
  193. $this->storage->delete($this->path);
  194. $this->path = str_replace(".$this->type", '.xml', $this->path);
  195. }
  196. protected function prepareForConvertPDF()
  197. {
  198. (new Process(['export HOME=' . env('USER_HOME_PATH')]))->run();
  199. $process = new Process([
  200. 'pip3',
  201. 'install',
  202. 'pdftotext',
  203. ]);
  204. $process->run();
  205. if (!$process->isSuccessful()) {
  206. throw new ProcessFailedException($process);
  207. }
  208. }
  209. protected function getImagesFromPDF()
  210. {
  211. $dir = str_replace('.pdf', '', $this->path);
  212. $this->storage->makeDirectory($dir);
  213. $process = new Process([
  214. 'pdfimages',
  215. '-p',
  216. $this->storage->path($this->path),
  217. '-tiff',
  218. $this->storage->path("$dir/ocr")
  219. ]);
  220. $process->run();
  221. if (!$process->isSuccessful()) {
  222. throw new ProcessFailedException($process);
  223. }
  224. return $this->storage->allFiles($dir);
  225. }
  226. protected function getTextContentsFromPDF()
  227. {
  228. $outputPath = $this->storage->path(str_replace('.pdf', '.txt', $this->path));
  229. $process = new Process([
  230. 'python3',
  231. storage_path('scripts' . DIRECTORY_SEPARATOR . 'parse-pdf.py'),
  232. '-i',
  233. $this->storage->path($this->path),
  234. '-o',
  235. $outputPath
  236. ]);
  237. $process->run();
  238. if (!$process->isSuccessful()) {
  239. throw new ProcessFailedException($process);
  240. }
  241. return file_get_contents($outputPath);
  242. }
  243. protected function getHtmlContentsFromPdfWithImages()
  244. {
  245. $dirName = str_replace('.pdf', '', $this->path);
  246. $this->storage->makeDirectory($dirName);
  247. $outputPath = $this->storage->path("$dirName/html");
  248. $process = new Process([
  249. 'pdftohtml',
  250. '-noframes',
  251. $this->storage->path($this->path),
  252. $outputPath
  253. ]);
  254. $process->run();
  255. if (!$process->isSuccessful()) {
  256. throw new ProcessFailedException($process);
  257. }
  258. $this->storage->delete($this->path);
  259. $this->path = $dirName;
  260. $converter = new HtmlConverter();
  261. $converter->getConfig()->setOption('strip_tags', true);
  262. $files = $this->storage->allFiles($this->path);
  263. $htmlFileIndex = null;
  264. foreach ($files as $index => $file) {
  265. // if (pathinfo($file, PATHINFO_BASENAME) === 'html-html.html') {
  266. // if (pathinfo($file, PATHINFO_EXTENSION) === 'html') {
  267. if (pathinfo($file, PATHINFO_BASENAME) === 'html.html') {
  268. $htmlFileIndex = $index;
  269. break;
  270. }
  271. }
  272. $htmlContents = $this->storage->get($files[$htmlFileIndex]);
  273. $contents = $converter->convert($htmlContents);
  274. // $this->storage->deleteDirectory($this->path);
  275. $this->path = "$this->path.md";
  276. $this->storage->put($this->path, $contents);
  277. dd(3);
  278. }
  279. protected function getContentsFromPdf()
  280. {
  281. $dirName = str_replace('.pdf', '', $this->path);
  282. $this->storage->makeDirectory($dirName);
  283. $outputPath = $this->storage->path("$dirName/html");
  284. $process = new Process([
  285. 'pdftohtml',
  286. '-xml',
  287. $this->storage->path($this->path),
  288. $outputPath
  289. ]);
  290. $process->run();
  291. if (!$process->isSuccessful()) {
  292. throw new ProcessFailedException($process);
  293. }
  294. $this->storage->delete($this->path);
  295. $this->path = $dirName;
  296. $contents = $this->storage->get("$this->path/html.xml");
  297. $xml = simplexml_load_string($contents);
  298. $fonts = [];
  299. foreach ($xml->page as $page) {
  300. foreach ($page as $p) {
  301. if ($p->getName() === 'fontspec') {
  302. $fonts[(int) $p['id']]['family'] = (string) $p['family'];
  303. $fonts[(int) $p['id']]['size'] = (string) $p['size'];
  304. $fonts[(int) $p['id']]['color'] = (string) $p['color'];
  305. }
  306. }
  307. }
  308. $htmls = [];
  309. $hasImages = false;
  310. $hasText = false;
  311. try {
  312. foreach ($xml->page as $page) {
  313. $html = '';
  314. $previousP = null;
  315. foreach ($page as $p) {
  316. if ($p->getName() == 'image') {
  317. $html = $html . '<img style="position: absolute; top: ' . $p['top'] . 'px; left: ' . $p['left'] . 'px;" width="' . $p['width'] . '" height="' . $p['height'] . '" src="' . $p['src'] . '">';
  318. $hasImages = true;
  319. }
  320. if ($p->getName() == 'text') {
  321. $id = (int) $p['font'];
  322. $font_size = $fonts[$id]['size'];
  323. $font_color = $fonts[$id]['color'];
  324. $font_family = $fonts[$id]['family'];
  325. $style = '';
  326. $style = $style . 'position: absolute;';
  327. $style = $style . "color: $font_color;";
  328. $style = $style . "font-family: $font_family;";
  329. $style = $style . "font-weight: 900;";
  330. $style = $style . "width: " . $p['width'] . "px;";
  331. $style = $style . "height: " . $p['height'] . "px;";
  332. $style = $style . "top: " . $p['top'] . "px;";
  333. $style = $style . "left: " . $p['left'] . "px;";
  334. // $style = $style . "font-size: $font_size" . "px;";
  335. if ($p->i) {
  336. $content = '<i>' . $p->i . '</i>';
  337. } else if ($p->b) {
  338. $content = '<b>' . $p->b . '</b>';
  339. } else {
  340. $content = $p;
  341. }
  342. // @TODO Must chain paragraphs if top are almost same.
  343. $tag = $this->getTag($p, $previousP, $font_size);
  344. $html = $html . '<' . $tag . ' style="' . $style . '">' . $content . '</' . $tag . '>';
  345. $hasText = true;
  346. }
  347. $previousP = $p;
  348. }
  349. $htmls[] = '<html><head><title></title></head><body>' . $html . '</body></html>';
  350. }
  351. } catch (\Exception $exception) {
  352. \Illuminate\Support\Facades\Log::info($exception->getTraceAsString());
  353. }
  354. return [
  355. 'has_images' => $hasImages,
  356. 'has_text' => $hasText,
  357. 'htmls' => $htmls,
  358. ];
  359. }
  360. protected function getTag($p, $previousP, $size)
  361. {
  362. if ($size > 24) {
  363. return 'h1';
  364. }
  365. if ($size > 18) {
  366. return 'h2';
  367. }
  368. if ($size > 16) {
  369. return 'h3';
  370. }
  371. if ($previousP && $p['top'] - $previousP['top'] <= 5) {
  372. return 'span';
  373. }
  374. return 'p';
  375. }
  376. }