Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

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