fabricatio 0.2.7.dev2__cp312-cp312-win_amd64.whl → 0.2.7.dev3__cp312-cp312-win_amd64.whl

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.
@@ -0,0 +1,276 @@
1
+ """A module containing the ArticleOutline class, which represents the outline of an academic paper."""
2
+
3
+ from enum import Enum
4
+ from typing import TYPE_CHECKING, Generator, List, Optional, Tuple, Union, overload
5
+
6
+ import regex
7
+ from fabricatio.models.extra.article_proposal import ArticleProposal
8
+ from fabricatio.models.generic import Base, CensoredAble, Display, PersistentAble, WithRef
9
+ from fabricatio.models.utils import ok
10
+ from pydantic import Field
11
+
12
+ if TYPE_CHECKING:
13
+ from fabricatio.models.extra.article_main import Article, ArticleBase
14
+
15
+
16
+ class ReferringType(str, Enum):
17
+ """Enumeration of different types of references that can be made in an article."""
18
+
19
+ CHAPTER: str = "chapter"
20
+ SECTION: str = "section"
21
+ SUBSECTION: str = "subsection"
22
+
23
+
24
+ class ArticleRef(CensoredAble):
25
+ """Reference to a specific chapter, section or subsection within the article. You SHALL not refer to an article component that is external and not present within our own article."""
26
+
27
+ referred_chapter_title: str
28
+ """`title` Field of the referenced chapter"""
29
+
30
+ referred_section_title: Optional[str] = None
31
+ """`title` Field of the referenced section. Defaults to None if not applicable, which means the reference is pointing to the entire chapter."""
32
+
33
+ referred_subsection_title: Optional[str] = None
34
+ """`title` Field of the referenced subsection. Defaults to None if not applicable, which means the reference is pointing to the entire section."""
35
+
36
+ def __hash__(self) -> int:
37
+ """Overrides the default hash function to ensure consistent hashing across instances."""
38
+ return hash((self.referred_chapter_title, self.referred_section_title, self.referred_subsection_title))
39
+
40
+ @overload
41
+ def deref(self, article: "Article") -> Optional["ArticleBase"]:
42
+ """Dereference the reference to the actual section or subsection within the provided article."""
43
+
44
+ @overload
45
+ def deref(self, article: "ArticleOutline") -> Optional["ArticleOutlineBase"]:
46
+ """Dereference the reference to the actual section or subsection within the provided article."""
47
+
48
+ def deref(self, article: Union["ArticleOutline", "Article"]) -> Union["ArticleOutlineBase", "ArticleBase", None]:
49
+ """Dereference the reference to the actual section or subsection within the provided article.
50
+
51
+ Args:
52
+ article (ArticleOutline | Article): The article to dereference the reference from.
53
+
54
+ Returns:
55
+ ArticleBase | ArticleOutline | None: The dereferenced section or subsection, or None if not found.
56
+ """
57
+ chap = next((chap for chap in article.chapters if chap.title == self.referred_chapter_title), None)
58
+ if self.referred_section_title is None or chap is None:
59
+ return chap
60
+ sec = next((sec for sec in chap.sections if sec.title == self.referred_section_title), None)
61
+ if self.referred_subsection_title is None or sec is None:
62
+ return sec
63
+ return next((subsec for subsec in sec.subsections if subsec.title == self.referred_subsection_title), None)
64
+
65
+ @property
66
+ def referring_type(self) -> ReferringType:
67
+ """Determine the type of reference based on the presence of specific attributes."""
68
+ if self.referred_subsection_title is not None:
69
+ return ReferringType.SUBSECTION
70
+ if self.referred_section_title is not None:
71
+ return ReferringType.SECTION
72
+ return ReferringType.CHAPTER
73
+
74
+
75
+ class ArticleOutlineBase(Base):
76
+ """Base class for article outlines."""
77
+
78
+ writing_aim: List[str]
79
+ """Required: List of specific rhetorical objectives (3-5 items).
80
+ Format: Each item must be an actionable phrase starting with a verb.
81
+ Example: ['Establish metric validity', 'Compare with baseline approaches',
82
+ 'Justify threshold selection']"""
83
+ depend_on: List[ArticleRef]
84
+ """Required: List of all essential ArticleRef objects identifying components this section builds upon.
85
+ Format: Each reference must point to a previously defined chapter, section, or subsection.
86
+ Note: Circular dependencies are not permitted."""
87
+ support_to: List[ArticleRef]
88
+ """Required: List of all essential ArticleRef objects identifying components this section provides evidence for.
89
+ Format: Each reference must point to a specific chapter, section, or subsection.
90
+ Note: References form a directed acyclic graph in the document structure."""
91
+
92
+ description: str
93
+ """Description of the research component in academic style."""
94
+ title: str
95
+ """Title of the research component in academic style."""
96
+
97
+
98
+ class ArticleSubsectionOutline(ArticleOutlineBase):
99
+ """Atomic research component specification for academic paper generation."""
100
+
101
+
102
+ class ArticleSectionOutline(ArticleOutlineBase):
103
+ """A slightly more detailed research component specification for academic paper generation."""
104
+
105
+ subsections: List[ArticleSubsectionOutline] = Field(min_length=1)
106
+ """List of subsections, each containing a specific research component. Must contains at least 1 subsection, But do remember you should always add more subsection as required."""
107
+
108
+
109
+ class ArticleChapterOutline(ArticleOutlineBase):
110
+ """Macro-structural unit implementing standard academic paper organization."""
111
+
112
+ sections: List[ArticleSectionOutline] = Field(min_length=1)
113
+ """Standard academic progression implementing chapter goals:
114
+ 1. Context Establishment
115
+ 2. Technical Presentation
116
+ 3. Empirical Validation
117
+ 4. Comparative Analysis
118
+ 5. Synthesis
119
+
120
+ Must contains at least 1 sections, But do remember you should always add more section as required.
121
+ """
122
+
123
+
124
+ class ArticleOutline(Display, CensoredAble, WithRef[ArticleProposal], PersistentAble):
125
+ """Complete academic paper blueprint with hierarchical validation."""
126
+
127
+ article_language: str
128
+ """Written language of the article. SHALL be aligned to the language of the article proposal provided."""
129
+
130
+ title: str
131
+ """Title of the academic paper."""
132
+
133
+ prospect: str
134
+ """Consolidated research statement with four pillars:
135
+ 1. Problem Identification: Current limitations
136
+ 2. Methodological Response: Technical approach
137
+ 3. Empirical Validation: Evaluation strategy
138
+ 4. Scholarly Impact: Field contributions
139
+
140
+ Example: 'Addressing NAS computational barriers through constrained
141
+ differentiable search spaces, validated via cross-lingual MT experiments
142
+ across 50+ languages, enabling efficient architecture discovery with
143
+ 60% reduced search costs.'"""
144
+
145
+ chapters: List[ArticleChapterOutline]
146
+ """List of ArticleChapterOutline objects representing the academic paper's structure."""
147
+
148
+ abstract: str
149
+ """The abstract is a concise summary of the academic paper's main findings."""
150
+
151
+ def finalized_dump(self) -> str:
152
+ """Generates standardized hierarchical markup for academic publishing systems.
153
+
154
+ Implements ACL 2024 outline conventions with four-level structure:
155
+ = Chapter Title (Level 1)
156
+ == Section Title (Level 2)
157
+ === Subsection Title (Level 3)
158
+ ==== Subsubsection Title (Level 4)
159
+
160
+ Returns:
161
+ str: Strictly formatted outline with academic sectioning
162
+
163
+ Example:
164
+ = Methodology
165
+ == Neural Architecture Search Framework
166
+ === Differentiable Search Space
167
+ ==== Constrained Optimization Parameters
168
+ === Implementation Details
169
+ == Evaluation Protocol
170
+ """
171
+ lines: List[str] = []
172
+ for i, chapter in enumerate(self.chapters, 1):
173
+ lines.append(f"= Chapter {i}: {chapter.title}")
174
+ for j, section in enumerate(chapter.sections, 1):
175
+ lines.append(f"== {i}.{j} {section.title}")
176
+ for k, subsection in enumerate(section.subsections, 1):
177
+ lines.append(f"=== {i}.{j}.{k} {subsection.title}")
178
+ return "\n".join(lines)
179
+
180
+ def iter_dfs(self) -> Generator[ArticleOutlineBase, None, None]:
181
+ """Iterates through the article outline in a depth-first manner.
182
+
183
+ Returns:
184
+ ArticleOutlineBase: Each component in the article outline.
185
+ """
186
+ for chapter in self.chapters:
187
+ for section in chapter.sections:
188
+ yield from section.subsections
189
+ yield section
190
+ yield chapter
191
+
192
+ def resolve_ref_error(self) -> str:
193
+ """Resolve reference errors in the article outline.
194
+
195
+ Returns:
196
+ str: Error message indicating reference errors in the article outline.
197
+
198
+ Notes:
199
+ This function is designed to find all invalid `ArticleRef` objs in `depend_on` and `support_to` fields, which will be added to the final error summary.
200
+ """
201
+ summary = ""
202
+ for component in self.iter_dfs():
203
+ for ref in component.depend_on:
204
+ if not ref.deref(self):
205
+ summary += f"Invalid internal reference in {component.__class__.__name__} titled `{component.title}` at `depend_on` field, because the referred {ref.referring_type} is not exists within the article, see the original obj dump: {ref.model_dump()}\n"
206
+ for ref in component.support_to:
207
+ if not ref.deref(self):
208
+ summary += f"Invalid internal reference in {component.__class__.__name__} titled `{component.title}` at `support_to` field, because the referred {ref.referring_type} is not exists within the article, see the original obj dump: {ref.model_dump()}\n"
209
+
210
+ return summary
211
+
212
+ @classmethod
213
+ def from_typst_code(
214
+ cls, typst_code: str, title: str = "", article_language: str = "en", prospect: str = "", abstract: str = ""
215
+ ) -> "ArticleOutline":
216
+ """Parses a Typst code string and creates an ArticleOutline instance."""
217
+ self = cls(article_language=article_language, prospect=prospect, abstract=abstract, chapters=[], title=title)
218
+ stack = [self] # 根节点为ArticleOutline实例
219
+
220
+ for line in typst_code.splitlines():
221
+ parsed = cls._parse_line(line)
222
+ if not parsed:
223
+ continue
224
+ level, title = parsed
225
+ cls._adjust_stack(stack, level)
226
+ parent = stack[-1]
227
+ component = cls._create_component(level, title)
228
+ cls._add_to_parent(parent, component, level)
229
+ stack.append(component)
230
+
231
+ return self
232
+
233
+ @classmethod
234
+ def _parse_line(cls, line: str) -> Optional[Tuple[int, str]]:
235
+ stripped = line.strip()
236
+ if not stripped.startswith("="):
237
+ return None
238
+ match = regex.match(r"^(\=+)(.*)", stripped)
239
+ if not match:
240
+ return None
241
+ eqs, title_part = match.groups()
242
+ return len(eqs), title_part.strip()
243
+
244
+ @classmethod
245
+ def _adjust_stack(cls, stack: List[object], target_level: int) -> None:
246
+ while len(stack) > target_level:
247
+ stack.pop()
248
+
249
+ @classmethod
250
+ def _create_component(cls, level: int, title: str) -> ArticleOutlineBase:
251
+ default_kwargs = {
252
+ "writing_aim": [],
253
+ "depend_on": [],
254
+ "support_to": [],
255
+ "description": [],
256
+ }
257
+ component_map = {
258
+ 1: lambda: ArticleChapterOutline(title=title, sections=[], **default_kwargs),
259
+ 2: lambda: ArticleSectionOutline(title=title, subsections=[], **default_kwargs),
260
+ 3: lambda: ArticleSubsectionOutline(title=title, **default_kwargs),
261
+ }
262
+ return ok(component_map.get(level, lambda: None)(), "Invalid level")
263
+
264
+ @classmethod
265
+ def _add_to_parent(
266
+ cls,
267
+ parent: Union["ArticleOutline", ArticleChapterOutline, ArticleSectionOutline],
268
+ component: ArticleOutlineBase,
269
+ level: int,
270
+ ) -> None:
271
+ if level == 1 and isinstance(component, ArticleChapterOutline):
272
+ parent.chapters.append(component)
273
+ elif level == 2 and isinstance(component, ArticleSectionOutline): # noqa: PLR2004
274
+ parent.sections.append(component)
275
+ elif level == 3 and isinstance(component, ArticleSubsectionOutline): # noqa: PLR2004
276
+ parent.subsections.append(component)
@@ -0,0 +1,37 @@
1
+ """A structured proposal for academic paper development with core research elements."""
2
+
3
+ from typing import Dict, List
4
+
5
+ from fabricatio.models.generic import AsPrompt, CensoredAble, Display, PersistentAble, WithRef
6
+ from pydantic import Field
7
+
8
+
9
+ class ArticleProposal(CensoredAble, Display, WithRef[str], AsPrompt, PersistentAble):
10
+ """Structured proposal for academic paper development with core research elements.
11
+
12
+ Guides LLM in generating comprehensive research proposals with clearly defined components.
13
+ """
14
+
15
+ article_language: str
16
+ """Written language of the article. SHALL be aligned to the language of the article briefing provided."""
17
+
18
+ title: str = Field(...)
19
+ """Paper title in academic style (Title Case, 8-15 words). Example: 'Exploring Neural Architecture Search for Low-Resource Machine Translation'"""
20
+
21
+ focused_problem: List[str]
22
+ """Specific research problem(s) or question(s) addressed (list of 1-3 concise statements).
23
+ Example: ['NAS computational overhead in low-resource settings', 'Architecture transferability across language pairs']"""
24
+
25
+ research_aim: List[str]
26
+ """Primary research objectives (list of 2-4 measurable goals).
27
+ Example: ['Develop parameter-efficient NAS framework', 'Establish cross-lingual architecture transfer metrics']"""
28
+
29
+ research_methods: List[str]
30
+ """Methodological components (list of techniques/tools).
31
+ Example: ['Differentiable architecture search', 'Transformer-based search space', 'Multi-lingual perplexity evaluation']"""
32
+
33
+ technical_approaches: List[str]
34
+ """Technical approaches"""
35
+
36
+ def _as_prompt_inner(self) -> Dict[str, str]:
37
+ return {"ArticleBriefing": self.referenced, "ArticleProposal": self.display()}
@@ -103,6 +103,41 @@ class WithRef[T](Base):
103
103
  return self
