dronefly-core 0.3.6.dev6__tar.gz → 0.3.6.dev8__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.
Files changed (24) hide show
  1. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/PKG-INFO +3 -4
  2. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/commands/__init__.py +24 -9
  3. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/constants.py +1 -1
  4. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/formatters/generic.py +272 -82
  5. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/pyproject.toml +3 -4
  6. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/setup.py +4 -5
  7. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/LICENSE +0 -0
  8. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/README.md +0 -0
  9. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/__init__.py +0 -0
  10. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/clients/__init__.py +0 -0
  11. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/clients/inat.py +0 -0
  12. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/formatters/__init__.py +0 -0
  13. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/formatters/constants.py +0 -0
  14. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/models/__init__.py +0 -0
  15. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/models/controlled_terms.py +0 -0
  16. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/models/user.py +0 -0
  17. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/parsers/__init__.py +0 -0
  18. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/parsers/constants.py +0 -0
  19. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/parsers/natural.py +0 -0
  20. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/parsers/unixlike.py +0 -0
  21. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/parsers/url.py +0 -0
  22. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/query/__init__.py +0 -0
  23. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/query/query.py +0 -0
  24. {dronefly_core-0.3.6.dev6 → dronefly_core-0.3.6.dev8}/dronefly/core/utils/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: dronefly-core
3
- Version: 0.3.6.dev6
3
+ Version: 0.3.6.dev8
4
4
  Summary: Core dronefly components
5
5
  License: AGPL-3.0-or-later
6
6
  Author: Ben Armstrong
@@ -11,12 +11,11 @@ Classifier: Programming Language :: Python :: 3
11
11
  Classifier: Programming Language :: Python :: 3.9
12
12
  Classifier: Programming Language :: Python :: 3.10
13
13
  Classifier: Programming Language :: Python :: 3.11
14
- Requires-Dist: attrs (>=21.2)
15
14
  Requires-Dist: dateparser (>=1.1.1,<2.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 (>=0.19.0.dev2,<0.20)
19
- Requires-Dist: rich (>=10.9,<14)
17
+ Requires-Dist: pyinaturalist (>=0.19.0.dev3,<0.20)
18
+ Requires-Dist: rich (>=13.4)
20
19
  Description-Content-Type: text/markdown
21
20
 
22
21
  # Dronefly core
@@ -46,6 +46,7 @@ class Context:
46
46
  # be active at a time.
47
47
  page_formatter: Union[BaseFormatter, ListFormatter] = None
48
48
  page: int = 0
49
+ per_page: int = 0
49
50
 
50
51
  def get_inat_user_default(self, inat_param: str):
51
52
  """Return iNat API default for user param default, if any, otherwise global default."""
@@ -88,11 +89,19 @@ class Commands:
88
89
  def _parse(self, query_str):
89
90
  return self.parser.parse(query_str)
90
91
 
91
- def _format_markdown(self, formatter, page: int = 0):
92
+ def _get_formatted_page(self, formatter, page: int = 0):
92
93
  if getattr(formatter, "format_page", None):
93
94
  markdown_text = formatter.format_page(page)
95
+ last_page = formatter.last_page()
96
+ if last_page > 0:
97
+ markdown_text = "\n\n".join(
98
+ [markdown_text, f"Page {page + 1}/{last_page + 1}"]
99
+ )
94
100
  else:
95
101
  markdown_text = formatter.format()
102
+ return self._format_markdown(markdown_text)
103
+
104
+ def _format_markdown(self, markdown_text: str):
96
105
  if self.format == Format.rich:
97
106
  # Richify the markdown:
98
107
  # - In Discord markdown, all newlines are rendered as line breaks
@@ -121,7 +130,7 @@ class Commands:
121
130
  def life(self, ctx: Context, *args):
122
131
  _args = " ".join(args) or "by me"
123
132
  query = self._parse(_args)
124
- per_rank = query.per or "leaf"
133
+ per_rank = query.per or "main"
125
134
  if per_rank not in [*RANK_KEYWORDS, "leaf", "main", "any"]:
126
135
  return "Specify `per <rank-or-keyword>`"
127
136
 
@@ -154,12 +163,18 @@ class Commands:
154
163
  if not life_list:
155
164
  return f"No life list {query_response.obs_query_description()}"
156
165
 
166
+ per_page = ctx.per_page
157
167
  formatter = LifeListFormatter(
158
- life_list, per_rank, query_response, with_taxa=True, per_page=20
168
+ life_list, per_rank, query_response, with_indent=True, per_page=per_page
159
169
  )
160
170
  ctx.page_formatter = formatter
161
171
  ctx.page = 0
162
- return self._format_markdown(formatter)
172
+ title = formatter.format_title()
173
+ first_page = formatter.get_first_page() or ""
174
+ if first_page:
175
+ first_page = "\n".join([title, "", first_page])
176
+ formatter.pages[0] = first_page
177
+ return self._get_formatted_page(formatter, 0)
163
178
 
164
179
  def next(self, ctx: Context):
165
180
  if not ctx.page_formatter:
@@ -167,7 +182,7 @@ class Commands:
167
182
  ctx.page += 1
168
183
  if ctx.page > ctx.page_formatter.last_page():
169
184
  ctx.page = 0
170
- return self._format_markdown(ctx.page_formatter, ctx.page)
185
+ return self._get_formatted_page(ctx.page_formatter, ctx.page)
171
186
 
172
187
  def page(self, ctx: Context, page: int = 1):
173
188
  if not ctx.page_formatter:
@@ -179,7 +194,7 @@ class Commands:
179
194
  msg += f" through {last_page}"
180
195
  return msg
181
196
  ctx.page = page - 1
182
- return self._format_markdown(ctx.page_formatter, ctx.page)
197
+ return self._get_formatted_page(ctx.page_formatter, ctx.page)
183
198
 
184
199
  def prev(self, ctx: Context):
185
200
  if not ctx.page_formatter:
@@ -187,7 +202,7 @@ class Commands:
187
202
  ctx.page -= 1
188
203
  if ctx.page < 0:
189
204
  ctx.page = ctx.page_formatter.last_page()
190
- return self._format_markdown(ctx.page_formatter, ctx.page)
205
+ return self._get_formatted_page(ctx.page_formatter, ctx.page)
191
206
 
192
207
  def taxon(self, ctx: Context, *args):
193
208
  query = self._parse(" ".join(args))
@@ -208,7 +223,7 @@ class Commands:
208
223
  lang=ctx.get_inat_user_default("inat_lang"),
209
224
  with_url=True,
210
225
  )
