Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

368 řádky
15 KiB

  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. from pathlib import Path
  22. from tabulate import tabulate
  23. from termcolor import colored
  24. from .data import ASTERS, AsterEphemerides, MoonPhase, Event
  25. from .i18n import _, FULL_DATE_FORMAT, SHORT_DATETIME_FORMAT, TIME_FORMAT
  26. from .version import VERSION
  27. from .exceptions import UnavailableFeatureError
  28. try:
  29. from latex import build_pdf
  30. except ImportError:
  31. build_pdf = None
  32. class Dumper(ABC):
  33. def __init__(self, ephemerides: [AsterEphemerides] = None, moon_phase: MoonPhase = None, events: [Event] = None,
  34. date: datetime.date = datetime.date.today(), timezone: int = 0, with_colors: bool = True,
  35. show_graph: bool = False):
  36. self.ephemerides = ephemerides
  37. self.moon_phase = moon_phase
  38. self.events = events
  39. self.date = date
  40. self.timezone = timezone
  41. self.with_colors = with_colors
  42. self.show_graph = show_graph
  43. def get_date_as_string(self, capitalized: bool = False) -> str:
  44. date = self.date.strftime(FULL_DATE_FORMAT)
  45. if capitalized:
  46. return ''.join([date[0].upper(), date[1:]])
  47. return date
  48. def __str__(self):
  49. return self.to_string()
  50. @abstractmethod
  51. def to_string(self):
  52. pass
  53. @staticmethod
  54. def is_file_output_needed() -> bool:
  55. return False
  56. class JsonDumper(Dumper):
  57. def to_string(self):
  58. return json.dumps({
  59. 'ephemerides': [ephemeris.serialize() for ephemeris in self.ephemerides],
  60. 'moon_phase': self.moon_phase.serialize(),
  61. 'events': [event.serialize() for event in self.events]
  62. }, indent=4)
  63. class TextDumper(Dumper):
  64. def to_string(self):
  65. text = [self.style(self.get_date_as_string(capitalized=True), 'h1')]
  66. if self.ephemerides is not None:
  67. text.append(self.stringify_ephemerides())
  68. text.append(self.get_moon(self.moon_phase))
  69. if len(self.events) > 0:
  70. text.append('\n'.join([self.style(_('Expected events:'), 'h2'),
  71. self.get_events(self.events)]))
  72. if self.timezone == 0:
  73. text.append(self.style(_('Note: All the hours are given in UTC.'), 'em'))
  74. else:
  75. tz_offset = str(self.timezone)
  76. if self.timezone > 0:
  77. tz_offset = ''.join(['+', tz_offset])
  78. text.append(self.style(_('Note: All the hours are given in the UTC{offset} timezone.').format(
  79. offset=tz_offset), 'em'))
  80. return '\n\n'.join(text)
  81. def style(self, text: str, tag: str) -> str:
  82. if not self.with_colors:
  83. return text
  84. styles = {
  85. 'h1': lambda t: colored(t, 'yellow', attrs=['bold']),
  86. 'h2': lambda t: colored(t, 'magenta', attrs=['bold']),
  87. 'th': lambda t: colored(t, 'white', attrs=['bold']),
  88. 'strong': lambda t: colored(t, attrs=['bold']),
  89. 'em': lambda t: colored(t, attrs=['dark'])
  90. }
  91. return styles[tag](text)
  92. def stringify_ephemerides(self) -> str:
  93. data = []
  94. for ephemeris in self.ephemerides:
  95. name = self.style(ephemeris.object.name, 'th')
  96. if ephemeris.rise_time is not None:
  97. time_fmt = TIME_FORMAT if ephemeris.rise_time.day == self.date.day else SHORT_DATETIME_FORMAT
  98. planet_rise = ephemeris.rise_time.strftime(time_fmt)
  99. else:
  100. planet_rise = '-'
  101. if ephemeris.culmination_time is not None:
  102. time_fmt = TIME_FORMAT if ephemeris.culmination_time.day == self.date.day \
  103. else SHORT_DATETIME_FORMAT
  104. planet_culmination = ephemeris.culmination_time.strftime(time_fmt)
  105. else:
  106. planet_culmination = '-'
  107. if ephemeris.set_time is not None:
  108. time_fmt = TIME_FORMAT if ephemeris.set_time.day == self.date.day else SHORT_DATETIME_FORMAT
  109. planet_set = ephemeris.set_time.strftime(time_fmt)
  110. else:
  111. planet_set = '-'
  112. data.append([name, planet_rise, planet_culmination, planet_set])
  113. return tabulate(data, headers=[self.style(_('Object'), 'th'),
  114. self.style(_('Rise time'), 'th'),
  115. self.style(_('Culmination time'), 'th'),
  116. self.style(_('Set time'), 'th')],
  117. tablefmt='simple', stralign='center', colalign=('left',))
  118. def get_events(self, events: [Event]) -> str:
  119. data = []
  120. for event in events:
  121. time_fmt = TIME_FORMAT if event.start_time.day == self.date.day else SHORT_DATETIME_FORMAT
  122. data.append([self.style(event.start_time.strftime(time_fmt), 'th'),
  123. event.get_description()])
  124. return tabulate(data, tablefmt='plain', stralign='left')
  125. def get_moon(self, moon_phase: MoonPhase) -> str:
  126. if moon_phase is None:
  127. return _('Moon phase is unavailable for this date.')
  128. current_moon_phase = ' '.join([self.style(_('Moon phase:'), 'strong'), moon_phase.get_phase()])
  129. new_moon_phase = _('{next_moon_phase} on {next_moon_phase_date} at {next_moon_phase_time}').format(
  130. next_moon_phase=moon_phase.get_next_phase_name(),
  131. next_moon_phase_date=moon_phase.next_phase_date.strftime(FULL_DATE_FORMAT),
  132. next_moon_phase_time=moon_phase.next_phase_date.strftime(TIME_FORMAT)
  133. )
  134. return '\n'.join([current_moon_phase, new_moon_phase])
  135. class _LatexDumper(Dumper):
  136. def to_string(self):
  137. template_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
  138. 'assets', 'pdf', 'template.tex')
  139. with open(template_path, mode='r') as file:
  140. template = file.read()
  141. return self._make_document(template)
  142. def _make_document(self, template: str) -> str:
  143. kosmorro_logo_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
  144. 'assets', 'png', 'kosmorro-logo.png')
  145. if self.moon_phase is None:
  146. self.moon_phase = MoonPhase('UNKNOWN')
  147. moon_phase_graphics = os.path.join(os.path.abspath(os.path.dirname(__file__)),
  148. 'assets', 'moonphases', 'png',
  149. '.'.join([self.moon_phase.identifier.lower().replace('_', '-'),
  150. 'png']))
  151. document = template
  152. if self.ephemerides is None:
  153. document = self._remove_section(document, 'ephemerides')
  154. if len(self.events) == 0:
  155. document = self._remove_section(document, 'events')
  156. document = self.add_strings(document, kosmorro_logo_path, moon_phase_graphics)
  157. if self.show_graph:
  158. # The graphephemerides environment beginning tag must end with a percent symbol to ensure
  159. # that no extra space will interfere with the graph.
  160. document = document.replace(r'\begin{ephemerides}', r'\begin{graphephemerides}%')\
  161. .replace(r'\end{ephemerides}', r'\end{graphephemerides}')
  162. return document
  163. def add_strings(self, document, kosmorro_logo_path, moon_phase_graphics) -> str:
  164. document = document \
  165. .replace('+++KOSMORRO-VERSION+++', VERSION) \
  166. .replace('+++KOSMORRO-LOGO+++', kosmorro_logo_path) \
  167. .replace('+++DOCUMENT-TITLE+++', _('A Summary of your Sky')) \
  168. .replace('+++DOCUMENT-DATE+++', self.get_date_as_string(capitalized=True)) \
  169. .replace('+++INTRODUCTION+++',
  170. '\n\n'.join([
  171. _("This document summarizes the ephemerides and the events of {date}. "
  172. "It aims to help you to prepare your observation session. "
  173. "All the hours are given in {timezone}.").format(
  174. date=self.get_date_as_string(),
  175. timezone='UTC+%d' % self.timezone if self.timezone != 0 else 'UTC'
  176. ),
  177. _("Don't forget to check the weather forecast before you go out with your equipment.")
  178. ])) \
  179. .replace('+++SECTION-EPHEMERIDES+++', _('Ephemerides of the day')) \
  180. .replace('+++EPHEMERIDES-OBJECT+++', _('Object')) \
  181. .replace('+++EPHEMERIDES-RISE-TIME+++', _('Rise time')) \
  182. .replace('+++EPHEMERIDES-CULMINATION-TIME+++', _('Culmination time')) \
  183. .replace('+++EPHEMERIDES-SET-TIME+++', _('Set time')) \
  184. .replace('+++EPHEMERIDES+++', self._make_ephemerides()) \
  185. .replace('+++GRAPH_LABEL_HOURS+++', _('hours')) \
  186. .replace('+++MOON-PHASE-GRAPHICS+++', moon_phase_graphics) \
  187. .replace('+++CURRENT-MOON-PHASE-TITLE+++', _('Moon phase:')) \
  188. .replace('+++CURRENT-MOON-PHASE+++', self.moon_phase.get_phase()) \
  189. .replace('+++SECTION-EVENTS+++', _('Expected events')) \
  190. .replace('+++EVENTS+++', self._make_events())
  191. for aster in ASTERS:
  192. document = document.replace('+++ASTER_%s+++' % aster.skyfield_name.upper().split(' ')[0],
  193. aster.name)
  194. return document
  195. def _make_ephemerides(self) -> str:
  196. latex = []
  197. graph_y_component = 18
  198. if self.ephemerides is not None:
  199. for ephemeris in self.ephemerides:
  200. if ephemeris.rise_time is not None:
  201. time_fmt = TIME_FORMAT if ephemeris.rise_time.day == self.date.day else SHORT_DATETIME_FORMAT
  202. aster_rise = ephemeris.rise_time.strftime(time_fmt)
  203. else:
  204. aster_rise = '-'
  205. if ephemeris.culmination_time is not None:
  206. time_fmt = TIME_FORMAT if ephemeris.culmination_time.day == self.date.day\
  207. else SHORT_DATETIME_FORMAT
  208. aster_culmination = ephemeris.culmination_time.strftime(time_fmt)
  209. else:
  210. aster_culmination = '-'
  211. if ephemeris.set_time is not None:
  212. time_fmt = TIME_FORMAT if ephemeris.set_time.day == self.date.day else SHORT_DATETIME_FORMAT
  213. aster_set = ephemeris.set_time.strftime(time_fmt)
  214. else:
  215. aster_set = '-'
  216. if not self.show_graph:
  217. latex.append(r'\object{%s}{%s}{%s}{%s}' % (ephemeris.object.name,
  218. aster_rise,
  219. aster_culmination,
  220. aster_set))
  221. else:
  222. if ephemeris.rise_time is not None:
  223. raise_hour = ephemeris.rise_time.hour
  224. raise_minute = ephemeris.rise_time.minute
  225. else:
  226. raise_hour = raise_minute = 0
  227. aster_rise = ''
  228. if ephemeris.set_time is not None:
  229. set_hour = ephemeris.set_time.hour
  230. set_minute = ephemeris.set_time.minute
  231. else:
  232. set_hour = 24
  233. set_minute = 0
  234. aster_set = ''
  235. sets_after_end = set_hour > raise_hour
  236. if not sets_after_end:
  237. latex.append(r'\graphobject{%d}{gray}{0}{0}{%d}{%d}{}{%s}' % (graph_y_component,
  238. set_hour,
  239. set_minute,
  240. aster_set))
  241. set_hour = 24
  242. set_minute = 0
  243. latex.append(r'\graphobject{%d}{gray}{%d}{%d}{%d}{%d}{%s}{%s}' % (
  244. graph_y_component,
  245. raise_hour,
  246. raise_minute,
  247. set_hour,
  248. set_minute,
  249. aster_rise,
  250. aster_set if sets_after_end else ''
  251. ))
  252. graph_y_component -= 2
  253. return ''.join(latex)
  254. def _make_events(self) -> str:
  255. latex = []
  256. for event in self.events:
  257. latex.append(r'\event{%s}{%s}' % (event.start_time.strftime(TIME_FORMAT),
  258. event.get_description()))
  259. return ''.join(latex)
  260. @staticmethod
  261. def _remove_section(document: str, section: str):
  262. begin_section_tag = '%%%%%% BEGIN-%s-SECTION' % section.upper()
  263. end_section_tag = '%%%%%% END-%s-SECTION' % section.upper()
  264. document = document.split('\n')
  265. new_document = []
  266. ignore_line = False
  267. for line in document:
  268. if begin_section_tag in line or end_section_tag in line:
  269. ignore_line = not ignore_line
  270. continue
  271. if ignore_line:
  272. continue
  273. new_document.append(line)
  274. return '\n'.join(new_document)
  275. class PdfDumper(Dumper):
  276. def to_string(self):
  277. try:
  278. latex_dumper = _LatexDumper(self.ephemerides, self.moon_phase, self.events,
  279. date=self.date, timezone=self.timezone, with_colors=self.with_colors,
  280. show_graph=self.show_graph)
  281. return self._compile(latex_dumper.to_string())
  282. except RuntimeError:
  283. raise UnavailableFeatureError(_("Building PDFs was not possible, because some dependencies are not"
  284. " installed.\nPlease look at the documentation at http://kosmorro.space "
  285. "for more information."))
  286. @staticmethod
  287. def is_file_output_needed() -> bool:
  288. return True
  289. @staticmethod
  290. def _compile(latex_input) -> bytes:
  291. if build_pdf is None:
  292. raise RuntimeError('Python latex module not found')
  293. package = str(Path(__file__).parent.absolute()) + '/assets/pdf/'
  294. return bytes(build_pdf(latex_input, [package]))