No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

347 líneas
10 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. import argparse
  18. import sys
  19. import os.path
  20. from babel.dates import format_date
  21. from kosmorrolib import Position, get_ephemerides, get_events, get_moon_phase
  22. from kosmorrolib.exceptions import OutOfRangeDateError
  23. from datetime import date
  24. from . import dumper, environment, debug
  25. from .date import parse_date
  26. from .geolocation import get_position
  27. from .utils import (
  28. KOSMORRO_VERSION,
  29. KOSMORROLIB_VERSION,
  30. colored,
  31. set_colors_activated,
  32. print_stderr,
  33. )
  34. from .exceptions import (
  35. InvalidOutputFormatError,
  36. UnavailableFeatureError,
  37. OutOfRangeDateError as DateRangeError,
  38. )
  39. from kosmorro.i18n.utils import _
  40. def run():
  41. env_vars = environment.get_env_vars()
  42. output_formats = get_dumpers()
  43. args = get_args(list(output_formats.keys()))
  44. debug.show_debug_messages = args.show_debug_messages
  45. output_format = args.format
  46. set_colors_activated(args.colors)
  47. if args.special_action is not None:
  48. return 0 if args.special_action() else 1
  49. try:
  50. compute_date = parse_date(args.date)
  51. except ValueError as error:
  52. print_stderr(colored(error.args[0], color="red", attrs=["bold"]))
  53. return -1
  54. position = None
  55. if args.position not in [None, ""]:
  56. position = get_position(args.position)
  57. elif env_vars.position not in [None, ""]:
  58. position = get_position(env_vars.position)
  59. # if output format is not specified, try to use output file extension as output format
  60. if args.output is not None and output_format is None:
  61. file_extension = os.path.splitext(args.output)[-1][1:].lower()
  62. if file_extension:
  63. output_format = file_extension
  64. # default to .txt if output format was not given and output file did not have file extension
  65. if output_format is None:
  66. output_format = "txt"
  67. if output_format == "pdf":
  68. print(
  69. _(
  70. "Save the planet and paper!\n"
  71. "Consider printing your PDF document only if really necessary, and use the other side of the sheet."
  72. )
  73. )
  74. if position is None:
  75. print_stderr(
  76. colored(
  77. _(
  78. "PDF output will not contain the ephemerides, because you didn't provide the observation "
  79. "coordinates."
  80. ),
  81. "yellow",
  82. )
  83. )
  84. timezone = args.timezone
  85. if timezone is None and env_vars.timezone is not None:
  86. timezone = int(env_vars.timezone)
  87. elif timezone is None:
  88. timezone = 0
  89. try:
  90. use_colors = not environment.NO_COLOR and args.colors
  91. output = get_information(
  92. compute_date,
  93. position,
  94. timezone,
  95. output_format,
  96. use_colors,
  97. args.show_graph,
  98. )
  99. except InvalidOutputFormatError as error:
  100. print_stderr(colored(error.msg, "red"))
  101. debug.debug_print(error)
  102. return 3
  103. except UnavailableFeatureError as error:
  104. print_stderr(colored(error.msg, "red"))
  105. debug.debug_print(error)
  106. return 2
  107. except DateRangeError as error:
  108. print_stderr(colored(error.msg, "red"))
  109. debug.debug_print(error)
  110. return 1
  111. if args.output is not None:
  112. try:
  113. file_content = output.to_string()
  114. opening_mode = get_opening_mode(output_format)
  115. with open(args.output, opening_mode) as output_file:
  116. output_file.write(file_content)
  117. except UnavailableFeatureError as error:
  118. print_stderr(colored(error.msg, "red"))
  119. debug.debug_print(error)
  120. return 2
  121. except OSError as error:
  122. print_stderr(
  123. colored(
  124. _('The file could not be saved in "{path}": {error}').format(
  125. path=args.output, error=error.strerror
  126. ),
  127. "red",
  128. )
  129. )
  130. debug.debug_print(error)
  131. return 3
  132. elif not output.is_file_output_needed():
  133. print(output)
  134. else:
  135. print_stderr(
  136. colored(
  137. _("Please provide a file path to export in this format (--output)."),
  138. color="red",
  139. )
  140. )
  141. return 1
  142. return 0
  143. def get_information(
  144. compute_date: date,
  145. position: Position,
  146. timezone: int,
  147. output_format: str,
  148. colors: bool,
  149. show_graph: bool,
  150. ) -> dumper.Dumper:
  151. try:
  152. if position is not None:
  153. eph = get_ephemerides(
  154. for_date=compute_date, position=position, timezone=timezone
  155. )
  156. else:
  157. eph = []
  158. try:
  159. moon_phase = get_moon_phase(for_date=compute_date, timezone=timezone)
  160. except OutOfRangeDateError as error:
  161. moon_phase = None
  162. print_stderr(
  163. colored(
  164. _(
  165. "Moon phase can only be computed between {min_date} and {max_date}"
  166. ).format(
  167. min_date=format_date(error.min_date, "long"),
  168. max_date=format_date(error.max_date, "long"),
  169. ),
  170. "yellow",
  171. )
  172. )
  173. events_list = get_events(compute_date, timezone)
  174. return get_dumpers()[output_format](
  175. ephemerides=eph,
  176. moon_phase=moon_phase,
  177. events=events_list,
  178. date=compute_date,
  179. timezone=timezone,
  180. with_colors=colors,
  181. show_graph=show_graph,
  182. )
  183. except KeyError as error:
  184. raise InvalidOutputFormatError(output_format, list(get_dumpers().keys()))
  185. except OutOfRangeDateError as error:
  186. raise DateRangeError(error.min_date, error.max_date)
  187. def get_dumpers() -> {str: dumper.Dumper}:
  188. return {
  189. "txt": dumper.TextDumper,
  190. "json": dumper.JsonDumper,
  191. "pdf": dumper.PdfDumper,
  192. "tex": dumper.LatexDumper,
  193. }
  194. def get_opening_mode(format: str) -> str:
  195. if format == "pdf":
  196. return "wb"
  197. return "w"
  198. def output_version() -> bool:
  199. python_version = "%d.%d.%d" % (
  200. sys.version_info[0],
  201. sys.version_info[1],
  202. sys.version_info[2],
  203. )
  204. print("Kosmorro %s" % KOSMORRO_VERSION)
  205. print(
  206. _(
  207. "Running on Python {python_version} "
  208. "with Kosmorrolib v{kosmorrolib_version}"
  209. ).format(python_version=python_version, kosmorrolib_version=KOSMORROLIB_VERSION)
  210. )
  211. return True
  212. def get_args(output_formats: [str]):
  213. today = date.today()
  214. parser = argparse.ArgumentParser(
  215. description=_(
  216. "Compute the ephemerides and the events for a given date and a given position on Earth."
  217. ),
  218. epilog=_(
  219. "By default, only the events will be computed for today.\n"
  220. "To compute also the ephemerides, latitude and longitude arguments are needed."
  221. ),
  222. )
  223. parser.add_argument(
  224. "--version",
  225. "-v",
  226. dest="special_action",
  227. action="store_const",
  228. const=output_version,
  229. default=None,
  230. help=_("Show the program version"),
  231. )
  232. parser.add_argument(
  233. "--format",
  234. "-f",
  235. type=str,
  236. default=None,
  237. choices=output_formats,
  238. help=_(
  239. "The format to output the information to. If not provided, the output format "
  240. "will be inferred from the file extension of the output file."
  241. ),
  242. )
  243. parser.add_argument(
  244. "--position",
  245. "-p",
  246. type=str,
  247. default=None,
  248. help=_(
  249. 'The observer\'s position on Earth, in the "{latitude},{longitude}" format. '
  250. "Can also be set in the KOSMORRO_POSITION environment variable."
  251. ),
  252. )
  253. parser.add_argument(
  254. "--date",
  255. "-d",
  256. type=str,
  257. default=today.strftime("%Y-%m-%d"),
  258. help=_(
  259. "The date for which the ephemerides must be calculated. Can be in the YYYY-MM-DD format "
  260. 'or an interval in the "[+-]YyMmDd" format (with Y, M, and D numbers). '
  261. "Defaults to current date."
  262. ).format(default_date=today.strftime("%Y-%m-%d")),
  263. )
  264. parser.add_argument(
  265. "--timezone",
  266. "-t",
  267. type=int,
  268. default=None,
  269. help=_(
  270. "The timezone to display the hours in (e.g. 2 for UTC+2 or -3 for UTC-3). "
  271. "Can also be set in the KOSMORRO_TIMEZONE environment variable."
  272. ),
  273. )
  274. parser.add_argument(
  275. "--no-colors",
  276. dest="colors",
  277. action="store_false",
  278. help=_("Disable the colors in the console."),
  279. )
  280. parser.add_argument(
  281. "--output",
  282. "-o",
  283. type=str,
  284. default=None,
  285. help=_(
  286. "A file to export the output to. If not given, the standard output is used. "
  287. "This argument is needed for PDF format."
  288. ),
  289. )
  290. parser.add_argument(
  291. "--no-graph",
  292. dest="show_graph",
  293. action="store_false",
  294. help=_(
  295. "Do not generate a graph to represent the rise and set times in the PDF format."
  296. ),
  297. )
  298. parser.add_argument(
  299. "--debug",
  300. dest="show_debug_messages",
  301. action="store_true",
  302. help=_("Show debugging messages"),
  303. )
  304. return parser.parse_args()
  305. def main():
  306. sys.exit(run())