Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. #!/usr/bin/env python3
  2. # Kosmorro - Compute The Next Ephemerides
  3. # Copyright (C) 2019 Jérôme Deuchnord <jerome@deuchnord.fr>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. from abc import ABC, abstractmethod
  18. import datetime
  19. import json
  20. import os
  21. import tempfile
  22. import subprocess
  23. import shutil
  24. from pathlib import Path
  25. from tabulate import tabulate
  26. from termcolor import colored
  27. from .data import ASTERS, AsterEphemerides, MoonPhase, Event
  28. from .i18n import _, FULL_DATE_FORMAT, SHORT_DATETIME_FORMAT, TIME_FORMAT
  29. from .version import VERSION
  30. from .exceptions import UnavailableFeatureError, CompileError
  31. class Dumper(ABC):
  32. def __init__(self, ephemerides: [AsterEphemerides] = None, moon_phase: MoonPhase = None, events: [Event] = None,
  33. date: datetime.date = datetime.date.today(), timezone: int = 0, with_colors: bool = True,
  34. show_graph: bool = False):
  35. self.ephemerides = ephemerides
  36. self.moon_phase = moon_phase
  37. self.events = events
  38. self.date = date
  39. self.timezone = timezone
  40. self.with_colors = with_colors
  41. self.show_graph = show_graph
  42. def get_date_as_string(self, capitalized: bool = False) -> str:
  43. date = self.date.strftime(FULL_DATE_FORMAT)
  44. if capitalized:
  45. return ''.join([date[0].upper(), date[1:]])
  46. return date
  47. def __str__(self):
  48. return self.to_string()
  49. @abstractmethod
  50. def to_string(self):
  51. pass
  52. @staticmethod
  53. def is_file_output_needed() -> bool:
  54. return False
  55. class JsonDumper(Dumper):
  56. def to_string(self):
  57. return json.dumps({
  58. 'ephemerides': [ephemeris.serialize() for ephemeris in self.ephemerides],
  59. 'moon_phase': self.moon_phase.serialize(),
  60. 'events': [event.serialize() for event in self.events]
  61. }, indent=4)
  62. class TextDumper(Dumper):
  63. def to_string(self):
  64. text = [self.style(self.get_date_as_string(capitalized=True), 'h1')]
  65. if self.ephemerides is not None:
  66. text.append(self.stringify_ephemerides())
  67. text.append(self.get_moon(self.moon_phase))
  68. if len(self.events) > 0:
  69. text.append('\n'.join([self.style(_('Expected events:'), 'h2'),
  70. self.get_events(self.events)]))
  71. if self.timezone == 0:
  72. text.append(self.style(_('Note: All the hours are given in UTC.'), 'em'))
  73. else:
  74. tz_offset = str(self.timezone)
  75. if self.timezone > 0:
  76. tz_offset = ''.join(['+', tz_offset])
  77. text.append(self.style(_('Note: All the hours are given in the UTC{offset} timezone.').format(
  78. offset=tz_offset), 'em'))
  79. return '\n\n'.join(text)
  80. def style(self, text: str, tag: str) -> str:
  81. if not self.with_colors:
  82. return text
  83. styles = {
  84. 'h1': lambda t: colored(t, 'yellow', attrs=['bold']),
  85. 'h2': lambda t: colored(t, 'magenta', attrs=['bold']),
  86. 'th': lambda t: colored(t, 'white', attrs=['bold']),
  87. 'strong': lambda t: colored(t, attrs=['bold']),
  88. 'em': lambda t: colored(t, attrs=['dark'])
  89. }
  90. return styles[tag](text)
  91. def stringify_ephemerides(self) -> str:
  92. data = []
  93. for ephemeris in self.ephemerides:
  94. name = self.style(ephemeris.object.name, 'th')
  95. if ephemeris.rise_time is not None:
  96. time_fmt = TIME_FORMAT if ephemeris.rise_time.day == self.date.day else SHORT_DATETIME_FORMAT
  97. planet_rise = ephemeris.rise_time.strftime(time_fmt)
  98. else:
  99. planet_rise = '-'
  100. if ephemeris.culmination_time is not None:
  101. time_fmt = TIME_FORMAT if ephemeris.culmination_time.day == self.date.day \
  102. else SHORT_DATETIME_FORMAT
  103. planet_culmination = ephemeris.culmination_time.strftime(time_fmt)
  104. else:
  105. planet_culmination = '-'
  106. if ephemeris.set_time is not None:
  107. time_fmt = TIME_FORMAT if ephemeris.set_time.day == self.date.day else SHORT_DATETIME_FORMAT
  108. planet_set = ephemeris.set_time.strftime(time_fmt)
  109. else:
  110. planet_set = '-'
  111. data.append([name, planet_rise, planet_culmination, planet_set])
  112. return tabulate(data, headers=[self.style(_('Object'), 'th'),
  113. self.style(_('Rise time'), 'th'),
  114. self.style(_('Culmination time'), 'th'),
  115. self.style(_('Set time'), 'th')],
  116. tablefmt='simple', stralign='center', colalign=('left',))
  117. def get_events(self, events: [Event]) -> str:
  118. data = []
  119. for event in events:
  120. time_fmt = TIME_FORMAT if event.start_time.day == self.date.day else SHORT_DATETIME_FORMAT
  121. data.append([self.style(event.start_time.strftime(time_fmt), 'th'),
  122. event.get_description()])
  123. return tabulate(data, tablefmt='plain', stralign='left')
  124. def get_moon(self, moon_phase: MoonPhase) -> str:
  125. if moon_phase is None:
  126. return _('Moon phase is unavailable for this date.')
  127. current_moon_phase = ' '.join([self.style(_('Moon phase:'), 'strong'), moon_phase.phase_type.value])
  128. new_moon_phase = _('{next_moon_phase} on {next_moon_phase_date} at {next_moon_phase_time}').format(
  129. next_moon_phase=moon_phase.get_next_phase().value,
  130. next_moon_phase_date=moon_phase.next_phase_date.strftime(FULL_DATE_FORMAT),
  131. next_moon_phase_time=moon_phase.next_phase_date.strftime(TIME_FORMAT)
  132. )
  133. return '\n'.join([current_moon_phase, new_moon_phase])
  134. class _LatexDumper(Dumper):
  135. def to_string(self):
  136. template_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
  137. 'assets', 'pdf', 'template.tex')
  138. with open(template_path, mode='r') as file:
  139. template = file.read()
  140. return self._make_document(template)
  141. def _make_document(self, template: str) -> str:
  142. kosmorro_logo_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
  143. 'assets', 'png', 'kosmorro-logo.png')
  144. moon_phase_graphics = os.path.join(os.path.abspath(os.path.dirname(__file__)),
  145. 'assets', 'moonphases', 'png',
  146. '.'.join([self.moon_phase.phase_type.name.lower().replace('_', '-'),
  147. 'png']))
  148. document = template
  149. if self.ephemerides is None:
  150. document = self._remove_section(document, 'ephemerides')
  151. if len(self.events) == 0:
  152. document = self._remove_section(document, 'events')
  153. document = self.add_strings(document, kosmorro_logo_path, moon_phase_graphics)
  154. if self.show_graph:
  155. # The graphephemerides environment beginning tag must end with a percent symbol to ensure
  156. # that no extra space will interfere with the graph.
  157. document = document.replace(r'\begin{ephemerides}', r'\begin{graphephemerides}%')\
  158. .replace(r'\end{ephemerides}', r'\end{graphephemerides}')
  159. return document
  160. def add_strings(self, document, kosmorro_logo_path, moon_phase_graphics) -> str:
  161. document = document \
  162. .replace('+++KOSMORRO-VERSION+++', VERSION) \
  163. .replace('+++KOSMORRO-LOGO+++', kosmorro_logo_path) \
  164. .replace('+++DOCUMENT-TITLE+++', _('A Summary of your Sky')) \
  165. .replace('+++DOCUMENT-DATE+++', self.get_date_as_string(capitalized=True)) \
  166. .replace('+++INTRODUCTION+++',
  167. '\n\n'.join([
  168. _("This document summarizes the ephemerides and the events of {date}. "
  169. "It aims to help you to prepare your observation session. "
  170. "All the hours are given in {timezone}.").format(
  171. date=self.get_date_as_string(),
  172. timezone='UTC+%d' % self.timezone if self.timezone != 0 else 'UTC'
  173. ),
  174. _("Don't forget to check the weather forecast before you go out with your equipment.")
  175. ])) \
  176. .replace('+++SECTION-EPHEMERIDES+++', _('Ephemerides of the day')) \
  177. .replace('+++EPHEMERIDES-OBJECT+++', _('Object')) \
  178. .replace('+++EPHEMERIDES-RISE-TIME+++', _('Rise time')) \
  179. .replace('+++EPHEMERIDES-CULMINATION-TIME+++', _('Culmination time')) \
  180. .replace('+++EPHEMERIDES-SET-TIME+++', _('Set time')) \
  181. .replace('+++EPHEMERIDES+++', self._make_ephemerides()) \
  182. .replace('+++GRAPH_LABEL_HOURS+++', _('hours')) \
  183. .replace('+++MOON-PHASE-GRAPHICS+++', moon_phase_graphics) \
  184. .replace('+++CURRENT-MOON-PHASE-TITLE+++', _('Moon phase:')) \
  185. .replace('+++CURRENT-MOON-PHASE+++', self.moon_phase.phase_type.value) \
  186. .replace('+++SECTION-EVENTS+++', _('Expected events')) \
  187. .replace('+++EVENTS+++', self._make_events())
  188. for aster in ASTERS:
  189. document = document.replace('+++ASTER_%s+++' % aster.skyfield_name.upper().split(' ')[0],
  190. aster.name)
  191. return document
  192. def _make_ephemerides(self) -> str:
  193. latex = []
  194. graph_y_component = 18
  195. if self.ephemerides is not None:
  196. for ephemeris in self.ephemerides:
  197. if ephemeris.rise_time is not None:
  198. time_fmt = TIME_FORMAT if ephemeris.rise_time.day == self.date.day else SHORT_DATETIME_FORMAT
  199. aster_rise = ephemeris.rise_time.strftime(time_fmt)
  200. else:
  201. aster_rise = '-'
  202. if ephemeris.culmination_time is not None:
  203. time_fmt = TIME_FORMAT if ephemeris.culmination_time.day == self.date.day\
  204. else SHORT_DATETIME_FORMAT
  205. aster_culmination = ephemeris.culmination_time.strftime(time_fmt)
  206. else:
  207. aster_culmination = '-'
  208. if ephemeris.set_time is not None:
  209. time_fmt = TIME_FORMAT if ephemeris.set_time.day == self.date.day else SHORT_DATETIME_FORMAT
  210. aster_set = ephemeris.set_time.strftime(time_fmt)
  211. else:
  212. aster_set = '-'
  213. if not self.show_graph:
  214. latex.append(r'\object{%s}{%s}{%s}{%s}' % (ephemeris.object.name,
  215. aster_rise,
  216. aster_culmination,
  217. aster_set))
  218. else:
  219. if ephemeris.rise_time is not None:
  220. raise_hour = ephemeris.rise_time.hour
  221. raise_minute = ephemeris.rise_time.minute
  222. else:
  223. raise_hour = raise_minute = 0
  224. aster_rise = ''
  225. if ephemeris.set_time is not None:
  226. set_hour = ephemeris.set_time.hour
  227. set_minute = ephemeris.set_time.minute
  228. else:
  229. set_hour = 24
  230. set_minute = 0
  231. aster_set = ''
  232. sets_after_end = set_hour > raise_hour
  233. if not sets_after_end:
  234. latex.append(r'\graphobject{%d}{gray}{0}{0}{%d}{%d}{}{%s}' % (graph_y_component,
  235. set_hour,
  236. set_minute,
  237. aster_set))
  238. set_hour = 24
  239. set_minute = 0
  240. latex.append(r'\graphobject{%d}{gray}{%d}{%d}{%d}{%d}{%s}{%s}' % (
  241. graph_y_component,
  242. raise_hour,
  243. raise_minute,
  244. set_hour,
  245. set_minute,
  246. aster_rise,
  247. aster_set if sets_after_end else ''
  248. ))
  249. graph_y_component -= 2
  250. return ''.join(latex)
  251. def _make_events(self) -> str:
  252. latex = []
  253. for event in self.events:
  254. latex.append(r'\event{%s}{%s}' % (event.start_time.strftime(TIME_FORMAT),
  255. event.get_description()))
  256. return ''.join(latex)
  257. @staticmethod
  258. def _remove_section(document: str, section: str):
  259. begin_section_tag = '%%%%%% BEGIN-%s-SECTION' % section.upper()
  260. end_section_tag = '%%%%%% END-%s-SECTION' % section.upper()
  261. document = document.split('\n')
  262. new_document = []
  263. ignore_line = False
  264. for line in document:
  265. if begin_section_tag in line or end_section_tag in line:
  266. ignore_line = not ignore_line
  267. continue
  268. if ignore_line:
  269. continue
  270. new_document.append(line)
  271. return '\n'.join(new_document)
  272. class PdfDumper(Dumper):
  273. def to_string(self):
  274. try:
  275. latex_dumper = _LatexDumper(self.ephemerides, self.moon_phase, self.events,
  276. date=self.date, timezone=self.timezone, with_colors=self.with_colors,
  277. show_graph=self.show_graph)
  278. return self._compile(latex_dumper.to_string())
  279. except CompileError as error:
  280. raise UnavailableFeatureError from error
  281. except RuntimeError as error:
  282. raise UnavailableFeatureError(_("Building PDFs was not possible, because some dependencies are not"
  283. " installed.\nPlease look at the documentation at http://kosmorro.space "
  284. "for more information.")) from error
  285. @staticmethod
  286. def is_file_output_needed() -> bool:
  287. return True
  288. @staticmethod
  289. def _compile(latex_input) -> bytes:
  290. package = str(Path(__file__).parent.absolute()) + '/assets/pdf/kosmorro.sty'
  291. with tempfile.TemporaryDirectory() as tempdir:
  292. timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
  293. shutil.copy(package, tempdir)
  294. with open('%s/%s.tex' % (tempdir, timestamp), 'w') as texfile:
  295. texfile.write(latex_input)
  296. os.chdir(tempdir)
  297. try:
  298. subprocess.run(['pdflatex', '-interaction', 'nonstopmode', '%s.tex' % timestamp],
  299. capture_output=True, check=True)
  300. except FileNotFoundError as error:
  301. raise RuntimeError('pdflatex is not installed.') from error
  302. except subprocess.CalledProcessError as error:
  303. with open('/tmp/kosmorro-%s.log' % timestamp, 'wb') as file:
  304. file.write(error.stdout)
  305. raise CompileError(_('An error occured during the compilation of the PDF.\n'
  306. 'Please open an issue at https://github.com/Kosmorro/kosmorro/issues and share '
  307. 'the content of the log file at /tmp/kosmorro-%s.log' % timestamp)) from error
  308. with open('%s.pdf' % timestamp, 'rb') as pdffile:
  309. return bytes(pdffile.read())