Metadata-Version: 2.5
Name: foodscholar
Version: 0.1.0
Summary: Hierarchical knowledge graph over nutrition literature
Project-URL: Homepage, https://github.com/wisefood/foodscholar-lib
Project-URL: Documentation, https://foodscholar-lib.readthedocs.io
Project-URL: Issues, https://github.com/wisefood/foodscholar-lib/issues
Author-email: dpetrou <dpetrou@athenarc.gr>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Requires-Python: >=3.11
Requires-Dist: networkx
Requires-Dist: numpy
Requires-Dist: pandas
Requires-Dist: pyarrow
Requires-Dist: pydantic>=2
Requires-Dist: pyyaml
Requires-Dist: structlog
Requires-Dist: typer>=0.12
Provides-Extra: all
Requires-Dist: anthropic; extra == 'all'
Requires-Dist: docling; extra == 'all'
Requires-Dist: docling-core; extra == 'all'
Requires-Dist: elasticsearch>=8; extra == 'all'
Requires-Dist: gliner; extra == 'all'
Requires-Dist: gliner2; extra == 'all'
Requires-Dist: google-genai; extra == 'all'
Requires-Dist: graphviz>=0.20; extra == 'all'
Requires-Dist: groq; extra == 'all'
Requires-Dist: hdbscan; extra == 'all'
Requires-Dist: hnswlib; extra == 'all'
Requires-Dist: inflect; extra == 'all'
Requires-Dist: leidenalg; extra == 'all'
Requires-Dist: matplotlib>=3.7; extra == 'all'
Requires-Dist: neo4j>=5; extra == 'all'
Requires-Dist: nltk; extra == 'all'
Requires-Dist: ollama; extra == 'all'
Requires-Dist: openai; extra == 'all'
Requires-Dist: pronto; extra == 'all'
Requires-Dist: python-igraph; extra == 'all'
Requires-Dist: pyvis>=0.3; extra == 'all'
Requires-Dist: scikit-learn; extra == 'all'
Requires-Dist: semhash; extra == 'all'
Requires-Dist: sentence-transformers; extra == 'all'
Requires-Dist: sumy; extra == 'all'
Requires-Dist: torch; extra == 'all'
Requires-Dist: transformers; extra == 'all'
Requires-Dist: umap-learn; extra == 'all'
Provides-Extra: annotate
Requires-Dist: gliner; extra == 'annotate'
Requires-Dist: gliner2; extra == 'annotate'
Requires-Dist: hnswlib; extra == 'annotate'
Requires-Dist: sentence-transformers; extra == 'annotate'
Requires-Dist: torch; extra == 'annotate'
Requires-Dist: transformers; extra == 'annotate'
Provides-Extra: bertopic
Requires-Dist: bertopic; extra == 'bertopic'
Provides-Extra: chunking
Requires-Dist: docling; extra == 'chunking'
Requires-Dist: docling-core; extra == 'chunking'
Requires-Dist: nltk; extra == 'chunking'
Requires-Dist: transformers; extra == 'chunking'
Provides-Extra: clustering
Requires-Dist: hdbscan; extra == 'clustering'
Requires-Dist: leidenalg; extra == 'clustering'
Requires-Dist: python-igraph; extra == 'clustering'
Requires-Dist: scikit-learn; extra == 'clustering'
Requires-Dist: umap-learn; extra == 'clustering'
Provides-Extra: dev
Requires-Dist: hatch; extra == 'dev'
Requires-Dist: mypy; extra == 'dev'
Requires-Dist: pronto; extra == 'dev'
Requires-Dist: pytest; extra == 'dev'
Requires-Dist: pytest-asyncio; extra == 'dev'
Requires-Dist: pytest-cov; extra == 'dev'
Requires-Dist: ruff; extra == 'dev'
Requires-Dist: twine; extra == 'dev'
Provides-Extra: elastic
Requires-Dist: elasticsearch>=8; extra == 'elastic'
Provides-Extra: llm
Requires-Dist: anthropic; extra == 'llm'
Requires-Dist: google-genai; extra == 'llm'
Requires-Dist: groq; extra == 'llm'
Requires-Dist: ollama; extra == 'llm'
Requires-Dist: openai; extra == 'llm'
Provides-Extra: neo4j
Requires-Dist: neo4j>=5; extra == 'neo4j'
Provides-Extra: ontology
Requires-Dist: pronto; extra == 'ontology'
Provides-Extra: relations
Requires-Dist: inflect; extra == 'relations'
Requires-Dist: semhash; extra == 'relations'
Provides-Extra: summarization
Requires-Dist: nltk; extra == 'summarization'
Requires-Dist: sumy; extra == 'summarization'
Provides-Extra: viz
Requires-Dist: graphviz>=0.20; extra == 'viz'
Requires-Dist: matplotlib>=3.7; extra == 'viz'
Requires-Dist: pyvis>=0.3; extra == 'viz'
Description-Content-Type: text/markdown

