-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
package_builder.py
1820 lines (1574 loc) · 66.2 KB
/
package_builder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Package Builder Class."""
# pylint: disable=too-many-lines
import builtins
import inspect
import re
import shutil
import sys
from dataclasses import Field as DCField
from functools import partial
from inspect import Parameter, _empty, isclass, signature
from json import dumps, load
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Literal,
Optional,
OrderedDict,
Set,
Tuple,
Type,
TypeVar,
Union,
get_args,
get_origin,
get_type_hints,
)
from importlib_metadata import entry_points
from pydantic.fields import FieldInfo
from pydantic_core import PydanticUndefined
from starlette.routing import BaseRoute
from typing_extensions import Annotated, _AnnotatedAlias
from openbb_core.app.extension_loader import ExtensionLoader, OpenBBGroups
from openbb_core.app.model.example import Example
from openbb_core.app.model.field import OpenBBField
from openbb_core.app.model.obbject import OBBject
from openbb_core.app.provider_interface import ProviderInterface
from openbb_core.app.router import RouterLoader
from openbb_core.app.service.system_service import SystemService
from openbb_core.app.static.utils.console import Console
from openbb_core.app.static.utils.linters import Linters
from openbb_core.app.version import CORE_VERSION, VERSION
from openbb_core.env import Env
if TYPE_CHECKING:
# pylint: disable=import-outside-toplevel
from numpy import ndarray # noqa
from pandas import DataFrame, Series # noqa
from openbb_core.provider.abstract.data import Data # noqa
try:
from openbb_charting import Charting # type: ignore
CHARTING_INSTALLED = True
except ImportError:
CHARTING_INSTALLED = False
DataProcessingSupportedTypes = TypeVar(
"DataProcessingSupportedTypes",
list,
dict,
"DataFrame",
List["DataFrame"],
"Series",
List["Series"],
"ndarray",
"Data",
)
TAB = " "
def create_indent(n: int) -> str:
"""Create n indentation space."""
return TAB * n
class PackageBuilder:
"""Build the extension package for the Platform."""
def __init__(
self, directory: Optional[Path] = None, lint: bool = True, verbose: bool = False
) -> None:
"""Initialize the package builder."""
self.directory = directory or Path(__file__).parent
self.lint = lint
self.verbose = verbose
self.console = Console(verbose)
self.route_map = PathHandler.build_route_map()
self.path_list = PathHandler.build_path_list(route_map=self.route_map)
def auto_build(self) -> None:
"""Trigger build if there are differences between built and installed extensions."""
if Env().AUTO_BUILD:
reference = PackageBuilder._read(
self.directory / "assets" / "reference.json"
)
ext_map = reference.get("info", {}).get("extensions", {})
add, remove = PackageBuilder._diff(ext_map)
if add:
a = ", ".join(sorted(add))
print(f"Extensions to add: {a}") # noqa: T201
if remove:
r = ", ".join(sorted(remove))
print(f"Extensions to remove: {r}") # noqa: T201
if add or remove:
print("\nBuilding...") # noqa: T201
self.build()
def build(
self,
modules: Optional[Union[str, List[str]]] = None,
) -> None:
"""Build the extensions for the Platform."""
self.console.log("\nBuilding extensions package...\n")
self._clean(modules)
ext_map = self._get_extension_map()
self._save_modules(modules, ext_map)
self._save_package()
self._save_reference_file(ext_map)
if self.lint:
self._run_linters()
def _clean(self, modules: Optional[Union[str, List[str]]] = None) -> None:
"""Delete the assets and package folder or modules before building."""
shutil.rmtree(self.directory / "assets", ignore_errors=True)
if modules:
for module in modules:
module_path = self.directory / "package" / f"{module}.py"
if module_path.exists():
module_path.unlink()
else:
shutil.rmtree(self.directory / "package", ignore_errors=True)
def _get_extension_map(self) -> Dict[str, List[str]]:
"""Get map of extensions available at build time."""
el = ExtensionLoader()
og = OpenBBGroups.groups()
ext_map: Dict[str, List[str]] = {}
for group, entry_point in zip(og, el.entry_points):
ext_map[group] = [
f"{e.name}@{getattr(e.dist, 'version', '')}" for e in entry_point
]
return ext_map
def _save_modules(
self,
modules: Optional[Union[str, List[str]]] = None,
ext_map: Optional[Dict[str, List[str]]] = None,
):
"""Save the modules."""
self.console.log("\nWriting modules...")
if not self.path_list:
self.console.log("\nThere is nothing to write.")
return
MAX_LEN = max([len(path) for path in self.path_list if path != "/"])
_path_list = (
[path for path in self.path_list if path in modules]
if modules
else self.path_list
)
for path in _path_list:
route = PathHandler.get_route(path, self.route_map)
if route is None:
code = ModuleBuilder.build(path, ext_map)
name = PathHandler.build_module_name(path)
self.console.log(f"({path})", end=" " * (MAX_LEN - len(path)))
self._write(code, name)
def _save_package(self):
"""Save the package."""
self.console.log("\nWriting package __init__...")
code = "### THIS FILE IS AUTO-GENERATED. DO NOT EDIT. ###\n"
self._write(code=code, name="__init__")
def _save_reference_file(self, ext_map: Optional[Dict[str, List[str]]] = None):
"""Save the reference.json file."""
self.console.log("\nWriting reference file...")
code = dumps(
obj={
"openbb": VERSION.replace("dev", ""),
"info": {
"title": "OpenBB Platform (Python)",
"description": "Investment research for everyone, anywhere.",
"core": CORE_VERSION.replace("dev", ""),
"extensions": ext_map,
},
"paths": ReferenceGenerator.get_paths(self.route_map),
"routers": ReferenceGenerator.get_routers(self.route_map),
},
indent=4,
)
self._write(code=code, name="reference", extension="json", folder="assets")
def _run_linters(self):
"""Run the linters."""
self.console.log("\nRunning linters...")
linters = Linters(self.directory / "package", self.verbose)
linters.ruff()
linters.black()
def _write(
self, code: str, name: str, extension: str = "py", folder: str = "package"
) -> None:
"""Write the module to the package."""
package_folder = self.directory / folder
package_path = package_folder / f"{name}.{extension}"
package_folder.mkdir(exist_ok=True)
self.console.log(str(package_path))
with package_path.open("w", encoding="utf-8", newline="\n") as file:
file.write(code.replace("typing.", ""))
@staticmethod
def _read(path: Path) -> dict:
"""Get content from folder."""
try:
with open(Path(path)) as fp:
content = load(fp)
except Exception:
content = {}
return content
@staticmethod
def _diff(ext_map: Dict[str, List[str]]) -> Tuple[Set[str], Set[str]]:
"""Check differences between built and installed extensions.
Parameters
----------
ext_map: Dict[str, List[str]]
Dictionary containing the extensions.
Example:
{
"openbb_core_extension": [
"commodity@1.0.1",
...
],
"openbb_provider_extension": [
"benzinga@1.1.3",
...
],
"openbb_obbject_extension": [
"openbb_charting@1.0.0",
...
]
}
Returns
-------
Tuple[Set[str], Set[str]]
First element: set of installed extensions that are not in the package.
Second element: set of extensions in the package that are not installed.
"""
add: Set[str] = set()
remove: Set[str] = set()
groups = OpenBBGroups.groups()
for g in groups:
built = set(ext_map.get(g, {}))
installed = set(
f"{e.name}@{getattr(e.dist, 'version', '')}"
for e in entry_points(group=g)
)
add = add.union(installed - built)
remove = remove.union(built - installed)
return add, remove
class ModuleBuilder:
"""Build the module for the Platform."""
@staticmethod
def build(path: str, ext_map: Optional[Dict[str, List[str]]] = None) -> str:
"""Build the module."""
code = "### THIS FILE IS AUTO-GENERATED. DO NOT EDIT. ###\n\n"
code += ImportDefinition.build(path)
code += ClassDefinition.build(path, ext_map)
return code
class ImportDefinition:
"""Build the import definition for the Platform."""
@staticmethod
def filter_hint_type_list(hint_type_list: List[Type]) -> List[Type]:
"""Filter the hint type list."""
new_hint_type_list = []
for hint_type in hint_type_list:
if hint_type != _empty and hint_type.__module__ != "builtins":
new_hint_type_list.append(hint_type)
new_hint_type_list = list(set(new_hint_type_list))
return new_hint_type_list
@classmethod
def get_function_hint_type_list(cls, func: Callable) -> List[Type]:
"""Get the hint type list from the function."""
sig = signature(func)
parameter_map = sig.parameters
return_type = sig.return_annotation
hint_type_list = []
for parameter in parameter_map.values():
hint_type_list.append(parameter.annotation)
if return_type:
if not issubclass(return_type, OBBject):
raise ValueError("Return type must be an OBBject.")
hint_type = get_args(get_type_hints(return_type)["results"])[0]
hint_type_list.append(hint_type)
hint_type_list = cls.filter_hint_type_list(hint_type_list)
return hint_type_list
@classmethod
def get_path_hint_type_list(cls, path: str) -> List[Type]:
"""Get the hint type list from the path."""
route_map = PathHandler.build_route_map()
path_list = PathHandler.build_path_list(route_map=route_map)
child_path_list = PathHandler.get_child_path_list(
path=path, path_list=path_list
)
hint_type_list = []
for child_path in child_path_list:
route = PathHandler.get_route(path=child_path, route_map=route_map)
if route:
if route.deprecated:
hint_type_list.append(type(route.summary.metadata))
function_hint_type_list = cls.get_function_hint_type_list(func=route.endpoint) # type: ignore
hint_type_list.extend(function_hint_type_list)
hint_type_list = list(set(hint_type_list))
return hint_type_list
@classmethod
def build(cls, path: str) -> str:
"""Build the import definition."""
hint_type_list = cls.get_path_hint_type_list(path=path)
code = "from openbb_core.app.static.container import Container"
code += "\nfrom openbb_core.app.model.obbject import OBBject"
# These imports were not detected before build, so we add them manually and
# ruff --fix the resulting code to remove unused imports.
# TODO: Find a better way to handle this. This is a temporary solution.
code += "\nimport openbb_core.provider"
code += "\nfrom openbb_core.provider.abstract.data import Data"
code += "\nimport pandas"
code += "\nfrom pandas import DataFrame, Series"
code += "\nimport numpy"
code += "\nfrom numpy import ndarray"
code += "\nimport datetime"
code += "\nfrom datetime import date"
code += "\nimport pydantic"
code += "\nfrom pydantic import BaseModel"
code += "\nfrom inspect import Parameter"
code += "\nimport typing"
code += "\nfrom typing import TYPE_CHECKING, ForwardRef, List, Dict, Union, Optional, Literal, Any"
code += "\nfrom annotated_types import Ge, Le, Gt, Lt"
code += "\nfrom warnings import warn, simplefilter"
if sys.version_info < (3, 9):
code += "\nimport typing_extensions"
else:
code += "\nfrom typing_extensions import Annotated, deprecated"
# code += "\nfrom openbb_core.app.utils import df_to_basemodel"
code += "\nfrom openbb_core.app.static.utils.decorators import exception_handler, validate\n"
code += "\nfrom openbb_core.app.static.utils.filters import filter_inputs\n"
code += "\nfrom openbb_core.app.deprecation import OpenBBDeprecationWarning\n"
code += "\nfrom openbb_core.app.model.field import OpenBBField"
# if path.startswith("/quantitative"):
# code += "\nfrom openbb_quantitative.models import "
# code += "(CAPMModel,NormalityModel,OmegaModel,SummaryModel,UnitRootModel)"
module_list = [hint_type.__module__ for hint_type in hint_type_list]
module_list = list(set(module_list))
module_list.sort()
code += "\n"
for module in module_list:
code += f"import {module}\n"
return code
class ClassDefinition:
"""Build the class definition for the Platform."""
@staticmethod
def build(path: str, ext_map: Optional[Dict[str, List[str]]] = None) -> str:
"""Build the class definition."""
class_name = PathHandler.build_module_class(path=path)
code = f"class {class_name}(Container):\n"
route_map = PathHandler.build_route_map()
path_list = PathHandler.build_path_list(route_map)
child_path_list = sorted(
PathHandler.get_child_path_list(
path=path,
path_list=path_list,
)
)
doc = f' """{path}\n' if path else ' # fmt: off\n """\nRouters:\n'
methods = ""
for c in child_path_list:
route = PathHandler.get_route(c, route_map)
if route:
doc += f" {route.name}\n"
methods += MethodDefinition.build_command_method(
path=route.path,
func=route.endpoint,
model_name=(
route.openapi_extra.get("model", None)
if route.openapi_extra
else None
),
examples=(route.openapi_extra.get("examples", []) or []),
)
else:
doc += " /" if path else " /"
doc += c.split("/")[-1] + "\n"
methods += MethodDefinition.build_class_loader_method(path=c)
if not path:
if ext_map:
doc += "\n"
doc += "Extensions:\n"
doc += "\n".join(
[f" - {ext}" for ext in ext_map.get("openbb_core_extension", [])]
)
doc += "\n\n"
doc += "\n".join(
[
f" - {ext}"
for ext in ext_map.get("openbb_provider_extension", [])
]
)
doc += ' """\n'
doc += " # fmt: on\n"
else:
doc += ' """\n'
code += doc + "\n"
code += " def __repr__(self) -> str:\n"
code += ' return self.__doc__ or ""\n'
code += methods
return code
class MethodDefinition:
"""Build the method definition for the Platform."""
# These are types we want to expand.
# For example, start_date is always a 'date', but we also accept 'str' as input.
# Be careful, if the type is not coercible by pydantic to the original type, you
# will need to add some conversion code in the input filter.
TYPE_EXPANSION = {
"data": DataProcessingSupportedTypes,
"start_date": str,
"end_date": str,
"date": str,
"provider": None,
}
@staticmethod
def build_class_loader_method(path: str) -> str:
"""Build the class loader method."""
module_name = PathHandler.build_module_name(path=path)
class_name = PathHandler.build_module_class(path=path)
function_name = path.rsplit("/", maxsplit=1)[-1].strip("/")
code = "\n @property\n"
code += f" def {function_name}(self):\n"
code += " # pylint: disable=import-outside-toplevel\n"
code += f" from . import {module_name}\n\n"
code += f" return {module_name}.{class_name}(command_runner=self._command_runner)\n"
return code
@staticmethod
def get_type(field: FieldInfo) -> type:
"""Get the type of the field."""
field_type = getattr(
field, "annotation", getattr(field, "type", Parameter.empty)
)
if isclass(field_type):
name = field_type.__name__
if name.startswith("Constrained") and name.endswith("Value"):
name = name[11:-5].lower()
return getattr(builtins, name, field_type)
return field_type
return field_type
@staticmethod
def get_default(field: FieldInfo):
"""Get the default value of the field."""
field_default = getattr(field, "default", None)
if field_default is None or field_default is PydanticUndefined:
return Parameter.empty
default_default = getattr(field_default, "default", None)
if default_default is PydanticUndefined or default_default is Ellipsis:
return Parameter.empty
return default_default
@staticmethod
def get_extra(field: FieldInfo) -> dict:
"""Get json schema extra."""
field_default = getattr(field, "default", None)
if field_default:
# Getting json_schema_extra without changing the original dict
json_schema_extra = getattr(field_default, "json_schema_extra", {}).copy()
json_schema_extra.pop("choices", None)
return json_schema_extra
return {}
@staticmethod
def is_annotated_dc(annotation) -> bool:
"""Check if the annotation is an annotated dataclass."""
return isinstance(annotation, _AnnotatedAlias) and hasattr(
annotation.__args__[0], "__dataclass_fields__"
)
@staticmethod
def is_data_processing_function(path: str) -> bool:
"""Check if the function is a data processing function."""
methods = PathHandler.build_route_map()[path].methods # type: ignore
return "POST" in methods
@staticmethod
def is_deprecated_function(path: str) -> bool:
"""Check if the function is deprecated."""
return getattr(PathHandler.build_route_map()[path], "deprecated", False)
@staticmethod
def get_deprecation_message(path: str) -> str:
"""Get the deprecation message."""
return getattr(PathHandler.build_route_map()[path], "summary", "")
@staticmethod
def reorder_params(
params: Dict[str, Parameter], var_kw: Optional[List[str]] = None
) -> "OrderedDict[str, Parameter]":
"""Reorder the params and make sure VAR_KEYWORD come after 'provider."""
formatted_keys = list(params.keys())
for k in ["provider"] + (var_kw or []):
if k in formatted_keys:
formatted_keys.remove(k)
formatted_keys.append(k)
od: OrderedDict[str, Parameter] = OrderedDict()
for k in formatted_keys:
od[k] = params[k]
return od
@staticmethod
def format_params(
path: str, parameter_map: Dict[str, Parameter]
) -> OrderedDict[str, Parameter]:
"""Format the params."""
parameter_map.pop("cc", None)
# we need to add the chart parameter here bc of the docstring generation
if CHARTING_INSTALLED and path.replace("/", "_")[1:] in Charting.functions():
parameter_map["chart"] = Parameter(
name="chart",
kind=Parameter.POSITIONAL_OR_KEYWORD,
annotation=Annotated[
bool,
OpenBBField(
description="Whether to create a chart or not, by default False.",
),
],
default=False,
)
formatted: Dict[str, Parameter] = {}
var_kw = []
for name, param in parameter_map.items():
if name == "extra_params":
formatted[name] = Parameter(name="kwargs", kind=Parameter.VAR_KEYWORD)
var_kw.append(name)
elif name == "provider_choices":
fields = param.annotation.__args__[0].__dataclass_fields__
field = fields["provider"]
type_ = getattr(field, "type")
default_priority = getattr(type_, "__args__")
formatted["provider"] = Parameter(
name="provider",
kind=Parameter.POSITIONAL_OR_KEYWORD,
annotation=Annotated[
Optional[MethodDefinition.get_type(field)],
OpenBBField(
description=(
"The provider to use, by default None. "
"If None, the priority list configured in the settings is used. "
f"Default priority: {', '.join(default_priority)}."
),
),
],
default=None,
)
elif MethodDefinition.is_annotated_dc(param.annotation):
fields = param.annotation.__args__[0].__dataclass_fields__
for field_name, field in fields.items():
type_ = MethodDefinition.get_type(field)
default = MethodDefinition.get_default(field)
extra = MethodDefinition.get_extra(field)
new_type = MethodDefinition.get_expanded_type(
field_name, extra, type_
)
updated_type = type_ if new_type is ... else Union[type_, new_type]
formatted[field_name] = Parameter(
name=field_name,
kind=Parameter.POSITIONAL_OR_KEYWORD,
annotation=updated_type,
default=default,
)
else:
new_type = MethodDefinition.get_expanded_type(name)
if hasattr(new_type, "__constraints__"):
types = new_type.__constraints__ + (param.annotation,) # type: ignore
updated_type = Union[types] # type: ignore
else:
updated_type = (
param.annotation
if new_type is ...
else Union[param.annotation, new_type]
)
formatted[name] = Parameter(
name=name,
kind=param.kind,
annotation=updated_type,
default=param.default,
)
if param.kind == Parameter.VAR_KEYWORD:
var_kw.append(name)
return MethodDefinition.reorder_params(params=formatted, var_kw=var_kw)
@staticmethod
def add_field_custom_annotations(
od: OrderedDict[str, Parameter], model_name: Optional[str] = None
):
"""Add the field custom description and choices to the param signature as annotations."""
if model_name:
available_fields: Dict[str, DCField] = (
ProviderInterface().params[model_name]["standard"].__dataclass_fields__
)
for param, value in od.items():
if param not in available_fields:
continue
field_default = available_fields[param].default
choices = getattr(field_default, "json_schema_extra", {}).get(
"choices", []
)
description = getattr(field_default, "description", "")
PartialParameter = partial(
OpenBBField,
description=description,
)
new_value = value.replace(
annotation=Annotated[
value.annotation,
(
PartialParameter(choices=choices)
if choices
else PartialParameter()
),
],
)
od[param] = new_value
@staticmethod
def build_func_params(formatted_params: OrderedDict[str, Parameter]) -> str:
"""Stringify function params."""
func_params = ",\n ".join(
str(param) for param in formatted_params.values()
)
func_params = func_params.replace("NoneType", "None")
func_params = func_params.replace(
"pandas.core.frame.DataFrame", "pandas.DataFrame"
)
func_params = func_params.replace(
"openbb_core.provider.abstract.data.Data", "Data"
)
func_params = func_params.replace("ForwardRef('Data')", "Data")
func_params = func_params.replace("ForwardRef('DataFrame')", "DataFrame")
func_params = func_params.replace("ForwardRef('Series')", "Series")
func_params = func_params.replace("ForwardRef('ndarray')", "ndarray")
return func_params
@staticmethod
def build_func_returns(return_type: type) -> str:
"""Build the function returns."""
if return_type == _empty:
func_returns = "None"
elif return_type.__module__ == "builtins":
func_returns = return_type.__name__
else:
func_returns = "OBBject"
return func_returns
@staticmethod
def build_command_method_signature(
func_name: str,
formatted_params: OrderedDict[str, Parameter],
return_type: type,
path: str,
model_name: Optional[str] = None,
) -> str:
"""Build the command method signature."""
MethodDefinition.add_field_custom_annotations(
od=formatted_params, model_name=model_name
) # this modified `od` in place
func_params = MethodDefinition.build_func_params(formatted_params)
func_returns = MethodDefinition.build_func_returns(return_type)
args = (
"(config=dict(arbitrary_types_allowed=True))"
if "DataFrame" in func_params
or "Series" in func_params
or "ndarray" in func_params
else ""
)
code = ""
deprecated = ""
if MethodDefinition.is_deprecated_function(path):
deprecation_message = MethodDefinition.get_deprecation_message(path)
deprecation_type_class = type(
deprecation_message.metadata # type: ignore
).__name__
deprecated = "\n @deprecated("
deprecated += f'\n "{deprecation_message}",'
deprecated += f"\n category={deprecation_type_class},"
deprecated += "\n )"
code += "\n @exception_handler"
code += f"\n @validate{args}"
code += deprecated
code += f"\n def {func_name}("
code += f"\n self,\n {func_params}\n ) -> {func_returns}:\n"
return code
@staticmethod
def build_command_method_doc(
path: str,
func: Callable,
formatted_params: OrderedDict[str, Parameter],
model_name: Optional[str] = None,
examples: Optional[List[Example]] = None,
):
"""Build the command method docstring."""
doc = func.__doc__
doc = DocstringGenerator.generate(
path=path,
func=func,
formatted_params=formatted_params,
model_name=model_name,
examples=examples,
)
code = (
f'{create_indent(2)}"""{doc}{create_indent(2)}""" # noqa: E501\n\n'
if doc
else ""
)
return code
@staticmethod
def build_command_method_body(path: str, func: Callable):
"""Build the command method implementation."""
sig = signature(func)
parameter_map = dict(sig.parameters)
parameter_map.pop("cc", None)
code = ""
if CHARTING_INSTALLED and path.replace("/", "_")[1:] in Charting.functions():
parameter_map["chart"] = Parameter(
name="chart",
kind=Parameter.POSITIONAL_OR_KEYWORD,
annotation=bool,
default=False,
)
if MethodDefinition.is_deprecated_function(path):
deprecation_message = MethodDefinition.get_deprecation_message(path)
code += " simplefilter('always', DeprecationWarning)\n"
code += f""" warn("{deprecation_message}", category=DeprecationWarning, stacklevel=2)\n\n"""
info = {}
code += " return self._run(\n"
code += f""" "{path}",\n"""
code += " **filter_inputs(\n"
for name, param in parameter_map.items():
if name == "extra_params":
fields = param.annotation.__args__[0].__dataclass_fields__
values = {k: k for k in fields}
for k in values:
if extra := MethodDefinition.get_extra(fields[k]):
info[k] = extra
code += f" {name}=kwargs,\n"
elif name == "provider_choices":
field = param.annotation.__args__[0].__dataclass_fields__["provider"]
available = field.type.__args__
cmd = path.strip("/").replace("/", ".")
code += " provider_choices={\n"
code += ' "provider": self._get_provider(\n'
code += " provider,\n"
code += f' "{cmd}",\n'
code += f" {available},\n"
code += " )\n"
code += " },\n"
elif MethodDefinition.is_annotated_dc(param.annotation):
fields = param.annotation.__args__[0].__dataclass_fields__
values = {k: k for k in fields}
code += f" {name}={{\n"
for k, v in values.items():
code += f' "{k}": {v},\n'
if extra := MethodDefinition.get_extra(fields[k]):
info[k] = extra
code += " },\n"
else:
code += f" {name}={name},\n"
if info:
code += f" info={info},\n"
if MethodDefinition.is_data_processing_function(path):
code += " data_processing=True,\n"
code += " )\n"
code += " )\n"
return code
@classmethod
def get_expanded_type(
cls,
field_name: str,
extra: Optional[dict] = None,
original_type: Optional[type] = None,
) -> object:
"""Expand the original field type."""
if extra and any(
(
v.get("multiple_items_allowed")
if isinstance(v, dict)
# For backwards compatibility, before this was a list
else "multiple_items_allowed" in v
)
for v in extra.values()
):
if original_type is None:
raise ValueError(
"multiple_items_allowed requires the original type to be specified."
)
return List[original_type] # type: ignore
return cls.TYPE_EXPANSION.get(field_name, ...)
@classmethod
def build_command_method(
cls,
path: str,
func: Callable,
model_name: Optional[str] = None,
examples: Optional[List[Example]] = None,
) -> str:
"""Build the command method."""
func_name = func.__name__
sig = signature(func)
parameter_map = dict(sig.parameters)
formatted_params = cls.format_params(path=path, parameter_map=parameter_map)
code = cls.build_command_method_signature(
func_name=func_name,
formatted_params=formatted_params,
return_type=sig.return_annotation,
path=path,
model_name=model_name,
)
code += cls.build_command_method_doc(
path=path,
func=func,
formatted_params=formatted_params,
model_name=model_name,
examples=examples,
)
code += cls.build_command_method_body(path=path, func=func)
return code
class DocstringGenerator:
"""Dynamically generate docstrings for the commands."""
provider_interface = ProviderInterface()
@staticmethod
def get_field_type(
field_type: Any,
is_required: bool,
target: Literal["docstring", "website"] = "docstring",
) -> str:
"""Get the implicit data type of a defined Pydantic field.
Parameters
----------
field_type : Any
Typing object containing the field type.
is_required : bool
Flag to indicate if the field is required.
target : Literal["docstring", "website"]
Target to return type for. Defaults to "docstring".
Returns
-------
str
String representation of the field type.
"""
is_optional = not is_required
try:
_type = field_type
if "BeforeValidator" in str(_type):
_type = "Optional[int]" if is_optional else "int" # type: ignore
_type = (
str(_type)
.replace("<class '", "")
.replace("'>", "")
.replace("typing.", "")
.replace("pydantic.types.", "")
.replace("datetime.datetime", "datetime")
.replace("datetime.date", "date")
.replace("NoneType", "None")
.replace(", None", "")
)
if "openbb_" in str(_type):
_type = (
str(_type).split(".", maxsplit=1)[0].split("openbb_")[0]
+ str(_type).rsplit(".", maxsplit=1)[-1]
)
_type = (
f"Optional[{_type}]"
if is_optional and "Optional" not in str(_type)
else _type
)
if target == "website":
_type = re.sub(r"Optional\[(.*)\]", r"\1", _type)
return _type
except TypeError:
# Fallback to the annotation if the repr fails
return field_type # type: ignore
@staticmethod
def get_OBBject_description(