104
104
 
105
105
 
106
+ class PersistentAble(Base):
107
+ """Class that provides a method to persist the object."""
108
+
109
+ def persist(self, path: str | Path) -> Self:
110
+ """Persist the object to a file.
111
+
112
+ Args:
113
+ path (str | Path): The path to save the object.
114
+
115
+ Returns:
116
+ Self: The current instance of the object.
117
+ """
118
+ p = Path(path)
119
+ out = self.model_dump_json()
120
+ if p.is_dir():
121
+ p.joinpath(f"{self.__class__.__name__}_{blake3_hash(out.encode())[:6]}.json").write_text(
122
+ out, encoding="utf-8"
123
+ )
124
+ return self
125
+ p.mkdir(exist_ok=True, parents=True)
126
+ p.write_text(out, encoding="utf-8")
127
+ return self
128
+
129
+ def from_persistent(self, path: str | Path) -> Self:
130
+ """Load the object from a file.
131
+
132
+ Args:
133
+ path (str | Path): The path to load the object from.
134
+
135
+ Returns:
136
+ Self: The current instance of the object.
137
+ """
138
+ return self.model_validate_json(Path(path).read_text(encoding="utf-8"))
139
+
140
+
106
141
  class WithBriefing(Named, Described):
107
142
  """Class that provides a briefing based on the name and description."""
