dronefly-core 0.3.8__tar.gz → 0.3.9.dev1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/LICENSE +8 -0
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/PKG-INFO +4 -5
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/dronefly/core/clients/inat.py +23 -2
- dronefly_core-0.3.9.dev1/dronefly/core/commands/__init__.py +542 -0
- dronefly_core-0.3.9.dev1/dronefly/core/constants.py +41 -0
- dronefly_core-0.3.9.dev1/dronefly/core/formatters/__init__.py +1 -0
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/dronefly/core/formatters/generic.py +275 -98
- dronefly_core-0.3.9.dev1/dronefly/core/menus/__init__.py +3 -0
- dronefly_core-0.3.9.dev1/dronefly/core/menus/menu.py +13 -0
- dronefly_core-0.3.9.dev1/dronefly/core/menus/source.py +348 -0
- dronefly_core-0.3.9.dev1/dronefly/core/menus/taxon_list.py +31 -0
- dronefly_core-0.3.9.dev1/dronefly/core/models/__init__.py +3 -0
- dronefly_core-0.3.9.dev1/dronefly/core/models/config.py +34 -0
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/dronefly/core/parsers/constants.py +16 -4
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/dronefly/core/parsers/natural.py +1 -1
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/dronefly/core/parsers/unixlike.py +5 -0
- dronefly_core-0.3.9.dev1/dronefly/core/query/__init__.py +1 -0
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/dronefly/core/query/query.py +26 -1
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/pyproject.toml +6 -4
- dronefly_core-0.3.8/dronefly/core/commands/__init__.py +0 -304
- dronefly_core-0.3.8/dronefly/core/constants.py +0 -17
- dronefly_core-0.3.8/dronefly/core/formatters/__init__.py +0 -0
- dronefly_core-0.3.8/dronefly/core/models/__init__.py +0 -0
- dronefly_core-0.3.8/dronefly/core/query/__init__.py +0 -1
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/README.md +0 -0
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/dronefly/core/__init__.py +0 -0
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/dronefly/core/clients/__init__.py +0 -0
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/dronefly/core/formatters/constants.py +0 -0
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/dronefly/core/models/controlled_terms.py +0 -0
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/dronefly/core/models/user.py +0 -0
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/dronefly/core/parsers/__init__.py +0 -0
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/dronefly/core/parsers/url.py +0 -0
- {dronefly_core-0.3.8 → dronefly_core-0.3.9.dev1}/dronefly/core/utils/__init__.py +0 -0
|
@@ -12,6 +12,12 @@ Copyright:
|
|
|
12
12
|
2015-2023 Rapptz
|
|
13
13
|
License: AGPL-3+, and MIT
|
|
14
14
|
|
|
15
|
+
Files: dronefly/core/menus/source.py
|
|
16
|
+
Copyright:
|
|
17
|
+
2019-2023 Ben Armstrong
|
|
18
|
+
2015-2022 Rapptz
|
|
19
|
+
License: AGPL-3+, and MIT
|
|
20
|
+
|
|
15
21
|
License: AGPL-3+
|
|
16
22
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
|
17
23
|
Version 3, 19 November 2007
|
|
@@ -1113,8 +1119,10 @@ License: MIT
|
|
|
1113
1119
|
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
1114
1120
|
and/or sell copies of the Software, and to permit persons to whom the
|
|
1115
1121
|
Software is furnished to do so, subject to the following conditions:
|
|
1122
|
+
.
|
|
1116
1123
|
The above copyright notice and this permission notice shall be included in
|
|
1117
1124
|
all copies or substantial portions of the Software.
|
|
1125
|
+
.
|
|
1118
1126
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
1119
1127
|
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
1120
1128
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
@@ -1,21 +1,20 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: dronefly-core
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.9.dev1
|
|
4
4
|
Summary: Core dronefly components
|
|
5
5
|
License: AGPL-3.0-or-later
|
|
6
6
|
Author: Ben Armstrong
|
|
7
7
|
Author-email: synrg@debian.org
|
|
8
|
-
Requires-Python: >=3.
|
|
8
|
+
Requires-Python: >=3.11,<3.13
|
|
9
9
|
Classifier: License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)
|
|
10
10
|
Classifier: Programming Language :: Python :: 3
|
|
11
|
-
Classifier: Programming Language :: Python :: 3.9
|
|
12
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
13
11
|
Classifier: Programming Language :: Python :: 3.11
|
|
14
12
|
Classifier: Programming Language :: Python :: 3.12
|
|
15
13
|
Requires-Dist: dateparser (>=1.1.1,<2.0.0)
|
|
14
|
+
Requires-Dist: filelock (>=3.13.3,<4.0.0)
|
|
16
15
|
Requires-Dist: html2markdown (>=0.1.7,<0.2.0)
|
|
17
16
|
Requires-Dist: inflect (>=5.3.0,<6.0.0)
|
|
18
|
-
Requires-Dist: pyinaturalist (
|
|
17
|
+
Requires-Dist: pyinaturalist (==0.20.0.dev1)
|
|
19
18
|
Requires-Dist: rich (>=13.4)
|
|
20
19
|
Description-Content-Type: text/markdown
|
|
21
20
|
|
|
@@ -1,17 +1,38 @@
|
|
|
1
1
|
"""Module to access iNaturalist API."""
|
|
2
2
|
from contextlib import contextmanager
|
|
3
3
|
from inspect import signature
|
|
4
|
+
import os
|
|
4
5
|
from typing import Optional
|
|
5
6
|
|
|
6
|
-
from pyinaturalist import
|
|
7
|
+
from pyinaturalist import (
|
|
8
|
+
ClientSession,
|
|
9
|
+
FileLockSQLiteBucket,
|
|
10
|
+
iNatClient as pyiNatClient,
|
|
11
|
+
)
|
|
7
12
|
from pyinaturalist.constants import RequestParams
|
|
8
13
|
|
|
9
|
-
from ..constants import INAT_DEFAULTS
|
|
14
|
+
from ..constants import INAT_DEFAULTS, USER_DATA_PATH
|
|
10
15
|
|
|
11
16
|
|
|
12
17
|
class iNatClient(pyiNatClient):
|
|
13
18
|
"""iNat client based on pyinaturalist."""
|
|
14
19
|
|
|
20
|
+
def __init__(self, *args, **kwargs):
|
|
21
|
+
ratelimit_path = os.path.join(USER_DATA_PATH, "ratelimit.db")
|
|
22
|
+
lock_path = os.path.join(USER_DATA_PATH, "ratelimit.lock")
|
|
23
|
+
cache_file = os.path.join(USER_DATA_PATH, "api_requests.db")
|
|
24
|
+
session = ClientSession(
|
|
25
|
+
bucket_class=FileLockSQLiteBucket,
|
|
26
|
+
cache_file=cache_file,
|
|
27
|
+
ratelimit_path=ratelimit_path,
|
|
28
|
+
lock_path=lock_path,
|
|
29
|
+
)
|
|
30
|
+
_kwargs = {
|
|
31
|
+
"session": session,
|
|
32
|
+
**kwargs,
|
|
33
|
+
}
|
|
34
|
+
super().__init__(*args, **_kwargs)
|
|
35
|
+
|
|
15
36
|
def add_client_settings(
|
|
16
37
|
self,
|
|
17
38
|
request_function,
|
|
@@ -0,0 +1,542 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
import re
|
|
3
|
+
from typing import Union
|
|
4
|
+
|
|
5
|
+
from attrs import define
|
|
6
|
+
from requests import HTTPError
|
|
7
|
+
from rich.markdown import Markdown
|
|
8
|
+
|
|
9
|
+
from ..clients.inat import iNatClient
|
|
10
|
+
from ..constants import (
|
|
11
|
+
CONFIG_PATH,
|
|
12
|
+
INAT_DEFAULTS,
|
|
13
|
+
INAT_USER_DEFAULT_PARAMS,
|
|
14
|
+
RANK_EQUIVALENTS,
|
|
15
|
+
RANKS_FOR_LEVEL,
|
|
16
|
+
RANK_KEYWORDS,
|
|
17
|
+
RANK_LEVELS,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
from ..parsers import NaturalParser
|
|
21
|
+
from ..formatters.generic import (
|
|
22
|
+
BaseFormatter,
|
|
23
|
+
TaxonListFormatter,
|
|
24
|
+
ListFormatter,
|
|
25
|
+
ObservationFormatter,
|
|
26
|
+
TaxonFormatter,
|
|
27
|
+
UserFormatter,
|
|
28
|
+
p,
|
|
29
|
+
)
|
|
30
|
+
from ..models.config import Config
|
|
31
|
+
from ..models.user import User
|
|
32
|
+
from ..query.query import get_base_query_args, QueryResponse
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
RICH_BQ_NEWLINE_PAT = re.compile(r"^(\> .*?)\n(?=\> )", re.MULTILINE)
|
|
36
|
+
RICH_BQ_END_PAT = re.compile(r"^((\> .*?\n)+)(?!> )", re.MULTILINE)
|
|
37
|
+
RICH_NO_BQ_NEWLINE_PAT = re.compile(r"^(?!\> )(.+?)(\n)(?!$|\> )", re.MULTILINE)
|
|
38
|
+
RICH_NEWLINE = " \\\n"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ArgumentError(ValueError):
|
|
42
|
+
"""Command arguments are not valid."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class CommandError(NameError):
|
|
46
|
+
"""Command is not known."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Format(Enum):
|
|
50
|
+
discord_markdown = 1
|
|
51
|
+
rich = 2
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@define
|
|
55
|
+
class Context:
|
|
56
|
+
"""A Dronefly command context."""
|
|
57
|
+
|
|
58
|
+
author: User = User()
|
|
59
|
+
# Optional page formatter and current page:
|
|
60
|
+
# - Provides support for next & prev commands to navigate through
|
|
61
|
+
# paged command results.
|
|
62
|
+
# - Every command providing paged results must:
|
|
63
|
+
# - Set page_formatter to the formatter for the new results.
|
|
64
|
+
# - Set page to the initial page number (default: 0).
|
|
65
|
+
# - Therefore, only a single command providing paged results can
|
|
66
|
+
# be active at a time.
|
|
67
|
+
page_formatter: Union[BaseFormatter, ListFormatter] = None
|
|
68
|
+
page: int = 0
|
|
69
|
+
per_page: int = 0
|
|
70
|
+
selected: int = 0
|
|
71
|
+
|
|
72
|
+
def get_inat_user_default(self, inat_param: str):
|
|
73
|
+
"""Return iNat API default for user param default, if any, otherwise global default."""
|
|
74
|
+
if inat_param not in INAT_USER_DEFAULT_PARAMS:
|
|
75
|
+
return None
|
|
76
|
+
default = None
|
|
77
|
+
if self.author:
|
|
78
|
+
default = getattr(self.author, inat_param, None)
|
|
79
|
+
if not default:
|
|
80
|
+
default = INAT_DEFAULTS.get(inat_param)
|
|
81
|
+
return default
|
|
82
|
+
|
|
83
|
+
def get_inat_defaults(self):
|
|
84
|
+
"""Return all iNat API defaults."""
|
|
85
|
+
defaults = {**INAT_DEFAULTS}
|
|
86
|
+
for user_param, inat_param in INAT_USER_DEFAULT_PARAMS.items():
|
|
87
|
+
default = self.get_inat_user_default(user_param)
|
|
88
|
+
if default is not None:
|
|
89
|
+
defaults[inat_param] = default
|
|
90
|
+
return defaults
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# TODO: everything below needs to be broken down into different layers
|
|
94
|
+
# handling each thing:
|
|
95
|
+
# - Context
|
|
96
|
+
# - user, channel, etc.
|
|
97
|
+
# - affects which settings are passed to inat (e.g. home place for conservation status)
|
|
98
|
+
@define
|
|
99
|
+
class Commands:
|
|
100
|
+
"""A Dronefly command processor."""
|
|
101
|
+
|
|
102
|
+
# TODO: platform: dronefly.Platform
|
|
103
|
+
# - e.g. discord, commandline, web
|
|
104
|
+
|
|
105
|
+
inat_client: iNatClient = iNatClient()
|
|
106
|
+
parser: NaturalParser = NaturalParser()
|
|
107
|
+
format: Format = Format.discord_markdown
|
|
108
|
+
config: Config = Config()
|
|
109
|
+
|
|
110
|
+
def _parse(self, query_str):
|
|
111
|
+
return self.parser.parse(query_str)
|
|
112
|
+
|
|
113
|
+
def _get_formatted_page(
|
|
114
|
+
self,
|
|
115
|
+
formatter,
|
|
116
|
+
page: int = 0,
|
|
117
|
+
selected: int = 0,
|
|
118
|
+
header: str = None,
|
|
119
|
+
footer: str = None,
|
|
120
|
+
):
|
|
121
|
+
if getattr(formatter, "format_page", None):
|
|
122
|
+
markdown_text = formatter.format_page(page, selected)
|
|
123
|
+
last_page = formatter.last_page()
|
|
124
|
+
if last_page > 0:
|
|
125
|
+
markdown_text = "\n\n".join(
|
|
126
|
+
[markdown_text, f"Page {page + 1}/{last_page + 1}"]
|
|
127
|
+
)
|
|
128
|
+
else:
|
|
129
|
+
markdown_text = formatter.format()
|
|
130
|
+
if header or footer:
|
|
131
|
+
markdown_text = "\n\n".join(
|
|
132
|
+
[item for item in (header, markdown_text, footer) if item is not None]
|
|
133
|
+
)
|
|
134
|
+
return self._format_markdown(markdown_text)
|
|
135
|
+
|
|
136
|
+
def _format_markdown(self, markdown_text: str):
|
|
137
|
+
"""Format Rich vs. Discord markdown."""
|
|
138
|
+
if self.format == Format.rich:
|
|
139
|
+
# Richify the markdown:
|
|
140
|
+
# - In Discord markdown, all newlines are rendered as line breaks
|
|
141
|
+
# - In Rich:
|
|
142
|
+
# - Before every newline, emit " \" to force a line break, except
|
|
143
|
+
# for these exceptions to handle blockquotes:
|
|
144
|
+
# - Don't do this for a line preceding a blockquote
|
|
145
|
+
# - Also don't do this on the last line of a blockquote
|
|
146
|
+
# - Ensure the last line of each blockquote has two newlines to
|
|
147
|
+
# end it
|
|
148
|
+
|
|
149
|
+
# Replace all but last newline of blockquote with line break sequence:
|
|
150
|
+
rich_markdown = re.sub(RICH_BQ_NEWLINE_PAT, r"\1 \\\n", markdown_text)
|
|
151
|
+
# Add extra newline at end of blockquote so following text won't be
|
|
152
|
+
# tacked on:
|
|
153
|
+
rich_markdown = re.sub(RICH_BQ_END_PAT, r"\1\n\n", rich_markdown)
|
|
154
|
+
# Finally, on any line that isn't part of a blockquote, isn't empty,
|
|
155
|
+
# and isn't at the end of the string, emit a line break:
|
|
156
|
+
rich_markdown = re.sub(RICH_NO_BQ_NEWLINE_PAT, r"\1 \\\n", rich_markdown)
|
|
157
|
+
response = Markdown(rich_markdown)
|
|
158
|
+
else:
|
|
159
|
+
# Return the literal markdown for Discord to render
|
|
160
|
+
response = markdown_text
|
|
161
|
+
return response
|
|
162
|
+
|
|
163
|
+
def _simple_format_markdown(self, markdown_text: str):
|
|
164
|
+
"""Simplified formatter for Rich vs. Discord markdown.
|
|
165
|
+
|
|
166
|
+
Discord vs. Rich linebreak rendering is harder than we thought, e.g.
|
|
167
|
+
`_format_markdown()` doesn't give correct results with point-form
|
|
168
|
+
or numbered lists. If special handling of newlines isn't needed, then
|
|
169
|
+
use this helper instead.
|
|
170
|
+
"""
|
|
171
|
+
if self.format == Format.rich:
|
|
172
|
+
# Richify the markdown
|
|
173
|
+
response = Markdown(markdown_text)
|
|
174
|
+
else:
|
|
175
|
+
# Return the literal markdown for Discord to render
|
|
176
|
+
response = markdown_text
|
|
177
|
+
return response
|
|
178
|
+
|
|
179
|
+
def life(self, ctx: Context, *args):
|
|
180
|
+
_args = " ".join(args) or "by me"
|
|
181
|
+
query = self._parse(_args)
|
|
182
|
+
per_rank = query.per or "main"
|
|
183
|
+
if per_rank not in [*RANK_KEYWORDS, "leaf", "child", "main", "any"]:
|
|
184
|
+
return "Specify `per <rank-or-keyword>`"
|
|
185
|
+
sort_by = query.sort_by or None
|
|
186
|
+
if sort_by not in [None, "obs", "name"]:
|
|
187
|
+
return "Specify `sort by obs` or `sort by name` (default)"
|
|
188
|
+
order = query.order or None
|
|
189
|
+
if order not in [None, "asc", "desc"]:
|
|
190
|
+
return "Specify `order asc` or `order desc`"
|
|
191
|
+
|
|
192
|
+
query_args = get_base_query_args(query)
|
|
193
|
+
with self.inat_client.set_ctx(ctx) as client:
|
|
194
|
+
# Handle a useful subset of query args in a simplistic way for now
|
|
195
|
+
# (i.e. no config table lookup yet) to model full query in bot
|
|
196
|
+
if query.user == "me":
|
|
197
|
+
if ctx.author.inat_user_id:
|
|
198
|
+
query_args["user"] = client.users.from_ids(
|
|
199
|
+
ctx.author.inat_user_id
|
|
200
|
+
).one()
|
|
201
|
+
else:
|
|
202
|
+
return "Your iNat user is not known"
|
|
203
|
+
elif query.user == "any":
|
|
204
|
+
# i.e. override default "by me" when no arguments are given
|
|
205
|
+
pass
|
|
206
|
+
else:
|
|
207
|
+
user = client.users.autocomplete(q=query.user).one()
|
|
208
|
+
if user:
|
|
209
|
+
query_args["user"] = user
|
|
210
|
+
if query and query.main and query.main.terms:
|
|
211
|
+
main_query_str = " ".join(query.main.terms)
|
|
212
|
+
taxon = client.taxa.autocomplete(q=main_query_str).one()
|
|
213
|
+
query_args["taxon"] = taxon
|
|
214
|
+
if query.place:
|
|
215
|
+
place = client.places.autocomplete(q=query.place).one()
|
|
216
|
+
query_args["place"] = place
|
|
217
|
+
if query.project:
|
|
218
|
+
project = client.projects.search(q=query.project).one()
|
|
219
|
+
query_args["project"] = project
|
|
220
|
+
query_response = QueryResponse(**query_args)
|
|
221
|
+
obs_args = query_response.obs_args()
|
|
222
|
+
life_list = client.observations.life_list(**obs_args)
|
|
223
|
+
|
|
224
|
+
if not life_list:
|
|
225
|
+
return f"No life list {query_response.obs_query_description()}"
|
|
226
|
+
|
|
227
|
+
per_page = ctx.per_page
|
|
228
|
+
with_index = self.format == Format.rich
|
|
229
|
+
taxon_list = life_list.data
|
|
230
|
+
formatter = TaxonListFormatter(
|
|
231
|
+
taxon_list,
|
|
232
|
+
per_rank,
|
|
233
|
+
query_response,
|
|
234
|
+
with_indent=True,
|
|
235
|
+
per_page=per_page,
|
|
236
|
+
with_index=with_index,
|
|
237
|
+
sort_by=sort_by,
|
|
238
|
+
order=order,
|
|
239
|
+
)
|
|
240
|
+
ctx.page_formatter = formatter
|
|
241
|
+
ctx.page = 0
|
|
242
|
+
ctx.selected = 0
|
|
243
|
+
title = formatter.format_title()
|
|
244
|
+
first_page = formatter.get_first_page() or ""
|
|
245
|
+
if first_page:
|
|
246
|
+
# TODO: Provide a method in the formatter to set the title:
|
|
247
|
+
formatter.pages[0]["header"] = title
|
|
248
|
+
return self._get_formatted_page(formatter, 0, 0)
|
|
249
|
+
|
|
250
|
+
def taxon_list(self, ctx: Context, *args):
|
|
251
|
+
query = self._parse(" ".join(args))
|
|
252
|
+
per_rank = query.per or "child"
|
|
253
|
+
if per_rank not in [*RANK_KEYWORDS, "child"]:
|
|
254
|
+
return "Specify `per <rank>` or `per child` (default)"
|
|
255
|
+
_per_rank = per_rank
|
|
256
|
+
rank_level = None
|
|
257
|
+
sort_by = query.sort_by or None
|
|
258
|
+
if sort_by not in [None, "obs", "name"]:
|
|
259
|
+
return "Specify `sort by obs` or `sort by name` (default)"
|
|
260
|
+
order = query.order or None
|
|
261
|
+
if order not in [None, "asc", "desc"]:
|
|
262
|
+
return "Specify `order asc` or `order desc`"
|
|
263
|
+
|
|
264
|
+
query_args = get_base_query_args(query)
|
|
265
|
+
taxon = None
|
|
266
|
+
taxon_list = []
|
|
267
|
+
short_description = ""
|
|
268
|
+
msg = None
|
|
269
|
+
with self.inat_client.set_ctx(ctx) as client:
|
|
270
|
+
# Handle a useful subset of query args in a simplistic way for now
|
|
271
|
+
# (i.e. no config table lookup yet) to model full query in bot
|
|
272
|
+
if query and query.main and query.main.terms:
|
|
273
|
+
main_query_str = " ".join(query.main.terms)
|
|
274
|
+
taxon = client.taxa.autocomplete(q=main_query_str).one()
|
|
275
|
+
if taxon:
|
|
276
|
+
taxon = client.taxa.populate(taxon)
|
|
277
|
+
query_args["taxon"] = taxon
|
|
278
|
+
query_response = QueryResponse(**query_args)
|
|
279
|
+
taxon = query_response.taxon
|
|
280
|
+
if not taxon:
|
|
281
|
+
return f"No taxon {query_response.obs_query_description()}"
|
|
282
|
+
|
|
283
|
+
_taxon_list = [
|
|
284
|
+
taxon,
|
|
285
|
+
*[_taxon for _taxon in taxon.children if _taxon.is_active],
|
|
286
|
+
]
|
|
287
|
+
if per_rank == "child":
|
|
288
|
+
short_description = "Children"
|
|
289
|
+
taxon_list = _taxon_list
|
|
290
|
+
else:
|
|
291
|
+
_per_rank = RANK_EQUIVALENTS.get(per_rank) or per_rank
|
|
292
|
+
rank_level = RANK_LEVELS[_per_rank]
|
|
293
|
+
if rank_level >= taxon.rank_level:
|
|
294
|
+
return self._format_markdown(
|
|
295
|
+
"\N{WARNING SIGN} "
|
|
296
|
+
f"**The rank `{per_rank}` is not lower than "
|
|
297
|
+
"the taxon rank: `{taxon.rank}`.**"
|
|
298
|
+
)
|
|
299
|
+
short_description = p.plural(_per_rank).capitalize()
|
|
300
|
+
_children = [
|
|
301
|
+
child for child in _taxon_list if child.rank_level == rank_level
|
|
302
|
+
]
|
|
303
|
+
_without_rank_ids = [
|
|
304
|
+
child.id for child in _taxon_list if child not in _children
|
|
305
|
+
]
|
|
306
|
+
if len(_without_rank_ids) > 0:
|
|
307
|
+
# One chance at retrieving the remaining children, i.e. if the
|
|
308
|
+
# remainder (direct children - those at the specified rank level)
|
|
309
|
+
# don't constitute a single page of results, then show children
|
|
310
|
+
# instead.
|
|
311
|
+
_descendants = client.taxa.search(
|
|
312
|
+
taxon_id=_without_rank_ids,
|
|
313
|
+
rank_level=rank_level,
|
|
314
|
+
is_active=True,
|
|
315
|
+
per_page=500,
|
|
316
|
+
)
|
|
317
|
+
# The choice of 2500 as our limit is arbitrary:
|
|
318
|
+
# - will take 5 more API calls to satisfy
|
|
319
|
+
# - encompasses the largest genera (e.g. Astragalus)
|
|
320
|
+
# - meant to limit unreasonable sized queries so they don't make
|
|
321
|
+
# excessive API demands
|
|
322
|
+
# - TODO: switch to using a local DB built from full taxonomy dump
|
|
323
|
+
# so we can lift this restriction
|
|
324
|
+
if _descendants.count() > 2500:
|
|
325
|
+
short_description = "Children"
|
|
326
|
+
msg = (
|
|
327
|
+
f"\N{WARNING SIGN} **Too many {p.plural(_per_rank)}. "
|
|
328
|
+
"Listing children instead:**"
|
|
329
|
+
)
|
|
330
|
+
_per_rank = "child"
|
|
331
|
+
taxon_list = _taxon_list
|
|
332
|
+
else:
|
|
333
|
+
taxon_list = [*_children, *_descendants.all()]
|
|
334
|
+
else:
|
|
335
|
+
taxon_list = _children
|
|
336
|
+
# List all ranks at the same level, not just the specified rank
|
|
337
|
+
if _per_rank != "child":
|
|
338
|
+
_per_rank = RANKS_FOR_LEVEL[rank_level]
|
|
339
|
+
|
|
340
|
+
per_page = ctx.per_page
|
|
341
|
+
with_index = self.format == Format.rich
|
|
342
|
+
formatter = TaxonListFormatter(
|
|
343
|
+
taxon_list,
|
|
344
|
+
per_rank=_per_rank,
|
|
345
|
+
query_response=query_response,
|
|
346
|
+
with_indent=True,
|
|
347
|
+
per_page=per_page,
|
|
348
|
+
with_index=with_index,
|
|
349
|
+
sort_by=sort_by,
|
|
350
|
+
order=order,
|
|
351
|
+
short_description=short_description,
|
|
352
|
+
)
|
|
353
|
+
ctx.page_formatter = formatter
|
|
354
|
+
ctx.page = 0
|
|
355
|
+
ctx.selected = 0
|
|
356
|
+
title = formatter.format_title()
|
|
357
|
+
first_page = formatter.get_first_page() or ""
|
|
358
|
+
if first_page:
|
|
359
|
+
# TODO: Provide a method in the formatter to set the title:
|
|
360
|
+
formatter.pages[0]["header"] = title
|
|
361
|
+
page = self._get_formatted_page(formatter, 0, 0, header=msg)
|
|
362
|
+
return page
|
|
363
|
+
|
|
364
|
+
def next(self, ctx: Context):
|
|
365
|
+
if not ctx.page_formatter:
|
|
366
|
+
return "Type a command that has pages first"
|
|
367
|
+
ctx.page += 1
|
|
368
|
+
if ctx.page > ctx.page_formatter.last_page():
|
|
369
|
+
ctx.page = 0
|
|
370
|
+
ctx.selected = 0
|
|
371
|
+
return self._get_formatted_page(ctx.page_formatter, ctx.page, ctx.selected)
|
|
372
|
+
|
|
373
|
+
def page(self, ctx: Context, page: int = 1):
|
|
374
|
+
if not ctx.page_formatter:
|
|
375
|
+
return "Type a command that has pages first"
|
|
376
|
+
last_page = ctx.page_formatter.last_page() + 1
|
|
377
|
+
if page > last_page or page < 1:
|
|
378
|
+
msg = "Specify page 1"
|
|
379
|
+
if last_page > 1:
|
|
380
|
+
msg += f" through {last_page}"
|
|
381
|
+
return msg
|
|
382
|
+
ctx.page = page - 1
|
|
383
|
+
ctx.selected = 0
|
|
384
|
+
return self._get_formatted_page(ctx.page_formatter, ctx.page, ctx.selected)
|
|
385
|
+
|
|
386
|
+
def sel(self, ctx: Context, sel: int = 1):
|
|
387
|
+
if not ctx.page_formatter:
|
|
388
|
+
return "Type a command that has pages first"
|
|
389
|
+
_page = ctx.page_formatter.get_page_of_taxa(ctx.page)
|
|
390
|
+
page_len = len(_page)
|
|
391
|
+
if sel > page_len or sel < 1:
|
|
392
|
+
msg = "Specify entry 1"
|
|
393
|
+
if page_len > 1:
|
|
394
|
+
msg += f" through {page_len}"
|
|
395
|
+
return msg
|
|
396
|
+
ctx.selected = sel - 1
|
|
397
|
+
return self._get_formatted_page(ctx.page_formatter, ctx.page, ctx.selected)
|
|
398
|
+
|
|
399
|
+
def prev(self, ctx: Context):
|
|
400
|
+
if not ctx.page_formatter:
|
|
401
|
+
return "Type a command that has pages first"
|
|
402
|
+
ctx.page -= 1
|
|
403
|
+
if ctx.page < 0:
|
|
404
|
+
ctx.page = ctx.page_formatter.last_page()
|
|
405
|
+
ctx.selected = 0
|
|
406
|
+
return self._get_formatted_page(ctx.page_formatter, ctx.page, ctx.selected)
|
|
407
|
+
|
|
408
|
+
def taxon(self, ctx: Context, *args):
|
|
409
|
+
taxon = None
|
|
410
|
+
if len(args) == 0 or args[0] == "sel":
|
|
411
|
+
formatter = ctx.page_formatter
|
|
412
|
+
if formatter and getattr(formatter, "get_page_of_taxa", None):
|
|
413
|
+
page = formatter.get_page_of_taxa(ctx.page)
|
|
414
|
+
with self.inat_client.set_ctx(ctx) as client:
|
|
415
|
+
taxon = client.taxa.populate(page[ctx.selected])
|
|
416
|
+
else:
|
|
417
|
+
return "Select a taxon first"
|
|
418
|
+
else:
|
|
419
|
+
query = self._parse(" ".join(args))
|
|
420
|
+
# TODO: Handle all query clauses, not just main.terms
|
|
421
|
+
# TODO: Doesn't do any ranking or filtering of results
|
|
422
|
+
if not query.main or not query.main.terms:
|
|
423
|
+
return "Not a taxon"
|
|
424
|
+
|
|
425
|
+
with self.inat_client.set_ctx(ctx) as client:
|
|
426
|
+
main_query_str = " ".join(query.main.terms)
|
|
427
|
+
taxon = client.taxa.autocomplete(q=main_query_str).one()
|
|
428
|
+
if not taxon:
|
|
429
|
+
return "Nothing found"
|
|
430
|
+
taxon = client.taxa.populate(taxon)
|
|
431
|
+
|
|
432
|
+
formatter = TaxonFormatter(
|
|
433
|
+
taxon,
|
|
434
|
+
lang=ctx.get_inat_user_default("inat_lang"),
|
|
435
|
+
with_url=True,
|
|
436
|
+
)
|
|
437
|
+
response = self._get_formatted_page(formatter)
|
|
438
|
+
|
|
439
|
+
return response
|
|
440
|
+
|
|
441
|
+
def obs(self, ctx: Context, *args):
|
|
442
|
+
query = self._parse(" ".join(args))
|
|
443
|
+
# TODO: Handle all query clauses, not just main.terms
|
|
444
|
+
# TODO: Doesn't do any ranking or filtering of results
|
|
445
|
+
if not query.main or not query.main.terms:
|
|
446
|
+
return "Not a taxon"
|
|
447
|
+
|
|
448
|
+
main_query_str = " ".join(query.main.terms)
|
|
449
|
+
with self.inat_client.set_ctx(ctx) as client:
|
|
450
|
+
taxon = client.taxa.autocomplete(q=main_query_str).one()
|
|
451
|
+
if not taxon:
|
|
452
|
+
return "No taxon found"
|
|
453
|
+
obs = client.observations.search(
|
|
454
|
+
user_id=ctx.author.inat_user_id,
|
|
455
|
+
taxon_id=taxon.id,
|
|
456
|
+
reverse=True,
|
|
457
|
+
).one()
|
|
458
|
+
if not obs:
|
|
459
|
+
return f"No observations by you found for: {taxon.full_name}"
|
|
460
|
+
|
|
461
|
+
taxon_summary = client.observations.taxon_summary(obs.id)
|
|
462
|
+
if obs.community_taxon_id and obs.community_taxon_id != obs.taxon.id:
|
|
463
|
+
community_taxon = client.taxa.from_ids(obs.community_taxon_id).one()
|
|
464
|
+
community_taxon_summary = client.observations.taxon_summary(
|
|
465
|
+
obs.id, community=1
|
|
466
|
+
)
|
|
467
|
+
else:
|
|
468
|
+
community_taxon = taxon
|
|
469
|
+
community_taxon_summary = taxon_summary
|
|
470
|
+
|
|
471
|
+
formatter = ObservationFormatter(
|
|
472
|
+
obs,
|
|
473
|
+
taxon_summary=taxon_summary,
|
|
474
|
+
community_taxon=community_taxon,
|
|
475
|
+
community_taxon_summary=community_taxon_summary,
|
|
476
|
+
with_link=True,
|
|
477
|
+
)
|
|
478
|
+
response = self._get_formatted_page(formatter)
|
|
479
|
+
|
|
480
|
+
return response
|
|
481
|
+
|
|
482
|
+
def user(self, ctx: Context, user_id: str):
|
|
483
|
+
with self.inat_client.set_ctx(ctx) as client:
|
|
484
|
+
user = None
|
|
485
|
+
try:
|
|
486
|
+
user = client.users(user_id)
|
|
487
|
+
except HTTPError as err:
|
|
488
|
+
if err.response.status_code == 404:
|
|
489
|
+
pass
|
|
490
|
+
if not user:
|
|
491
|
+
return "User not found."
|
|
492
|
+
|
|
493
|
+
return self._format_markdown(UserFormatter(user).format())
|
|
494
|
+
|
|
495
|
+
def user_add(self, ctx: Context, user_abbrev: str, user_id: str):
|
|
496
|
+
if user_abbrev != "me":
|
|
497
|
+
return "Only `user add me <user-id>` is supported at this time."
|
|
498
|
+
user_config = self.config.user(ctx.author.id)
|
|
499
|
+
configured_user_id = None
|
|
500
|
+
if user_config:
|
|
501
|
+
configured_user_id = user_config.get("inat_user_id")
|
|
502
|
+
|
|
503
|
+
with self.inat_client.set_ctx(ctx) as client:
|
|
504
|
+
user = None
|
|
505
|
+
try:
|
|
506
|
+
user = client.users(user_id)
|
|
507
|
+
except HTTPError as err:
|
|
508
|
+
if err.response.status_code == 404:
|
|
509
|
+
pass
|
|
510
|
+
if not user:
|
|
511
|
+
return "User not found."
|
|
512
|
+
|
|
513
|
+
response = ""
|
|
514
|
+
redefining = False
|
|
515
|
+
if configured_user_id:
|
|
516
|
+
if configured_user_id == user.id:
|
|
517
|
+
return "User already added."
|
|
518
|
+
configured_user = None
|
|
519
|
+
try:
|
|
520
|
+
configured_user = client.users(configured_user_id)
|
|
521
|
+
except HTTPError as err:
|
|
522
|
+
if err.response.status_code == 404:
|
|
523
|
+
pass
|
|
524
|
+
if configured_user:
|
|
525
|
+
configured_user_str = UserFormatter(configured_user).format()
|
|
526
|
+
else:
|
|
527
|
+
configured_user_str = f"User id not found: {configured_user_id}"
|
|
528
|
+
redefining = True
|
|
529
|
+
response += (
|
|
530
|
+
f"- Already defined as another user: {configured_user_str}\n"
|
|
531
|
+
)
|
|
532
|
+
response += "- To change to the specified user:\n"
|
|
533
|
+
|
|
534
|
+
response += f"1. Confirm this is you: {UserFormatter(user).format()}\n"
|
|
535
|
+
add_or_mod = "modify" if redefining else "add"
|
|
536
|
+
response += f"2. Edit `{CONFIG_PATH}` and {add_or_mod}:\n"
|
|
537
|
+
response += (
|
|
538
|
+
f"```toml\n[users.{ctx.author.id}]\ninat_user_id = {user.id}\n```\n"
|
|
539
|
+
)
|
|
540
|
+
response += "3. Restart dronefly-cli."
|
|
541
|
+
|
|
542
|
+
return self._simple_format_markdown(response)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from platformdirs import user_data_dir
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
from pyinaturalist.constants import COMMON_RANKS, RANK_EQUIVALENTS, RANK_LEVELS
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
USER_DATA_PATH = os.path.join(user_data_dir(), "dronefly-core")
|
|
8
|
+
CONFIG_PATH = os.path.join(USER_DATA_PATH, "config.toml")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
# Map Dronefly User param names to iNat API param names:
|
|
12
|
+
INAT_USER_DEFAULT_PARAMS = {
|
|
13
|
+
"inat_place_id": "preferred_place_id",
|
|
14
|
+
"inat_lang": "locale",
|
|
15
|
+
}
|
|
16
|
+
# User-settable defaults:
|
|
17
|
+
INAT_USER_DEFAULTS = {"locale": None, "preferred_place_id": 1}
|
|
18
|
+
# All defaults:
|
|
19
|
+
INAT_DEFAULTS = {**INAT_USER_DEFAULTS, "all_names": True}
|
|
20
|
+
|
|
21
|
+
PLANTAE_ID = 47126
|
|
22
|
+
TRACHEOPHYTA_ID = 211194
|
|
23
|
+
RANK_KEYWORDS = tuple(RANK_LEVELS.keys()) + tuple(RANK_EQUIVALENTS.keys())
|
|
24
|
+
RANK_LEVEL_NAMES = {}
|
|
25
|
+
# For levels with multiple ranks, name the level after the most broadly used
|
|
26
|
+
# rank at that level:
|
|
27
|
+
RANK_LEVEL_TO_NAME = {
|
|
28
|
+
5: "subspecies",
|
|
29
|
+
10: "species",
|
|
30
|
+
20: "genus",
|
|
31
|
+
}
|
|
32
|
+
RANKS_FOR_LEVEL = {}
|
|
33
|
+
for (rank, level) in RANK_LEVELS.items():
|
|
34
|
+
RANK_LEVEL_NAMES[level] = RANK_LEVEL_TO_NAME.get(level) or rank
|
|
35
|
+
if level not in RANKS_FOR_LEVEL:
|
|
36
|
+
RANKS_FOR_LEVEL[level] = [rank]
|
|
37
|
+
else:
|
|
38
|
+
RANKS_FOR_LEVEL[level].append(rank)
|
|
39
|
+
|
|
40
|
+
TAXON_PRIMARY_RANKS = COMMON_RANKS
|
|
41
|
+
TRINOMIAL_ABBR = {"variety": "var.", "subspecies": "ssp.", "form": "f."}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .generic import * # noqa: F401,F403
|