211
- response = self._format_markdown(formatter)
226
+ response = self._get_formatted_page(formatter)
212
227
 
213
228
  return response
214
229
 
@@ -252,6 +267,6 @@ class Commands:
252
267
  community_taxon_summary=community_taxon_summary,
253
268
  with_link=True,
254
269
  )
255
- response = self._format_markdown(formatter)
270
+ response = self._get_formatted_page(formatter)
256
271
 
257
272
  return response
@@ -13,5 +13,5 @@ INAT_DEFAULTS = {**INAT_USER_DEFAULTS, "all_names": True}
13
13
  PLANTAE_ID = 47126
14
14
  TRACHEOPHYTA_ID = 211194
15
15
  RANK_KEYWORDS = tuple(RANK_LEVELS.keys()) + tuple(RANK_EQUIVALENTS.keys())
16
- TAXON_PRIMARY_RANKS = COMMON_RANKS[-5:]
16
+ TAXON_PRIMARY_RANKS = COMMON_RANKS
17
17
  TRINOMIAL_ABBR = {"variety": "var.", "subspecies": "ssp.", "form": "f."}
@@ -20,14 +20,15 @@ from pyinaturalist import (
20
20
  EstablishmentMeans,
21
21
  JsonResponse,
22
22
  LifeList,
23
- LifeListTaxon,
24
23
  ListedTaxon,
25
24
  Observation,
26
25
  Taxon,
26
+ TaxonCount,
27
27
  TaxonSummary,
28
28
  User,
29
29
  )
30
- from pyinaturalist.constants import COMMON_RANKS
30
+ from pyinaturalist.models.taxon import make_tree
31
+ from pyinaturalist.constants import COMMON_RANKS, ROOT_TAXON_ID
31
32
 
