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.
 
 
 
 

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