summaryrefslogtreecommitdiff
path: root/bin/rdf2hours
blob: dea675a085450eaebdda4ae255005927197191c1 (plain)
  1. #!/usr/bin/perl
  2. #
  3. # Copyright © 2013 Jonas Smedegaard <dr@jones.dk>
  4. # Description: render opening hours webpage from RDF data
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 3, or (at your option)
  9. # any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful, but
  12. # WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. use 5.010;
  19. use strictures 1;
  20. use utf8::all;
  21. #use DDP alias => 'Dumper';
  22. use DateTimeX::Easy;
  23. use DateTime::Format::W3CDTF;
  24. use Carp;
  25. use Try::Tiny;
  26. use RDF::Query;
  27. use RDF::TrineX::Functions qw[curie model parse];
  28. use HTML::HTML5::Builder qw[:standard];
  29. use HTML::HTML5::Writer;
  30. # TODO: add options --verbose and --debug
  31. # TODO: add override options --theme and (multivalued) --category
  32. my @category = <<LIST =~ m/(\S.*\S)/g;
  33. restaurant
  34. groceries
  35. attraction
  36. transport
  37. public service
  38. LIST
  39. # TODO: add override options --from, --through and --theme
  40. #my $globalfrom = DateTimeX::Easy->new('now');
  41. # TODO: teach DTX::Easy / DT::F::Natural DT::F::Flexible words "current" and "present" (as alternatives to this)
  42. my $globalfrom = DateTimeX::Easy->new('first day of this month');
  43. # TODO: teach DTX::Easy / DT::F::Natural DT::F::Flexible these:
  44. # last day of month three months from now
  45. # last day of month in three months
  46. # last day of (the) month three months ahead
  47. # ... in the future
  48. # ... into the future
  49. # ... from now
  50. # ... later <- this last one for changing object, not create new
  51. #my $globalthrough = DateTimeX::Easy->new('last day of month in 3 months');
  52. my $globalthrough = DateTimeX::Easy->new($globalfrom);
  53. $globalthrough->add( months => 4 )->subtract( days => 1 );
  54. # TODO: add Getopt option --preset as shortcut to --category, --from and --through
  55. my $parser = RDF::Trine::Parser::Turtle->new;
  56. my $model = model();
  57. # TODO: throw sensible error if no (non-opt) args provided
  58. while (my $data = shift @ARGV) {
  59. try {
  60. parse($data, using => $parser, into => $model);
  61. } catch {
  62. say STDERR "Failed to parse file \"$data\": $_";
  63. die;
  64. }
  65. }
  66. # compose query for hourspec data at least partly within a "window" of time
  67. # (yes, comparing global dates against opposite spec dates is deliberate)
  68. my $w3c = DateTime::Format::W3CDTF->new;
  69. my $query = qurie( sprintf(<<'SPARQL', $w3c->format_datetime($globalthrough), $w3c->format_datetime($globalfrom) ));
  70. SELECT *
  71. WHERE {
  72. {
  73. ?location
  74. a schema:Place ;
  75. gr:category ?category ;
  76. gr:name ?name ;
  77. gr:hasOpeningHourSpecification ?spec .
  78. ?spec
  79. gr:opens ?opens ;
  80. gr:closes ?closes ;
  81. rdfs:label ?speclabel ;
  82. gr:validFrom ?specfrom ;
  83. gr:validThrough ?specthrough .
  84. OPTIONAL { ?spec rdfs:comment ?speccomment } .
  85. OPTIONAL { ?location gr:description ?locationcomment } .
  86. FILTER ( ?specfrom <= "%s"^^xsd:dateTime ) .
  87. FILTER ( ?specthrough > "%s"^^xsd:dateTime )
  88. } UNION {
  89. ?location
  90. gr:category ?category ;
  91. gr:name ?name ;
  92. gr:hasOpeningHourSpecification ?spec .
  93. ?spec
  94. gr:opens ?opens ;
  95. gr:closes ?closes .
  96. OPTIONAL {
  97. ?spec
  98. rdfs:label ?speclabel ;
  99. gr:validFrom ?specfrom ;
  100. gr:validThrough ?specthrough .
  101. } .
  102. OPTIONAL { ?spec rdfs:comment ?speccomment } .
  103. OPTIONAL { ?location gr:description ?locationcomment } .
  104. FILTER (!bound(?specfrom)) .
  105. FILTER (!bound(?specthrough))
  106. }
  107. }
  108. SPARQL
  109. # TODO: sort using SPARQL instead of perl
  110. # ORDER BY ?category ?name ?specfrom ?specthrough ?opens ?closes
  111. my %data;
  112. my $iterator = $query->execute($model);
  113. while ( my $row = $iterator->next ) {
  114. my $category = $row->{category}->literal_value;
  115. my $name = $row->{name}->literal_value;
  116. my $locationcomment = $row->{locationcomment} ? $row->{locationcomment}->literal_value : '';
  117. my $speclabel = $row->{speclabel} ? $row->{speclabel}->literal_value : '';
  118. # merge identically named locations, tying varying descriptions to spec instead
  119. # my $name_key = titledescribe( $name, $locationcomment );
  120. # my $specbundle_key = $speclabel;
  121. my $name_key = $name;
  122. my $specbundle_key = titledescribe( $speclabel, $locationcomment );
  123. my $specfrom = $row->{specfrom} ? $row->{specfrom}->datetime : '';
  124. my $specthrough = $row->{specthrough} ? $row->{specthrough}->datetime : '';
  125. my $speccomment = $row->{speccomment} ? $row->{speccomment}->literal_value : '';
  126. # TODO: use DateTime objects instead.
  127. my $opens = $row->{opens}->literal_value;
  128. $opens =~ s/:\d\d$//;
  129. my $closes = $row->{closes}->literal_value;
  130. $closes =~ s/:\d\d$//;
  131. $closes =~ s/^23:59/24/;
  132. my @weekdays;
  133. my $iterator = $model->get_statements($row->{spec}, curie('gr_hasOpeningHoursDayOfWeek'), undef);
  134. while (my $statement = $iterator->next) {
  135. my $label = $statement->object;
  136. given ($label->as_string) {
  137. when (/Monday/) { push @weekdays, 1 };
  138. when (/Tuesday/) { push @weekdays, 2 };
  139. when (/Wednesday/) { push @weekdays, 3 };
  140. when (/Thursday/) { push @weekdays, 4 };
  141. when (/Friday/) { push @weekdays, 5 };
  142. when (/Saturday/) { push @weekdays, 6 };
  143. when (/Sunday/) { push @weekdays, 7 };
  144. when (/PublicHolidays/) { push @weekdays, 8 };
  145. default { die "failed to parse weekday: ", $label->as_string };
  146. }
  147. }
  148. my $weekdays = join ', ', sort @weekdays;
  149. $weekdays = 0 unless ($weekdays);
  150. my $weekdays_key = titledescribe( $weekdays, $speccomment );
  151. # FIXME: support multiple specbundles on same days (e.g. Gaardstronomi sommer siesta)
  152. # $weekdays_key .= daterangedescribe($specfrom, $specthrough)
  153. # if ( ($specfrom) and ($specthrough) );
  154. $data{$category}{$name_key}{name} = $name;
  155. $data{$category}{$name_key}{specbundle}{$specbundle_key}{locationcomment} = $locationcomment;
  156. $data{$category}{$name_key}{specbundle}{$specbundle_key}{speclabel} = $speclabel;
  157. $data{$category}{$name_key}{specbundle}{$specbundle_key}{specfrom} = $specfrom;
  158. $data{$category}{$name_key}{specbundle}{$specbundle_key}{specthrough} = $specthrough;
  159. $data{$category}{$name_key}{specbundle}{$specbundle_key}{spec}{$weekdays_key}{weekdays} = $weekdays;
  160. # TODO: extend SPARQL to cover specs without opens/closes, or drop below check
  161. if ($opens and $closes) {
  162. $data{$category}{$name_key}{specbundle}{$specbundle_key}{spec}{$weekdays_key}{spec} = "$opens - $closes";
  163. $data{$category}{$name_key}{specbundle}{$specbundle_key}{spec}{$weekdays_key}{speccomment} = $speccomment;
  164. }
  165. }
  166. my $title = 'Åbningstider';
  167. my $intro = sprintf(
  168. 'Åbningstider på Orø indenfor udvalgte kategorier, dækkende perioden %s.',
  169. daterangedescribe($globalfrom, $globalthrough),
  170. );
  171. # TODO: make simplified html (preferred for Scribus) optional
  172. #push my @content, h1($title), "\n", p($intro);
  173. push my @content, h1($title), "\n", $intro;
  174. for my $category ( @category ) {
  175. push @content, "\n", h2( categorydescribe($category) ), "\n";
  176. for my $name ( sort keys %{ $data{$category} } ) {
  177. push @content, "\n", h3($name);
  178. my @bundle = keys %{ $data{$category}{$name}{specbundle} };
  179. # FIXME: respect locale when sorting (Galleri before Gaardstronomi)
  180. for my $specbundle ( sort {
  181. $data{$category}{$name}{specbundle}{$a}{specfrom}
  182. <=> $data{$category}{$name}{specbundle}{$b}{specfrom}
  183. || $a cmp $b
  184. } @bundle ) {
  185. # TODO: when global limits shown, show only speclabel plural spec bundles
  186. my $speclabel = speclabeldescribe(
  187. $data{$category}{$name}{specbundle}{$specbundle}{speclabel},
  188. $data{$category}{$name}{specbundle}{$specbundle}{locationcomment},
  189. $data{$category}{$name}{specbundle}{$specbundle}{specfrom},
  190. $data{$category}{$name}{specbundle}{$specbundle}{specthrough},
  191. scalar @bundle,
  192. );
  193. push @content, "\n", h4($speclabel) if ($speclabel);
  194. my @specbundle;
  195. for my $weekdays ( sort keys %{ $data{$category}{$name}{specbundle}{$specbundle}{spec} } ) {
  196. my $specdescription = specdescribe(
  197. $data{$category}{$name}{specbundle}{$specbundle}{spec}{$weekdays}{weekdays},
  198. $data{$category}{$name}{specbundle}{$specbundle}{spec}{$weekdays}{speccomment},
  199. );
  200. push @specbundle, br if (@specbundle);
  201. push @specbundle, "\n", span(
  202. span($specdescription, ":"),
  203. "\t",
  204. span($data{$category}{$name}{specbundle}{$specbundle}{spec}{$weekdays}{spec}),
  205. );
  206. }
  207. # TODO: make simplified html (preferred for Scribus) optional
  208. # push @content, p("\n", @specbundle) if (@specbundle);
  209. push @content, @specbundle if (@specbundle);
  210. }
  211. }
  212. }
  213. #Dumper %data;
  214. #die;
  215. my $writer = HTML::HTML5::Writer->new;
  216. say $writer->document( html(
  217. -lang => 'da',
  218. head(
  219. title($title),
  220. Meta(-charset => 'utf-8'),
  221. ),
  222. body(
  223. "\n", @content
  224. ),
  225. ));
  226. # create query object from curied SPARQL string
  227. sub qurie {
  228. my $sparql = shift;
  229. $sparql =~ s/(?<=\s|\^)([a-z]+):([a-zA-Z]+)(?=\s)/curie("$1_$2")/eg;
  230. my $query = RDF::Query->new( $sparql );
  231. if (!$query) {
  232. say STDERR $sparql;
  233. say STDERR RDF::Query->error;
  234. croak "failed to prepare SPARQL query";
  235. }
  236. return $query;
  237. }
  238. sub daterangedescribe {
  239. my ($from, $through) = @_;
  240. return sprintf( '%s - %s',
  241. $from->format_cldr('d/M'),
  242. $through->format_cldr('d/M'),
  243. );
  244. }
  245. sub categorydescribe {
  246. my $cat = shift;
  247. $cat =~ s/restaurant/spisesteder/;
  248. $cat =~ s/groceries/dagligvarer/;
  249. $cat =~ s/attraction/attraktioner og museer/;
  250. $cat =~ s/public service/offentlige services/;
  251. return ucfirst($cat);
  252. }
  253. sub titledescribe {
  254. my ($title, $comment) = @_;
  255. return ($comment) ? "$title ($comment)" : $title;
  256. }
  257. sub speclabeldescribe {
  258. my ($label, $comment, $from, $through, $size) = @_;
  259. # TODO: support optionally enabling descriptive label
  260. my $compact = 1;
  261. return '' if ( ($compact) and ( $size == 1 ) );
  262. my $daterange = daterangedescribe($from, $through);
  263. if (($from) and ($through)) {
  264. return titledescribe( $daterange, $comment )
  265. if ($compact);
  266. return $label, ' (', $daterange, ' - ', $comment, ')'
  267. if ($comment);
  268. return $label, ' (', $daterange, ')';
  269. }
  270. warn "gr:validFrom and gr:validThrough missing for label \"$label\"";
  271. return ($compact) ? '' : titledescribe( $label, $comment );
  272. }
  273. sub specdescribe {
  274. my ($weekdays, $comment) = @_;
  275. # TODO: translate properly
  276. $weekdays =~ s/1, 2, 3, 4, 5, 6, 7/alle ugedage/;
  277. $weekdays =~ s/1, 2, 3, 4, 5/mandag-fredag/;
  278. $weekdays =~ s/1, 2, 3, 4/mandag-torsdag/;
  279. $weekdays =~ s/2, 3, 4, 5, 6, 7/tirsdag-søndag/;
  280. $weekdays =~ s/3, 4, 5/onsdag-fredag/;
  281. $weekdays =~ s/^2, 3, 4(|, [^5].*)$/tirsdag-torsdag$1/;
  282. $weekdays =~ s/^(|.*?[\d^5], |.*?(?!fredag, ))6, 7(.*)$/$1weekend$2/;
  283. $weekdays =~ s/1/mandag/;
  284. $weekdays =~ s/2/tirsdag/;
  285. $weekdays =~ s/3/onsdag/;
  286. $weekdays =~ s/4/torsdag/;
  287. $weekdays =~ s/5/fredag/;
  288. $weekdays =~ s/6/lørdag/;
  289. $weekdays =~ s/7/søndag/;
  290. $weekdays =~ s/8/helligdage/;
  291. if ( $weekdays eq "0" and ($comment) ) {
  292. return $comment;
  293. }
  294. return titledescribe( $weekdays, $comment );
  295. }
  296. 1;