32
33
  from dronefly.core.constants import (
33
34
  TAXON_PRIMARY_RANKS,
@@ -78,6 +79,10 @@ p.defnoun("subphylum", "subphyla")
78
79
  p.defnoun("subgenus", "subgenera")
79
80
 
80
81
 
82
+ def protect_leading_blanks(text: str = ""):
83
+ return re.sub(r"^( +)", "\N{ZERO WIDTH SPACE}" + r"**\1**", text)
84
+
85
+
81
86
  def escape_markdown(
82
87
  text: str, *, as_needed: bool = False, ignore_links: bool = True
83
88
  ) -> str:
@@ -125,6 +130,35 @@ def escape_markdown(
125
130
  return _MARKDOWN_ESCAPE_REGEX.sub(r"\\\1", text)
126
131
 
127
132
 
133
+ def taxa_per_rank(
134
+ life_list: LifeList,
135
+ ranks_to_count: Union(list[str], str),
136
+ root_taxon_id: int = None,
137
+ ):
138
+ """Generate taxa matching ranks to count in treewise order."""
139
+ options = {}
140
+ subtree = (
141
+ lambda t: True
142
+ if root_taxon_id is None
143
+ else root_taxon_id in [t.id] + [a.id for a in t.ancestors]
144
+ )
145
+ if isinstance(ranks_to_count, list):
146
+ options["include_ranks"] = ranks_to_count
147
+ include = lambda t: subtree(t) # noqa: E731
148
+ else:
149
+ if ranks_to_count == "leaf":
150
+ include = (
151
+ lambda t: subtree(t) and t.count == t.descendant_obs_count
152
+ ) # noqa: E731
153
+ else:
154
+ options["include_ranks"] = [ranks_to_count]
155
+ include = lambda t: subtree(t) and t.rank == ranks_to_count # noqa: E731
156
+ tree = make_tree(life_list.data, **options)
157
+ for taxon_count in tree.flatten(hide_root=tree.id == ROOT_TAXON_ID):
158
+ if include(taxon_count):
159
+ yield taxon_count
160
+
161
+
128
162
  def format_datetime(time, compact=False):
129
163
  """Format datetime with compact option that drops less relevant parts."""
130
164
  hour = time.strftime("%I").lstrip("0")
@@ -146,13 +180,21 @@ def format_datetime(time, compact=False):
146
180
  return formatted_time
147
181
 
148
182
 
149
- def filter_life_list(life_list: LifeList, per_rank: str, taxon: Taxon):
183
+ def included_ranks(per_rank):
184
+ if per_rank == "main":
185
+ ranks = COMMON_RANKS
186
+ else:
187
+ ranks = list(RANK_LEVELS.keys())
188
+ return ranks
189
+
190
+
191
+ def filter_life_list(
192
+ life_list: LifeList, per_rank: str, taxon: Taxon, root_taxon_id: int = None
193
+ ):
150
194
  ranks = None
151
195
  rank_totals = {}
152
- if per_rank in ["main", "any"]:
153
- ranks_to_count = (
154
- COMMON_RANKS[-8:] if per_rank == "main" else list(RANK_LEVELS.keys())
155
- )
196
+ if per_rank in ("main", "any"):
197
+ ranks_to_count = included_ranks(per_rank)
156
198
  if taxon:
157
199
  if per_rank == "main" and taxon.rank not in ranks_to_count:
158
200
  rank_level = RANK_LEVELS[taxon.rank]
@@ -163,40 +205,49 @@ def filter_life_list(life_list: LifeList, per_rank: str, taxon: Taxon):
163
205
  else:
164
206
  ranks_to_count = ranks_to_count[: ranks_to_count.index(taxon.rank) + 1]
165
207
  ranks = "main ranks" if per_rank == "main" else "ranks"
166
- taxa = [
167
- life_list_taxon
168
- for life_list_taxon in life_list.data
169
- if life_list_taxon.rank in ranks_to_count
170
- ]
171
- tot = {}
172
- for taxon in taxa:
173
- rank = taxon.rank
174
- tot[rank] = tot.get(taxon.rank, 0) + 1
175
- max_digits = len(str(max(tot.values())))
176
- rank_totals = {
177
- rank: f"`{str(tot[rank]).rjust(max_digits)}` {p.plural_noun(rank, tot[rank])}"
178
- for rank in tot
179
- }
208
+ generate_taxa = taxa_per_rank(life_list, ranks_to_count, root_taxon_id)
180
209
  elif per_rank == "leaf":
181
210
  ranks = "leaf taxa"
182
- taxa = [
183
- life_list_taxon
184
- for life_list_taxon in life_list.data
185
- if life_list_taxon.direct_obs_count == life_list_taxon.descendant_obs_count
186
- ]
211
+ generate_taxa = taxa_per_rank(life_list, per_rank, root_taxon_id)
187
212
  else:
188
213
  rank = RANK_EQUIVALENTS[per_rank] if per_rank in RANK_EQUIVALENTS else per_rank
189
214
  ranks = p.plural_noun(rank)
190
- taxa = [
191
- life_list_taxon
192
- for life_list_taxon in life_list.data
193
- if life_list_taxon.rank == rank
194
- ]
195
- return (taxa, ranks, rank_totals)
215
+ generate_taxa = taxa_per_rank(life_list, per_rank, root_taxon_id)
216
+ counted_taxa = []
217
+ counted_taxon_ids = []
218
+ tot = {}
219
+ max_taxon_count_digits = 1
220
+ max_direct_count_digits = 1
221
+ for taxon_count in generate_taxa:
222
+ counted_taxon_ids.append(taxon_count.id)
223
+ taxon_count_digits = len(str(taxon_count.descendant_obs_count))
224
+ if taxon_count_digits > max_taxon_count_digits:
225
+ max_taxon_count_digits = taxon_count_digits
226
+ direct_count_digits = len(str(taxon_count.count))
227
+ if direct_count_digits > max_direct_count_digits:
228
+ max_direct_count_digits = direct_count_digits
229
+ counted_taxa.append(taxon_count)
230
+ rank = taxon_count.rank
231
+ tot[rank] = tot.get(taxon_count.rank, 0) + 1
232
+ max_rank_digits = len(str(max(tot.values()))) if tot else 1
233
+ rank_totals = {
234
+ rank: f"`{str(tot[rank]).rjust(max_rank_digits)}` {p.plural_noun(rank, tot[rank])}"
235
+ for rank in tot
236
+ }
237
+ if per_rank == "leaf":
238
+ counted_taxa.sort(key=lambda t: t.name)
239
+ return (
240
+ counted_taxa,
241
+ counted_taxon_ids,
242
+ ranks,
243
+ rank_totals,
244
+ max_taxon_count_digits,
245
+ max_direct_count_digits,
246
+ )
196
247
 
197
248
 
198
249
  def format_life_list_summary(
199
- taxa: list[LifeListTaxon], ranks: str, rank_totals: list[int]
250
+ taxa: list[TaxonCount], ranks: str, rank_totals: list[int]
200
251
  ):
201
252
  total = f"Total: {len(taxa)} {ranks}"
202
253
  if rank_totals:
@@ -440,7 +491,7 @@ def format_taxon_name(
440
491
  name (e.g. "Anser anser domesticus" -> "*Anser anser* var. *domesticus*")
441
492
  """
442
493
 
443
- if with_common:
494
+ def get_common_name():
444
495
  preferred_common_name = None
445
496
  if lang and taxon.names:
446
497
  name = next(
@@ -461,14 +512,20 @@ def format_taxon_name(
461
512
  common = None
462
513
  else:
463
514
  common = preferred_common_name
464
- else:
465
- common = None
515
+ return common
516
+
517
+ common = get_common_name() if with_common else None
466
518
  name = taxon.name
467
519
 
468
520
  rank = taxon.rank
469
521
  rank_level = RANK_LEVELS[rank]
470
522
 
471
- if rank_level <= RANK_LEVELS["genus"]:
523
+ # Note: We follow how iNat uses italics taxon names on the website, i.e. we:
524
+ # - don't apply italics to the name when it is rank Genushybrid or Subgenus
525
+ # - do italicize the name for Genus and every rank at species or below
526
+ # - any abbreviated english keywords within italicized intraspecific ranks
527
+ # are not italicized (spp. var. f.)
528
+ if rank == "genus" or rank_level <= RANK_LEVELS["species"]:
472
529
  name = f"*{name}*"
473
530
  if rank_level > RANK_LEVELS["species"]:
474
531
  if hierarchy:
@@ -556,8 +613,12 @@ class LifeListFormatter(ListFormatter):
556
613
  per_rank: str,
557
614
  query_response: QueryResponse,
558
615
  with_url: bool = True,
559
- with_taxa: bool = False,
616
+ with_taxa: bool = True,
617
+ with_indent: bool = False,
618
+ with_direct: bool = False,
619
+ with_common: bool = False,
560
620
  per_page: int = 20,
621
+ root_taxon_id: int = None,
561
622
  ):
562
623
  """
563
624
  Parameters
@@ -590,21 +651,50 @@ class LifeListFormatter(ListFormatter):
590
651
  When False, only page 0 can be formatted with the observations link
591
652
  and per rank summary alone.
592
653
 
654
+ with_indent: bool, optional
655
+ When with_indent is True, per_rank is 'main' or 'any', and with_taxa
656
+ is also True, the taxon names on the life list are displayed as
657
+ children of higher taxa on the same page using indent levels and "└"
658
+ to indicate child relationships.
659
+
660
+ with_direct: bool, optional
661
+ When with_direct is True, a column of direct observations counts of
662
+ each taxon is shown. The number is only shown when non-zero. If the
663
+ direct obs count is equal to the total obs count, then the total obs
664
+ count is omitted. When shown, the direct obs count is enclosed in
665
+ parentheses.
666
+
667
+ with_common: bool, optional
668
+ When with_common is True, if the life_list contains common names, then
669
+ common names are included in the output.
670
+
593
671
  per_page: int, optional
594
672
  The number of taxa to include in each page.
673
+
674
+ root_taxon_id: int, optional
675
+ If specified, make the taxon with this ID the root. The taxon with
676
+ this ID must be in the life list data.
595
677
  """
596
678
  self.life_list = life_list
597
679
  self.per_rank = per_rank
598
680
  self.query_response = query_response
599
681
  self.with_url = with_url
600
682
  self.with_taxa = with_taxa
601
- self.per_page = per_page
602
- (taxa, self.ranks, self.rank_totals) = filter_life_list(
603
- self.life_list, self.per_rank, self.query_response.taxon
604
- )
605
- self.taxa = list(taxa)
606
- self.max_digits = len(
607
- str(max([taxon.descendant_obs_count for taxon in self.taxa]))
683
+ self.with_indent = with_indent
684
+ self.with_direct = with_direct
685
+ self.with_common = with_common
686
+ self.pages = []
687
+ self.per_page = per_page if per_page >= 0 else 0
688
+ self.root_taxon_id = root_taxon_id
689
+ (
690
+ self.taxa,
691
+ self.taxon_ids,
692
+ self.ranks,
693
+ self.rank_totals,
694
+ self.count_digits,
695
+ self.direct_digits,
696
+ ) = filter_life_list(
697
+ self.life_list, self.per_rank, self.query_response.taxon, self.root_taxon_id
608
698
  )
609
699
 
610
700
  def format(self, with_title: bool = True, page: int = 0):
@@ -635,51 +725,151 @@ class LifeListFormatter(ListFormatter):
635
725
 
636
726
  def format_page(self, page: int = 0):
637
727
  """Format the life list description."""
638
- description = []
639
- query_response = self.query_response
640
- if page == 0:
641
- obs_link = format_link(
642
- "All Life List Observations",
643
- obs_url_from_v1(query_response.obs_args()),
728
+
729
+ def indent_level(taxon: Taxon):
730
+ if self.per_rank not in ("main", "any"):
731
+ return 0
732
+ root_indent_level = self.taxa[0].indent_level
733
+ return taxon.indent_level - root_indent_level
734
+
735
+ def indent_child(taxon: Taxon):
736
+ level = indent_level(taxon)
737
+ return protect_leading_blanks(
738
+ "\N{EN SPACE}\N{THIN SPACE}" * (level - 1) + "└\N{THIN SPACE}"
739
+ if level >= 1
740
+ else ""
644
741
  )
645
- description.append(obs_link)
646
- # TODO: if more than max_taxa, support paged result
647
- if self.taxa and self.with_taxa:
648
- page_start = page * self.per_page
649
- page_end = page_start + self.per_page
650
- page_of_taxa = self.taxa[page_start:page_end]
742
+
743
+ def make_page_header(taxon: Taxon):
744
+ """Make a page header for non-top-level taxa."""
745
+ ancestors = taxon.ancestors
746
+ if ancestors:
747
+ if ancestors[0].id == ROOT_TAXON_ID:
748
+ del ancestors[0]
749
+ if ancestors:
750
+ header_ranks = included_ranks(self.per_rank)
751
+ header_names = [
752
+ format_taxon_name(parent, with_rank=False)
753
+ for parent in ancestors
754
+ if parent.rank in header_ranks
755
+ ]
756
+ if header_names:
757
+ counts_width = self.count_digits
758
+ if self.with_direct:
759
+ counts_width += self.direct_digits + 2
760
+ return (
761
+ f"`{' ' * counts_width}` __"
762
+ + " > ".join(header_names)
763
+ + "__"
764
+ )
765
+ return None
766
+
767
+ def format_page_of_taxa(page_of_taxa):
768
+ query_response = self.query_response
651
769
  formatted_taxa = []
652
- obs_args = query_response.obs_args()
653
770
  for taxon in page_of_taxa:
654
- # Replace any taxa in the original query with just the one:
655
- if "taxon_ids" in obs_args:
656
- del obs_args["taxon_ids"]
657
- taxon_obs_url = obs_url_from_v1(
658
- {
659
- **obs_args,
660
- "taxon_id": taxon.id,
661
- }
771
+ formatted_count = str(taxon.descendant_obs_count).rjust(
772
+ self.count_digits
662
773
  )
663
- formatted_count = str(taxon.descendant_obs_count).rjust(self.max_digits)
664
- formatted_name = format_link(taxon.name, taxon_obs_url)
665
- formatted_taxa.append(f"`{formatted_count}` {formatted_name}")
666
- description.append("\n".join(formatted_taxa))
667
- if page == self.last_page():
668
- life_list_summary = format_life_list_summary(
669
- self.taxa, self.ranks, self.rank_totals
774
+ formatted_direct = ""
775
+ # Format the direct column similarly to Dynamic Life Lists on
776
+ # iNat web, i.e.
777
+ # - never show direct count on non-leaves when it is zero
778
+ # - only show one column at the leaves, as the counts are equal
779
+ # - show the leaf count as "direct" at ranks above species,
780
+ # a cue that the species count might be improved with more
781
+ # ID refinements
782
+ if self.with_direct:
783
+ formatted_direct = " " * (self.direct_digits + 2)
784
+ if taxon.count > 0:
785
+ formatted_direct = f"({taxon.count})".rjust(
786
+ self.direct_digits + 2
787
+ )
788
+ is_leaf = taxon.count == taxon.descendant_obs_count
789
+ terminal_rank = taxon.rank_level <= RANK_LEVELS["species"]
790
+ if is_leaf:
791
+ if terminal_rank:
792
+ formatted_direct = " " * (self.direct_digits + 2)
793
+ else:
794
+ formatted_count = " " * self.count_digits
795
+ taxon_name = format_taxon_name(taxon, with_common=False)
796
+ formatted_name = format_link(
797
+ taxon_name, taxon_obs_url(query_response, taxon)
798
+ )
799
+ if self.with_common and taxon.preferred_common_name:
800
+ formatted_name = f"{formatted_name} ({taxon.preferred_common_name})"
801
+ formatted_taxa.append(
802
+ f"`{formatted_count}{formatted_direct}` {indent_child(taxon)}{formatted_name}"
803
+ )
804
+ return formatted_taxa
805
+
806
+ def make_page(page):
807
+ sections = []
808
+ query_response = self.query_response
809
+ with_page_headers = self.per_rank in ("main", "any")
810
+ if page == 0:
811
+ obs_link = format_link(
812
+ "Observations",
813
+ obs_url_from_v1(query_response.obs_args()),
814
+ )
815
+ sections.append(obs_link)
816
+ if self.taxa and self.with_taxa:
817
+ page_of_taxa = self.get_page_of_taxa(page)
818
+ if page_of_taxa:
819
+ formatted_taxa = format_page_of_taxa(page_of_taxa)
820
+ if with_page_headers and indent_level(page_of_taxa[0]) > 1:
821
+ formatted_taxa.insert(0, make_page_header(page_of_taxa[0]))
822
+ sections.append("\n".join(formatted_taxa))
823
+ if page == self.last_page():
824
+ life_list_summary = format_life_list_summary(
825
+ self.taxa, self.ranks, self.rank_totals
826
+ )
827
+ sections.append(life_list_summary)
828
+ return "\n\n".join(sections)
829
+
830
+ def taxon_obs_url(query_response, taxon):
831
+ obs_args = query_response.obs_args()
832
+ # Replace multiple taxa in the original query with just the one:
833
+ if "taxon_ids" in obs_args:
834
+ del obs_args["taxon_ids"]
835
+ return obs_url_from_v1(
836
+ {
837
+ **obs_args,
838
+ "taxon_id": taxon.id,
839
+ }
670
840
  )
671
- description.append(life_list_summary)
672
- return "\n\n".join(description)
673
841
 
674
- def format_all(self):
675
- return [self.format_page(page) for page in range(0, self.last_page() + 1)]
842
+ last_cached_page = len(self.pages) - 1
843
+ # Extend page cache with new formatted pages up to and including
844
+ # requested page. Normally the user advances a page at a time, so this
845
+ # formats and caches new pages efficiently for for the normal case,
846
+ # while still supporting random access.
847
+ for new_page in range(last_cached_page + 1, page + 1):
848
+ self.pages.append(make_page(new_page))
849
+ return self.pages[page]
850
+
851
+ def generate_pages(self):
852
+ for page in range(0, self.last_page() + 1):
853
+ formatted_page = self.format_page(page)
854
+ yield formatted_page
855
+
856
+ def get_first_page(self):
857
+ first_page = self.format_page(0)
858
+ return first_page
859
+
860
+ def get_page_of_taxa(self, page: int):
861
+ if self.per_page > 0:
862
+ page_start = page * self.per_page
863
+ page_end = page_start + self.per_page
864
+ else:
865
+ page_start = 0
866
+ page_end = len(self.taxa) + 1
867
+ return self.taxa[page_start:page_end]
676
868
 
677
869
  def last_page(self):
678
- return (
679
- ceil(len(self.taxa) / self.per_page) - 1
680
- if self.with_taxa and self.taxa
681
- else 0
682
- )
870
+ if not (self.with_taxa and self.per_page > 0 and self.taxa):
871
+ return 0
872
+ return ceil(len(self.taxa) / self.per_page) - 1
683
873
 
684
874
 
685
875
  class TaxonFormatter(BaseFormatter):
@@ -6,7 +6,7 @@ max-line-length = 100
6
6
 
7
7
  [tool.poetry]
8
8
  name = "dronefly-core"
9
- version = "0.3.6.dev6"
9
+ version = "0.3.6.dev8"
10
10
  description = "Core dronefly components"
11
11
  authors = ["Ben Armstrong <synrg@debian.org>"]
12
12
  license = "AGPL-3.0-or-later"
@@ -17,12 +17,11 @@ packages = [
17
17
 
18
18
  [tool.poetry.dependencies]
19
19
  python = ">=3.8.1,<3.12"
20
- pyinaturalist = ">=0.19.0.dev2,<0.20"
20
+ pyinaturalist = ">=0.19.0.dev3,<0.20"
21
21
  dateparser = "^1.1.1"
22
22
  inflect = "^5.3.0"
23
- rich = ">=10.9,<14"
24
- attrs = ">=21.2"
25
23
  html2markdown = "^0.1.7"
24
+ rich = ">=13.4"
26
25
 
27
26
  [tool.poetry.dev-dependencies]
28
27
  black = "^22.12.0"
@@ -15,16 +15,15 @@ package_data = \
15
15
  {'': ['*']}
16
16
 
17
17
  install_requires = \
18
- ['attrs>=21.2',
19
- 'dateparser>=1.1.1,<2.0.0',
18
+ ['dateparser>=1.1.1,<2.0.0',
20
19
  'html2markdown>=0.1.7,<0.2.0',
21
20
  'inflect>=5.3.0,<6.0.0',
22
- 'pyinaturalist>=0.19.0.dev2,<0.20',
23
- 'rich>=10.9,<14']
21
+ 'pyinaturalist>=0.19.0.dev3,<0.20',
22
+ 'rich>=13.4']
24
23
 
25
24
  setup_kwargs = {
26
25
  'name': 'dronefly-core',
27
- 'version': '0.3.6.dev6',
26
+ 'version': '0.3.6.dev8',
28
27
  'description': 'Core dronefly components',
29
28
  'long_description': "# Dronefly core\n\nThis is an incomplete rewrite of [Dronefly](https://dronefly.readthedocs.io)\nDiscord bot's core components. We're not yet making version guarantees until\nit is more usable.\n\n# Related packages\n\n## Dronefly command-line client\n\nThe [dronefly-cli](https://github.com/dronefly-garden/dronefly-cli) command-line\nclient will provide a standalone text user interface that can perform a usable\nsubset of Dronefly Discord bot's capabilities, built solely with Dronefly core.\n\n## Dronefly Discord bot\n\nDronefly Discord bot brings [iNaturalist](https://www.inaturalist.org) taxa,\nobservations, and other data from the site into conversations on the\n[Discord](https://discord.com) chat platform.\n",
30
29
  'author': 'Ben Armstrong',