# foodscholar

**A hierarchical knowledge graph over a corpus of nutrition literature — built for grounded, citable answers.**

FoodScholar takes dietary guides, textbooks and scientific abstracts and runs the whole
pipeline: **chunk** the PDFs, **link** every mention to the [FoodOn](https://foodon.org)
ontology, **construct** a three-layer hierarchical graph over the result, and **retrieve**
over it. Every hit traces back to the source chunk it came from.

The library retrieves and stops there — ranked, scored evidence. Formulating an answer
means owning a model, a prompt registry, a citation format and an editorial policy, which
belong to the service asking the question.

- **Layer A — Backbone.** A curated, multi-facet menu of *shelves* projected from the
  [FoodOn](https://foodon.org) ontology (foods, health, nutrients, dietary patterns,
  allergies, sustainability).
- **Layer B — Themes.** Fine-grained topic communities discovered **per shelf** by two
  complementary passes — embedding similarity and entity relatedness — then merged.
- **Layer C — Cards.** LLM-generated write-ups for each shelf and theme, with **every
  claim cited back** to source chunks.

Underneath all three sits **Layer 0 — Relations**: typed, ontology-grounded edges
(`olive oil --reduces--> LDL cholesterol`) extracted from chunk text, each carrying the
passages it came from. Opt-in, because extraction costs an LLM pass over the corpus.

**Retrieval** (`fs.retrieve()`) is the Extended KG-Gen hybrid: a passage is scored on how
it reads (0.3), on what its extracted triples assert (0.3), and on where it sits in the
entity graph by Personalized PageRank (0.4). The graph branches make it more than vector
search — a passage on "sodium and hypertension" surfaces for "salt and blood pressure"
because the graph connects them, not because the words match. It reads the stores
directly, so there is no index artifact to build, mount or keep in step with the graph.

📖 **[Full documentation →](https://foodscholar-lib.readthedocs.io)**

## Install

```bash
conda create -n foodscholar python=3.11 -y
conda activate foodscholar
pip install -e '.[dev]'        # extras: llm, elastic, neo4j, clustering, viz,
                               #         annotate, ontology, relations, chunking
```

See [docs: Installation](docs/getting-started/installation.md) for the extras matrix and
local services.

## Quickstart

```python
from foodscholar import FoodScholar
from foodscholar.io.chunk import Chunk

# Zero-config: in-memory stores + mock embedder + mock LLM. No services, no keys.
fs = FoodScholar.in_memory()

fs.upsert_chunks([
    Chunk(chunk_id="c1", text="Mediterranean diet reduces cardiovascular risk.",
          source_doc_id="d1", source_type="abstract", section_type="abstract"),
])
fs.info()
```

For a real build, drive everything from a YAML config and run the phases:

```python
fs = FoodScholar.from_config("config.yaml")

# Optional: produce the corpus from source PDFs (needs the [chunking] extra).
fs.chunk_documents("data/pdfs/guides", out_dir="data/corpus", source_type="guide")

fs.init(); fs.ingest("data/corpus", nel_dir="data/ner"); fs.embed()
fs.build_entities()
fs.build_relations()              # Layer 0 — opt-in, needs a real LLM
fs.build_layer_a(); fs.attach(); fs.build_layer_b(facet="foods"); fs.build_layer_c()

fs.relations.for_entity("FOODON:03301710")   # what the corpus asserts about olive oil

# Retrieval: ranked passages + the branch scores that ranked them.
# The library retrieves; formulating an answer is your pipeline's job.
hits, trace = fs.retrieve("Is olive oil heart-healthy?", k=5)
```

[`notebooks/graph_build.ipynb`](notebooks/graph_build.ipynb) is a clean, phase-by-phase
walk-through with an offline (`memory`) and a real (`elastic` + `neo4j`) mode.

## Documentation

| | |
|---|---|
| [Quickstart](docs/getting-started/quickstart.md) · [Configuration](docs/getting-started/configuration.md) | get going, then configure stores/LLM/layers |
| [Architecture](docs/concepts/architecture.md) · [Layers A](docs/concepts/layer-a-backbone.md)/[B](docs/concepts/layer-b-themes.md)/[C](docs/concepts/layer-c-cards.md) | the design and the three layers |
| **[Extended KG-Gen](docs/concepts/extended-kg-gen.md)** | **the method: chunk → link → extract → ground → retrieve** |
| [Layer 0 — Relations](docs/concepts/layer-0-relations.md) | typed edges under the entity graph |
| [Retrieval](docs/concepts/retrieval.md) | the three scoring branches, the cost model and its bounds |
| [Corpus input](docs/concepts/corpus-input.md) · [Annotation](docs/concepts/annotation.md) | the input format and the NER/linking pipeline |
| [Chunking a corpus](docs/guides/chunking-a-corpus.md) · [Building](docs/guides/building-the-graph.md) · [Exploring](docs/guides/exploring-the-graph.md) · [Visualization](docs/guides/visualization.md) · [Tuning Layer B](docs/guides/tuning-layer-b.md) | task guides |
| [API reference](docs/reference/index.md) | the public surface, from docstrings |

`config.example.yaml` documents every config field; [`BRIEF.md`](BRIEF.md) is the
original design brief.

## Testing

Run in the `foodscholar` conda env (Python 3.11):

```bash
conda activate foodscholar
pytest                       # unit tests
pytest -m integration        # requires docker-compose: ES + Neo4j
ruff check src tests
```

> The `base` env's older NumPy can be incompatible with newer Pythons — always use the `foodscholar` env.

Method-selection provenance lives under `research/` and is not shipped — the Layer A
bake-off (`pytest research/`) and the NER/NEL bake-off harness
(`research/ner_nel_bakeoff/`, which gates any change to the NER or linker defaults).

## Layout

```
src/foodscholar/
├── facade.py        # the FoodScholar facade (entry point)
├── graph_view.py    # fs.graph + Shelf/Theme/Card handles
├── config.py        # Pydantic config + YAML loader
├── io/              # data contracts (Chunk, Shelf, Theme, Card, Entity, Relation)
├── corpus/          # chunker (PDFs/text -> corpus CSVs) + chunk & NEL loading
├── annotate/        # GLiNER / GLiNER2 NER + dense HNSW linking + embeddings
├── relations/       # Layer 0: extract -> dedupe -> ground -> aggregate
├── ontology/        # FoodOn loader + lookup (FoodOnAPI)
├── llm/             # provider-agnostic LLM client + fallback chain
├── layer_a/         # backbone projection + aliasing
├── layer_b/         # per-shelf theme discovery (two passes + merge)
├── layer_c/         # cited write-up cards
├── retrieval/       # Extended KG-Gen hybrid retrieval (fs.retrieve)
├── storage/         # protocols + memory / elastic / neo4j adapters
├── viz/             # renderable graph views (incl. the interactive tree)
├── cli/             # typer entry point
└── evaluation/      # gates + scorers
```
```
notebooks/graph_build.ipynb   # phase-by-phase build + interactive tree
docs/                         # Sphinx docs (published on Read the Docs)
research/                     # archived method bake-offs (not shipped)
scripts/corpus/               # corpus-prep tools that run upstream of the library
```