108
143
 
@@ -11,11 +11,11 @@ class Message(BaseModel):
11
11
  """A class representing a message."""
12
12
 
13
13
  model_config = ConfigDict(use_attribute_docstrings=True)
14
- role: Literal["user", "system", "assistant"] = Field(default="user")
14
+ role: Literal["user", "system", "assistant"]
15
15
  """
16
16
  Who is sending the message.
17
17
  """
18
- content: str = Field(default="")
18
+ content: str
19
19
  """
20
20
  The content of the message.
21
21
  """
@@ -172,12 +172,14 @@ def override_kwargs[T](kwargs: Dict[str, T], **overrides) -> Dict[str, T]:
172
172
  kwargs.update({k: v for k, v in overrides.items() if v is not None})
173
173
  return kwargs
174
174
 
175
+
175
176
  def fallback_kwargs[T](kwargs: Dict[str, T], **overrides) -> Dict[str, T]:
176
177
  """Fallback the values in kwargs with the provided overrides."""
177
- kwargs.update({k: v for k, v in overrides.items() if k not in kwargs})
178
+ kwargs.update({k: v for k, v in overrides.items() if k not in kwargs})
178
179
  return kwargs
179
180
 
180
- def ok[T](val: Optional[T], msg:str="Value is None") -> T:
181
+
182
+ def ok[T](val: Optional[T], msg: str = "Value is None") -> T:
181
183
  """Check if a value is None and raise a ValueError with the provided message if it is.
182
184
 
183
185
  Args:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fabricatio
3
- Version: 0.2.7.dev2
3
+ Version: 0.2.7.dev3
4
4
  Classifier: License :: OSI Approved :: MIT License
5
5
  Classifier: Programming Language :: Rust
6
6
  Classifier: Programming Language :: Python :: 3.12
@@ -1,7 +1,8 @@
1
- fabricatio-0.2.7.dev2.dist-info/METADATA,sha256=FuFYXWRaOSL3hauoIRP1WP_dJtA9qQ90MVE9H_HFrAk,14236
2
- fabricatio-0.2.7.dev2.dist-info/WHEEL,sha256=jABKVkLC9kJr8mi_er5jOqpiQUjARSLXDUIIxDqsS50,96
3
- fabricatio-0.2.7.dev2.dist-info/licenses/LICENSE,sha256=do7J7EiCGbq0QPbMAL_FqLYufXpHnCnXBOuqVPwSV8Y,1088
4
- fabricatio/actions/article.py,sha256=u1rS2AAUts2mnPqRePQFWhZBvUlNwQO4mKUmfR4qaJA,7514
1
+ fabricatio-0.2.7.dev3.dist-info/METADATA,sha256=6O8sm_fbzBC9kYdt9UKzf8ZoXEfFcLGWKHOgJMvC52Q,14236
2
+ fabricatio-0.2.7.dev3.dist-info/WHEEL,sha256=jABKVkLC9kJr8mi_er5jOqpiQUjARSLXDUIIxDqsS50,96
3
+ fabricatio-0.2.7.dev3.dist-info/licenses/LICENSE,sha256=do7J7EiCGbq0QPbMAL_FqLYufXpHnCnXBOuqVPwSV8Y,1088
4
+ fabricatio/actions/article.py,sha256=AgxNKIRLXF9T-TdrhLPE8NWmT8QZXz1QvFnouvuoRBc,7684
5
+ fabricatio/actions/article_rag.py,sha256=PiOFxI6VTmLXm3BK-01g_KH1mTE9uOtnA-CwUjt16AU,1456
5
6
  fabricatio/actions/output.py,sha256=K7xsBH8MjXRH6JOy3ZO94KCQzX2jNrwPPK_rRXVkS0E,1161
6
7
  fabricatio/actions/rag.py,sha256=QBdzEM8MloM_ahx5pTBZAETm9_631lTe_0ih_he_Iuo,2759
7
8
  fabricatio/capabilities/correct.py,sha256=8GOU2VBPUakjG-r59SqsCgCD0QHX-l__IynCLO-ib8Q,6482
@@ -19,14 +20,17 @@ fabricatio/fs/__init__.py,sha256=PCf0s_9KDjVfNw7AfPoJzGt3jMq4gJOfbcT4pb0D0ZY,588
19
20
  fabricatio/journal.py,sha256=stnEP88aUBA_GmU9gfTF2EZI8FS2OyMLGaMSTgK4QgA,476
20
21
  fabricatio/models/action.py,sha256=UlflniS__MMrUXglu_U3PDFAtKEjVsKEix17AT9oP3M,8769
21
22
  fabricatio/models/events.py,sha256=QvlnS8FEELg6KNabcJMeh2GV_y0ZBzKOPphcteKYWYU,4183
22
- fabricatio/models/extra.py,sha256=g1w4fPPN-znbDFLQYxTzT-ngvi_mwiA3BXBK3U4XfgU,33415
23
- fabricatio/models/generic.py,sha256=k4nGSnCKmCqcRs852jhphILZXwRRuNAhx1rf4ZBCPF0,15731
23
+ fabricatio/models/extra/article_essence.py,sha256=DUESuK4CGgkRvIMoJCv4l8MNp5MawRYoNOtLCrFRPXY,9229
24
+ fabricatio/models/extra/article_main.py,sha256=F6rhHMICErzvtRIEWdxS5AoY9thLhUUeDofoJbNF9ZI,13984
25
+ fabricatio/models/extra/article_outline.py,sha256=0t-aI3OtY1O1_dhwDDm1y4kUdqoh4bmQ8voNe6MDU4w,12452
26
+ fabricatio/models/extra/article_proposal.py,sha256=eXtomW88urP9M4aKbVNN9dct0GH-fBwYOM_Rcq3d7j4,1771
27
+ fabricatio/models/generic.py,sha256=TXNPGeVOWJnCKJ6KZU8T-SWQ913woX4Xt1BLJ0x4V9M,16820
24
28
  fabricatio/models/kwargs_types.py,sha256=chJ-rHaeBVRUPuORHuGR3DdNxxTUrotz0eflPEh4l4w,5474
25
29
  fabricatio/models/role.py,sha256=mmQbJ6GKr2Gx3wtjEz8d-vYoXs09ffcEkT_eCXaDd3E,2782
26
30
  fabricatio/models/task.py,sha256=8NaR7ojQWyM740EDTqt9stwHKdrD6axCRpLKo0QzS-I,10492
27
31
  fabricatio/models/tool.py,sha256=kD0eB7OxO9geZOxO6JIKvCBeG-KOpRAkfRZqK_WGfW4,7105
28
32
  fabricatio/models/usages.py,sha256=BSqTENSva8Flga3bPBfwuc1nHo5Z_29oYzar99NbjLM,31566
29
- fabricatio/models/utils.py,sha256=NyIS82Gex4Q9qs6pzys5HplQ6JJXOLJBj4OkMPZYioc,5910
33
+ fabricatio/models/utils.py,sha256=yjxPZ6N7QGpGwkI_Vb28Ud3EhkdlB-tyfGRHAZMcGxs,5872
30
34
  fabricatio/parser.py,sha256=9Jzw-yV6uKbFvf6sPna-XHdziVGVBZWvPctgX_6ODL8,6251
31
35
  fabricatio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
32
36
  fabricatio/toolboxes/arithmetic.py,sha256=WLqhY-Pikv11Y_0SGajwZx3WhsLNpHKf9drzAqOf_nY,1369
@@ -37,6 +41,6 @@ fabricatio/workflows/rag.py,sha256=-YYp2tlE9Vtfgpg6ROpu6QVO8j8yVSPa6yDzlN3qVxs,5
37
41
  fabricatio/_rust.pyi,sha256=dGTGV7viu3YAGl1cRKIWrdHPc1hlwk3_hbaDaswxdVo,3831
38
42
  fabricatio/_rust_instances.py,sha256=2GwF8aVfYNemRI2feBzH1CZfBGno-XJJE5imJokGEYw,314
39
43
  fabricatio/__init__.py,sha256=SzBYsRhZeL77jLtfJEjmoHOSwHwUGyvMATX6xfndLDM,1135
40
- fabricatio/_rust.cp312-win_amd64.pyd,sha256=lOWesZXJMOLJI1YaeUJ7POMGcUkj18dalXlv-eNHKQ0,1840128
41
- fabricatio-0.2.7.dev2.data/scripts/tdown.exe,sha256=3Hnf6QrzesUMqUflXmsbyS8IJgPJ45sTupsZlaWk9yM,3402752
42
- fabricatio-0.2.7.dev2.dist-info/RECORD,,
44
+ fabricatio/_rust.cp312-win_amd64.pyd,sha256=JqLbZHAa0qBcJyWzAWC4Px5MTCxV9VN_BMsfm4saGus,1840128
45
+ fabricatio-0.2.7.dev3.data/scripts/tdown.exe,sha256=2sqdWL-XEloL8IsQRQ9wZ_4O0aaLO02jgeb8KWCLgdM,3402752
46
+ fabricatio-0.2.7.dev3.dist-info/RECORD,,