| 1 | # Copyright (C) 2016--2026 Karl Wette | ||
| 2 | # | ||
| 3 | # This file is part of App::PDFLibrarian. | ||
| 4 | # | ||
| 5 | # App::PDFLibrarian is free software: you can redistribute it and/or modify | ||
| 6 | # it under the terms of the GNU General Public License as published by | ||
| 7 | # the Free Software Foundation, either version 3 of the License, or (at | ||
| 8 | # your option) any later version. | ||
| 9 | # | ||
| 10 | # App::PDFLibrarian is distributed in the hope that it will be useful, but | ||
| 11 | # WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
| 13 | # General Public License for more details. | ||
| 14 | # | ||
| 15 | # You should have received a copy of the GNU General Public License | ||
| 16 | # along with App::PDFLibrarian. If not, see <http://www.gnu.org/licenses/>. | ||
| 17 | |||
| 18 | use v5.18; | ||
| 19 | use strict; | ||
| 20 | use warnings; | ||
| 21 | use utf8; | ||
| 22 | use open qw(:std :encoding(UTF-8)); | ||
| 23 | |||
| 24 | package App::PDFLibrarian::Util; | ||
| 25 | $App::PDFLibrarian::Util::VERSION = '6.3.4'; | ||
| 26 | use parent 'Exporter'; | ||
| 27 | |||
| 28 | use Carp; | ||
| 29 | use Cwd; | ||
| 30 | use Encode; | ||
| 31 | use File::Find; | ||
| 32 | use File::MimeInfo::Magic; | ||
| 33 | use File::Spec; | ||
| 34 | use FindBin qw($Script); | ||
| 35 | use Parallel::Iterator; | ||
| 36 | use System::Info qw(sysinfo_hash); | ||
| 37 | use Text::Wrap; | ||
| 38 | use Unicode::Normalize; | ||
| 39 | |||
| 40 | use App::PDFLibrarian qw($pdflibrarydir); | ||
| 41 | |||
| 42 | our @EXPORT_OK = qw(unique_list is_in_dir get_file_list find_pdf_files keyword_display_str parallel_loop remove_tex_markup remove_tex_markup_undef remove_short_words replace_accents_with_latex run_async kill_async); | ||
| 43 | |||
| 44 | 1; | ||
| 45 | |||
| 46 | sub unique_list { | ||
| 47 | |||
| 48 | # return a list containing only unique elements | ||
| 49 | my %seen; | ||
| 50 | grep !$seen{$_}++, @_; | ||
| 51 | |||
| 52 | } | ||
| 53 | |||
| 54 | sub is_in_dir { | ||
| 55 | my ($dir, $path) = @_; | ||
| 56 | |||
| 57 | # return true if '$path' is in '$dir', false otherwise | ||
| 58 | sub spliteverything { | ||
| 59 | my $p = $_[0]; | ||
| 60 | $p = File::Spec->rel2abs($p); | ||
| 61 | $p = Cwd::abs_path($p); | ||
| 62 | my ($v, $d, $f) = File::Spec->splitpath($p); | ||
| 63 | my @d = File::Spec->splitdir(File::Spec->catdir($d)); | ||
| 64 | ($v, @d, $f) | ||
| 65 | } | ||
| 66 | my @dir = spliteverything($dir); | ||
| 67 | my @path = spliteverything($path); | ||
| 68 | return 0 if @dir > @path; | ||
| 69 | while (@dir) { | ||
| 70 | return 0 if shift(@dir) ne shift(@path); | ||
| 71 | } | ||
| 72 | |||
| 73 | return 1; | ||
| 74 | } | ||
| 75 | |||
| 76 | sub get_file_list { | ||
| 77 | |||
| 78 | # get list of files either from command line or from standard input | ||
| 79 | if (@ARGV > 0) { | ||
| 80 | return @ARGV; | ||
| 81 | } else { | ||
| 82 | chomp(my @stdin = <STDIN>); | ||
| 83 | return @stdin; | ||
| 84 | } | ||
| 85 | |||
| 86 | } | ||
| 87 | |||
| 88 | sub find_pdf_files { | ||
| 89 | |||
| 90 | # return unique found PDF files | ||
| 91 | my %pdffileorder; | ||
| 92 | my $order = 0; | ||
| 93 | my $preprocess = sub { | ||
| 94 | return sort @_; | ||
| 95 | }; | ||
| 96 | my $wanted = sub { | ||
| 97 | if (-l $_) { | ||
| 98 | $_ = readlink($_) or croak "$Script: could not resolve '$_': %!"; | ||
| 99 | } | ||
| 100 | return unless -f && mimetype($_) eq 'application/pdf'; | ||
| 101 | $pdffileorder{File::Spec->rel2abs($_)} = ++$order; | ||
| 102 | }; | ||
| 103 | |||
| 104 | # find PDF files in the given list of search paths | ||
| 105 | foreach (@_) { | ||
| 106 | if (-d $_) { | ||
| 107 | find({preprocess => \&$preprocess, wanted => \&$wanted, no_chdir => 1}, $_); | ||
| 108 | } elsif (-r $_) { | ||
| 109 | &$wanted($_); | ||
| 110 | } elsif (!File::Spec->file_name_is_absolute($_) && -d File::Spec->catdir($pdflibrarydir, $_)) { | ||
| 111 | find({preprocess => \&$preprocess, wanted => \&$wanted, no_chdir => 1}, File::Spec->catdir($pdflibrarydir, $_)); | ||
| 112 | } elsif (!File::Spec->file_name_is_absolute($_) && -r File::Spec->catfile($pdflibrarydir, $_)) { | ||
| 113 | &$wanted(File::Spec->catfile($pdflibrarydir, $_)); | ||
| 114 | } else { | ||
| 115 | croak "$Script: '$_' is neither a file nor a directory, either by itself or within '$pdflibrarydir'"; | ||
| 116 | } | ||
| 117 | } | ||
| 118 | |||
| 119 | return sort { $pdffileorder{$a} <=> $pdffileorder{$b} } keys %pdffileorder; | ||
| 120 | } | ||
| 121 | |||
| 122 | sub keyword_display_str { | ||
| 123 | |||
| 124 | # build list of keyword directories in PDF library | ||
| 125 | my $pdfkeyworddir = File::Spec->catdir($pdflibrarydir, 'Keywords'); | ||
| 126 | return "" unless -d $pdfkeyworddir; | ||
| 127 | my %keywords; | ||
| 128 | my $wanted = sub { | ||
| 129 | |||
| 130 | # only act on files, to get full keyword specification | ||
| 131 | return unless -f $_; | ||
| 132 | |||
| 133 | # get path relative to base keywork directory | ||
| 134 | my @kw = File::Spec->splitdir(File::Spec->abs2rel($_, $pdfkeyworddir)); | ||
| 135 | |||
| 136 | # remove filename | ||
| 137 | pop @kw; | ||
| 138 | |||
| 139 | # remove any "by author/title/year" directories | ||
| 140 | pop @kw if $kw[-1] =~ /^by_/; | ||
| 141 | |||
| 142 | # format keywords | ||
| 143 | foreach (@kw) { | ||
| 144 | s/^kw_//; | ||
| 145 | s/_/ /g; | ||
| 146 | } | ||
| 147 | |||
| 148 | # join all keywords apart from last one | ||
| 149 | my $lastkw = pop @kw; | ||
| 150 | my $kws = join(': ', @kw); | ||
| 151 | |||
| 152 | # add to keyword hash | ||
| 153 | if ($kws eq "") { | ||
| 154 | $keywords{$lastkw}{""} = 1; | ||
| 155 | } else { | ||
| 156 | $keywords{$kws}{$lastkw} = 1; | ||
| 157 | } | ||
| 158 | |||
| 159 | }; | ||
| 160 | find({wanted => \&$wanted, no_chdir => 1}, $pdfkeyworddir); | ||
| 161 | return "" unless scalar(%keywords) > 0; | ||
| 162 | |||
| 163 | # format keyword display string | ||
| 164 | my $str = "%% Currently defined keywords:\n"; | ||
| 165 | foreach my $kws (sort { $a cmp $b } keys(%keywords)) { | ||
| 166 | my @lastkws = keys(%{$keywords{$kws}}); | ||
| 167 | @lastkws = grep { $_ ne "" } @lastkws; | ||
| 168 | @lastkws = sort { $a cmp $b } @lastkws; | ||
| 169 | my $lastkws = join(', ', @lastkws); | ||
| 170 | if ($lastkws eq "") { | ||
| 171 | $str .= "%% $kws\n"; | ||
| 172 | } else { | ||
| 173 | $str .= "%% $kws:\n"; | ||
| 174 | my $prefix = "%% "; | ||
| 175 | $str .= wrap($prefix, $prefix, $lastkws) . "\n"; | ||
| 176 | } | ||
| 177 | } | ||
| 178 | |||
| 179 | return $str; | ||
| 180 | } | ||
| 181 | |||
| 182 | sub parallel_loop { | ||
| 183 | my ($progfmt, $inarray, $body) = @_; | ||
| 184 | die unless ref($inarray) eq 'ARRAY'; | ||
| 185 | die unless ref($body) eq 'CODE'; | ||
| 186 | |||
| 187 | # return if '@$inarray' is empty | ||
| 188 | return () unless @$inarray > 0; | ||
| 189 | |||
| 190 | # get number of CPUs | ||
| 191 | my $sysinfo = sysinfo_hash(); | ||
| 192 | my $ncpus = $sysinfo->{"cpu_cores"}; | ||
| 193 | |||
| 194 | # run code '$body' over all elements of '@$inarray', return the results | ||
| 195 | # in '@outarray', and print occasional progress messages using '$progfmt' | ||
| 196 | my $total = scalar(@$inarray); | ||
| 197 | my $worker = sub { | ||
| 198 | my ($id, $in) = @_; | ||
| 199 | if ($id % (3 * $ncpus) == 0) { | ||
| 200 | printf STDERR "$Script: $progfmt\r", $id, $total; | ||
| 201 | flush STDERR; | ||
| 202 | } | ||
| 203 | my $out = &$body($in); | ||
| 204 | return $out; | ||
| 205 | }; | ||
| 206 | my @outarray = Parallel::Iterator::iterate_as_array( { workers => $ncpus, batch => 1 }, \&$worker, $inarray ); | ||
| 207 | @outarray = grep { defined($_) } @outarray; | ||
| 208 | printf STDERR "$Script: $progfmt\n", scalar(@outarray), $total; | ||
| 209 | flush STDERR; | ||
| 210 | |||
| 211 | return @outarray; | ||
| 212 | } | ||
| 213 | |||
| 214 | sub remove_tex_markup { | ||
| 215 | my (@words) = @_; | ||
| 216 | |||
| 217 | # save some TeX commands | ||
| 218 | my %saveTeX = ( | ||
| 219 | Gamma => "Gamma", Delta => "Delta", Theta => "Theta", Lambda => "Lambda", | ||
| 220 | Xi => "Xi", Pi => "Pi", Sigma => "Sigma", Upsilon => "Upsilon", | ||
| 221 | Phi => "Phi", Psi => "Psi", Omega => "Omega", alpha => "alpha", | ||
| 222 | beta => "beta", gamma => "gamma", delta => "delta", epsilon => "epsilon", | ||
| 223 | varepsilon => "varepsilon", zeta => "zeta", eta => "eta", theta => "theta", | ||
| 224 | vartheta => "vartheta", iota => "iota", kappa => "kappa", lambda => "lambda", | ||
| 225 | mu => "mu", nu => "nu", xi => "xi", pi => "pi", | ||
| 226 | varpi => "varpi", rho => "rho", varrho => "varrho", sigma => "sigma", | ||
| 227 | varsigma => "varsigma", tau => "tau", upsilon => "upsilon", phi => "phi", | ||
| 228 | varphi => "varphi", chi => "chi", psi => "psi", omega => "omega", | ||
| 229 | lt => "<=", gt => ">=", ll => "<<", gg => ">>", | ||
| 230 | sim => "~", approx => "~=", | ||
| 231 | ); | ||
| 232 | |||
| 233 | # remove TeX markup | ||
| 234 | foreach (@words) { | ||
| 235 | if (!defined($_)) { | ||
| 236 | $_ = ""; | ||
| 237 | } else { | ||
| 238 | s/~/ /g; | ||
| 239 | foreach my $t (keys %saveTeX) { | ||
| 240 | s/\\$t/$saveTeX{$t}/g; | ||
| 241 | } | ||
| 242 | s/\\_/_/g; | ||
| 243 | s/{\s*\\(\w)\s*}/$1/g; | ||
| 244 | s/\\(\w)\s+/$1/g; | ||
| 245 | s/\\\w+//g; | ||
| 246 | s/\\.//g; | ||
| 247 | s/[{}]//g; | ||
| 248 | s/\$//g; | ||
| 249 | } | ||
| 250 | } | ||
| 251 | |||
| 252 | return wantarray ? @words : "@words"; | ||
| 253 | } | ||
| 254 | |||
| 255 | sub remove_tex_markup_undef { | ||
| 256 | my $words = remove_tex_markup(@_); | ||
| 257 | |||
| 258 | # return undef if $words is empty, for use with // operator | ||
| 259 | return $words ne "" ? $words : undef; | ||
| 260 | |||
| 261 | } | ||
| 262 | |||
| 263 | sub remove_short_words { | ||
| 264 | my (@words) = @_; | ||
| 265 | |||
| 266 | # remove short words | ||
| 267 | my @short_words = | ||
| 268 | qw( | ||
| 269 | a | ||
| 270 | an as at by if in is of on or so to up | ||
| 271 | and are but for its nor now off per the via | ||
| 272 | amid down from into like near once onto over past than than that upon when with | ||
| 273 | ); | ||
| 274 | @words = grep { my $word = $_; ! scalar grep { $word =~ /^$_$/i } @short_words } @words; | ||
| 275 | |||
| 276 | return wantarray ? @words : "@words"; | ||
| 277 | } | ||
| 278 | |||
| 279 | sub replace_accents_with_latex { | ||
| 280 | my ($text) = @_; | ||
| 281 | |||
| 282 | my %latex_accents = ( | ||
| 283 | "\x{0300}" => '`', # Combining grave accent | ||
| 284 | "\x{0301}" => "'", # Combining acute accent | ||
| 285 | "\x{0302}" => '^', # Combining circumflex | ||
| 286 | "\x{0308}" => '"', # Combining diaeresis / umlaut | ||
| 287 | "\x{0303}" => '~', # Combining tilde | ||
| 288 | "\x{0307}" => '.', # Combining dot above | ||
| 289 | "\x{030B}" => 'H', # Combining double acute | ||
| 290 | ); | ||
| 291 | |||
| 292 | # decompose into base character + combining marks | ||
| 293 | my $decomp = Unicode::Normalize::NFKD($text); | ||
| 294 | |||
| 295 | # replace pattern: base character followed by combining marks | ||
| 296 | $decomp =~ s{([[:alpha:]])([\p{NonspacingMark}]+)}{ | ||
| 297 | my ($base, $marks) = ($1, $2); | ||
| 298 | my $res = $base; | ||
| 299 | # wrap the base with accumulated LaTeX accent commands | ||
| 300 | map { | ||
| 301 | my $cmd = $latex_accents{$_}; | ||
| 302 | if (defined($cmd)) { | ||
| 303 | $res = "\\${cmd}{$res}"; | ||
| 304 | } else { | ||
| 305 | $res .= $_; | ||
| 306 | } | ||
| 307 | } split //, $marks; | ||
| 308 | $res; | ||
| 309 | }ge; | ||
| 310 | |||
| 311 | # re-compose any remaining accented characters | ||
| 312 | my $newtext = Unicode::Normalize::NFC($decomp); | ||
| 313 | |||
| 314 | return $newtext; | ||
| 315 | } | ||
| 316 | |||
| 317 | sub run_async { | ||
| 318 | |||
| 319 | # execute command in separate process group | ||
| 320 | my $pid = fork(); | ||
| 321 | croak "$Script: could not fork: $!" unless defined($pid); | ||
| 322 | if ($pid == 0) { | ||
| 323 | setpgrp; | ||
| 324 | open STDIN, "/dev/null" or croak "$Script: could not open STDIN: $!"; | ||
| 325 | open STDOUT, ">/dev/null" or croak "$Script: could not open STDOUT: $!"; | ||
| 326 | open STDERR, ">/dev/null" or croak "$Script: could not open STDERR: $!"; | ||
| 327 | exec(@_); | ||
| 328 | exit 1; | ||
| 329 | } | ||
| 330 | |||
| 331 | # sleep for a while to allow process to start | ||
| 332 | sleep(1.5); | ||
| 333 | |||
| 334 | return $pid; | ||
| 335 | } | ||
| 336 | |||
| 337 | sub kill_async { | ||
| 338 | |||
| 339 | # kill process group | ||
| 340 | foreach my $pid (@_) { | ||
| 341 | kill 'TERM', -$pid if defined($pid); | ||
| 342 | } | ||
| 343 | |||
| 344 | } |