Full Code of sparkmicro/Ki-nTree for AI

main fb96b0cfcc4f cached
103 files
497.4 KB
128.9k tokens
287 symbols
1 requests
Download .txt
Showing preview only (529K chars total). Download the full file or copy to clipboard to get everything.
Repository: sparkmicro/Ki-nTree
Branch: main
Commit: fb96b0cfcc4f
Files: 103
Total size: 497.4 KB

Directory structure:
gitextract_ks9t75m5/

├── .coveragerc
├── .github/
│   └── workflows/
│       └── test_deploy.yaml
├── .gitignore
├── LICENSE
├── README.md
├── invoke.yaml
├── kintree/
│   ├── __init__.py
│   ├── common/
│   │   ├── part_tools.py
│   │   ├── progress.py
│   │   └── tools.py
│   ├── config/
│   │   ├── automationdirect/
│   │   │   ├── automationdirect_api.yaml
│   │   │   └── automationdirect_config.yaml
│   │   ├── config_interface.py
│   │   ├── digikey/
│   │   │   ├── digikey_api.yaml
│   │   │   ├── digikey_categories.yaml
│   │   │   └── digikey_config.yaml
│   │   ├── element14/
│   │   │   ├── element14_api.yaml
│   │   │   └── element14_config.yaml
│   │   ├── inventree/
│   │   │   ├── categories.yaml
│   │   │   ├── inventree_dev.yaml
│   │   │   ├── inventree_prod.yaml
│   │   │   ├── parameters.yaml
│   │   │   ├── parameters_filters.yaml
│   │   │   ├── stock_locations.yaml
│   │   │   ├── supplier_parameters.yaml
│   │   │   └── suppliers.yaml
│   │   ├── jameco/
│   │   │   ├── jameco_api.yaml
│   │   │   └── jameco_config.yaml
│   │   ├── kicad/
│   │   │   ├── kicad.yaml
│   │   │   └── kicad_map.yaml
│   │   ├── lcsc/
│   │   │   ├── lcsc_api.yaml
│   │   │   └── lcsc_config.yaml
│   │   ├── mouser/
│   │   │   ├── mouser_api.yaml
│   │   │   └── mouser_config.yaml
│   │   ├── settings.py
│   │   ├── tme/
│   │   │   ├── tme_api.yaml
│   │   │   └── tme_config.yaml
│   │   └── user/
│   │       ├── general.yaml
│   │       ├── internal_part_number.yaml
│   │       └── search_api.yaml
│   ├── database/
│   │   ├── inventree_api.py
│   │   └── inventree_interface.py
│   ├── gui/
│   │   ├── gui.py
│   │   └── views/
│   │       ├── common.py
│   │       ├── main.py
│   │       └── settings.py
│   ├── kicad/
│   │   ├── kicad_interface.py
│   │   ├── kicad_symbol.py
│   │   ├── templates/
│   │   │   ├── LICENSE
│   │   │   ├── capacitor-polarized.kicad_sym
│   │   │   ├── capacitor.kicad_sym
│   │   │   ├── connector.kicad_sym
│   │   │   ├── crystal-2p.kicad_sym
│   │   │   ├── default.kicad_sym
│   │   │   ├── diode-led.kicad_sym
│   │   │   ├── diode-schottky.kicad_sym
│   │   │   ├── diode-standard.kicad_sym
│   │   │   ├── diode-zener.kicad_sym
│   │   │   ├── eeprom-sot23.kicad_sym
│   │   │   ├── ferrite-bead.kicad_sym
│   │   │   ├── fuse.kicad_sym
│   │   │   ├── inductor.kicad_sym
│   │   │   ├── integrated-circuit.kicad_sym
│   │   │   ├── library_template.kicad_sym
│   │   │   ├── oscillator-4p.kicad_sym
│   │   │   ├── protection-unidir.kicad_sym
│   │   │   ├── resistor-sm.kicad_sym
│   │   │   ├── resistor.kicad_sym
│   │   │   ├── transistor-nfet.kicad_sym
│   │   │   ├── transistor-npn.kicad_sym
│   │   │   ├── transistor-pfet.kicad_sym
│   │   │   └── transistor-pnp.kicad_sym
│   │   └── templates_project/
│   │       ├── templates_project.kicad_pcb
│   │       ├── templates_project.kicad_prl
│   │       ├── templates_project.kicad_pro
│   │       └── templates_project.kicad_sch
│   ├── kintree_gui.py
│   ├── search/
│   │   ├── automationdirect_api.py
│   │   ├── digikey_api.py
│   │   ├── element14_api.py
│   │   ├── jameco_api.py
│   │   ├── lcsc_api.py
│   │   ├── mouser_api.py
│   │   ├── search_api.py
│   │   ├── snapeda_api.py
│   │   └── tme_api.py
│   └── setup_inventree.py
├── kintree_gui.py
├── poetry.toml
├── pyproject.toml
├── requirements.txt
├── run_tests.py
├── setup.cfg
├── tasks.py
└── tests/
    ├── files/
    │   ├── FOOTPRINTS/
    │   │   └── RF.pretty/
    │   │       ├── Skyworks_SKY13575_639LF.kicad_mod
    │   │       └── Skyworks_SKY65404-31.kicad_mod
    │   ├── SYMBOLS/
    │   │   └── TEST.kicad_sym
    │   ├── digikey_config.yaml
    │   ├── inventree_default_db.sqlite3
    │   ├── inventree_dev.yaml
    │   ├── kicad_map.yaml
    │   └── results.tgz
    └── test_samples.yaml

================================================
FILE CONTENTS
================================================

================================================
FILE: .coveragerc
================================================
[run]
omit =
    # Do not run coverage on environment files
    *env*
    # Skip GUI coverage
    kintree/kintree_gui.py
    kintree/gui/*
    kintree/common/progress.py
    # Skip test script
    run_tests.py

================================================
FILE: .github/workflows/test_deploy.yaml
================================================
name: tests | linting | publishing

on:
  push:
    branches:
      - main
    tags:
      - "*.*.*"
    paths-ignore:
      - README.md
      - images/**
  pull_request:
    branches:
      - main

jobs:
  style:
    name: Style checks
    runs-on: ubuntu-latest

    strategy:
      matrix:
        python-version: ['3.9', '3.10', '3.11', '3.12']

    steps:
      - name: Checkout code
        uses: actions/checkout@v2
      - name: set up python ${{ matrix.python-version }}
        uses: actions/setup-python@v2
        with:
          python-version: ${{ matrix.python-version }}
      - name: Install dependencies
        run: |
          pip install -U flake8 invoke
      - name: PEP checks
        run: >
          invoke style

  tests:
    name: Integration tests

    runs-on: ubuntu-latest
    env:
      INVENTREE_DB_ENGINE: django.db.backends.sqlite3
      INVENTREE_DB_NAME: ${{ github.workspace }}/InvenTree/inventree_default_db.sqlite3
      INVENTREE_MEDIA_ROOT: ${{ github.workspace }}/InvenTree
      INVENTREE_STATIC_ROOT: ${{ github.workspace }}/InvenTree/static
      INVENTREE_BACKUP_DIR: ${{ github.workspace }}/InvenTree/backup
      INVENTREE_ENV: 0
      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      TOKEN_DIGIKEY: ${{ secrets.TOKEN_DIGIKEY }}
      DIGIKEY_CLIENT_ID: ${{ secrets.DIGIKEY_CLIENT_ID }}
      DIGIKEY_CLIENT_SECRET: ${{ secrets.DIGIKEY_CLIENT_SECRET }}
      DIGIKEY_LOCAL_SITE: US
      DIGIKEY_LOCAL_LANGUAGE: en
      DIGIKEY_LOCAL_CURRENCY: USD
      TME_API_TOKEN: ${{ secrets.TME_API_TOKEN }}
      TME_API_SECRET: ${{ secrets.TME_API_SECRET }}

    continue-on-error: true
    strategy:
      matrix:
        python-version: ['3.9', '3.10', '3.11', '3.12']

    steps:
      - name: Checkout code
        uses: actions/checkout@v2
      - name: Set up Python ${{ matrix.python-version }}
        uses: actions/setup-python@v2
        with:
          python-version: ${{ matrix.python-version }}
      - name: Install dependencies
        run: |
          sudo apt install sqlite3
          pip install -U pip invoke coveralls
      - name: InvenTree setup
        run: |
          git clone https://github.com/inventree/InvenTree/
          mkdir InvenTree/static
          cp tests/files/inventree_default_db.sqlite3 InvenTree/
          cd InvenTree/ && git switch stable && invoke install && invoke migrate && cd -
      - name: Ki-nTree setup
        run: |
          invoke install
          mkdir -p ~/.config/kintree/user/ && mkdir -p ~/.config/kintree/cache/search/
          cp tests/files/inventree_dev.yaml ~/.config/kintree/user/
          cp tests/files/kicad_map.yaml ~/.config/kintree/user/
          cp tests/files/digikey_config.yaml ~/.config/kintree/user/
          cp tests/files/results.tgz ~/.config/kintree/cache/search/
          cd ~/.config/kintree/cache/search/ && tar xvf results.tgz && cd -
      - name: GUI test
        run: |
          python kintree_gui.py b > gui.log 2>&1 &
          sleep 2
          cat gui.log
          export len_log=$(cat gui.log | wc -l)
          [[ ${len_log} -eq 0 ]] && true || false
      - name: Setup Digi-Key token
        if: ${{ github.ref == 'refs/heads/main' || github.event.pull_request.head.repo.full_name == 'sparkmicro/Ki-nTree' }}
        run: |
          git clone https://$TOKEN_DIGIKEY@github.com/eeintech/digikey-token.git
          cd digikey-token/
          python digikey_token_refresh.py
          git config --global user.email "kintree@github.actions"
          git config --global user.name "Ki-nTree Github Actions"
          git add -u
          git diff-index --quiet HEAD || git commit -m "Update token"
          git push origin master
          cp token_storage.json ~/.config/kintree/cache/
          dk_token=$(cat ~/.config/kintree/cache/token_storage.json)
          echo -e "Digi-Key Token: $dk_token\n"
          cd ..
      - name: Run tests
        if: ${{ github.ref == 'refs/heads/main' || github.event.pull_request.head.repo.full_name == 'sparkmicro/Ki-nTree' }}
        run: |
          invoke test -e 1
        env:
          MOUSER_PART_API_KEY: ${{ secrets.MOUSER_PART_API_KEY }}
          ELEMENT14_PART_API_KEY: ${{ secrets.ELEMENT14_PART_API_KEY }}
      - name: Run tests (skip APIs)
        if: ${{ github.ref != 'refs/heads/main' && github.event.pull_request.head.repo.full_name != 'sparkmicro/Ki-nTree' }}
        run: |
          invoke test -e 0
      - name: Coveralls
        if: ${{ github.ref == 'refs/heads/main' || github.event.pull_request.head.repo.full_name == 'sparkmicro/Ki-nTree' }}
        run: |
          coveralls --version
          coveralls --service=github
      - name: Run build
        run: |
          invoke build

  test-publish:
    name: Publish to Test PyPI, then PyPI
    if: startsWith(github.ref, 'refs/tags/')
    runs-on: ubuntu-latest
    needs:
      - style
      - tests
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
      - name: Alter the version in pyproject.toml and overwrite __version__
        run: >
          GTAG=$(echo $REF | sed -e 's#.*/##') &&
          sed
          --in-place
          --expression
          "s/version = \".*\" # placeholder/version = \"$GTAG\"/g"
          pyproject.toml
          && echo "__version__ = '$GTAG'" > kintree/__init__.py
        env:
          REF: ${{ github.ref }}
      - name: Display the inferred version
        run: |
          head pyproject.toml
          head kintree/__init__.py
      - name: Set up Python 3.10
        uses: actions/setup-python@v2
        with:
          python-version: '3.10'
      - name: Install dependencies
        run: pip install -U poetry
      - name: Install poetry dependencies
        run: poetry install --no-root --no-interaction
      - name: Build the package
        run: poetry build --no-interaction
      - name: Set up TestPyPI repo in poetry
        run: poetry config repositories.test https://test.pypi.org/legacy/
      - name: Publish to Test PyPI
        run: >
          poetry publish
          --repository "test"
          --username "__token__"
          --password "$TOKEN_TEST_PYPI"
        env:
          TOKEN_TEST_PYPI: ${{ secrets.TOKEN_TEST_PYPI }}
      - name: Publish to PyPI
        run: >
          poetry publish
          --username "__token__"
          --password "$TOKEN_PYPI"
        env:
          TOKEN_PYPI: ${{ secrets.TOKEN_PYPI }}


================================================
FILE: .gitignore
================================================
# Build files
dist/
build/
*.spec
# Cache and backup files
*__pycache__*
*.bck
# Test files
kintree/tests/*
.coverage
htmlcov/
.vscode/launch.json


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# <img src="https://raw.githubusercontent.com/sparkmicro/Ki-nTree/main/images/logo.png" width="auto" height="32"> Ki-nTree
### Fast part creation for [KiCad](https://kicad.org/) and [InvenTree](https://inventree.org/) 
[![License: GPL v3.0](https://img.shields.io/badge/license-GPL_v3.0-green.svg)](https://www.gnu.org/licenses/gpl-3.0)
[![Python Versions](https://raw.githubusercontent.com/sparkmicro/Ki-nTree/main/images/python_versions.svg)](https://www.python.org/)
[![PyPI](https://img.shields.io/pypi/v/kintree)](https://pypi.org/project/kintree/)
[![Tests | Linting | Publishing](https://github.com/sparkmicro/Ki-nTree/actions/workflows/test_deploy.yaml/badge.svg)](https://github.com/sparkmicro/Ki-nTree/actions)
[![Coverage Status](https://coveralls.io/repos/github/sparkmicro/Ki-nTree/badge.svg?branch=main&service=github)](https://coveralls.io/github/sparkmicro/Ki-nTree?branch=main)

## :warning: InvenTree Compatibility
InvenTree `0.12` introduced a new parameter template system which was not supported until version `0.12.6` came out, see https://github.com/sparkmicro/Ki-nTree/issues/165 for more details. In short, Ki-nTree currently supports InvenTree `0.11` or older versions, and `0.12.6` and future versions. From `0.13.0` onwards a InvenTree setting needs to be modified for Ki-nTree to work: `InvenTree Settings` -> `Part Parameters` -> `Enforce Parameter Units` -> **OFF** (requires administrator rights)

## :fast_forward: [Demo Video](https://youtu.be/YeWBqOCb4pw)

<img src="https://raw.githubusercontent.com/sparkmicro/Ki-nTree/main/images/doc/kintree_v1_example.png" width="auto" height="auto">

## Introduction
Ki-nTree (pronounced "Key Entry" or "Key 'n' Tree") aims to:
* automate part creation of KiCad library parts
* automate part creation of InvenTree parts
* synchronize parts data between KiCad and InvenTree

Ki-nTree works with:
- [Digi-Key](https://developer.digikey.com/), [Mouser](https://www.mouser.com/api-hub/), [Element14](https://partner.element14.com/docs) and [LCSC](https://lcsc.com/) **enormous** part databases and free APIs
- the awesome open-source [InvenTree Inventory Management System](https://github.com/inventree/inventree) built and maintained by [@SchrodingersGat](https://github.com/SchrodingersGat) and [@matmair](https://github.com/matmair)
- the reliable and SCM-friendly KiCad file parser [KiUtils](https://github.com/mvnmgrx/kiutils) built and maintained by [@mvnmgrx](https://github.com/mvnmgrx)
- the amazing [Digi-Key API python library](https://github.com/peeter123/digikey-api) built and maintained by [@peeter123](https://github.com/peeter123)
- the [Mouser Python API](https://github.com/sparkmicro/mouser-api/) built and maintained by [@eeintech](https://github.com/eeintech)

> :warning: **Important Note**
>
> Ki-nTree version `1.2.x` and forward support Digi-Key API version **4 only**.
>
> Ki-nTree version `1.0.x` and forward support KiCad versions **6 and up**.
>
> Ki-nTree versions `0.5.x` and `0.6.x` only support KiCad version **6** (`pip install kintree==0.6.6`).
>
> To use with KiCad version **5**, use older Ki-nTree `0.4.x` versions (`pip install kintree==0.4.8`).

Ki-nTree was developed by [@eeintech](https://github.com/eeintech) for [SPARK Microsystems](https://www.sparkmicro.com/), who generously accepted to make it open-source!

## Get Started

### Requirements

* Ki-nTree is currently tested for Python 3.9 to 3.12 versions.
* Ki-nTree requires a Digi-Key **production** API instance. To create one, go to https://developer.digikey.com/. Create an account, an organization and add a **production** API to your organization. Save both Client ID and Secret keys.
> [Here is a video](https://youtu.be/OI1EGEc0Ju0) to help with the different steps
* Ki-nTree requires a Mouser Search API key. To request one, head over to https://www.mouser.ca/api-search/ and click on "Sign Up for Search API"
* Ki-nTree requires an Element14 Product Search API key to fetch part information for the following suppliers: Farnell (Europe), Newark (North America) and Element14 (Asia-Pacific). To request one, head over to https://partner.element14.com/ and click on "Register"
* on rolling release distributions like Arch Linux some Flet dependencies need to be repaired manually:
```
sudo pacman -S mpv
sudo ln -s /usr/lib/libmpv.so /usr/lib/libmpv.so.1 
```

### Installation (system wide)

1. Install using Pip

``` bash
pip install -U kintree
```

2. Run Ki-nTree

``` bash
kintree
```

### Run in virtual environment (contained)

##### Linux / MacOS

Create a virtual environment and activate it with:

``` bash
$ python3 -m venv env-kintree
$ source env-kintree/bin/activate
```

Then follow the steps from the [installation section](#installation-system-wide).

##### Windows

In Git Bash, use the following commands to create and activate a virtual environment:
``` bash
$ python3 -m venv env-kintree
$ source env-kintree/Scripts/activate
```
For any other Windows terminal, refer to the [official documentation](https://docs.python.org/library/venv.html#creating-virtual-environments)

### Packages
#### Arch Linux

Ki-nTree is [available on Arch Linux's AUR](https://aur.archlinux.org/packages/python-kintree/) as `python-kintree`.

### Usage Instructions

#### Before Starting

If you intend to use Ki-nTree with InvenTree, this tool offers to setup the InvenTree category tree with a simple script that you can run as follow:

> :warning: Warning: Before running it, make sure you have setup your category tree in your `categories.yaml` configuration file according to your own preferences, else it will use the [default setup](https://github.com/sparkmicro/Ki-nTree/blob/main/kintree/config/inventree/categories.yaml).

``` bash
python3 -m kintree.setup_inventree
```

If the InvenTree category tree is **not setup** before starting to use Ki-nTree, you **won't be able to add parts** to InvenTree.

#### Advanced Configuration

Configuration files are stored in the folder pointed by the `Configuration Files Folder` path in the "User Settings" window:

<img src="https://raw.githubusercontent.com/sparkmicro/Ki-nTree/main/images/doc/kintree_v1_settings_user.png" width="600" height="auto">

<details>
<summary><b>Click here to read about configuration files</b></summary>
<p>

Ki-nTree uses a number of YAML configuration files to function. New users shouldn't need to worry about them to try out Ki-nTree (except for `categories.yaml` as mentioned in the previous section), however they can be modified to customize behavior and workflow.

Below is a summary table of the different configuration files, their function and if they are updated by the GUI:
| Filename | Function | GUI Update? |
| --- | --- | --- |
| `categories.yaml` | InvenTree categories hierarchy tree and category codes for IPN generation (see [Before Starting section](#before-starting)) | :x: |
| `general.yaml` | General user settings | :heavy_check_mark: |
| `internal_part_number.yaml` | Controls for IPN generation | :heavy_check_mark: |
| `inventree_<env>.yaml` | InvenTree login credentials, per environment (`<env>=['dev', 'prod']`) | :heavy_check_mark: |
| `kicad.yaml` | KiCad symbol, footprint and library paths | :heavy_check_mark: |
| `kicad_map.yaml` | Mapping between InvenTree parent categories and KiCad symbol/footprint libraries and templates | :x: |
| `parameters.yaml` | List of InvenTree parameters templates (see [InvenTree Part Parameters documentation](https://docs.inventree.org/en/latest/part/parameter/)) | :x: |
| `parameters_filters.yaml` | Mapping between InvenTree parent categories and InvenTree parameters templates | :x: |
| `search_api.yaml` | Generic controls for Supplier search APIs like cache validity | :heavy_check_mark: |
| `supplier_parameters.yaml` | Mapping between InvenTree parameters templates and suppliers parameters/attributes, sorted by InvenTree parent categories (see [Part Parameters section](#part-parameters)) | :x: |
| `<supplier>_config.yaml` | Mapping for supplier name and search results fields, to overwrite defaults (`<supplier>=['digikey', 'element14', 'lcsc', 'mouser']`) | :x: |
| `<supplier>_api.yaml` | Required supplier API fields, custom to each supplier (`<supplier>=['digikey', 'element14', 'lcsc', 'mouser']`) | :heavy_check_mark: |
| `digikey_categories.yaml` | Mapping between InvenTree categories and Digi-Key categories | :x: |
| `digikey_parameters.yaml` | Mapping between InvenTree parameters and Digi-Key parameters/attributes | :x: |

> Ki-nTree only supports matching between InvenTree and Digi-Key categories and parameters/attributes (help wanted!)

</p>
</details>

#### InvenTree Permissions

Each InvenTree user has a set of permissions associated to them.
Please refer to the [InvenTree documentation](https://inventree.readthedocs.io/en/latest/settings/permissions/) to understand how to setup user permissions.

The minimum set of user/group permission required to add parts to InvenTree is:
- "Part - Add" to add InvenTree parts
- "Purchase Orders - Add" to add manufacturers, suppliers and their associated parts

If you wish to automatically add subcategories while creating InvenTree parts, you will need to enable the "Part Categories - Add" permission.

Note that each time you enable the "Add" permission to an object, InvenTree automatically enables the "Change" permission to that object too.

#### Settings
1. With Ki-nTree GUI open, click on "Settings > Supplier > Digi-Key" and fill in both Digi-Key API Client ID and Secret keys (optional: click on "Test" to [get an API token](#get-digi-key-api-token))
2. Click on "Settings > Supplier > Mouser" and fill in the Mouser part search API key
3. Click on "Settings > Supplier > Element14" and fill in the Element14 product search API key (key is shared with Farnell and Newark)
4. Click on "Settings > KiCad", browse to the location where KiCad symbol, template and footprint libraries are stored on your computer then click "Save"
5. If you intend to use InvenTree with this tool, click on "Settings > InvenTree" and fill in your InvenTree server address and credentials then click "Save" (optional: click on "Test" to check communication with server)  
  a. It is possible to define a Proxy Server over which all interactions with InvenTree will be routed. To set a proxy server use the "Enable Proxy Support" switch in "Settings > InvenTree" and define the proxy address in the new input field.  
  b. Instead of user credential authentication token authentication is also supported. To use a token add it it to the "Password or Token" field and leave the "Username" empty. You can retrieve your personal access token from your InvenTree server by sending an get-request to its api url `api/user/token/`.
  c. If needed this tool can try to download the parts datasheet from the suppliers and upload it it to the attachment section of each part. For this just activate "Upload Datasheets to InvenTree" in the InvenTree settings
  d. It is also possible to sync the prices in InvenTree with the latest supplier prices. For this enable "Upload Pricing Data to InvenTree"
6. If your InvenTree server requires a IPN in a specific pattern make sure to adjust "Settings > InvenTree > Internal Part Number" to match it or adjust the servers pattern to the one yo set in Ki-nTree 

> Note: All URLs should start with "http://" if they do not have a valid SSL certificate.

#### Get Digi-Key API token
<details>
<summary>Show steps (click to expand)</summary>
<p>

Enter your Digi-Key developer account credentials then login. The following page will appear (`user@email.com` will show your email address):

<img src="https://raw.githubusercontent.com/sparkmicro/Ki-nTree/main/images/doc/digikey_api_approval_request.png" width="600" height="auto">

Click on "Allow", another page will open.  
Click on the "Advanced" button, then click on "Proceed to localhost (unsafe)" at the bottom of the page:

<img src="https://raw.githubusercontent.com/sparkmicro/Ki-nTree/main/images/doc/digikey_api_approval_request2.png"  width="600" height="auto">

> On Chrome, if the "Proceed to localhost (unsafe)" link does not appear, enable the following flag: [chrome://flags/#allow-insecure-localhost](chrome://flags/#allow-insecure-localhost)

Lastly, a new page will open with a "You may now close this window." message, proceed to get the token.

</p>
</details>

#### Part Parameters

Ki-nTree uses **supplier** parameters to populate **InvenTree** parameters. In order to match between supplier and InvenTree, users need to setup the configuration file `supplier_parameters.yaml` with the following mapping for each category:
``` yaml
CATEGORY_NAME:
  INVENTREE_PARAMETER_NAME:
    - SUPPLIER_1_PARAMETER_NAME_1
    - SUPPLIER_1_PARAMETER_NAME_2
    - SUPPLIER_2_PARAMETER_NAME_1
```

It is also possible to cross reference the mappings of different categories. To define one or multiple parent categories a parameter named `parent` can be added where the items then are the desired parent categories. If a parameter name is present in both parent and child, the childs definition will override the parent.

A template image for an category can be set by using the `image` parameter. The sole item in this parameter must the filename of an already existing part image on the the InvenTree server.

Refer to [this file](https://github.com/sparkmicro/Ki-nTree/blob/main/kintree/config/inventree/supplier_parameters.yaml) as a starting point / example.

#### Part Number Search

Ki-nTree currently supports APIs for the following electronics suppliers: Digi-Key, Mouser, Element14, TME and LCSC.

1. In the main window, enter the part number and select the supplier in drop-down list, then click the "Submit" button (arrow). It will start by fetching part data using the supplier's API
2. In the case Digi-Key has been selected and the API token is not found or expired, a browser window will pop-up. To get a new token: [follow those steps](#get-digi-key-api-token)
3. Once the part data has been successfully fetched from the supplier's API, you can review the part information in the different fields and edit them, if needed.
4. Then, go to the Inventree tabl to pick the `Category` and `Subcategory` to use for this part
5. If you desire to add this part to KiCad, click the KiCad tab and select the KiCad symbol library, the template and the footprint library to use for this part
6. Finally, go to the Create tab and launch the part creation. It will take some time to complete the process in InvenTree and/or KiCad, once it finishes you'll be notified of the result  

If the part was created or found in InvenTree, and if you have selected this option in the settings, your browser will automatically open and navigate to the new Inventree part page.

#### Kicad Templates

The automatic part generation in KiCad is controlled via templates:

* Template examples are shipped together with Ki-nTree, these can be adjusted to your liking or you also can create completely new ones.
* Each template has its own library file where the file name defines the templates name.
* The templates can use the parameters and attributes of the InvenTree part on a wildcard base. So you can add for example `Resistance@Tolerance` into a field and the resulting part will then have the resistance and the tolerance value inside this text field. 
* Using the templates and wildcards without the InvenTree functions enabled is also possible. In this case the library parameter wildcards need to be configured in the `supplier_parameters.yaml` for each library individually.


Enjoy!

*For any problem/bug you find, please [report an issue](https://github.com/sparkmicro/Ki-nTree/issues).*

## Development

### Requirements

You need `python>=3.9` and `poetry`.

You can install poetry by following the instructions [on its official website](https://python-poetry.org/docs/master/#installation), by using `pip install poetry` or by installing a package on your Linux distro.

### Setup and run
1. Clone this repository
``` bash
git clone https://github.com/sparkmicro/Ki-nTree
```

2. Install the requirements into a `poetry`-managed virtual environment
``` bash
poetry install
Installing dependencies from lock file
...
Installing the current project: kintree (1.1.99)
```
> Note: the version is not accurate (placeholder only)

3. Run Ki-nTree in the virtual environment
```bash
poetry run python -m kintree_gui
```
or

```bash
$ poetry shell
$ python -m kintree_gui
```

#### Build
1. Make sure you followed the previous installation steps, then run:
``` bash
$ poetry build
Building kintree (1.1.99)
  - Building sdist
  - Built kintree-1.1.99.tar.gz
  - Building wheel
  - Built kintree-1.1.99-py3-none-any.whl
```
2. Exit the virtual environment (`Ctrl + D` on Linux; you can also close the
   terminal and reopen it in the same folder).

   Run `pip install dist/<wheel_file>.whl` with the file name from the previous
   step. For example:

```bash
pip install dist/kintree-1.1.99-py3-none-any.whl
```

3. You can now start Ki-nTree by typing `kintree` in the terminal, provided
   that your python dist path is a part of your `$PATH`.

## License
The Ki-nTree source code is licensed under the [GPL3.0 license](https://github.com/sparkmicro/Ki-nTree/blob/main/LICENSE) as it uses source code under that license:
* https://github.com/mvnmgrx/kiutils
* https://github.com/peeter123/digikey-api

The [KiCad templates](https://github.com/sparkmicro/Ki-nTree/tree/main/kintree/kicad/templates) are licensed under the [Creative Commons CC0 1.0 license](https://github.com/sparkmicro/Ki-nTree/blob/main/kintree/kicad/templates/LICENSE) which means that "you can copy, modify, distribute and perform the work, even for commercial purposes, all without asking permission" ([reference](https://creativecommons.org/publicdomain/zero/1.0/)).


================================================
FILE: invoke.yaml
================================================
debug: true
run:
    echo: false

================================================
FILE: kintree/__init__.py
================================================
# WARNING: This file is overwriten when publishing to PyPI
# __version__ refers to the tag version instead

# VERSION INFORMATION
version_info = {
    'MAJOR_REVISION': 1,
    'MINOR_REVISION': 2,
    'RELEASE_STATUS': '1',
}

__version__ = '.'.join([str(v) for v in version_info.values()])


================================================
FILE: kintree/common/part_tools.py
================================================
import re

from ..config import settings
from ..config import config_interface
from .tools import cprint


def generate_part_number(category: str, part_pk: int, category_code='') -> str:
    ''' Generate Internal Part Number (IPN) '''
    ipn_elements = []

    # Prefix
    if settings.CONFIG_IPN.get('IPN_ENABLE_PREFIX', False):
        ipn_elements.append(settings.CONFIG_IPN.get('IPN_PREFIX', ''))
    
    # Category code
    if settings.CONFIG_IPN.get('IPN_CATEGORY_CODE', False):
        if not category_code:
            CATEGORY_CODES = config_interface.load_file(settings.CONFIG_CATEGORIES)['CODES']
            try:
                category_code = CATEGORY_CODES.get(category, '')
            except AttributeError:
                category_code = None
        if category_code:
            ipn_elements.append(category_code)

    # Unique ID (mandatory)
    try:
        unique_id = str(part_pk).zfill(int(settings.CONFIG_IPN.get('IPN_UNIQUE_ID_LENGTH', '6')))
    except:
        return None
    ipn_elements.append(unique_id)
    
    # Suffix
    if settings.CONFIG_IPN.get('IPN_ENABLE_SUFFIX', False):
        ipn_elements.append(settings.CONFIG_IPN.get('IPN_SUFFIX', ''))
    
    # Build IPN
    ipn = '-'.join(ipn_elements)

    return ipn


def compare(new_part_parameters: dict, db_part_parameters: dict, include_filters: list) -> bool:
    ''' Compare two InvenTree parts based on parameters (specs) '''
    try:
        for parameter, value in new_part_parameters.items():
            # Check for filters
            if include_filters:
                # Compare only parameters present in include_filters
                if parameter in include_filters and value != db_part_parameters[parameter]:
                    return False
            else:
                # Compare all parameters
                if value != db_part_parameters[parameter]:
                    return False
    except KeyError:
        cprint('[INFO]\tWarning: Failed to compare part with database', silent=settings.HIDE_DEBUG)
        return False

    return True


def clean_parameter_value(category: str, name: str, value: str) -> str:
    ''' Clean-up parameter value for consumption in InvenTree and KiCad '''
    category = category.lower()
    name = name.lower()

    # Parameter specific filters
    # Package
    if 'package' in name and 'size' not in name:
        space_split = value.split()

        # Return value before the space
        if len(space_split) > 1:
            value = space_split[0].replace(',', '')

    # Sizes
    if 'size' in name or \
            'height' in name or \
            'pitch' in name or \
            'outline' in name:
        # imperial = re.findall('[.0-9]*"', value)
        metric = re.findall('[.0-9]*mm', value)
        len_metric = len(metric)

        # Return only the metric dimensions
        if len_metric > 0 and len_metric <= 1:
            # One dimension
            if 'dia' in value.lower():
                # Check if diameter value
                value = '⌀' + metric[0]
            else:
                value = metric[0]
        elif len_metric > 1 and len_metric <= 2:
            # Two dimensions
            value = metric[0].replace('mm', '') + 'x' + metric[1]
        elif len_metric > 2 and len_metric <= 3:
            # Three dimensions
            value = metric[0].replace('mm', '') + 'x' + metric[1].replace('mm', '') + 'x' + metric[2]

    # Power
    if 'power' in name:
        # decimal = re.findall('[0-9]\.[0-9]*W', value)
        ratio = re.findall('[0-9]/[0-9]*W', value)

        # Return ratio
        if len(ratio) > 0:
            value = ratio[0]

    # ESR, DCR, RDS
    if 'esr' in name or \
            'dcr' in name or \
            'rds' in name:
        value = value.replace('Max', '').replace(' ', '').replace('Ohm', 'R')

    # Category specific filters
    # RESISTORS
    if 'resistor' in category:
        if 'resistance' in name:
            space_split = value.split()

            if len(space_split) > 1:
                resistance = space_split[0]
                unit = space_split[1]

                unit_filter = ['kOhms', 'MOhms', 'GOhms']
                if unit in unit_filter:
                    unit = unit.replace('Ohms', '').upper()
                else:
                    unit = unit.replace('Ohms', 'R')

                value = resistance + unit

    # General filters
    # Clean-up ranges
    separator = '~'
    if separator in value:
        space_split = value.split()
        first_value = space_split[0]
        if len(space_split) > 2:
            second_value = space_split[2]

            # Substract digits, negative sign, points from first value to get unit
            unit = first_value.replace(re.findall('[-.0-9]*', first_value)[0], '')

            if unit:
                value = first_value.replace(unit, '') + separator + second_value

    # Remove parenthesis section
    if '(' in value:
        parenthesis = re.findall(r'\(.*\)', value)

        if parenthesis:
            for item in parenthesis:
                value = value.replace(item, '')

            # Remove leftover spaces
            value = value.replace(' ', '')

    # Remove spaces (for specific cases)
    if '@' in value:
        value = value.replace(' ', '')

    # Escape double-quote (else causes library error in KiCad)
    if '"' in value:
        value = value.replace('"', '\\"')

    # cprint(value)
    return value


================================================
FILE: kintree/common/progress.py
================================================
import time

CREATE_PART_PROGRESS: float
MAX_PROGRESS = 1.0
DEFAULT_PROGRESS = 0.1


def reset_progress_bar(progress_bar) -> bool:
    ''' Reset progress bar '''
    global CREATE_PART_PROGRESS

    # Reset progress
    CREATE_PART_PROGRESS = 0
    progress_bar.color = None
    progress_bar.value = 0
    progress_bar.update()
    time.sleep(0.1)

    return True


def progress_increment(inc):
    ''' Increment progress '''
    global CREATE_PART_PROGRESS, MAX_PROGRESS

    if CREATE_PART_PROGRESS + inc < MAX_PROGRESS:
        CREATE_PART_PROGRESS += inc
    else:
        CREATE_PART_PROGRESS = MAX_PROGRESS

    return CREATE_PART_PROGRESS


def update_progress_bar(progress_bar, increment=0) -> bool:
    ''' Update progress bar during part creation '''
    global DEFAULT_PROGRESS

    if not progress_bar:
        return True

    if increment:
        inc = increment
    else:
        # Default
        inc = DEFAULT_PROGRESS

    current_value = progress_bar.value * 100
    new_value = progress_increment(inc) * 100
    # Smooth progress
    for i in range(int(new_value - current_value)):
        progress_bar.value += i / 100
        progress_bar.update()
        time.sleep(0.05)

    return True


================================================
FILE: kintree/common/tools.py
================================================
import builtins
import json
import os
from shutil import copyfile


# CUSTOM PRINT METHOD
class pcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    ERROR = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

# Overload print function with custom pretty-print


def cprint(*args, **kwargs):
    # Check if silent is set
    try:
        silent = kwargs.pop('silent')
    except:
        silent = False
    if not silent:
        if type(args[0]) is dict:
            return builtins.print(json.dumps(*args, **kwargs, indent=4, sort_keys=True))
        else:
            try:
                args = list(args)
                if 'warning' in args[0].lower():
                    args[0] = f'{pcolors.WARNING}{args[0]}{pcolors.ENDC}'
                elif 'error' in args[0].lower():
                    args[0] = f'{pcolors.ERROR}{args[0]}{pcolors.ENDC}'
                elif 'fail' in args[0].lower():
                    args[0] = f'{pcolors.ERROR}{args[0]}{pcolors.ENDC}'
                elif 'success' in args[0].lower():
                    args[0] = f'{pcolors.OKGREEN}{args[0]}{pcolors.ENDC}'
                elif 'pass' in args[0].lower():
                    args[0] = f'{pcolors.OKGREEN}{args[0]}{pcolors.ENDC}'
                elif 'main' in args[0].lower():
                    args[0] = f'{pcolors.HEADER}{args[0]}{pcolors.ENDC}'
                elif 'skipping' in args[0].lower():
                    args[0] = f'{pcolors.BOLD}{args[0]}{pcolors.ENDC}'
                args = tuple(args)
            except:
                pass
            return builtins.print(*args, **kwargs, flush=True)
###


def create_library(library_path: str, symbol: str, template_lib: str):
    ''' Create library files if they don\'t exist '''
    if not os.path.exists(library_path):
        os.mkdir(library_path)
    new_kicad_sym_file = os.path.join(library_path, f'{symbol}.kicad_sym')
    if not os.path.exists(new_kicad_sym_file):
        copyfile(template_lib, new_kicad_sym_file)


def get_image_with_retries(url, headers, retries=3, wait=5, silent=False):
    """ Method to download image with cloudscraper library and retry attempts"""
    import cloudscraper
    import time
    scraper = cloudscraper.create_scraper()
    for attempt in range(retries):
        try:
            response = scraper.get(url, headers=headers, timeout=wait)
            if response.status_code == 200:
                return response
            else:
                cprint(f'[INFO]\tWarning: Image download Attempt {attempt + 1} failed with status code {response.status_code}. Retrying in {wait} seconds...', silent=silent)
        except Exception as e:
            cprint(f'[INFO]\tWarning: Image download Attempt {attempt + 1} encountered an error: {e}. Retrying in {wait} seconds...', silent=silent)
        time.sleep(wait)
    cprint('[INFO]\tWarning: All Image download attempts failed. Could not retrieve the image.', silent=silent)
    return None


def download(url, filetype='API data', fileoutput='', timeout=3, enable_headers=False, requests_lib=False, try_cloudscraper=False, silent=False):
    ''' Standard method to download URL content, with option to save to local file (eg. images) '''

    import socket
    import urllib.request
    import requests

    # A more detailed headers was needed for request to Jameco
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36',
        'Accept': 'applicaiton/json,image/webp,image/apng,image/*,*/*;q=0.8',
        'Accept-Encoding': 'Accept-Encoding: gzip, deflate, br',
        'Accept-Language': 'en-US,en;q=0.9',
        'Connection': 'keep-alive',
        'Cache-Control': 'no-cache',
    }

    # Set default timeout for download socket
    socket.setdefaulttimeout(timeout)
    if enable_headers and not requests_lib:
        opener = urllib.request.build_opener()
        opener.addheaders = list(headers.items())
        urllib.request.install_opener(opener)
    try:
        if filetype == 'PDF':
            # some distributors/manufacturers implement
            # redirects which don't allow direct downloads
            if 'gotoUrl' in url and 'www.ti.com' in url:
                mpn = url.split('%2F')[-1]
                url = f'https://www.ti.com/lit/ds/symlink/{mpn}.pdf'
        if filetype == 'Image' or filetype == 'PDF':
            # Enable use of requests library for downloading files (some URLs do NOT work with urllib)
            if requests_lib:
                response = requests.get(url, headers=headers, timeout=timeout, allow_redirects=True)
                if filetype.lower() not in response.headers['Content-Type'].lower():
                    cprint(f'[INFO]\tWarning: {filetype} download returned the wrong file type', silent=silent)
                    return None
                with open(fileoutput, 'wb') as file:
                    file.write(response.content)
            elif try_cloudscraper:
                response = get_image_with_retries(url, headers=headers)
                if filetype.lower() not in response.headers['Content-Type'].lower():
                    cprint(f'[INFO]\tWarning: {filetype} download returned the wrong file type', silent=silent)
                    return None
                with open(fileoutput, 'wb') as file:
                    file.write(response.content)
            else:
                (file, headers) = urllib.request.urlretrieve(url, filename=fileoutput)
                if filetype.lower() not in headers['Content-Type'].lower():
                    cprint(f'[INFO]\tWarning: {filetype} download returned the wrong file type', silent=silent)
                    return None
            return file
        else:
            # some suppliers work with requests.get(), others need urllib.request.urlopen()
            try:
                response = requests.get(url)
                data_json = response.json()
                return data_json
            except requests.exceptions.JSONDecodeError:
                try:
                    url_data = urllib.request.urlopen(url)
                    data = url_data.read()
                    data_json = json.loads(data.decode('utf-8'))
                    return data_json
                finally:
                    pass
    except (socket.timeout, requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout):
        cprint(f'[INFO]\tWarning: {filetype} download socket timed out ({timeout}s)', silent=silent)
    except (urllib.error.HTTPError, requests.exceptions.ConnectionError):
        cprint(f'[INFO]\tWarning: {filetype} download failed (HTTP Error)', silent=silent)
    except (urllib.error.URLError, ValueError, AttributeError):
        cprint(f'[INFO]\tWarning: {filetype} download failed (URL Error)', silent=silent)
    except requests.exceptions.SSLError:
        cprint(f'[INFO]\tWarning: {filetype} download failed (SSL Error)', silent=silent)
    except FileNotFoundError:
        cprint(f'[INFO]\tWarning: {os.path.dirname(fileoutput)} folder does not exist', silent=silent)
    return None


def download_with_retry(url: str, full_path: str, silent=False, **kwargs) -> str:
    ''' Standard method to download image URL to local file '''

    if not url:
        cprint('[INFO]\tError: Missing image URL', silent=silent)
        return False
    
    # Try without headers
    file = download(url, fileoutput=full_path, silent=silent, **kwargs)

    if not file:
        # Try with headers
        file = download(url, fileoutput=full_path, enable_headers=True, silent=silent, **kwargs)

    if not file:
        # Try with requests library
        file = download(url, fileoutput=full_path, enable_headers=True, requests_lib=True, silent=silent, **kwargs)
    
    if not file:
        # Try with cloudscraper
        file = download(url, fileoutput=full_path, enable_headers=True, requests_lib=False, try_cloudscraper=True, silent=silent, **kwargs)

    # Still nothing
    if not file:
        return False

    cprint(f'[INFO]\tDownload success ({url=})', silent=silent)
    return True


================================================
FILE: kintree/config/automationdirect/automationdirect_api.yaml
================================================
AUTOMATIONDIRECT_API_ROOT_URL: "https://www.automationdirect.com"
AUTOMATIONDIRECT_API_URL: "https://www.automationdirect.com/ajax?&fctype=adc.falcon.search.SearchFormCtrl&cmd=AjaxSearch"
AUTOMATIONDIRECT_API_SEARCH_QUERY: "&searchquery="              # can be anything but probably best to set to search term
AUTOMATIONDIRECT_API_SEARCH_STRING: "&solrQueryString=q%3D"     # append search term to this and combine with other params
AUTOMATIONDIRECT_API_IMAGE_PATH: "https://cdn.automationdirect.com/images/products/medium/m_" # image path for medium size image on product page

================================================
FILE: kintree/config/automationdirect/automationdirect_config.yaml
================================================
SUPPLIER_DATABASE_NAME: Automation Direct
SEARCH_NAME: null
SEARCH_DESCRIPTION: null
SEARCH_REVISION: null
SEARCH_KEYWORDS: null
SEARCH_SKU: null
SEARCH_MANUFACTURER: null
SEARCH_MPN: null
SEARCH_SUPPLIER_URL: null
SEARCH_DATASHEET: null
EXTRA_FIELDS: null

================================================
FILE: kintree/config/config_interface.py
================================================
import base64
import copy
import os
from sys import platform

import yaml
from ..common.tools import cprint

FUNCTION_FILTER_KEY = '__'


def load_file(file_path: str, silent=True) -> dict:
    ''' Safe load YAML file '''
    try:
        with open(file_path, 'r') as file:
            try:
                data = yaml.safe_load(file)
            except yaml.YAMLError as exc:
                print(exc)
                return None
    except FileNotFoundError:
        cprint(f'[ERROR]\tFile {file_path} does not exists!', silent=silent)
        return None

    return data


def dump_file(data: dict, file_path: str) -> bool:
    ''' Safe dump YAML file '''
    with open(file_path, 'w') as file:
        try:
            if platform == "win32":
                yaml.safe_dump(data, file, default_flow_style=False)
            else:
                yaml.safe_dump(data, file, default_flow_style=False, allow_unicode=True)
        except yaml.YAMLError as exc:
            print(exc)
            return False

    return True


def load_user_paths(home_dir='') -> dict:
    ''' Load user config and cache paths '''

    user_settings_file = os.path.join(home_dir, 'settings.yaml')
    user_config = load_file(user_settings_file)

    if not user_config:
        user_config = {
            'USER_FILES': os.path.join(home_dir, 'user', ''),
            'USER_CACHE': os.path.join(home_dir, 'cache', ''),
        }
        dump_file(user_config, user_settings_file)

    return user_config


def load_user_config_files(path_to_root: str, path_to_user_files: str, silent=True) -> bool:
    ''' Load user configuration files '''
    result = True

    def load_config(path):
        for template_file in os.listdir(path):
            filename = os.path.basename(template_file)
            template_data = load_file(os.path.join(path, filename))
            try:
                user_data = load_file(os.path.join(path_to_user_files, filename))
                if list(template_data.keys()) == list(user_data.keys()):
                    # Join user data to template data
                    user_settings = {**template_data, **user_data}
                else:
                    user_settings = user_data
                    # Warn user about config data discrepancies with template data
                    template_vs_user = set(template_data) - set(user_data)
                    # user_vs_template = set(user_data) - set(template_data)
                    if template_vs_user:
                        print(f'[INFO]\tTEMPLATE "{filename}" configuration file contains the following keys which are NOT in your user settings: {template_vs_user}')
                    # if user_vs_template:
                    #     cprint(f'[INFO]\tUSER SETTINGS {filename} configuration file contains the following keys which are NOT in the template: {user_vs_template}', silent=silent)

            except (TypeError, AttributeError):
                cprint(f'[INFO]\tCreating new {filename} configuration file', silent=silent)
                # Config file does not exists
                user_settings = template_data

            dump_file(user_settings, os.path.join(path_to_user_files, filename))

    for dir in ['user', 'inventree', 'kicad', 'digikey', 'mouser', 'element14', 'lcsc', 'tme', 'jameco', 'automationdirect']:
        try:
            # Load configuration
            config_files = os.path.join(path_to_root, dir, '')
            load_config(config_files)
        except FileNotFoundError:
            cprint(f'[INFO]\tWarning: Failed to load {dir.title()} configuration', silent=silent)
            result = False

    return result


def load_inventree_user_settings(user_config_path: str) -> dict:
    ''' Load InvenTree user settings from file '''
    user_settings = load_file(user_config_path)

    try:
        password = user_settings.get('PASSWORD', None)
    except AttributeError:
        return user_settings

    try:
        # Use base64 encoding to make password unreadable inside the file
        user_settings['PASSWORD'] = base64.b64decode(password).decode()
    except TypeError:
        user_settings['PASSWORD'] = ''

    if 'ENABLE_PROXY' not in user_settings:
        user_settings['ENABLE_PROXY'] = False
    proxies = user_settings.get('PROXIES', None)
    if not proxies:
        user_settings['PROXY'] = ''
    else:
        # loading the proxy independent if it is http or https
        user_settings['PROXY'] = list(proxies.values())[0]

    if 'DATASHEET_UPLOAD' not in user_settings:
        user_settings['DATASHEET_UPLOAD'] = False
    if 'PRICING_UPLOAD' not in user_settings:
        user_settings['PRICING_UPLOAD'] = False
    return user_settings


def save_inventree_user_settings(enable: bool,
                                 server: str,
                                 username: str,
                                 password: str,
                                 enable_proxy: bool,
                                 proxies: dict,
                                 datasheet_upload: bool,
                                 pricing_upload: bool,
                                 user_config_path: str):
    ''' Save InvenTree user settings to file '''
    user_settings = {}

    user_settings['ENABLE'] = enable
    user_settings['SERVER_ADDRESS'] = server
    user_settings['USERNAME'] = username
    # Use base64 encoding to make password unreadable inside the file
    user_settings['PASSWORD'] = base64.b64encode(password.encode())
    user_settings['ENABLE_PROXY'] = enable_proxy
    user_settings['PROXIES'] = proxies
    user_settings['DATASHEET_UPLOAD'] = datasheet_upload
    user_settings['PRICING_UPLOAD'] = pricing_upload

    return dump_file(user_settings, user_config_path)


def load_library_path(user_config_path: str, silent=False):
    ''' Load KiCad library from KiCad settings file '''
    user_settings = load_file(user_config_path)

    try:
        if not user_settings['KICAD_SYMBOLS_PATH'] and not silent:
            print('[INFO]\tEmpty KiCad library path')
        return user_settings['KICAD_SYMBOLS_PATH']
    except:
        # If not defined: use application root folder
        return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def add_library_path(user_config_path: str, category: str, symbol_library: str) -> bool:
    ''' Save KiCad library to KiCad settings file '''
    user_settings = load_file(user_config_path)

    if category:
        index = category
    else:
        index = symbol_library

    if not user_settings['KICAD_LIBRARIES']:
        user_settings['KICAD_LIBRARIES'] = {}

    try:
        if symbol_library not in user_settings['KICAD_LIBRARIES'][index]:
            user_settings['KICAD_LIBRARIES'][index].append(symbol_library)
    except:
        user_settings['KICAD_LIBRARIES'][index] = [symbol_library]

    return dump_file(user_settings, user_config_path)


def load_libraries_paths(user_config_path: str, library_path: str) -> dict:
    ''' Construct KiCad library files names and paths from KiCad settings file '''
    user_settings = load_file(user_config_path)

    if not os.path.exists(library_path):
        return None

    found_library_files = []
    for file in os.listdir(library_path):
        if file.endswith('.kicad_sym'):
            found_library_files.append(file.replace('.kicad_sym', ''))

    symbol_libraries_paths = {}
    assigned_files = []
    try:
        for category, libraries in user_settings['KICAD_LIBRARIES'].items():
            symbol_libraries_paths[category] = {}
            if libraries:
                for library in libraries:
                    if library in found_library_files:
                        symbol_libraries_paths[category][library] = library_path + \
                            library + '.kicad_sym'
                        assigned_files.append(library)
    except:
        pass

    for file in found_library_files:
        if file not in assigned_files:
            try:
                symbol_libraries_paths['uncategorized'].append(file)
            except:
                symbol_libraries_paths['uncategorized'] = [file]
    try:
        symbol_libraries_paths['uncategorized'] = sorted(
            symbol_libraries_paths['uncategorized'])
    except:
        pass

    # Check that library paths are loaded
    path_loaded = False
    for category, paths in symbol_libraries_paths.items():
        if paths:
            path_loaded = True
            break
    if not path_loaded:
        return None

    # print(symbol_libraries_paths)
    return symbol_libraries_paths


def load_templates_paths(user_config_path: str, template_path: str) -> dict:
    ''' Construct KiCad template files names and paths from KiCad settings file '''
    symbol_templates_paths = {}
    if not template_path or not os.path.exists(template_path):
        return symbol_templates_paths

    # Load configuration file
    user_settings = load_file(user_config_path)

    try:
        for category in user_settings['KICAD_TEMPLATES'].keys():
            for subcategory, file_name in user_settings['KICAD_TEMPLATES'][category].items():
                if subcategory == 'Default' and not file_name:
                    file_name = 'default'
                if file_name:
                    try:
                        symbol_templates_paths[category][subcategory] = template_path + \
                            file_name + '.kicad_sym'
                    except KeyError:
                        symbol_templates_paths[category] = {
                            subcategory: template_path + file_name + '.kicad_sym'
                        }
    except:
        pass

    return symbol_templates_paths


def load_footprint_paths(user_config_path: str, footprint_path: str) -> dict:
    ''' Construct KiCad footprint folder names and paths from KiCad settings file '''
    user_settings = load_file(user_config_path)

    if not os.path.exists(footprint_path):
        return None

    found_library_folders = [item.replace('.pretty', '') for item in os.listdir(footprint_path)
                             if os.path.isdir(footprint_path + item)]

    footprint_libraries_paths = {}
    assigned_folders = []
    try:
        for category, libraries in user_settings['KICAD_FOOTPRINTS'].items():
            footprint_libraries_paths[category] = {}
            if libraries:
                for folder in libraries:
                    footprint_libraries_paths[category][folder] = footprint_path + \
                        folder + '.pretty'
                    assigned_folders.append(folder)
    except:
        pass

    for folder in found_library_folders:
        if folder not in assigned_folders:
            try:
                footprint_libraries_paths['uncategorized'].append(folder)
            except:
                footprint_libraries_paths['uncategorized'] = [folder]

        # Sort uncategorized library paths
        footprint_libraries_paths['uncategorized'] = sorted(
            footprint_libraries_paths.get('uncategorized', []))

    return footprint_libraries_paths


def add_footprint_library(user_config_path: str, category: str, library_folder: str) -> bool:
    ''' Add KiCad footprint folder name to KiCad settings file '''
    user_settings = load_file(user_config_path)

    if category:
        index = category
    else:
        index = library_folder

    if not user_settings['KICAD_FOOTPRINTS']:
        user_settings['KICAD_FOOTPRINTS'] = {}

    try:
        if library_folder not in user_settings['KICAD_FOOTPRINTS'][index]:
            user_settings['KICAD_FOOTPRINTS'][index].append(library_folder)
    except:
        user_settings['KICAD_FOOTPRINTS'][index] = [library_folder]

    return dump_file(user_settings, user_config_path)


def load_supplier_categories(supplier_config_path: str, clean=False) -> dict:
    ''' Load Supplier category mapping from Supplier settings file '''
    supplier_categories = load_file(supplier_config_path)

    if clean:
        clean_supplier_categories = copy.deepcopy(supplier_categories)

        for category in supplier_categories:
            for subcategory in supplier_categories[category]:
                if FUNCTION_FILTER_KEY in subcategory:
                    clean_supplier_categories[category][subcategory.replace(FUNCTION_FILTER_KEY, '')] \
                        = supplier_categories[category][subcategory]
                    del clean_supplier_categories[category][subcategory]

        return clean_supplier_categories

    # print(supplier_categories)
    return supplier_categories


def load_supplier_categories_inversed(supplier_config_path: str) -> dict:
    ''' Load Supplier category mapping from Supplier settings file (inversed relation) '''
    supplier_categories = load_file(supplier_config_path)

    try:
        supplier_categories_inversed = {}
        for category in supplier_categories.keys():
            if supplier_categories[category]:
                for user, supplier in supplier_categories[category].items():
                    # Supplier is list type
                    if supplier:
                        if category not in supplier_categories_inversed.keys():
                            supplier_categories_inversed[category] = {}
                        for item in supplier:
                            supplier_categories_inversed[category][item] = user
    except:
        return None

    # print(supplier_categories_inversed)
    return supplier_categories_inversed


def sync_inventree_supplier_categories(inventree_config_path: str, supplier_config_path: str) -> dict:
    ''' Synchronize supplier categories dict from InvenTree categories '''
    inventree_categories = load_file(inventree_config_path)['CATEGORIES']
    supplier_categories = load_supplier_categories(supplier_config_path, clean=True)
    updated_supplier_categories = copy.deepcopy(supplier_categories)

    try:
        for category in inventree_categories:
            if category not in supplier_categories.keys():
                updated_supplier_categories[category] = inventree_categories[category]
    except:
        pass

    return updated_supplier_categories


def add_supplier_category(categories: dict, supplier_config_path: str) -> bool:
    ''' Add Supplier category mapping to Supplier settings file

        categories = {
            'Capacitors':
                { 'Tantalum': 'Tantalum Capacitors' }
        }
    '''
    try:
        supplier_categories = load_file(supplier_config_path)
    except:
        return None

    for category in categories.keys():
        for user_subcategory, supplier_category in categories[category].items():
            try:
                supplier_category_keys = supplier_categories[category].keys()
            except:
                supplier_categories[category] = {
                    user_subcategory: [supplier_category]}
                break

            # Function filtered
            inventree_subcategory_filter = FUNCTION_FILTER_KEY + user_subcategory
            if inventree_subcategory_filter in supplier_category_keys:
                try:
                    if supplier_category not in supplier_categories[category][inventree_subcategory_filter]:
                        supplier_categories[category][inventree_subcategory_filter].append(
                            supplier_category)
                    break
                except:
                    pass

                try:
                    supplier_categories[category][inventree_subcategory_filter] = [
                        supplier_category]
                    break
                except:
                    pass
            else:
                try:
                    if supplier_category not in supplier_categories[category][user_subcategory]:
                        supplier_categories[category][user_subcategory].append(
                            supplier_category)
                    break
                except:
                    pass

                try:
                    supplier_categories[category][user_subcategory] = [
                        supplier_category]
                    break
                except:
                    pass

            return False

    return dump_file(supplier_categories, supplier_config_path)


def load_category_parameters(categories: list, supplier_config_path: str) -> dict:
    ''' Load Supplier parameters mapping from Supplier settings file '''
    def find_parameters(output_dict, category_list):
        category_parameters = None
        combined = ''
        for category in reversed(category_list):
            if category:
                combined = category + combined
            if combined in category_file:
                category_parameters = category_file[combined]
                break
            if category in category_file:
                category_parameters = category_file[category]
                break
            combined = '/' + combined
        if not category_parameters:
            return
        if 'parent' in category_parameters:
            for parent in category_parameters['parent']:
                find_parameters(output_dict, [parent])
            del category_parameters['parent']

        for parameter in category_parameters.keys():
            if category_parameters[parameter]:
                for supplier_parameter in category_parameters[parameter]:
                    output_dict[supplier_parameter] = parameter

    try:
        category_file = load_file(supplier_config_path)
    except:
        return None
    category_parameters_inversed = {}

    find_parameters(category_parameters_inversed, categories)

    return category_parameters_inversed


def load_category_parameters_filters(category: str, supplier_config_path: str) -> list:
    ''' Load Supplier parameters filters from Supplier settings file '''
    try:
        parameters_filters = load_file(supplier_config_path)[category]
    except:
        return []

    # print(parameters_filters)
    return parameters_filters


================================================
FILE: kintree/config/digikey/digikey_api.yaml
================================================
DIGIKEY_CLIENT_ID: ''
DIGIKEY_CLIENT_SECRET: ''

================================================
FILE: kintree/config/digikey/digikey_categories.yaml
================================================
Capacitors:
  Aluminium:
  - Aluminum Electrolytic Capacitors
  Ceramic:
  - Ceramic Capacitors
  - Ceramic
  Polymer:
  - Aluminum - Polymer Capacitors
  - Tantalum - Polymer Capacitors
  Super Capacitors:
  - Electric Double Layer Capacitors (EDLC), Supercapacitors
  Tantalum:
  - Tantalum Capacitors
Circuit Protections:
  Fuses:
  - Fuses
  PTC:
  - PTC Resettable Fuses
  TVS:
  - TVS - Diodes
Connectors:
  Board-to-Board:
  - Rectangular Connectors - Arrays, Edge Type, Mezzanine (Board to Board)
  - Rectangular Connectors - Spring Loaded
  Coaxial:
  - Coaxial Connectors (RF)
  FPC:
  - FFC, FPC (Flat Flexible) Connectors
  Header:
  - Rectangular Connectors - Headers, Male Pins
  - Rectangular Connectors - Headers, Receptacles, Female Sockets
  Interface:
  - USB, DVI, HDMI Connectors
  - Barrel - Audio Connectors
  - Memory Connectors - PC Card Sockets
  - Modular Connectors - Jacks With Magnetics
Crystals and Oscillators:
  Crystals:
  - Crystals
  Oscillators:
  - Oscillators
Diodes:
  LED:
  - LED Indication - Discrete
  - Addressable, Specialty
  Zener:
  - Diodes - Zener - Single
  __Schottky:
  - Diodes - Rectifiers - Single
  __Standard:
  - Diodes - Rectifiers - Single
Inductors:
  Ferrite Bead:
  - Ferrite Beads and Chips
  Power:
  - Fixed Inductors
Integrated Circuits:
  Interface:
  - Interface - CODECs
  - PMIC - Battery Chargers
  - Interface - Analog Switches, Multiplexers, Demultiplexers
  - Interface - Controllers
  Logic:
  - Logic - Translators, Level Shifters
  - Clock/Timing - Clock Generators, PLLs, Frequency Synthesizers
  - Logic - Buffers, Drivers, Receivers, Transceivers
  Microcontroller:
  - Embedded - Microcontrollers
  Memory:
  - Memory
  Sensor:
  - Humidity, Moisture Sensors
  - Motion Sensors - IMUs (Inertial Measurement Units)
  - PMIC - Current Regulation/Management
Mechanicals:
  Standoff:
  - Board Spacers, Standoffs
  Switch:
  - Tactile Switches
  - Slide Switches
Power Management:
  LDO:
  - PMIC - Voltage Regulators - Linear
  __Boost:
  - PMIC - Voltage Regulators - DC DC Switching Regulators
  __Buck:
  - PMIC - Voltage Regulators - DC DC Switching Regulators
RF:
  Antenna: null
  Chipset: null
  Filter:
  - Balun
Resistors:
  Potentiometers:
  - Potentiometers, Variable Resistors
  - Rotary Potentiometers, Rheostats
  Surface Mount:
  - Chip Resistor - Surface Mount
  Through Hole:
  - Through Hole Resistors
Transistors:
  __N-Channel FET:
  - Transistors - FETs, MOSFETs - Single
  __NPN:
  - Transistors - Bipolar (BJT) - Single
  - Transistors - FETs, MOSFETs - Single
  __P-Channel FET:
  - Transistors - FETs, MOSFETs - Single
  __PNP:
  - Transistors - Bipolar (BJT) - Single
  Load Switches:
  - PMIC - Power Distribution Switches, Load Drivers


================================================
FILE: kintree/config/digikey/digikey_config.yaml
================================================
SUPPLIER_INVENTREE_NAME: Digi-Key
SEARCH_NAME: null
SEARCH_DESCRIPTION: null
SEARCH_REVISION: null
SEARCH_KEYWORDS: null
SEARCH_SKU: null
SEARCH_MANUFACTURER: null
SEARCH_MPN: null
SEARCH_SUPPLIER_URL: null
SEARCH_DATASHEET: null
EXTRA_FIELDS: null

================================================
FILE: kintree/config/element14/element14_api.yaml
================================================
ELEMENT14_PRODUCT_SEARCH_API_KEY: null
FARNELL_STORE: null
NEWARK_STORE: null
ELEMENT14_STORE: null

================================================
FILE: kintree/config/element14/element14_config.yaml
================================================
SUPPLIER_INVENTREE_NAME: null
SEARCH_NAME: null
SEARCH_DESCRIPTION: null
SEARCH_REVISION: null
SEARCH_KEYWORDS: null
SEARCH_SKU: null
SEARCH_MANUFACTURER: null
SEARCH_MPN: null
SEARCH_SUPPLIER_URL: null
SEARCH_DATASHEET: null
EXTRA_FIELDS: null

================================================
FILE: kintree/config/inventree/categories.yaml
================================================
CATEGORIES:
  Assemblies:
    Printed-Circuit Board Assembly: null
    Product: null
  Capacitors:
    Aluminium: null
    Ceramic:
      '0402': null
      '0603': null
      '0805': null
    Polymer: null
    Super Capacitors: null
    Tantalum: null
  Circuit Protections:
    Fuses: null
    PTC: null
    TVS: null
  Connectors:
    Battery: null
    Board-to-Board: null
    Coaxial: null
    FPC: null
    Header: null
    Interface: null
  Crystals and Oscillators:
    Crystals: null
    Oscillators: null
  Diodes:
    LED: null
    Schottky: null
    Standard: null
    Zener: null
  Inductors:
    Ferrite Bead: null
    Power: null
  Integrated Circuits:
    Interface: null
    Logic: null
    Memory: null
    Microcontroller: null
    Sensor: null
  Mechanicals:
    Nuts: null
    Screws: null
    Standoff: null
    Switch: null
  Miscellaneous:
    Batteries: null
  Modules: null
  Power Management:
    Boost: null
    Buck: null
    LDO: null
    PMIC: null
  Printed-Circuit Boards: null
  RF:
    Antenna: null
    Chipset: null
    Filter: null
    Shield: null
  Resistors:
    NTC: null
    Potentiometers: null
    Surface Mount: null
    Through Hole: null
  Transistors:
    Load Switches: null
    N-Channel FET: null
    NPN: null
    P-Channel FET: null
    PNP: null
CODES:
  Assemblies: PCA
  Capacitors: CAP
  Circuit Protections: PRO
  Connectors: CON
  Crystals and Oscillators: CLK
  Diodes: DIO
  Inductors: IND
  Integrated Circuits: ICS
  Mechanicals: MEC
  Miscellaneous: MIS
  Modules: MOD
  Power Management: PWR
  Printed-Circuit Boards: PCB
  RF: RFC
  Resistors: RES
  Transistors: TRA

================================================
FILE: kintree/config/inventree/inventree_dev.yaml
================================================
ENABLE: true
ENABLE_PROXY: false
PASSWORD: !!binary |
  ''
PROXIES: null
SERVER_ADDRESS: ''
USERNAME: ''
DATASHEET_UPLOAD: false

================================================
FILE: kintree/config/inventree/inventree_prod.yaml
================================================
ENABLE: true
ENABLE_PROXY: false
PASSWORD: !!binary |
  ''
PROXIES: null
SERVER_ADDRESS: ''
USERNAME: ''
DATASHEET_UPLOAD: false

================================================
FILE: kintree/config/inventree/parameters.yaml
================================================
# Parameters
# Name: Unit
Min Output Voltage: V
Antenna Type: null
B Constant: K
Breakdown Voltage: V
Capacitance: nF
Clamping Voltage: V
Collector Gate Voltage: V
DC Resistance: "m\u03A9"
ESR: "m\u03A9"
Footprint: null
Forward Voltage: V
Frequency: Hz
Frequency Stability: ppm
Frequency Tolerance: ppm
Function Type: null
Interface Type: null
LED Color: null
Load Capacitance: pF
Locking: null
Mating Height: mm
Max Input Voltage: V
Max Output Voltage: V
Maximum Gate Voltage: V
Memory Size: null
Min Input Voltage: V
Mounting Type: null
Number of Channels: null
Number of Contacts: null
Number of Elements: null
Number of Rows: null
Orientation: null
Output Current: A
Output Type: null
Package Height: mm
Package Size: mm
Package Type: null
Pitch: mm
Polarity: null
Quiescent Current: A
RDS On Resistance: "\u03A9"
RDS On Voltage: V
Rated Current: A
Rated Power: W
Rated Voltage: V
Saturation Current: A
Shielding: null
Standoff Voltage: V
Symbol: null
Temperature Grade: null
Temperature Range: "\xB0C"
Tolerance: '%'
Value: null


================================================
FILE: kintree/config/inventree/parameters_filters.yaml
================================================
Capacitors:
- Value
- Rated Voltage
- Tolerance
- Package Type
- Temperature Grade
Circuit Protections:
- Value
Connectors:
- Value
Crystals and Oscillators:
- Value
- Package Type
- Package Size
- Temperature Range
Diodes:
- Value
Inductors:
- Value
- Rated Current
- Package Type
- Package Size
- Temperature Range
Integrated Circuits:
- Value
Mechanicals:
- Value
Modules:
- null
Power Management:
- Value
Printed-Circuit Boards:
- null
RF:
- Value
Resistors:
- Value
- Tolerance
- Rated Power
- Package Type
- Temperature Range
Transistors:
- Value


================================================
FILE: kintree/config/inventree/stock_locations.yaml
================================================
STOCK_LOCATIONS: null

================================================
FILE: kintree/config/inventree/supplier_parameters.yaml
================================================
# Parameter Mapping between InvenTree parameter template and suppliers parameters naming
# Each template parameter can match to multiple suppliers parameters
# Categories (main keys) should match categories in the categories.yaml file
# Parameter template names should match those found in the parameters.yaml file
Base:
  Temperature Range:
  - Operating Temperature
  Package Type:
  - Package / Case
Passives:
  Tolerance:
  - Tolerance
Capacitors:
  parent:
  - Base
  - Passives
  ESR:
  - ESR (Equivalent Series Resistance)
  Package Height:
  - Height - Seated (Max)
  - Thickness (Max)
  Package Size:
  - Size / Dimension
  Rated Voltage:
  - Voltage - Rated
  - Voltage Rated
  Temperature Grade:
  - Temperature Coefficient
  Temperature Range:
  - Operating Temperature
  Value:
  - Capacitance
Circuit Protections:
  parent:
  - Base
  Breakdown Voltage:
  - Voltage - Breakdown (Min)
  Capacitance:
  - Capacitance @ Frequency
  Clamping Voltage:
  - Voltage - Clamping (Max) @ Ipp
  Rated Current:
  - Current Rating (Amps)
  - Current - Max
  Rated Power:
  - Power - Peak Pulse
  Rated Voltage:
  - Voltage Rating - DC
  - Voltage - Max
  Standoff Voltage:
  - Voltage - Reverse Standoff (Typ)
  Value:
  - Manufacturer Part Number
Connectors:
  Frequency:
  - Frequency - Max
  Interface Type:
  - Connector Type
  - Flat Flex Type
  Locking:
  - Locking Feature
  - Fastening Type
  Mating Height:
  - Mated Stacking Heights
  Mounting Type:
  - Mounting Type
  Number of Contacts:
  - Number of Contacts
  - Number of Positions
  Number of Rows:
  - Number of Rows
  Orientation:
  - Orientation
  Package Height:
  - Height Above Board
  - Insulation Height
  Pitch:
  - Pitch
  - Pitch - Mating
  Polarity:
  - Gender
  Shielding:
  - Shielding
  Temperature Range:
  - Operating Temperature
  Value:
  - Manufacturer Part Number
Crystals and Oscillators:
  parent:
  - Base
  Frequency Stability:
  - Frequency Stability
  Frequency Tolerance:
  - Frequency Tolerance
  Load Capacitance:
  - Load Capacitance
  Package Height:
  - Height - Seated (Max)
  Package Size:
  - Size / Dimension
  Rated Current:
  - Current - Supply (Max)
  Rated Voltage:
  - Voltage - Supply
  Value:
  - Frequency
Diodes:
  parent:
  - Base
  Forward Voltage:
  - Voltage - Forward (Vf) (Max) @ If
  - Voltage - Forward (Vf) (Typ)
  Function Type:
  - Diode Type
  LED Color:
  - Color
  Rated Current:
  - Current - Average Rectified (Io)
  Rated Power:
  - Power - Max
  Rated Voltage:
  - Voltage - DC Reverse (Vr) (Max)
  - Voltage - Zener (Nom) (Vz)
  Temperature Range:
  - Operating Temperature - Junction
  Value:
  - Manufacturer Part Number
Inductors:
  parent:
  - Base
  - Passives
  ESR:
  - DC Resistance (DCR)
  - DC Resistance (DCR) (Max)
  Package Height:
  - Height - Seated (Max)
  - Height (Max)
  Package Size:
  - Size / Dimension
  Rated Current:
  - Current Rating (Max)
  - Current Rating (Amps)
  Saturation Current:
  - Current - Saturation
  Shielding:
  - Shielding
  Value:
  - Inductance
  - Impedance @ Frequency
Integrated Circuits:
  parent:
  - Base
  Frequency:
  - Clock Frequency
  - Speed
  - Data Rate
  - Frequency Range
  - -3db Bandwidth
  Function Type:
  - Translator Type
  - Technology
  - Core Processor
  - Type
  - Sensor Type
  Memory Size:
  - Program Memory Size
  - Memory Size
  Number of Channels:
  - Channels per Circuit
  Rated Voltage:
  - Voltage - VCCA
  - Voltage - VCCB
  - Voltage - Supply
  - Voltage - Supply (Vcc/Vdd)
  - Voltage - Supply, Digital
  - Voltage - Supply, Single (V+)
  Value:
  - Manufacturer Part Number
Mechanicals:
  parent:
  - Base
  Function Type:
  - Circuit
  - Type
  Mounting Type:
  - Mounting Type
  - Features
  Package Height:
  - Between Board Height
  Package Size:
  - Outline
  - Diameter - Outside
  Package Type:
  - Screw, Thread Size
  Rated Current:
  - Contact Rating @ Voltage
  Value:
  - Manufacturer Part Number
Power Management:
  parent:
  - Base
  Min Output Voltage:
  - Voltage - Output (Min/Fixed)
  Frequency:
  - Frequency - Switching
  Function Type:
  - Topology
  Max Input Voltage:
  - Voltage - Input (Max)
  Max Output Voltage:
  - Voltage - Output (Max)
  Min Input Voltage:
  - Voltage - Input (Min)
  Output Type:
  - Output Type
  Package Type:
  - Supplier Device Package
  Quiescent Current:
  - Current - Quiescent (Iq)
  Rated Current:
  - Current - Output
  Value:
  - Manufacturer Part Number
RF:
  parent:
  - Base
  Frequency:
  - Frequency Range
  Function Type: null
  Rated Voltage: null
  Value:
  - Manufacturer Part Number
Resistors:
  parent:
  - Passives
  Package Type:
  - Supplier Device Package
  Rated Power:
  - Power (Watts)
  Temperature Range:
  - Operating Temperature
  Value:
  - Resistance
Transistors:
  Collector-Gate Voltage:
  - Vce Saturation (Max) @ Ib, Ic
  - Vgs(th) (Max) @ Id
  Function Type:
  - Transistor Type
  - FET Type
  Maximum Gate Voltage:
  - Vgs (Max)
  Package Type:
  - Supplier Device Package
  RDS On Resistance:
  - Rds On (Max) @ Id, Vgs
  Rated Current:
  - Current - Collector (Ic) (Max)
  - "Current - Continuous Drain (Id) @ 25\xB0C"
  Rated Power:
  - Power - Max
  - Power Dissipation (Max)
  Rated Voltage:
  - Voltage - Collector Emitter Breakdown (Max)
  - Drain to Source Voltage (Vdss)
  Temperature Range:
  - Operating Temperature
  Value:
  - Manufacturer Part Number


================================================
FILE: kintree/config/inventree/suppliers.yaml
================================================
Digi-Key:
  enable: true
  name: Digi-Key
Mouser:
  enable: true
  name: Mouser
Element14:
  enable: true
  name: Element14
Farnell:
  enable: true
  name: Farnell
Jameco:
  enable: true
  name: Jameco
AutomationDirect:
  enable: true
  name: Automation Direct
Newark:
  enable: true
  name: Newark
LCSC:
  enable: true
  name: LCSC
TME:
  enable: true
  name: TME

================================================
FILE: kintree/config/jameco/jameco_api.yaml
================================================
JAMECO_API_URL: https://ahzbkf.a.searchspring.io/api/search/search.json?ajaxCatalog=v3&resultsFormat=native&siteId=ahzbkf&q=

================================================
FILE: kintree/config/jameco/jameco_config.yaml
================================================
SUPPLIER_INVENTREE_NAME: Jameco Electronics
SEARCH_NAME: null
SEARCH_DESCRIPTION: null
SEARCH_REVISION: null
SEARCH_KEYWORDS: null
SEARCH_SKU: null
SEARCH_MANUFACTURER: null
SEARCH_MPN: null
SEARCH_SUPPLIER_URL: null
SEARCH_DATASHEET: null
EXTRA_FIELDS: null

================================================
FILE: kintree/config/kicad/kicad.yaml
================================================
KICAD_SYMBOLS_PATH: ''
KICAD_TEMPLATES_PATH: kintree/kicad/templates/
KICAD_FOOTPRINTS_PATH: ''

================================================
FILE: kintree/config/kicad/kicad_map.yaml
================================================
KICAD_FOOTPRINTS:
KICAD_LIBRARIES:
KICAD_TEMPLATES:
  Capacitors:
    Aluminium: capacitor-polarized
    Ceramic: capacitor
    Default: capacitor
    Polymer: capacitor-polarized
    Super Capacitors: capacitor-polarized
    Tantalum: capacitor-polarized
  Circuit Protections:
    Default: protection-unidir
    Fuse: fuse
    TVS: protection-unidir
  Connectors:
    Default: connector
  Crystals and Oscillators:
    Crystal 2P: crystal-2p
    Default: crystal-2p
    Oscillator 4P: oscillator-4p
  Diodes:
    Default: diode-standard
    LED: diode-led
    Schottky: diode-schottky
    Standard: diode-standard
    Zener: diode-zener
  Inductors:
    Default: inductor
    Ferrite Bead: ferrite-bead
    Power: inductor
  Integrated Circuits:
    Default: integrated-circuit
  Mechanicals:
    Default: default
  Power Management:
    Default: integrated-circuit
  Resistors:
    Default: resistor
    Surface Mount: resistor-sm
    Through Hole: resistor
  RF:
    Default: integrated-circuit
  Transistors:
    Default: transistor-nfet
    N-Channel FET: transistor-nfet
    NPN: transistor-npn
    P-Channel FET: transistor-pfet
    PNP: transistor-pnp


================================================
FILE: kintree/config/lcsc/lcsc_api.yaml
================================================
LCSC_API_URL: https://wmsc.lcsc.com/ftps/wm/product/detail?productCode=


================================================
FILE: kintree/config/lcsc/lcsc_config.yaml
================================================
SUPPLIER_INVENTREE_NAME: LCSC Electronics
SEARCH_NAME: null
SEARCH_DESCRIPTION: null
SEARCH_REVISION: null
SEARCH_KEYWORDS: null
SEARCH_SKU: null
SEARCH_MANUFACTURER: null
SEARCH_MPN: null
SEARCH_SUPPLIER_URL: null
SEARCH_DATASHEET: null
EXTRA_FIELDS: null

================================================
FILE: kintree/config/mouser/mouser_api.yaml
================================================
MOUSER_PART_API_KEY: null

================================================
FILE: kintree/config/mouser/mouser_config.yaml
================================================
SUPPLIER_INVENTREE_NAME: Mouser Electronics
SEARCH_NAME: null
SEARCH_DESCRIPTION: null
SEARCH_REVISION: null
SEARCH_KEYWORDS: null
SEARCH_SKU: null
SEARCH_MANUFACTURER: null
SEARCH_MPN: null
SEARCH_SUPPLIER_URL: null
SEARCH_DATASHEET: null
EXTRA_FIELDS: null

================================================
FILE: kintree/config/settings.py
================================================
import os
import sys
import platform
from enum import Enum

from ..common.tools import cprint
from .import config_interface

# DEBUG
# Testing
ENABLE_TEST = False
# Silent Mode
SILENT = False
# Debug
HIDE_DEBUG = True


def enable_test_mode():
    global ENABLE_TEST
    global SILENT
    ENABLE_TEST = True
    SILENT = True


# PATHS
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
    PROJECT_DIR = os.path.abspath(os.path.dirname(sys.executable))
else:
    PROJECT_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
# InvenTree API
sys.path.append(os.path.join(PROJECT_DIR, 'database', 'inventree-python'))
# Digi-Key API
sys.path.append(os.path.join(PROJECT_DIR, 'search', 'digikey_api'))
# KiCad Library Utils
sys.path.append(os.path.join(PROJECT_DIR, 'kicad'))
# Tests
sys.path.append(os.path.join(PROJECT_DIR, 'tests'))

# HOME FOLDER
USER_HOME = os.path.expanduser("~")
# APP NAME
APP_NAME = 'kintree'
# CONFIG PATH
if platform.system() == 'Linux':
    HOME_DIR = os.path.join(USER_HOME, '.config', APP_NAME, '')
else:
    HOME_DIR = os.path.join(USER_HOME, APP_NAME, '')
# Create config path if it does not exists
if not os.path.exists(HOME_DIR):
    os.makedirs(HOME_DIR, exist_ok=True)


# USER AND CONFIG FILES
def load_user_config():
    global USER_SETTINGS
    global CONFIG_ROOT
    global CONFIG_USER_FILES

    USER_SETTINGS = config_interface.load_user_paths(home_dir=HOME_DIR)
    CONFIG_ROOT = os.path.join(PROJECT_DIR, 'config', '')
    CONFIG_USER_FILES = os.path.join(USER_SETTINGS['USER_FILES'], '')

    # Create user files folder if it does not exists
    if not os.path.exists(CONFIG_USER_FILES):
        os.makedirs(CONFIG_USER_FILES)
    # Create user files
    return config_interface.load_user_config_files(path_to_root=CONFIG_ROOT,
                                                   path_to_user_files=CONFIG_USER_FILES,
                                                   silent=HIDE_DEBUG)


# Load user config
USER_CONFIG_FILE = os.path.join(HOME_DIR, 'settings.yaml')
if not load_user_config():
    # Check if configuration files already exist
    if not os.path.isfile(os.path.join(CONFIG_USER_FILES, 'categories.yaml')):
        cprint('\n[ERROR]\tSome Ki-nTree configuration files seem to be missing')
        exit(-1)

# KiCad
KICAD_CONFIG_PATHS = os.path.join(CONFIG_USER_FILES, 'kicad.yaml')
KICAD_CONFIG_CATEGORY_MAP = os.path.join(CONFIG_USER_FILES, 'kicad_map.yaml')

# Inventree
CONFIG_CATEGORIES = os.path.join(CONFIG_USER_FILES, 'categories.yaml')
CONFIG_STOCK_LOCATIONS = os.path.join(CONFIG_USER_FILES, 'stock_locations.yaml')
CONFIG_PARAMETERS = os.path.join(CONFIG_USER_FILES, 'parameters.yaml')
CONFIG_PARAMETERS_FILTERS = os.path.join(
    CONFIG_USER_FILES, 'parameters_filters.yaml')

# INTERNAL PART NUMBERS
CONFIG_IPN_PATH = os.path.join(CONFIG_USER_FILES, 'internal_part_number.yaml')


def load_ipn_settings():
    global CONFIG_IPN
    CONFIG_IPN = config_interface.load_file(CONFIG_IPN_PATH)


load_ipn_settings()

# GENERAL SETTINGS
CONFIG_GENERAL_PATH = os.path.join(CONFIG_USER_FILES, 'general.yaml')
CONFIG_GENERAL = config_interface.load_file(CONFIG_GENERAL_PATH)
# Datasheets
DATASHEET_SAVE_ENABLED = CONFIG_GENERAL.get('DATASHEET_SAVE_ENABLED', False)
DATASHEET_SAVE_PATH = CONFIG_GENERAL.get('DATASHEET_SAVE_PATH', '')
# Open Browser
AUTOMATIC_BROWSER_OPEN = CONFIG_GENERAL.get('AUTOMATIC_BROWSER_OPEN', False)
# Default Supplier
DEFAULT_SUPPLIER = CONFIG_GENERAL.get('DEFAULT_SUPPLIER', 'Digi-Key')


# Load enable flags
def reload_enable_flags():
    global ENABLE_KICAD
    global ENABLE_INVENTREE
    global ENABLE_ALTERNATE
    global UPDATE_INVENTREE
    global CHECK_EXISTING

    try:
        ENABLE_KICAD = CONFIG_GENERAL.get('ENABLE_KICAD', False)
        ENABLE_INVENTREE = CONFIG_GENERAL.get('ENABLE_INVENTREE', False)
        ENABLE_ALTERNATE = CONFIG_GENERAL.get('ENABLE_ALTERNATE', False)
        UPDATE_INVENTREE = CONFIG_GENERAL.get('UPDATE_INVENTREE', False)
        CHECK_EXISTING = CONFIG_GENERAL.get('CHECK_EXISTING', True)
        return True
    except TypeError:
        pass

    return False


reload_enable_flags()

# Supported suppliers APIs
CONFIG_SUPPLIERS_PATH = os.path.join(CONFIG_USER_FILES, 'suppliers.yaml')
CONFIG_SUPPLIERS = config_interface.load_file(CONFIG_SUPPLIERS_PATH)
SUPPORTED_SUPPLIERS_API = []


# Load suppliers
def load_suppliers():
    global CONFIG_SUPPLIERS
    global SUPPORTED_SUPPLIERS_API

    update_supplier_config = {}
    SUPPORTED_SUPPLIERS_API = []
    for supplier, data in CONFIG_SUPPLIERS.items():
        try:
            if data['enable']:
                if data['name']:
                    supplier_name = data['name'].replace(' ', '')
                    SUPPORTED_SUPPLIERS_API.append(supplier_name)
                else:
                    supplier_key = supplier.replace(' ', '')
                    SUPPORTED_SUPPLIERS_API.append(supplier_key)
        except (TypeError, KeyError):
            update_supplier_config[supplier] = {
                'enable': True,
                'name': supplier,
            }

    # Update supplier configuration file
    if update_supplier_config:
        config_interface.dump_file({**CONFIG_SUPPLIERS, **update_supplier_config}, CONFIG_SUPPLIERS_PATH)
        CONFIG_SUPPLIERS = config_interface.load_file(CONFIG_SUPPLIERS_PATH)
        return False
    return True


if not load_suppliers():
    # Re-load updated configuration file
    load_suppliers()

# Generic API user configuration
CONFIG_SUPPLIER_PARAMETERS = os.path.join(CONFIG_USER_FILES, 'supplier_parameters.yaml')
CONFIG_SEARCH_API_PATH = os.path.join(CONFIG_USER_FILES, 'search_api.yaml')
CONFIG_SEARCH_API = config_interface.load_file(CONFIG_SEARCH_API_PATH)

# Digi-Key user configuration
CONFIG_DIGIKEY = config_interface.load_file(os.path.join(CONFIG_USER_FILES, 'digikey_config.yaml'))
CONFIG_DIGIKEY_API = os.path.join(CONFIG_USER_FILES, 'digikey_api.yaml')
CONFIG_DIGIKEY_CATEGORIES = os.path.join(CONFIG_USER_FILES, 'digikey_categories.yaml')

# Mouser user configuration
CONFIG_MOUSER = config_interface.load_file(os.path.join(CONFIG_USER_FILES, 'mouser_config.yaml'))
CONFIG_MOUSER_API = os.path.join(CONFIG_USER_FILES, 'mouser_api.yaml')

# Element14 user configuration (includes Farnell, Newark and Element14)
CONFIG_ELEMENT14 = config_interface.load_file(os.path.join(CONFIG_USER_FILES, 'element14_config.yaml'))
CONFIG_ELEMENT14_API = os.path.join(CONFIG_USER_FILES, 'element14_api.yaml')

# LCSC user configuration
CONFIG_LCSC = config_interface.load_file(os.path.join(CONFIG_USER_FILES, 'lcsc_config.yaml'))
CONFIG_LCSC_API = os.path.join(CONFIG_USER_FILES, 'lcsc_api.yaml')

# JAMECO user configuration
CONFIG_JAMECO = config_interface.load_file(os.path.join(CONFIG_USER_FILES, 'jameco_config.yaml'))
CONFIG_JAMECO_API = os.path.join(CONFIG_USER_FILES, 'jameco_api.yaml')

# AUTOMATIONDIRECT user configuration
CONFIG_AUTOMATIONDIRECT = config_interface.load_file(os.path.join(CONFIG_USER_FILES, 'automationdirect_config.yaml'))
CONFIG_AUTOMATIONDIRECT_API = os.path.join(CONFIG_USER_FILES, 'automationdirect_api.yaml')

# TME user configuration
CONFIG_TME = config_interface.load_file(os.path.join(CONFIG_USER_FILES, 'tme_config.yaml'))
CONFIG_TME_API = os.path.join(CONFIG_USER_FILES, 'tme_api.yaml')

# Automatic category match confidence level (from 0 to 100)
CATEGORY_MATCH_RATIO_LIMIT = CONFIG_SEARCH_API.get('CATEGORY_MATCH_RATIO_LIMIT', 100)
# Search results caching (stored in files)
CACHE_ENABLED = CONFIG_SEARCH_API.get('CACHE_ENABLED', True)
# Cache validity in days
CACHE_VALID_DAYS = int(CONFIG_SEARCH_API.get('CACHE_VALID_DAYS', '7'))


# Caching settings
def load_cache_settings():
    global search_results
    global search_images
    global search_datasheets
    global CACHE_ENABLED
    global DIGIKEY_STORAGE_PATH

    USER_SETTINGS = config_interface.load_user_paths(home_dir=HOME_DIR)

    search_results = {
        'directory': os.path.join(USER_SETTINGS['USER_CACHE'], 'search', ''),
        'extension': '.yaml',
    }
    # Create folder if it does not exists
    if not os.path.exists(search_results['directory']):
        os.makedirs(search_results['directory'])

    # Part images
    search_images = os.path.join(USER_SETTINGS['USER_CACHE'], 'images', '')
    # Create folder if it does not exists
    if not os.path.exists(search_images):
        os.makedirs(search_images)

    # Part images
    search_datasheets = os.path.join(
        USER_SETTINGS['USER_CACHE'], 'datasheets', '')
    # Create folder if it does not exists
    if not os.path.exists(search_datasheets):
        os.makedirs(search_datasheets)

    # API token storage path
    DIGIKEY_STORAGE_PATH = os.path.join(USER_SETTINGS['USER_CACHE'], '')


# Load cache settings
load_cache_settings()

# KICAD
# User Settings
KICAD_SETTINGS = {}


def load_kicad_settings():
    global KICAD_CONFIG_PATHS
    global KICAD_SETTINGS

    kicad_user_settings = config_interface.load_file(KICAD_CONFIG_PATHS, silent=False)
    if kicad_user_settings:
        KICAD_SETTINGS['KICAD_SYMBOLS_PATH'] = kicad_user_settings.get('KICAD_SYMBOLS_PATH', None)
        KICAD_SETTINGS['KICAD_TEMPLATES_PATH'] = kicad_user_settings.get('KICAD_TEMPLATES_PATH', None)
        KICAD_SETTINGS['KICAD_FOOTPRINTS_PATH'] = kicad_user_settings.get('KICAD_FOOTPRINTS_PATH', None)


# Load kicad settings
load_kicad_settings()


def set_default_supplier(value: str, save=False):
    global DEFAULT_SUPPLIER
    DEFAULT_SUPPLIER = value
    if save:
        user_settings = config_interface.load_file(os.path.join(CONFIG_USER_FILES, 'general.yaml'))
        user_settings['DEFAULT_SUPPLIER'] = value
        config_interface.dump_file(user_settings, os.path.join(CONFIG_USER_FILES, 'general.yaml'))
    return


# Library Paths
if not ENABLE_TEST:
    symbol_libraries_paths = config_interface.load_libraries_paths(
        KICAD_CONFIG_CATEGORY_MAP,
        KICAD_SETTINGS['KICAD_SYMBOLS_PATH'],
    )
# cprint(symbol_libraries_paths)

# Template Paths
symbol_templates_paths = config_interface.load_templates_paths(
    KICAD_CONFIG_CATEGORY_MAP,
    KICAD_SETTINGS['KICAD_TEMPLATES_PATH'],
)
# cprint(symbol_templates_paths)

# Footprint Libraries
footprint_libraries_paths = config_interface.load_footprint_paths(
    KICAD_CONFIG_CATEGORY_MAP,
    KICAD_SETTINGS['KICAD_FOOTPRINTS_PATH'],
)
# cprint(footprint_libraries_paths)
footprint_name_default = 'TBD'

AUTO_GENERATE_LIB = True
symbol_template_lib = os.path.join(
    PROJECT_DIR,
    'kicad',
    'templates',
    'library_template.kicad_sym'
)


# INVENTREE
class Environment(Enum):
    '''
    Server/Remote Development: DEVELOPMENT
    Server/Remote Production: PRODUCTION
    '''
    DEVELOPMENT = 0
    PRODUCTION = 1


# Pick environment
environment = CONFIG_GENERAL.get('INVENTREE_ENV', None)
environment = os.environ.get('INVENTREE_ENV', environment)

try:
    environment = int(environment)
except TypeError:
    environment = 0

# Load correct user file
if environment == Environment.PRODUCTION.value:
    INVENTREE_CONFIG = os.path.join(CONFIG_USER_FILES, 'inventree_prod.yaml')
else:
    INVENTREE_CONFIG = os.path.join(CONFIG_USER_FILES, 'inventree_dev.yaml')

# Load user settings
inventree_settings = config_interface.load_inventree_user_settings(INVENTREE_CONFIG)


# Server settings
def load_inventree_settings():
    global SERVER_ADDRESS
    global USERNAME
    global PASSWORD
    global ENABLE_PROXY
    global PROXIES
    global PART_URL_ROOT
    global DATASHEET_UPLOAD
    global PRICING_UPLOAD

    inventree_settings = config_interface.load_inventree_user_settings(INVENTREE_CONFIG)

    SERVER_ADDRESS = inventree_settings.get('SERVER_ADDRESS', None)
    USERNAME = inventree_settings.get('USERNAME', None)
    PASSWORD = inventree_settings.get('PASSWORD', None)
    ENABLE_PROXY = inventree_settings.get('ENABLE_PROXY', False)
    PROXIES = inventree_settings.get('PROXIES', None)
    DATASHEET_UPLOAD = inventree_settings.get('DATASHEET_UPLOAD', False)
    PRICING_UPLOAD = inventree_settings.get('PRICING_UPLOAD', False)
    # Part URL
    if SERVER_ADDRESS:
        # If missing, append slash to root URL
        root_url = SERVER_ADDRESS
        if not SERVER_ADDRESS.endswith('/'):
            root_url = root_url + '/'
        # Set part URL
        PART_URL_ROOT = root_url + 'part/'


# InvenTree part dictionary template
inventree_part_template = {
    'name': None,
    'description': None,
    'IPN': None,
    'revision': None,
    'keywords': None,
    'image': None,
    'inventree_url': None,
    'manufacturer_name': None,
    'manufacturer_part_number': None,
    'datasheet': None,
    'supplier_name': None,
    'supplier_part_number': None,
    'supplier_link': None,
    'parameters': {},
}


# Enable flags
def set_enable_flag(key: str, value: bool):
    global CONFIG_GENERAL

    user_settings = CONFIG_GENERAL
    if key in ['kicad', 'inventree', 'alternate', 'update', 'check_existing']:
        if key == 'kicad':
            user_settings['ENABLE_KICAD'] = value
        elif key == 'inventree':
            user_settings['ENABLE_INVENTREE'] = value
        elif key == 'alternate':
            user_settings['ENABLE_ALTERNATE'] = value
        elif key == 'update':
            user_settings['UPDATE_INVENTREE'] = value
        elif key == 'check_existing':
            user_settings['CHECK_EXISTING'] = value

        # Save
        config_interface.dump_file(
            data=user_settings,
            file_path=os.path.join(CONFIG_USER_FILES, 'general.yaml'),
        )

    return reload_enable_flags()


================================================
FILE: kintree/config/tme/tme_api.yaml
================================================
TME_API_TOKEN: NULL
TME_API_SECRET: NULL
TME_API_COUNTRY: US
TME_API_LANGUAGE: EN

================================================
FILE: kintree/config/tme/tme_config.yaml
================================================
SUPPLIER_INVENTREE_NAME: TME
SEARCH_NAME: null
SEARCH_DESCRIPTION: null
SEARCH_REVISION: null
SEARCH_KEYWORDS: null
SEARCH_SKU: null
SEARCH_MANUFACTURER: null
SEARCH_MPN: null
SEARCH_SUPPLIER_URL: null
SEARCH_DATASHEET: null

================================================
FILE: kintree/config/user/general.yaml
================================================
DATASHEET_SAVE_ENABLED: false
DATASHEET_SAVE_PATH: null
DATASHEET_INVENTREE_ENABLED: false
AUTOMATIC_BROWSER_OPEN: true
INVENTREE_ENV: null
DEFAULT_SUPPLIER: Digi-Key
ENABLE_KICAD: false
ENABLE_INVENTREE: false
ENABLE_ALTERNATE: false
CHECK_EXISTING: true

================================================
FILE: kintree/config/user/internal_part_number.yaml
================================================
IPN_ENABLE_CREATE: true
IPN_USE_MANUFACTURER_PART_NUMBER: false
IPN_PREFIX: null
IPN_CATEGORY_CODE: true
IPN_UNIQUE_ID_LENGTH: '6'
IPN_ENABLE_PREFIX: false
IPN_ENABLE_SUFFIX: true
IPN_SUFFIX: '00'
INVENTREE_DEFAULT_REV: 'A'

================================================
FILE: kintree/config/user/search_api.yaml
================================================
CATEGORY_MATCH_RATIO_LIMIT: 100
CACHE_ENABLED: true
CACHE_VALID_DAYS: '7'

================================================
FILE: kintree/database/inventree_api.py
================================================
from ..config import settings
import validators
from ..common import part_tools
from ..common.tools import cprint, download_with_retry
from ..config import config_interface
import re

# Required to use local CA certificates on Linux
# For more details, refer to https://github.com/sparkmicro/Ki-nTree/pull/45
import platform
import os
if platform.system() == 'Linux':
    cert_path = '/etc/ssl/certs/ca-certificates.crt'
    if os.path.isfile(cert_path):
        os.environ['REQUESTS_CA_BUNDLE'] = cert_path

# InvenTree
from inventree.api import InvenTreeAPI
from inventree.company import Company, ManufacturerPart, SupplierPart, SupplierPriceBreak
from inventree.part import Part, PartCategory
from inventree.currency import CurrencyManager
from inventree.stock import StockLocation
from inventree.stock import StockItem
from inventree.base import ParameterTemplate, Parameter


def connect(server: str,
            username: str,
            password: str,
            connect_timeout=5,
            silent=False,
            proxies=None,
            token='') -> bool:
    ''' Connect to InvenTree server and create API object '''
    from wrapt_timeout_decorator import timeout
    global inventree_api

    @timeout(dec_timeout=connect_timeout)
    def get_inventree_api_timeout():
        return InvenTreeAPI(server,
                            username=username,
                            password=password,
                            proxies=proxies,
                            token=token)

    try:
        inventree_api = get_inventree_api_timeout()
    except:
        return False

    if inventree_api.token:
        return True
    return False


def set_inventree_db_test_mode():
    ''' InvenTree test database setup '''
    global inventree_api

    inventree_api.patch('settings/global/PARAMETER_ENFORCE_UNITS/', {'value': False})


def get_inventree_category_id(category_tree: list) -> int:
    ''' Get InvenTree category ID from name, specificy parent if subcategory '''
    global inventree_api

    # Fetch all categories
    part_categories = PartCategory.list(inventree_api, name=category_tree[-1])
    if len(part_categories) == 1:
        return part_categories[0].pk
    else:
        if len(category_tree) > 1:
            # Match the parent category
            parent_category_id = get_inventree_category_id(category_tree[:-1])
            if parent_category_id:
                for category in part_categories:
                    try:
                        if parent_category_id == category.getParentCategory().pk:
                            return category.pk
                    except AttributeError:
                        pass
                    #     # Check parent id match (if passed as argument)
                    #     match = True
                    #     if parent_category_id:
                    #         cprint(f'[TREE]\t{item.getParentCategory().pk} ?= {parent_category_id}', silent=settings.HIDE_DEBUG)
                    #         if item.getParentCategory().pk != parent_category_id:
                    #             match = False
                    #     if match:
                    #         cprint(f'[TREE]\t{item.name} ?= {category_name} => True', silent=settings.HIDE_DEBUG)
                    #         return item.pk
                    # else:
                    #     cprint(f'[TREE]\t{item.name} ?= {category_name} => False', silent=settings.HIDE_DEBUG)

    return -1


def get_inventree_stock_location_id(stock_location_tree: list) -> int:
    ''' Get InvenTree stock location ID from name, specificy parent if subcategory '''
    global inventree_api

    # Fetch all categories
    stock_locations = StockLocation.list(inventree_api, name=stock_location_tree[-1])
    if len(stock_locations) == 1:
        return stock_locations[0].pk
    else:
        if len(stock_location_tree) > 1:
            # Match the parent category
            parent_stock_location_id = get_inventree_category_id(stock_location_tree[:-1])
            if parent_stock_location_id:
                for location in stock_locations:
                    try:
                        if parent_stock_location_id == location.getParentLocation().pk:
                            return location.pk
                    except AttributeError:
                        pass
                    #     # Check parent id match (if passed as argument)
                    #     match = True
                    #     if parent_stock_location_id:
                    #         cprint(f'[TREE]\t{item.getParentCategory().pk} ?= {parent_stock_location_id}', silent=settings.HIDE_DEBUG)
                    #         if item.getParentCategory().pk != parent_stock_location_id:
                    #             match = False
                    #     if match:
                    #         cprint(f'[TREE]\t{item.name} ?= {category_name} => True', silent=settings.HIDE_DEBUG)
                    #         return item.pk
                    # else:
                    #     cprint(f'[TREE]\t{item.name} ?= {category_name} => False', silent=settings.HIDE_DEBUG)

    return -1


def get_categories() -> dict:
    '''Fetch InvenTree categories'''
    global inventree_api

    categories = {}
    # Get all categories (list)
    db_categories = PartCategory.list(inventree_api)

    def deep_add(tree: dict, keys: list, item: dict):
        if len(keys) == 1:
            try:
                tree[keys[0]].update(item)
            except (KeyError, AttributeError):
                tree[keys[0]] = item
            return
        return deep_add(tree.get(keys[0]), keys[1:], item)

    for category in db_categories:
        parent = category.getParentCategory()
        children = category.getChildCategories()

        if not parent and not children:
            categories[category.name] = None
            continue
        elif parent:
            parent_list = []
            while parent:
                parent_list.insert(0, parent.name)
                parent = parent.getParentCategory()
            cat = {category.name: None}
            deep_add(categories, parent_list, cat)

    return categories


def get_stock_locations() -> dict:
    '''Fetch InvenTree stock locations'''
    global inventree_api

    categories = {}
    # Get all categories (list)
    db_categories = StockLocation.list(inventree_api)

    def deep_add(tree: dict, keys: list, item: dict):
        if len(keys) == 1:
            try:
                tree[keys[0]].update(item)
            except (KeyError, AttributeError):
                tree[keys[0]] = item
            return
        return deep_add(tree.get(keys[0]), keys[1:], item)

    for category in db_categories:
        parent = category.getParentLocation()
        children = category.getChildLocations()

        if not parent and not children:
            categories[category.name] = None
            continue
        elif parent:
            parent_list = []
            while parent:
                parent_list.insert(0, parent.name)
                parent = parent.getParentLocation()
            cat = {category.name: None}
            deep_add(categories, parent_list, cat)

    return categories


def get_category_tree(category_id: int) -> dict:
    ''' Get all parents of a category'''
    category = PartCategory(inventree_api, category_id)
    category_list = {category_id: category.name}

    while category.parent:
        category = category.getParentCategory()
        category_list[category.pk] = category.name

    return category_list


def get_stock_location_tree(id: int) -> dict:
    ''' Get all parents of a stock_location'''
    location = StockLocation(inventree_api, id)
    list = {id: location.name}

    while location.parent:
        location = location.getParentLocation()
        list[location.pk] = location.name

    return list


def create_stock(stock_data: dict) -> dict:
    return StockItem.create(inventree_api, stock_data)


def get_category_parameters(category_id: int) -> list:
    ''' Get all default parameter templates for category '''
    global inventree_api

    parameter_templates = []

    category = PartCategory(inventree_api, category_id)

    try:
        category_templates = category.getCategoryParameterTemplates(fetch_parent=True)
    except AttributeError:
        category_templates = None

    if category_templates:
        for template in category_templates:

            default_value = template.default_value
            if not default_value:
                default_value = '-'

            parameter_templates.append([template.getTemplate().name, default_value])

    return parameter_templates


def get_part_info(part_id: int) -> str:
    ''' Get InvenTree part info from specified Part ID '''
    global inventree_api

    part = Part(inventree_api, part_id)
    part_info = {'IPN': part.IPN}
    attachment = part.getAttachments()
    if attachment:
        part_info['datasheet'] = f'{inventree_api.base_url.strip("/")}{attachment[0]["attachment"]}'
    return part_info


def set_part_number(part_id: int, ipn: str) -> bool:
    ''' Set InvenTree part number for specified Part ID '''
    data = {'IPN': ipn}
    update_part(part_id, data)

    if Part(inventree_api, part_id).IPN == ipn:
        return True
    else:
        return False


def get_part_from_ipn(part_ipn='') -> int:
    ''' Get Part ID from Part IPN '''
    global inventree_api

    parts = Part.list(inventree_api, IPN=part_ipn)

    if not parts:
        # No part found
        return None
    else:
        # parts should have only one entry
        return parts[0]


def fetch_part(part_id='', part_ipn='') -> int:
    ''' Fetch part from database using either ID or IPN '''
    from requests.exceptions import HTTPError
    global inventree_api

    part = None
    if part_id:
        try:
            part = Part(inventree_api, part_id)
        except TypeError:
            # Part ID is invalid (eg. decimal value)
            cprint('[TREE] Error: Part ID type is invalid')
        except ValueError:
            # Part ID is not a positive integer
            cprint('[TREE] Error: Part ID must be positive')
        except HTTPError:
            # Part ID does not exist
            cprint(f'[TREE] Error: Part with ID={part_id} does not exist in database')
    elif part_ipn:
        part = get_part_from_ipn(part_ipn)
    else:
        pass

    return part


def is_new_part(category_id: int, part_info: dict) -> int:
    ''' Check if part exists based on parameters (or description) '''
    global inventree_api

    # Get category object
    part_category = PartCategory(inventree_api, category_id)

    # Fetch all parts from category and subcategories
    part_list = []
    part_list.extend(part_category.getParts())
    for subcategory in part_category.getChildCategories():
        part_list.extend(subcategory.getParts())

    # Extract parameter from part info
    # Verify parameters values are not empty
    new_part_parameters = part_info['parameters'] if list(set(part_info['parameters'].values())) != ['-'] else None

    template_list = ParameterTemplate.list(inventree_api)

    def fetch_template_name(template_id):
        for item in template_list:
            if item.pk == template_id:
                return item.name

    # Retrieve parent category name for parameters compare
    try:
        category_name = part_category.getParentCategory().name
    except AttributeError:
        category_name = part_category.name
    filters = config_interface.load_category_parameters_filters(category=category_name,
                                                                supplier_config_path=settings.CONFIG_PARAMETERS_FILTERS)
    # cprint(filters)

    for part in part_list:
        # TODO: This statement below seems erroneous...
        # Compare fields (InvenTree does not allow those to be identicals between two parts)
        # compare_fields = part_info['name'] == part.name and part_info['revision'] == part.revision
        # if compare_fields:
        #     cprint(f'[TREE]\tWarning: Found part with same name and revision (pk = {part.pk})', silent=settings.SILENT)
        #     return part.pk

        # Compare parameters
        compare_parameters = False
        # Get part parameters
        db_part_parameters = part.getParameters()
        part_parameters = {}
        for parameter in db_part_parameters:
            parameter_name = fetch_template_name(parameter.template)
            parameter_value = parameter.data
            part_parameters[parameter_name] = parameter_value

        if new_part_parameters and part_parameters:
            # Compare database part with new part
            compare_parameters = part_tools.compare(new_part_parameters=new_part_parameters,
                                                    db_part_parameters=part_parameters,
                                                    include_filters=filters)
                                                            
        if compare_parameters:
            cprint(f'[TREE]\tWarning: Found part with same parameters in database (pk = {part.pk})', silent=settings.SILENT)
            return part.pk

    # Check if manufacturer part exists in database
    manufacturer = part_info['manufacturer_name']
    mpn = part_info['manufacturer_part_number']
    part_pk = is_new_manufacturer_part(manufacturer, mpn, create=False)

    if part_pk:
        cprint(f'[TREE]\tWarning: Found part with same manufacturer and MPN in database (pk = {part_pk})', silent=settings.SILENT)
        return part_pk

    cprint('\n[TREE]\tNo match found in database', silent=settings.HIDE_DEBUG)
    return 0


def create_category(parent: str, name: str):
    ''' Create InvenTree category, use parent for subcategories '''
    global inventree_api

    parent_id = 0
    is_new_category = False

    # Check if category already exists
    category_list = PartCategory.list(inventree_api)
    for category in category_list:
        if name == category.name:
            try:
                # Check if parents are the same
                if category.getParentCategory().name == parent:
                    # Return category ID
                    return category.pk, is_new_category
            except:
                return category.pk, is_new_category
        elif parent == category.name:
            # Get Parent ID
            parent_id = category.pk
        else:
            pass

    if parent:
        if parent_id > 0:
            category = PartCategory.create(inventree_api, {
                'name': name,
                'parent': parent_id,
            })

            is_new_category = True
        else:
            cprint(f'[TREE]\tError: Check parent category name ({parent})', silent=settings.SILENT)
            return -1, is_new_category
    else:
        # No parent
        category = PartCategory.create(inventree_api, {
            'name': name,
            'parent': None,
        })
        is_new_category = True

    try:
        category_pk = category.pk
    except AttributeError:
        # User does not have the permission to create categories
        category_pk = 0

    return category_pk, is_new_category


def upload_part_image(image_url: str, part_id: int, silent=False) -> bool:
    ''' Upload InvenTree part thumbnail'''
    global inventree_api

    # Get image full path
    image_name = f'{str(part_id)}_thumbnail.jpeg'
    image_location = settings.search_images + image_name

    # Download image (multiple attempts)
    if not download_with_retry(image_url, image_location, filetype='Image', silent=silent):
        return False

    # Upload image to InvenTree
    part = Part(inventree_api, part_id)
    if part:
        try:
            return part.uploadImage(image=image_location)
        except Exception:
            return False
    else:
        return False


def upload_part_datasheet(datasheet_url: str, part_ipn: int, part_pk: int, silent=False) -> str:
    ''' Upload InvenTree part attachment'''
    global inventree_api

    datasheet_name = f'{part_ipn}.pdf'
    # Get datasheet path based on user settings for local storage
    if settings.DATASHEET_SAVE_ENABLED:
        datasheet_location = os.path.join(settings.DATASHEET_SAVE_PATH, datasheet_name)
    else:
        datasheet_location = os.path.join(settings.search_datasheets, datasheet_name)

    if not os.path.isfile(datasheet_location):
        # Download datasheet (multiple attempts)
        if not download_with_retry(
            datasheet_url,
            datasheet_location,
            filetype='PDF',
            timeout=10,
            silent=silent,
        ):
            return ''

    # Upload Datasheet to InvenTree
    part = Part(inventree_api, part_pk)
    if part:
        try:
            attachment = part.uploadAttachment(attachment=datasheet_location)
            return f'{inventree_api.base_url.strip("/")}{attachment["attachment"]}'
        except Exception:
            return ''
    else:
        return ''


def create_part(category_id: int, name: str, description: str, revision: str, ipn: str, keywords=None) -> int:
    ''' Create InvenTree part '''
    global inventree_api

    try:
        part = Part.create(inventree_api, {
            'name': name,
            'description': description,
            'category': category_id,
            'keywords': keywords,
            'revision': revision,
            'IPN': ipn,
            'active': True,
            'virtual': False,
            'component': True,
            'purchaseable': True,
        })
    except Exception as e:
        cprint('[TREE]\tError: Part creation failed. Check if Ki-nTree settings match InvenTree part settings.', silent=settings.SILENT)
        cprint(repr(e), silent=settings.SILENT)
        return 0

    if part:
        return part.pk
    else:
        return 0


def set_part_default_location(part_pk: int, location_pk: int):
    global inventree_api

    # Retrieve part instance with primary-key of 1
    part = Part(inventree_api, pk=part_pk)

    # Update specified part parameters
    part.save(data={
        "default_location": location_pk,
    })


def update_part(pk: int, data: dict) -> int:
    '''Update an existing parts data'''
    global inventree_api

    part = Part(inventree_api, pk)
    if part:
        part.save(data=data)
        return part.pk
    else:
        return 0


def create_company(company_name: str, manufacturer=False, supplier=False) -> bool:
    ''' Create InvenTree company '''
    global inventree_api

    if not manufacturer and not supplier:
        return None

    company = Company.create(inventree_api, {
        'name': company_name,
        'description': company_name,
        'is_customer': False,
        'is_supplier': supplier,
        'is_manufacturer': manufacturer,
    })

    return company


def get_all_companies() -> dict:
    ''' Get all existing companies (supplier/manufacturer) from database '''
    global inventree_api

    company_list = Company.list(inventree_api)
    companies = {}
    for company in company_list:
        companies[company.name] = company.pk

    return companies


def get_company_id(company_name: str) -> int:
    ''' Get company (supplier/manufacturer) primary key (ID) '''

    try:
        return get_all_companies()[company_name]
    except:
        return 0


def is_new_manufacturer_part(manufacturer_name: str, manufacturer_mpn: str, create=True) -> int:
    ''' Check if InvenTree manufacturer part exists to avoid duplicates '''
    global inventree_api

    if not manufacturer_name:
        return 0

    # Fetch all companies
    cprint('[TREE]\tFetching manufacturers', silent=settings.HIDE_DEBUG)
    company_list = Company.list(inventree_api, is_manufacturer=True, is_customer=False)
    companies = {}
    for company in company_list:
        companies[company.name] = company

    try:
        # Get all parts
        part_list = companies[manufacturer_name].getManufacturedParts()
    except:
        part_list = None

    if part_list is None:
        if create:
            # Create manufacturer
            cprint(f'[TREE]\tCreating new manufacturer "{manufacturer_name}"', silent=settings.SILENT)
            create_company(
                company_name=manufacturer_name,
                manufacturer=True,
            )
        # Get all parts
        part_list = []

    for item in part_list:
        try:
            if manufacturer_mpn in item.MPN:
                cprint(f'[TREE]\t{item.MPN} ?= {manufacturer_mpn} => True', silent=settings.HIDE_DEBUG)
                return item.part
            else:
                cprint(f'[TREE]\t{item.MPN} ?= {manufacturer_mpn} => False', silent=settings.HIDE_DEBUG)
        except TypeError:
            cprint(f'[TREE]\t{item.MPN} ?= {manufacturer_mpn} => *** SKIPPED ***', silent=settings.HIDE_DEBUG)

    return 0


def is_new_supplier_part(supplier_name: str, supplier_sku: str):
    ''' Check if InvenTree supplier part exists to avoid duplicates '''
    global inventree_api

    # Fetch all companies
    cprint('[TREE]\tFetching suppliers', silent=settings.HIDE_DEBUG)
    company_list = Company.list(inventree_api, is_supplier=True, is_customer=False)
    companies = {}
    for company in company_list:
        companies[company.name] = company

    try:
        # Get all parts
        part_list = companies[supplier_name].getSuppliedParts()
    except:
        part_list = None

    if part_list is None:
        # Create
        cprint(f'[TREE]\tCreating new supplier "{supplier_name}"', silent=settings.SILENT)
        create_company(
            company_name=supplier_name,
            supplier=True,
        )
        # Get all parts
        part_list = []

    for item in part_list:
        if supplier_sku in item.SKU:
            cprint(f'[TREE]\t{item.SKU} ?= {supplier_sku} => True', silent=settings.HIDE_DEBUG)
            return False, item
        else:
            cprint(f'[TREE]\t{item.SKU} ?= {supplier_sku} => False', silent=settings.HIDE_DEBUG)

    return True, False


def create_manufacturer_part(part_id: int, manufacturer_name: str, manufacturer_mpn: str, description: str, datasheet: str) -> bool:
    ''' Create InvenTree manufacturer part

        part_id: Part the manufacturer data is linked to
        manufacturer: Company that manufactures the SupplierPart (leave blank if it is the sample as the Supplier!)
        MPN: Manufacture part number
        datasheet: Datasheet link
        description: Descriptive notes field
    '''
    global inventree_api

    # Get Manufacturer ID
    manufacturer_id = get_company_id(manufacturer_name)

    if manufacturer_id:
        # Validate datasheet link
        if not validators.url(datasheet):
            datasheet = ''

        manufacturer_part = ManufacturerPart.create(inventree_api, {
            'part': part_id,
            'manufacturer': manufacturer_id,
            'MPN': manufacturer_mpn,
            'link': datasheet,
            'description': description,
        })

        if manufacturer_part:
            return True
    else:
        cprint(f'[TREE]\tError: Manufacturer "{manufacturer_name}" not found (failed to create manufacturer part)',
               silent=settings.SILENT)

    return False


def create_supplier_part(part_id: int, manufacturer_name: str, manufacturer_mpn: str, supplier_name: str, supplier_sku: str, description: str, link: str):
    ''' Create InvenTree supplier part

        part_id: Part the supplier data is linked to
        manufacturer_name: Manufacturer the supplier data is linked to
        manufacturer_mpn: MPN the supplier data is linked to
        supplier: Company that supplies this SupplierPart object
        SKU: Stock keeping unit (supplier part number)
        manufacturer: Company that manufactures the SupplierPart (leave blank if it is the sample as the Supplier!)
        MPN: Manufacture part number
        link: Link to part detail page on supplier's website
        description: Descriptive notes field
    '''
    global inventree_api

    # Get Supplier ID
    supplier_id = get_company_id(supplier_name)

    if not manufacturer_name or not manufacturer_mpn:
        # Unset manufacturer data
        manufacturer_name = None
        manufacturer_mpn = None

    if supplier_id:
        # Validate supplier link
        if not validators.url(link):
            link = ''

        supplier_part = SupplierPart.create(inventree_api, {
            'part': part_id,
            'manufacturer': manufacturer_name,
            'MPN': manufacturer_mpn,
            'supplier': supplier_id,
            'SKU': supplier_sku,
            'link': link,
            'description': description,
        })

        if supplier_part:
            return True, supplier_part
    else:
        cprint(f'[TREE]\tError: Supplier "{supplier_name}" not found (failed to create supplier part)',
               silent=settings.SILENT)

    return False, False


def update_price_breaks(supplier_part,
                        price_breaks: dict,
                        currency='USD') -> bool:
    ''' Update the Price Breaks associated with a supplier part '''
    def sanitize_price(price_in):
        price = re.findall(r'\d+.\d+', price_in)[0]
        price = price.replace(',', '.')
        price = price.replace('\xa0', '')
        return price

    def convert_currency(price):
        manager = CurrencyManager(inventree_api)
        base = manager.getBaseCurrency()
        if base != currency:
            try:
                price = manager.convertCurrency(float(price), currency, base)
            except Exception:
                cprint('[TREE]\tWarning: Currency conversion failed.',
                       silent=settings.SILENT)
        return price

    if not isinstance(supplier_part, SupplierPart):
        try:
            supplier_part = SupplierPart(inventree_api, supplier_part)
        except:
            cprint('[TREE]\tWarning: Supplier part not found, skipping price break update',
                   silent=settings.SILENT)
            return False
    if not price_breaks:
        cprint('[TREE]\tWarning: No price breaks found, skipping.', silent=settings.SILENT)
        return False

    old_price_breaks = supplier_part.getPriceBreaks()
    updated = []
    # First process existing price breaks
    for old_price_break in old_price_breaks:
        quantity = old_price_break.quantity
        if quantity in price_breaks:
            price = price_breaks[quantity]
            # remove everything but the numbers from the price break
            if isinstance(price, str):
                price = sanitize_price(price)
            price = convert_currency(price)
            old_price_break.save(data={'price': price})
            updated.append(quantity)
        else:
            old_price_break.delete()
    for quantity in updated:
        del price_breaks[quantity]
    # if any price breaks are left over these will be created
    for quantity, price in price_breaks.items():
        # remove everything but the numbers from the price break
        if isinstance(price, str):
            price = sanitize_price(price)
        price = convert_currency(price)
        SupplierPriceBreak.create(inventree_api, {
            'part': supplier_part.pk,
            'quantity': quantity,
            'price': price,
        })
    cprint('[INFO]\tSuccess: The price breaks were updated', silent=settings.SILENT)
    return True


def create_parameter_template(name: str, units: str) -> int:
    ''' Create InvenTree parameter template '''
    global inventree_api

    parameter_templates = ParameterTemplate.list(inventree_api)
    for item in parameter_templates:
        if name == item.name:
            return 0

    try:
        parameter_template = ParameterTemplate.create(inventree_api, {
            'name': name,
            'units': units if units else '',
        })
    except:
        cprint(f'[TREE]\tError: Failed to create parameter template "{name}".', silent=settings.SILENT)
        return 0

    if parameter_template:
        return parameter_template.pk
    else:
        return 0


def create_parameter(part_id: int, template_name: int, value: str):
    ''' Create InvenTree part parameter based on template '''
    global inventree_api

    parameter_template_list = ParameterTemplate.list(inventree_api)

    template_id = 0
    for item in parameter_template_list:
        if template_name == item.name:
            template_id = item.pk
            break

    # Check if template_id already exists for this part
    part = Part(inventree_api, part_id)
    part_parameters = part.getParameters()
    is_new_part_parameters_template_id = True
    was_updated = False
    parameter = None
    for item in part_parameters:
        # cprint(f'[TREE]\t{parameter.template} ?= {template_id}', silent=SILENT)
        if item.template == template_id:
            is_new_part_parameters_template_id = False
            if settings.UPDATE_INVENTREE:
                if value != item.data and value != '-':
                    parameter = item
                    was_updated = True
                    try:
                        parameter.save(data={
                            'data': value
                        })
                    except Exception as e:
                        cprint(f'[TREE]\tError: Failed to update part parameter "{template_name}".', silent=settings.SILENT)
                        if "Could not convert" in e.args[0]['body'].__str__():
                            cprint(f'[TREE]\tError: Parameter value "{value}" is not allowed by server settings.', silent=settings.SILENT)
            break
    # cprint(part_parameters, silent=SILENT)

    '''
        Create parameter only if:
        - template exists
        - parameter does not exist for this part
    '''
    if template_id > 0 and is_new_part_parameters_template_id:
        try:
            parameter = Parameter.create(inventree_api, {
                'model_type': 'part',
                'model_id': part.pk,
                'template': template_id,
                'data': value,
            })
        except Exception as e:
            cprint(f'[TREE]\tError: Failed to create part parameter "{template_name}".', silent=settings.SILENT)
            if "Could not convert" in e.args[0]['body'].__str__():
                cprint(f'[TREE]\tError: Parameter value "{value}" is not allowed by server settings.', silent=settings.SILENT)

    if parameter:
        return parameter.pk, is_new_part_parameters_template_id, was_updated
    else:
        if template_id == 0:
            cprint(f'[TREE]\tError: Parameter template "{template_name}" does not exist', silent=settings.SILENT)
        return 0, False, False


================================================
FILE: kintree/database/inventree_interface.py
================================================
import copy

from ..config import settings
from ..common import part_tools, progress
from ..common.tools import cprint
from ..config import config_interface
from ..database import inventree_api
from ..search import search_api, automationdirect_api, digikey_api, mouser_api, element14_api, lcsc_api, jameco_api, tme_api

category_separator = '/'


def connect_to_server(timeout=5) -> bool:
    ''' Connect to InvenTree server using user settings '''
    connect = False
    settings.load_inventree_settings()
    if not settings.USERNAME:
        token = settings.PASSWORD
    else:
        token = ''

    try:
        connect = inventree_api.connect(server=settings.SERVER_ADDRESS,
                                        username=settings.USERNAME,
                                        password=settings.PASSWORD,
                                        proxies=settings.PROXIES,
                                        token=token,
                                        connect_timeout=timeout)
    except TimeoutError:
        pass

    if not connect:
        if not settings.SERVER_ADDRESS:
            cprint('[TREE]\tError connecting to InvenTree server: missing server address')
            return connect
        if not settings.USERNAME:
            cprint('[TREE]\tError connecting to InvenTree server: missing username')
            return connect
        if not settings.PASSWORD:
            cprint('[TREE]\tError connecting to InvenTree server: missing password')
            return connect
        cprint('[TREE]\tError connecting to InvenTree server: invalid address, username or password')
    else:
        env = [env_type.name for env_type in settings.Environment
               if env_type.value == settings.environment][0]
        cprint(f'[TREE]\tSuccessfully connected to InvenTree server (ENV={env})', silent=settings.SILENT)

    return connect


def category_tree(tree: str) -> str:
    import re
    find_prefix = re.match(r'^-+ (.+?)$', tree)
    if find_prefix:
        return find_prefix.group(1)
    return tree


def split_category_tree(tree: str) -> list:
    return category_tree(tree).split(category_separator)


def build_category_tree(reload=False, category=None) -> dict:
    '''Build InvenTree category tree from database data'''

    category_data = config_interface.load_file(settings.CONFIG_CATEGORIES)

    def build_tree(tree, left_to_go, level) -> list:
        try:
            last_entry = f' {category_tree(tree[-1])}{category_separator}'
        except IndexError:
            last_entry = ''
        if isinstance(left_to_go, dict):
            for key, value in left_to_go.items():
                tree.append(f'{"-" * level}{last_entry}{key}')
                build_tree(tree, value, level + 1)
        elif isinstance(left_to_go, list):
            # Supports legacy structure
            for item in left_to_go:
                tree.append(f'{"-" * level}{last_entry}{item}')
        elif left_to_go is None:
            pass
        return

    if reload:
        categories = inventree_api.get_categories()
        category_data.update({'CATEGORIES': categories})
        config_interface.dump_file(category_data, settings.CONFIG_CATEGORIES)
    else:
        categories = category_data.get('CATEGORIES', {})

    # Get specified branch
    if category:
        categories = {category: categories.get(category, {})}

    inventree_categories = []
    # Build category tree
    build_tree(inventree_categories, categories, 0)

    return inventree_categories


def build_stock_location_tree(reload=False, location=None) -> dict:
    '''Build InvenTree stock locations tree from database data'''

    locations_data = config_interface.load_file(settings.CONFIG_STOCK_LOCATIONS)

    def build_tree(tree, left_to_go, level) -> list:
        try:
            last_entry = f' {category_tree(tree[-1])}{category_separator}'
        except IndexError:
            last_entry = ''
        if isinstance(left_to_go, dict):
            for key, value in left_to_go.items():
                tree.append(f'{"-" * level}{last_entry}{key}')
                build_tree(tree, value, level + 1)
        elif isinstance(left_to_go, list):
            # Supports legacy structure
            for item in left_to_go:
                tree.append(f'{"-" * level}{last_entry}{item}')
        elif left_to_go is None:
            pass
        return

    if reload:
        stock_locations = inventree_api.get_stock_locations()
        locations_data.update({'STOCK_LOCATIONS': stock_locations})
        config_interface.dump_file(locations_data, settings.CONFIG_STOCK_LOCATIONS)
    else:
        stock_locations = locations_data.get('STOCK_LOCATIONS', {})

    # Get specified branch
    if location:
        stock_locations = {location: stock_locations.get(location, {})}

    inventree_stock_locations = []
    # Build category tree
    build_tree(inventree_stock_locations, stock_locations, 0)

    return inventree_stock_locations


def get_categories_from_supplier_data(part_info: dict, supplier_only=False) -> list:
    ''' Find categories from part supplier data, use "somewhat automatic" matching '''
    from thefuzz import fuzz
    
    categories = [None, None]

    try:
        supplier_category = str(part_info['category_tree'][0])
        supplier_subcategory = str(part_info['category_tree'][1])
    except KeyError:
        return categories

    # Return supplier category, if match not needed
    if supplier_only:
        categories[0] = supplier_category
        categories[1] = supplier_subcategory
        return categories

    function_filter = False
    # TODO: Make 'filter_parameter' user defined?
    filter_parameter = 'Function Type'

    # Check existing matches
    # Load inversed category map
    category_map = config_interface.load_supplier_categories_inversed(supplier_config_path=settings.CONFIG_DIGIKEY_CATEGORIES)

    try:
        for inventree_category in category_map.keys():
            for key, inventree_subcategory in category_map[inventree_category].items():
                if supplier_subcategory == key:
                    categories[0] = inventree_category
                    # Check if filtering by function
                    if inventree_subcategory.startswith(config_interface.FUNCTION_FILTER_KEY):
                        function_filter = True

                    # Save subcategory if not function filtered
                    if not function_filter:
                        categories[1] = inventree_subcategory

                    break
    except:
        pass

    # Function Filter
    if not categories[1] and function_filter:
        cprint(f'[INFO]\tSubcategory is filtered using "{filter_parameter}" parameter', silent=settings.SILENT, end='')
        # Load parameter map
        parameter_map = config_interface.load_category_parameters(categories, settings.CONFIG_SUPPLIER_PARAMETERS)
        # Build compare list
        compare = []
        for supplier_parameter, inventree_parameter in parameter_map.items():
            if (supplier_parameter in part_info['parameters'].keys() and inventree_parameter == filter_parameter):
                compare.append(part_info['parameters'][supplier_parameter])

        # Load subcategory map
        category_map = config_interface.load_supplier_categories(supplier_config_path=settings.CONFIG_DIGIKEY_CATEGORIES)[categories[0]]
        for inventree_subcategory in category_map.keys():
            for item in compare:
                fuzzy_match = fuzz.partial_ratio(inventree_subcategory, item)
                display_result = f'"{inventree_subcategory}" ?= "{item}"'.ljust(50)
                cprint(f'{display_result} => {fuzzy_match}', silent=settings.HIDE_DEBUG)
                if fuzzy_match >= settings.CATEGORY_MATCH_RATIO_LIMIT:
                    categories[1] = inventree_subcategory.replace(config_interface.FUNCTION_FILTER_KEY, '')
                    break

            if categories[1]:
                cprint('\t[ PASS ]', silent=settings.SILENT)
                break

    if not categories[1] and function_filter:
        cprint('\t[ FAILED ]', silent=settings.SILENT)

    # Automatic Match
    if not (categories[0] and categories[1]):
        # Load category map
        category_map = config_interface.load_supplier_categories(supplier_config_path=settings.CONFIG_DIGIKEY_CATEGORIES)

        def find_supplier_category_match(supplier_category: str, ignore_categories=False):
            # Check for match with Inventree categories
            category_match = None
            subcategory_match = None

            for inventree_category in category_map.keys():
                fuzzy_match = 0
                
                if not ignore_categories:
                    fuzzy_match = fuzz.partial_ratio(supplier_category, inventree_category)
                    display_result = f'"{supplier_category}" ?= "{inventree_category}"'.ljust(50)
                    cprint(f'{display_result} => {fuzzy_match}', silent=settings.HIDE_DEBUG)

                if fuzzy_match < settings.CATEGORY_MATCH_RATIO_LIMIT and category_map[inventree_category]:
                    # Compare to subcategories
                    for inventree_subcategory in category_map[inventree_category]:
                        fuzzy_match = fuzz.partial_ratio(supplier_category, inventree_subcategory)
                        display_result = f'"{supplier_category}" ?= "{inventree_subcategory}"'.ljust(50)
                        cprint(f'{display_result} => {fuzzy_match}', silent=settings.HIDE_DEBUG)

                        if fuzzy_match >= settings.CATEGORY_MATCH_RATIO_LIMIT:
                            subcategory_match = inventree_subcategory
                            break

                if fuzzy_match >= settings.CATEGORY_MATCH_RATIO_LIMIT:
                    category_match = inventree_category
                    break

            return category_match, subcategory_match

        # Find category and subcategories match
        category, subcategory = find_supplier_category_match(supplier_category)
        if category:
            categories[0] = category
        if subcategory:
            categories[1] = subcategory

        # Run match with supplier subcategory
        if not categories[0] or not categories[1]:
            if categories[0]:
                # If category was found: ignore them for the comparison
                category, subcategory = find_supplier_category_match(supplier_subcategory, ignore_categories=True)
            else:
                category, subcategory = find_supplier_category_match(supplier_subcategory)

        if category and not categories[0]:
            categories[0] = category
        if subcategory and not categories[1]:
            categories[1] = subcategory

    # Final checks
    if not categories[0]:
        cprint(f'[INFO]\tWarning: "{part_info["category_tree"][0]}" did not match any supplier category ', silent=settings.SILENT)
    else:
        cprint(f'[INFO]\tCategory: "{categories[0]}"', silent=settings.SILENT)
    if not categories[1]:
        cprint(f'[INFO]\tWarning: "{part_info["category_tree"][1]}" did not match any supplier subcategory ', silent=settings.SILENT)
    else:
        cprint(f'[INFO]\tSubcategory: "{categories[1]}"', silent=settings.SILENT)
    
    # print(f'{supplier_category=} | {supplier_subcategory=} | {categories[0]=} | {categories[1]=}')
    return categories


def translate_form_to_inventree(part_info: dict, category_tree: list, is_custom=False) -> dict:
    ''' Using supplier part data and categories, fill-in InvenTree part dictionary '''

    # Copy template
    inventree_part = copy.deepcopy(settings.inventree_part_template)

    # Translate form data to inventree part
    inventree_part['category_tree'] = category_tree
    inventree_part['name'] = part_info['name']
    inventree_part['description'] = part_info['description']
    inventree_part['revision'] = part_info['revision']
    inventree_part['keywords'] = part_info['keywords']
    inventree_part['supplier_name'] = part_info['supplier_name']
    inventree_part['supplier_part_number'] = part_info['supplier_part_number']
    inventree_part['manufacturer_name'] = part_info['manufacturer_name']
    inventree_part['manufacturer_part_number'] = part_info['manufacturer_part_number']
    inventree_part['IPN'] = part_info.get('IPN', '')
    # Replace whitespaces in URL
    inventree_part['supplier_link'] = part_info['supplier_link'].replace(' ', '%20')
    inventree_part['datasheet'] = part_info['datasheet'].replace(' ', '%20')
    # Image URL is not shown to user so force default key/value
    try:
        inventree_part['image'] = part_info['image'].replace(' ', '%20')
    except AttributeError:
        # Part image URL is null (no product picture)
        pass
    inventree_part['pricing'] = part_info.get('pricing', {})
    inventree_part['currency'] = part_info.get('currency', 'USD')

    parameters = part_info.get('parameters', {})

    # Load parameters map
    if category_tree:
        parameter_map = config_interface.load_category_parameters(
            categories=category_tree,
            supplier_config_path=settings.CONFIG_SUPPLIER_PARAMETERS,
        )
    else:
        cprint('[INFO]\tWarning: Parameter map not loaded (no category selected)', silent=settings.SILENT)

    if not is_custom:
        # Add Parameters
        if parameter_map:
            parameters_missing = []
            for supplier_param, inventree_param in parameter_map.items():
                # Some parameters may not be mapped
                if inventree_param not in inventree_part['parameters'].keys():
                    if supplier_param == 'Manufacturer Part Number':
                        inventree_part['parameters'][inventree_param] = part_info['manufacturer_part_number']
                    elif inventree_param == 'image':
                        inventree_part['existing_image'] = supplier_param
                    else:
                        try:
                            parameter_value = part_tools.clean_parameter_value(
                                category=category_tree[0],
                                name=supplier_param,
                                value=parameters[supplier_param],
                            )
                            inventree_part['parameters'][inventree_param] = parameter_value
                        except KeyError:
                            parameters_missing.append(supplier_param)
            if parameters_missing:
                msg = '[INFO]\tWarning: The following parameters were not found in supplier data:\n'
                msg += str(parameters_missing)
                cprint(msg, silent=settings.SILENT)

            # Check for missing InvenTree parameters and fill value with dash
            for inventree_param in parameter_map.values():
                if inventree_param == 'image':
                    continue
                if inventree_param not in inventree_part['parameters'].keys():
                    inventree_part['parameters'][inventree_param] = '-'

            # Check for extra parameters which weren't mapped
            parameters_unmapped = []
            for search_param in parameters.keys():
                if search_param not in parameter_map.keys():
                    parameters_unmapped.append(search_param)
            
            if parameters_unmapped:
                if not settings.SILENT:
                    msg = f'[INFO]\tThe following parameters are not mapped in {inventree_part["supplier_name"]} parameters configuration:\n'
                    msg += str(parameters_unmapped)
                    print(msg)
        else:
            cprint(f'[INFO]\tWarning: Parameter map for "{category_tree[0]}" does not exist or is empty', silent=settings.SILENT)

    return inventree_part


def get_supplier_name(supplier: str) -> str:
    ''' Get InvenTree supplier name '''

    supplier_name = supplier

    for supplier, data in settings.CONFIG_SUPPLIERS.items():
        if data['name'] == supplier_name:
            # Update supplier name
            supplier_name = supplier
            break
    
    return supplier_name


def translate_supplier_to_form(supplier: str, part_info: dict) -> dict:
    ''' Translate supplier data to user form format '''

    part_form = {}

    def get_value_from_user_key(user_key: str, default_key: str, default_value=None) -> str:
        ''' Get value mapped from user search key, else default search key '''
        user_search_key = None
        if supplier == 'Digi-Key':
            user_search_key = settings.CONFIG_DIGIKEY.get(user_key, None)
        elif supplier == 'Mouser':
            user_search_key = settings.CONFIG_MOUSER.get(user_key, None)
        elif supplier in ['Farnell', 'Newark', 'Element14']:
            user_search_key = settings.CONFIG_ELEMENT14.get(user_key, None)
        elif supplier == 'LCSC':
            user_search_key = settings.CONFIG_LCSC.get(user_key, None)
        elif supplier == 'Jameco':
            user_search_key = settings.CONFIG_JAMECO.get(user_key, None)
        elif supplier == 'TME':
            user_search_key = settings.CONFIG_TME.get(user_key, None)
        elif supplier == 'AutomationDirect':
            user_search_key = settings.CONFIG_AUTOMATIONDIRECT.get(user_key, None)

        else:
            return default_value
        
        # If no user key, use default
        if not user_search_key:
            return part_info.get(default_key, default_value)

        # Get value for user key, return value from default key if not found
        return part_info.get(user_search_key, part_info.get(default_key, default_value))

    # Check that supplier argument is valid
    if not supplier and supplier != 'custom':
        return part_form
    # Get default keys
    if supplier == 'Digi-Key':
        default_search_keys = digikey_api.get_default_search_keys()
    elif supplier == 'Mouser':
        default_search_keys = mouser_api.get_default_search_keys()
    elif supplier in ['Farnell', 'Newark', 'Element14']:
        default_search_keys = element14_api.get_default_search_keys()
    elif supplier == 'LCSC':
        default_search_keys = lcsc_api.get_default_search_keys()
    elif supplier == 'Jameco':
        default_search_keys = jameco_api.get_default_search_keys()
    elif supplier == 'TME':
        default_search_keys = tme_api.get_default_search_keys()
    elif supplier == 'AutomationDirect':
        default_search_keys = automationdirect_api.get_default_search_keys()
    else:
        # Empty array of default search keys
        default_search_keys = [''] * len(digikey_api.get_default_search_keys())

    # Default revision
    revision = settings.CONFIG_IPN.get('INVENTREE_DEFAULT_REV', '')
    # Translate supplier data to form fields
    part_form['name'] = get_value_from_user_key('SEARCH_NAME', default_search_keys[0], default_value='')
    part_form['description'] = get_value_from_user_key('SEARCH_DESCRIPTION', default_search_keys[1], default_value='')
    part_form['revision'] = get_value_from_user_key('SEARCH_REVISION', default_search_keys[2], default_value=revision)
    part_form['keywords'] = get_value_from_user_key('SEARCH_KEYWORDS', default_search_keys[3], default_value='')
    part_form['supplier_name'] = settings.CONFIG_SUPPLIERS[supplier]['name']
    part_form['supplier_part_number'] = get_value_from_user_key('SEARCH_SKU', default_search_keys[4], default_value='')
    part_form['supplier_link'] = get_value_from_user_key('SEARCH_SUPPLIER_URL', default_search_keys[7], default_value='')
    part_form['manufacturer_name'] = get_value_from_user_key('SEARCH_MANUFACTURER', default_search_keys[5], default_value='')
    part_form['manufacturer_part_number'] = get_value_from_user_key('SEARCH_MPN', default_search_keys[6], default_value='')
    part_form['datasheet'] = get_value_from_user_key('SEARCH_DATASHEET', default_search_keys[8], default_value='')
    part_form['image'] = get_value_from_user_key('', default_search_keys[9], default_value='')
    
    return part_form


def supplier_search(supplier: str, part_number: str, test_mode=False) -> dict:
    ''' Wrapper for supplier search, allow use of cached data (limited daily API calls) '''
    part_info = {}
    # Check part number exist
    if not part_number:
        cprint('\n[MAIN]\tError: Missing Part Number', silent=settings.SILENT)
        return part_info

    store = ''
    if supplier in ['Farnell', 'Newark', 'Element14']:
        try:
            element14_config = config_interface.load_file(settings.CONFIG_ELEMENT14_API)
            store = element14_config.get(f'{supplier.upper()}_STORE', '').replace(' ', '')
        except AttributeError:
            cprint(f'\n[INFO]\tWarning: {supplier.upper()}_STORE value not found', silent=False)

    search_filename = f"{settings.search_results['directory']}{supplier}{store}_{part_number}{settings.search_results['extension']}"
    # Get cached data, if cache is enabled (else returns None)
    part_cache = search_api.load_from_file(search_filename, test_mode)

    if part_cache:
        cprint(f'\n[MAIN]\tUsing {supplier} cached data for {part_number}', silent=settings.SILENT)
        part_info = part_cache
    else:
        cprint(f'\n[MAIN]\t{supplier} search for {part_number}', silent=settings.SILENT)
        if supplier == 'Digi-Key':
            part_info = digikey_api.fetch_part_info(part_number)
        elif supplier == 'Mouser':
            part_info = mouser_api.fetch_part_info(part_number)
        elif supplier in ['Farnell', 'Newark', 'Element14']:
            part_info = element14_api.fetch_part_info(part_number, supplier)
        elif supplier == 'LCSC':
            part_info = lcsc_api.fetch_part_info(part_number)
        elif supplier == 'Jameco':
            part_info = jameco_api.fetch_part_info(part_number)
        elif supplier == 'TME':
            part_info = tme_api.fetch_part_info(part_number)
        elif supplier == 'AutomationDirect':
            part_info = automationdirect_api.fetch_part_info(part_number)

    # Check supplier data exist
    if not part_info:
        cprint(f'[INFO]\tError: Failed to fetch data for "{part_number}"', silent=settings.SILENT)

    # Save search results
    if part_info:
        update_ts = not bool(part_cache) or test_mode
        search_api.save_to_file(part_info, search_filename, update_ts=update_ts)

    return part_info


def inventree_fuzzy_company_match(name: str) -> str:
    ''' Fuzzy match company name to exisiting companies '''
    from thefuzz import fuzz
    
    inventree_companies = inventree_api.get_all_companies()

    for company_name in inventree_companies.keys():
        cprint(f'{name.lower()} == {company_name.lower()} % {fuzz.partial_ratio(name.lower(), company_name.lower())}',
               silent=settings.HIDE_DEBUG)
        if fuzz.partial_ratio(name.lower(), company_name.lower()) == 100 and len(name) == len(company_name):
            return company_name
    
    return name


def inventree_create_manufacturer_part(part_id: int, manufacturer_name: str, manufacturer_mpn: str, datasheet: str, description: str) -> bool:
    ''' Create manufacturer part '''

    cprint('\n[MAIN]\tCreating manufacturer part', silent=settings.SILENT)
    manufacturer_part = inventree_api.is_new_manufacturer_part(manufacturer_name=manufacturer_name,
                                                               manufacturer_mpn=manufacturer_mpn)

    if manufacturer_part:
        cprint('[INFO]\tManufacturer part already exists, skipping.', silent=settings.SILENT)
    else:
        # Create a new manufacturer part
        is_manufacturer_part_created = inventree_api.create_manufacturer_part(part_id=part_id,
                                                                              manufacturer_name=manufacturer_name,
                                                                              manufacturer_mpn=manufacturer_mpn,
                                                                              datasheet=datasheet,
                                                                              description=description)

        if is_manufacturer_part_created:
            cprint('[INFO]\tSuccess: Added new manufacturer part', silent=settings.SILENT)
            return True

    return False


def inventree_create_supplier_part(part) -> bool:
    return


def get_inventree_stock_location_id(stock_location_tree: list):
    return inventree_api.get_inventree_stock_location_id(stock_location_tree)


def inventree_create(part_info: dict, stock=None, kicad=False, symbol=None, footprint=None, show_progress=True, is_custom=False, enable_upload=True):
    ''' Create InvenTree part from supplier part data and categories '''

    part_pk = 0
    new_part = False

    category_tree = part_info['category_tree']
    if not category_tree:
        cprint(f'[INFO]\tError: Category tree is empty {category_tree=}', silent=settings.SILENT)
        return new_part, part_pk, {}

    # Translate to InvenTree part format
    inventree_part = translate_form_to_inventree(
        part_info=part_info,
        category_tree=category_tree,
        is_custom=is_custom,
    )

    if not inventree_part:
        cprint('\n[MAIN]\tError: Failed to process form data', silent=settings.SILENT)

    category_pk = inventree_api.get_inventree_category_id(category_tree)
    if category_pk <= 0:
        cprint(f'[ERROR]\tCategory ({category_tree}) does not exist in InvenTree', silent=settings.SILENT)
    else:
        if settings.CHECK_EXISTING:
            # Check if part already exists
            part_pk = inventree_api.is_new_part(category_pk, inventree_part)
            # Part exists
            if part_pk > 0:
                cprint('[INFO]\tPart already exists, skipping.', silent=settings.SILENT)
                info = inventree_api.get_part_info(part_pk)
                if info:
                    # Update InvenTree part number
                    inventree_part = {**inventree_part, **info}
                    # Update InvenTree URL
                    inventree_part['inventree_url'] = f'{settings.PART_URL_ROOT}{part_pk}/'
                else:
                    inventree_part['inventree_url'] = f'{settings.PART_URL_ROOT}{part_pk}/'
        # Part is new
        if not part_pk:
            new_part = True
            if settings.CONFIG_IPN.get('IPN_ENABLE_CREATE', True):
                # Generate Placeholder Internal Part Number
                ipn = part_tools.generate_part_number(
                    category=category_tree[0],
                    part_pk=0,
                    category_code=part_info.get('category_code', ''),
                )
            else:
                ipn = ''
            # Create a new Part
            # Use the pk (primary-key) of the category
            part_pk = inventree_api.create_part(
                category_id=category_pk,
                name=inventree_part['name'],
                description=inventree_part['description'],
                revision=inventree_part['revision'],
                keywords=inventree_part['keywords'],
                ipn=ipn)

            # Check part primary key
            if not part_pk:
                return new_part, part_pk, inventree_part
            # Progress Update
            if not progress.update_progress_bar(show_progress):
                return new_part, part_pk, inventree_part

            if settings.CONFIG_IPN.get('IPN_ENABLE_CREATE', True):
                # Generate Internal Part Number
                cprint('\n[MAIN]\tGenerating Internal Part Number', silent=settings.SILENT)
                if settings.CONFIG_IPN.get('IPN_USE_MANUFACTURER_PART_NUMBER', False):
                    ipn = inventree_part['manufacturer_part_number']
                else:
                    ipn = part_tools.generate_part_number(
                        category=category_tree[0],
                        part_pk=part_pk,
                        category_code=part_info.get('category_code', ''),
                    )
                cprint(f'[INFO]\tInternal Part Number = {ipn}', silent=settings.SILENT)
                # Update InvenTree part number
                ipn_update = inventree_api.set_part_number(part_pk, ipn)
                if not ipn_update:
                    cprint('\n[INFO]\tError updating IPN', silent=settings.SILENT)
                inventree_part['IPN'] = ipn
            # Update InvenTree URL
            inventree_part['inventree_url'] = f'{settings.PART_URL_ROOT}{part_pk}/'

    # Progress Update
    if not progress.update_progress_bar(show_progress):
        return new_part, part_pk, inventree_part

    if part_pk > 0:
        if new_part:
            cprint('[INFO]\tSuccess: Added new part to InvenTree', silent=settings.SILENT)
            if inventree_part.get('existing_image', ''):
                inventree_api.update_part(
                    part_pk,
                    data={'existing_image': inventree_part['existing_image']})
            elif inventree_part['image']:
                if enable_upload:
                    # Add image
                    image_result = inventree_api.upload_part_image(inventree_part['image'], part_pk, silent=settings.SILENT)
                    if not image_result:
                        cprint('[TREE]\tWarning: Failed to upload part image', silent=settings.SILENT)
        if inventree_part['datasheet'] and settings.DATASHEET_UPLOAD:
            if enable_upload:
                # Upload datasheet
                datasheet_link = inventree_api.upload_part_datasheet(
                    datasheet_url=inventree_part['datasheet'],
                    part_ipn=inventree_part['IPN'],
                    part_pk=part_pk,
                    silent=settings.SILENT,
                )
                if not datasheet_link:
                    cprint('[TREE]\tWarning: Failed to upload part datasheet', silent=settings.SILENT)
                else:
                    cprint('[TREE]\tSuccess: Uploaded part datasheet', silent=settings.SILENT)

        if kicad:
            try:
                symbol_name = ipn
            except UnboundLocalError:
                symbol_name = inventree_part.get('manufacturer_part_number')

            # Create symbol & footprint parameters
            if symbol:
                symbol = f'{symbol.split(":")[0]}:{symbol_name}'
                inventree_part['parameters']['Symbol'] = symbol
            if footprint:
                inventree_part['parameters']['Footprint'] = footprint

        if not inventree_part['parameters']:
            category_parameters = inventree_api.get_category_parameters(category_pk)

            # Add category-defined parameters
            for parameter in category_parameters:
                inventree_part['parameters'][parameter[0]] = parameter[1]

        # Create parameters
        if len(inventree_part['parameters']) > 0:
            if not inventree_process_parameters(
                    part_id=part_pk,
                    parameters=inventree_part['parameters'],
                    show_progress=show_progress):
                return new_part, part_pk, inventree_part
            
        # Create manufacturer part
        if inventree_part['manufacturer_name'] and inventree_part['manufacturer_part_number']:
            # Overwrite manufacturer name with matching one from database
            manufacturer_name = inventree_fuzzy_company_match(inventree_part['manufacturer_name'])
            # Get MPN
            manufacturer_mpn = inventree_part['manufacturer_part_number']

            cprint('\n[MAIN]\tCreating manufacturer part', silent=settings.SILENT)
            manufacturer_part = inventree_api.is_new_manufacturer_part(
                manufacturer_name=manufacturer_name,
                manufacturer_mpn=manufacturer_mpn,
            )

            if manufacturer_part:
                cprint('[INFO]\tManufacturer part already exists, skipping.', silent=settings.SILENT)
            else:
                # Create a new manufacturer part
                is_manufacturer_part_created = inventree_api.create_manufacturer_part(
                    part_id=part_pk,
                    manufacturer_name=manufacturer_name,
                    manufacturer_mpn=manufacturer_mpn,
                    datasheet=inventree_part['datasheet'],
                    description=inventree_part['description'],
                )

                if is_manufacturer_part_created:
                    cprint('[INFO]\tSuccess: Added new manufacturer part', silent=settings.SILENT)

        # Create supplier part
        if inventree_part['supplier_name'] and inventree_part['supplier_part_number']:
            # Overwrite manufacturer name with matching one from database
            supplier_name = inventree_fuzzy_company_match(inventree_part['supplier_name'])
            # Get SKU
            supplier_sku = inventree_part['supplier_part_number']

            cprint('\n[MAIN]\tCreating supplier part', silent=settings.SILENT)
            is_new_supplier_part, supplier_part = inventree_api.is_new_supplier_part(
                supplier_name=supplier_name,
                supplier_sku=supplier_sku)

            if not is_new_supplier_part:
                cprint('[INFO]\tSupplier part already exists, skipping.', silent=settings.SILENT)
            else:
                # Create a new supplier part
                is_supplier_part_created, supplier_part = inventree_api.create_supplier_part(
                    part_id=part_pk,
                    manufacturer_name=manufacturer_name,
                    manufacturer_mpn=manufacturer_mpn,
                    supplier_name=supplier_name,
                    supplier_sku=supplier_sku,
                    description=inventree_part['description'],
                    link=inventree_part['supplier_link'],
                )

                if is_supplier_part_created:
                    cprint('[INFO]\tSuccess: Added new supplier part', silent=settings.SILENT)
            
            if supplier_part and settings.PRICING_UPLOAD:
                cprint('\n[MAIN]\tProcessing Price Breaks', silent=settings.SILENT)
                inventree_api.update_price_breaks(
                    supplier_part=supplier_part,
                    price_breaks=inventree_part['pricing'],
                    currency=inventree_part['currency'])

        if stock is not None:
            stock['part'] = part_pk
            inventree_api.create_stock(stock)
            if stock['make_default']:
                inventree_api.set_part_default_location(part_pk, stock['location'])

    # Progress Update
    if not progress.update_progress_bar(show_progress):
        pass

    return new_part, part_pk, inventree_part


def inventree_process_parameters(part_id: str, parameters: dict, show_progress=True) -> bool:
    ''' Create or Update parameters for an InvenTree part'''
    cprint('\n[MAIN]\tCreating parameters', silent=settings.SILENT)
    parameters_lists = [
        [],  # Store new parameters
        [],  # Store updated parameters
        [],  # Store unchanged parameters
    ]
    for name, value in parameters.items():
        parameter, is_new_parameter, was_updated = inventree_api.create_parameter(part_id=part_id, template_name=name, value=value)
        # Progress Update
        if not progress.update_progress_bar(show_progress, increment=0.03):
            return False
        if is_new_parameter:
            parameters_lists[0].append(name)
        elif was_updated:
            parameters_lists[1].append(name)
        else:
            parameters_lists[2].append(name)
    if parameters_lists[0]:
        cprint('[INFO]\tSuccess: The following parameters were created:', silent=settings.SILENT)
        for item in parameters_lists[0]:
            cprint(f'--->\t{item}', silent=settings.SILENT)
    if parameters_lists[1]:
        cprint('[INFO]\tSuccess: The following parameters were updated:', silent=settings.SILENT)
        for item in parameters_lists[1]:
            cprint(f'--->\t{item}', silent=settings.SILENT)
    if parameters_lists[2]:
        cprint('[TREE]\tWarning: The following parameters were skipped:', silent=settings.SILENT)
        for item in parameters_lists[2]:
            cprint(f'--->\t{item}', silent=settings.SILENT)
    return True


def inventree_create_alternate(part_info: dict, part_id='', part_ipn='', show_progress=None) -> bool:
    ''' Create alternate manufacturer and supplier entries for an existing InvenTree part '''

    result = False
    cprint('\n[MAIN]\tSearching for original part in database', silent=settings.SILENT)
    part = inventree_api.fetch_part(part_id, part_ipn)

    if part:
        part_pk = part.pk
        part_description = part.description
        cprint(f'[INFO] Success: Found original part in database (ID = {part_pk} | Description = "{part_description}")', silent=settings.SILENT)
    else:
        cprint('[INFO] Error: Original part was not found in database', silent=settings.SILENT)
        return result
    # Translate to InvenTree part format
    category_tree = inventree_api.get_category_tree(part.category)
    category_tree = list(category_tree.values())
    category_tree.reverse()
    inventree_part = translate_form_to_inventree(
        part_info=part_info,
        category_tree=category_tree,
    )

    # If the part has no image yet try to upload it from the data
    if not part.image:
        image = part_info.get('image', '')
        existing_image = inventree_part.get('existing_image', '')
        if existing_image:
            inventree_api.update_part(pk=part_pk,
                                      data={'existing_image': existing_image})
        elif image:
            inventree_api.upload_part_image(image_url=image, part_id=part_pk, silent=settings.SILENT)

    # create or update parameters
    if inventree_part.get('parameters', {}):
        inventree_process_parameters(part_id=part_pk,
                                     parameters=inventree_part['parameters'],
                                     show_progress=show_progress)

    # Overwrite manufacturer name with matching one from database
    manufacturer_name = inventree_fuzzy_company_match(part_info.get('manufacturer_name', ''))
    manufacturer_mpn = part_info.get('manufacturer_part_number', '')
    datasheet = part_info.get('datasheet', '')

    attachment = part.getAttachments()
    # if datasheet upload is enabled and no attachment present yet then upload
    if settings.DATASHEET_UPLOAD and not attachment:
        if datasheet:
            part_info['datasheet'] = inventree_api.upload_part_datasheet(
                datasheet_url=datasheet,
                part_ipn=part_ipn,
                part_pk=part_id,
                silent=settings.SILENT,
            )
            if not part_info['datasheet']:
                cprint('[TREE]\tWarning: Failed to upload part datasheet', silent=settings.SILENT)
            else:
                cprint('[TREE]\tSuccess: Uploaded part datasheet', silent=settings.SILENT)
    # if an attachment is present, set it as the datasheet field
    if attachment:
        part_info['datasheet'] = f'{inventree_api.inventree_api.base_url.strip("/")}{attachment[0]["attachment"]}'

    # Create manufacturer part
    if manufacturer_name and manufacturer_mpn:
        inventree_create_manufacturer_part(part_id=part_pk,
                                           manufacturer_name=manufacturer_name,
                                           manufacturer_mpn=manufacturer_mpn,
                                           datasheet=datasheet,
                                           description=part_description)
    else:
        cprint('[INFO]\tWarning: No manufacturer part to create', silent=settings.SILENT)

    # Progress Update
    if not progress.update_progress_bar(show_progress, increment=0.2):
        return

    supplier_name = part_info.get('supplier_name', '')
    supplier_sku = part_info.get('sup
Download .txt
gitextract_ks9t75m5/

├── .coveragerc
├── .github/
│   └── workflows/
│       └── test_deploy.yaml
├── .gitignore
├── LICENSE
├── README.md
├── invoke.yaml
├── kintree/
│   ├── __init__.py
│   ├── common/
│   │   ├── part_tools.py
│   │   ├── progress.py
│   │   └── tools.py
│   ├── config/
│   │   ├── automationdirect/
│   │   │   ├── automationdirect_api.yaml
│   │   │   └── automationdirect_config.yaml
│   │   ├── config_interface.py
│   │   ├── digikey/
│   │   │   ├── digikey_api.yaml
│   │   │   ├── digikey_categories.yaml
│   │   │   └── digikey_config.yaml
│   │   ├── element14/
│   │   │   ├── element14_api.yaml
│   │   │   └── element14_config.yaml
│   │   ├── inventree/
│   │   │   ├── categories.yaml
│   │   │   ├── inventree_dev.yaml
│   │   │   ├── inventree_prod.yaml
│   │   │   ├── parameters.yaml
│   │   │   ├── parameters_filters.yaml
│   │   │   ├── stock_locations.yaml
│   │   │   ├── supplier_parameters.yaml
│   │   │   └── suppliers.yaml
│   │   ├── jameco/
│   │   │   ├── jameco_api.yaml
│   │   │   └── jameco_config.yaml
│   │   ├── kicad/
│   │   │   ├── kicad.yaml
│   │   │   └── kicad_map.yaml
│   │   ├── lcsc/
│   │   │   ├── lcsc_api.yaml
│   │   │   └── lcsc_config.yaml
│   │   ├── mouser/
│   │   │   ├── mouser_api.yaml
│   │   │   └── mouser_config.yaml
│   │   ├── settings.py
│   │   ├── tme/
│   │   │   ├── tme_api.yaml
│   │   │   └── tme_config.yaml
│   │   └── user/
│   │       ├── general.yaml
│   │       ├── internal_part_number.yaml
│   │       └── search_api.yaml
│   ├── database/
│   │   ├── inventree_api.py
│   │   └── inventree_interface.py
│   ├── gui/
│   │   ├── gui.py
│   │   └── views/
│   │       ├── common.py
│   │       ├── main.py
│   │       └── settings.py
│   ├── kicad/
│   │   ├── kicad_interface.py
│   │   ├── kicad_symbol.py
│   │   ├── templates/
│   │   │   ├── LICENSE
│   │   │   ├── capacitor-polarized.kicad_sym
│   │   │   ├── capacitor.kicad_sym
│   │   │   ├── connector.kicad_sym
│   │   │   ├── crystal-2p.kicad_sym
│   │   │   ├── default.kicad_sym
│   │   │   ├── diode-led.kicad_sym
│   │   │   ├── diode-schottky.kicad_sym
│   │   │   ├── diode-standard.kicad_sym
│   │   │   ├── diode-zener.kicad_sym
│   │   │   ├── eeprom-sot23.kicad_sym
│   │   │   ├── ferrite-bead.kicad_sym
│   │   │   ├── fuse.kicad_sym
│   │   │   ├── inductor.kicad_sym
│   │   │   ├── integrated-circuit.kicad_sym
│   │   │   ├── library_template.kicad_sym
│   │   │   ├── oscillator-4p.kicad_sym
│   │   │   ├── protection-unidir.kicad_sym
│   │   │   ├── resistor-sm.kicad_sym
│   │   │   ├── resistor.kicad_sym
│   │   │   ├── transistor-nfet.kicad_sym
│   │   │   ├── transistor-npn.kicad_sym
│   │   │   ├── transistor-pfet.kicad_sym
│   │   │   └── transistor-pnp.kicad_sym
│   │   └── templates_project/
│   │       ├── templates_project.kicad_pcb
│   │       ├── templates_project.kicad_prl
│   │       ├── templates_project.kicad_pro
│   │       └── templates_project.kicad_sch
│   ├── kintree_gui.py
│   ├── search/
│   │   ├── automationdirect_api.py
│   │   ├── digikey_api.py
│   │   ├── element14_api.py
│   │   ├── jameco_api.py
│   │   ├── lcsc_api.py
│   │   ├── mouser_api.py
│   │   ├── search_api.py
│   │   ├── snapeda_api.py
│   │   └── tme_api.py
│   └── setup_inventree.py
├── kintree_gui.py
├── poetry.toml
├── pyproject.toml
├── requirements.txt
├── run_tests.py
├── setup.cfg
├── tasks.py
└── tests/
    ├── files/
    │   ├── FOOTPRINTS/
    │   │   └── RF.pretty/
    │   │       ├── Skyworks_SKY13575_639LF.kicad_mod
    │   │       └── Skyworks_SKY65404-31.kicad_mod
    │   ├── SYMBOLS/
    │   │   └── TEST.kicad_sym
    │   ├── digikey_config.yaml
    │   ├── inventree_default_db.sqlite3
    │   ├── inventree_dev.yaml
    │   ├── kicad_map.yaml
    │   └── results.tgz
    └── test_samples.yaml
Download .txt
SYMBOL INDEX (287 symbols across 26 files)

FILE: kintree/common/part_tools.py
  function generate_part_number (line 8) | def generate_part_number(category: str, part_pk: int, category_code='') ...
  function compare (line 44) | def compare(new_part_parameters: dict, db_part_parameters: dict, include...
  function clean_parameter_value (line 64) | def clean_parameter_value(category: str, name: str, value: str) -> str:

FILE: kintree/common/progress.py
  function reset_progress_bar (line 8) | def reset_progress_bar(progress_bar) -> bool:
  function progress_increment (line 22) | def progress_increment(inc):
  function update_progress_bar (line 34) | def update_progress_bar(progress_bar, increment=0) -> bool:

FILE: kintree/common/tools.py
  class pcolors (line 8) | class pcolors:
  function cprint (line 21) | def cprint(*args, **kwargs):
  function create_library (line 54) | def create_library(library_path: str, symbol: str, template_lib: str):
  function get_image_with_retries (line 63) | def get_image_with_retries(url, headers, retries=3, wait=5, silent=False):
  function download (line 82) | def download(url, filetype='API data', fileoutput='', timeout=3, enable_...
  function download_with_retry (line 161) | def download_with_retry(url: str, full_path: str, silent=False, **kwargs...

FILE: kintree/config/config_interface.py
  function load_file (line 12) | def load_file(file_path: str, silent=True) -> dict:
  function dump_file (line 28) | def dump_file(data: dict, file_path: str) -> bool:
  function load_user_paths (line 43) | def load_user_paths(home_dir='') -> dict:
  function load_user_config_files (line 59) | def load_user_config_files(path_to_root: str, path_to_user_files: str, s...
  function load_inventree_user_settings (line 101) | def load_inventree_user_settings(user_config_path: str) -> dict:
  function save_inventree_user_settings (line 132) | def save_inventree_user_settings(enable: bool,
  function load_library_path (line 157) | def load_library_path(user_config_path: str, silent=False):
  function add_library_path (line 170) | def add_library_path(user_config_path: str, category: str, symbol_librar...
  function load_libraries_paths (line 191) | def load_libraries_paths(user_config_path: str, library_path: str) -> dict:
  function load_templates_paths (line 242) | def load_templates_paths(user_config_path: str, template_path: str) -> d...
  function load_footprint_paths (line 270) | def load_footprint_paths(user_config_path: str, footprint_path: str) -> ...
  function add_footprint_library (line 307) | def add_footprint_library(user_config_path: str, category: str, library_...
  function load_supplier_categories (line 328) | def load_supplier_categories(supplier_config_path: str, clean=False) -> ...
  function load_supplier_categories_inversed (line 348) | def load_supplier_categories_inversed(supplier_config_path: str) -> dict:
  function sync_inventree_supplier_categories (line 370) | def sync_inventree_supplier_categories(inventree_config_path: str, suppl...
  function add_supplier_category (line 386) | def add_supplier_category(categories: dict, supplier_config_path: str) -...
  function load_category_parameters (line 446) | def load_category_parameters(categories: list, supplier_config_path: str...
  function load_category_parameters_filters (line 484) | def load_category_parameters_filters(category: str, supplier_config_path...

FILE: kintree/config/settings.py
  function enable_test_mode (line 18) | def enable_test_mode():
  function load_user_config (line 54) | def load_user_config():
  function load_ipn_settings (line 95) | def load_ipn_settings():
  function reload_enable_flags (line 115) | def reload_enable_flags():
  function load_suppliers (line 144) | def load_suppliers():
  function load_cache_settings (line 220) | def load_cache_settings():
  function load_kicad_settings (line 262) | def load_kicad_settings():
  function set_default_supplier (line 277) | def set_default_supplier(value: str, save=False):
  class Environment (line 320) | class Environment(Enum):
  function load_inventree_settings (line 349) | def load_inventree_settings():
  function set_enable_flag (line 398) | def set_enable_flag(key: str, value: bool):

FILE: kintree/database/inventree_api.py
  function connect (line 27) | def connect(server: str,
  function set_inventree_db_test_mode (line 56) | def set_inventree_db_test_mode():
  function get_inventree_category_id (line 63) | def get_inventree_category_id(category_tree: list) -> int:
  function get_inventree_stock_location_id (line 97) | def get_inventree_stock_location_id(stock_location_tree: list) -> int:
  function get_categories (line 131) | def get_categories() -> dict:
  function get_stock_locations (line 166) | def get_stock_locations() -> dict:
  function get_category_tree (line 201) | def get_category_tree(category_id: int) -> dict:
  function get_stock_location_tree (line 213) | def get_stock_location_tree(id: int) -> dict:
  function create_stock (line 225) | def create_stock(stock_data: dict) -> dict:
  function get_category_parameters (line 229) | def get_category_parameters(category_id: int) -> list:
  function get_part_info (line 254) | def get_part_info(part_id: int) -> str:
  function set_part_number (line 266) | def set_part_number(part_id: int, ipn: str) -> bool:
  function get_part_from_ipn (line 277) | def get_part_from_ipn(part_ipn='') -> int:
  function fetch_part (line 291) | def fetch_part(part_id='', part_ipn='') -> int:
  function is_new_part (line 317) | def is_new_part(category_id: int, part_info: dict) -> int:
  function create_category (line 391) | def create_category(parent: str, name: str):
  function upload_part_image (line 443) | def upload_part_image(image_url: str, part_id: int, silent=False) -> bool:
  function upload_part_datasheet (line 466) | def upload_part_datasheet(datasheet_url: str, part_ipn: int, part_pk: in...
  function create_part (line 500) | def create_part(category_id: int, name: str, description: str, revision:...
  function set_part_default_location (line 528) | def set_part_default_location(part_pk: int, location_pk: int):
  function update_part (line 540) | def update_part(pk: int, data: dict) -> int:
  function create_company (line 552) | def create_company(company_name: str, manufacturer=False, supplier=False...
  function get_all_companies (line 570) | def get_all_companies() -> dict:
  function get_company_id (line 582) | def get_company_id(company_name: str) -> int:
  function is_new_manufacturer_part (line 591) | def is_new_manufacturer_part(manufacturer_name: str, manufacturer_mpn: s...
  function is_new_supplier_part (line 635) | def is_new_supplier_part(supplier_name: str, supplier_sku: str):
  function create_manufacturer_part (line 672) | def create_manufacturer_part(part_id: int, manufacturer_name: str, manuf...
  function create_supplier_part (line 708) | def create_supplier_part(part_id: int, manufacturer_name: str, manufactu...
  function update_price_breaks (line 755) | def update_price_breaks(supplier_part,
  function create_parameter_template (line 819) | def create_parameter_template(name: str, units: str) -> int:
  function create_parameter (line 843) | def create_parameter(part_id: int, template_name: int, value: str):

FILE: kintree/database/inventree_interface.py
  function connect_to_server (line 13) | def connect_to_server(timeout=5) -> bool:
  function category_tree (line 51) | def category_tree(tree: str) -> str:
  function split_category_tree (line 59) | def split_category_tree(tree: str) -> list:
  function build_category_tree (line 63) | def build_category_tree(reload=False, category=None) -> dict:
  function build_stock_location_tree (line 103) | def build_stock_location_tree(reload=False, location=None) -> dict:
  function get_categories_from_supplier_data (line 143) | def get_categories_from_supplier_data(part_info: dict, supplier_only=Fal...
  function translate_form_to_inventree (line 284) | def translate_form_to_inventree(part_info: dict, category_tree: list, is...
  function get_supplier_name (line 374) | def get_supplier_name(supplier: str) -> str:
  function translate_supplier_to_form (line 388) | def translate_supplier_to_form(supplier: str, part_info: dict) -> dict:
  function supplier_search (line 461) | def supplier_search(supplier: str, part_number: str, test_mode=False) ->...
  function inventree_fuzzy_company_match (line 513) | def inventree_fuzzy_company_match(name: str) -> str:
  function inventree_create_manufacturer_part (line 528) | def inventree_create_manufacturer_part(part_id: int, manufacturer_name: ...
  function inventree_create_supplier_part (line 552) | def inventree_create_supplier_part(part) -> bool:
  function get_inventree_stock_location_id (line 556) | def get_inventree_stock_location_id(stock_location_tree: list):
  function inventree_create (line 560) | def inventree_create(part_info: dict, stock=None, kicad=False, symbol=No...
  function inventree_process_parameters (line 784) | def inventree_process_parameters(part_id: str, parameters: dict, show_pr...
  function inventree_create_alternate (line 818) | def inventree_create_alternate(part_info: dict, part_id='', part_ipn='',...

FILE: kintree/gui/gui.py
  function init_gui (line 21) | def init_gui(page: ft.Page):
  function kintree_gui (line 43) | def kintree_gui(page: ft.Page):

FILE: kintree/gui/views/common.py
  class DialogType (line 28) | class DialogType(Enum):
  function handle_transition (line 34) | def handle_transition(page: ft.Page, transition: bool, update_page=False...
  function update_theme (line 60) | def update_theme(page: ft.Page, mode='light', transition=False, compact=...
  class CommonView (line 78) | class CommonView(ft.View):
    method __init__ (line 89) | def __init__(self, page: ft.Page, appbar: ft.AppBar, navigation_rail: ...
    method build_column (line 100) | def build_column(self):
    method build (line 104) | def build(self):
    method build_dialog (line 120) | def build_dialog(self):
    method build_snackbar (line 123) | def build_snackbar(self, d_type: DialogType, message: str):
    method show_dialog (line 155) | def show_dialog(
  class SwitchWithRefs (line 178) | class SwitchWithRefs(ft.Switch):
    method __init__ (line 183) | def __init__(
    method enable_refs (line 195) | def enable_refs(self, enable):
    method process_change (line 206) | def process_change(self, e, handler, *args, **kwargs):
    method refs (line 214) | def refs(self):
    method refs (line 218) | def refs(self, references: List[ft.Ref]):
    method on_change (line 234) | def on_change(self, handler, *args, **kwargs):
  class DropdownWithSearch (line 241) | class DropdownWithSearch(ft.UserControl):
    method build (line 250) | def build(self):
    method __str__ (line 257) | def __str__(self):
    method __init__ (line 260) | def __init__(
    method label (line 300) | def label(self):
    method label (line 304) | def label(self, label):
    method value (line 308) | def value(self):
    method value (line 312) | def value(self, value):
    method disabled (line 319) | def disabled(self):
    method disabled (line 323) | def disabled(self, disabled):
    method options (line 337) | def options(self):
    method options (line 341) | def options(self, options):
    method on_change (line 346) | def on_change(self):
    method on_change (line 350) | def on_change(self, on_change):
    method update_option_list (line 353) | def update_option_list(self, input: str):
    method on_search (line 360) | def on_search(self, e):
    method search_now (line 373) | def search_now(self, e):
    method done_search (line 385) | def done_search(self, e=None):
  class MenuButton (line 397) | class MenuButton(ft.Container):
    method __init__ (line 398) | def __init__(
    method item_click (line 416) | def item_click(self, _):
    method build (line 419) | def build(self):
    method _before_build_command (line 429) | def _before_build_command(self):

FILE: kintree/gui/views/main.py
  class MainView (line 108) | class MainView(CommonView):
    method __init__ (line 114) | def __init__(self, page: ft.Page):
    method nav_rail_redirect (line 153) | def nav_rail_redirect(self, e):
    method call_settings (line 156) | def call_settings(self, e):
    method reset_view (line 160) | def reset_view(self, e, ignore=['enable'], hidden={}):
    method partial_update (line 187) | def partial_update(self):
    method process_enable (line 191) | def process_enable(self, e, value=None, ignore=['enable']):
    method sanitize_data (line 209) | def sanitize_data(self):
    method push_data (line 212) | def push_data(self, e=None, hidden={}):
    method did_mount (line 228) | def did_mount(self, enable=False):
  class PartSearchView (line 244) | class PartSearchView(MainView):
    method reset_view (line 293) | def reset_view(self, e, ignore=['enable']):
    method enable_search_fields (line 305) | def enable_search_fields(self):
    method run_search (line 312) | def run_search(self, e):
    method push_data (line 400) | def push_data(self, e=None):
    method partial_update (line 411) | def partial_update(self):
    method update_suppliers (line 415) | def update_suppliers(self):
    method switch_view (line 430) | def switch_view(self, e=None):
    method perform_pn_search (line 453) | def perform_pn_search(self, e):
    method build_column (line 460) | def build_column(self):
    method did_mount (line 506) | def did_mount(self, enable=False):
  class InventreeView (line 519) | class InventreeView(MainView):
    method __init__ (line 618) | def __init__(self, page: ft.Page):
    method partial_update (line 625) | def partial_update(self):
    method sanitize_data (line 629) | def sanitize_data(self):
    method process_enable (line 637) | def process_enable(self, e):
    method process_alternate (line 658) | def process_alternate(self, e, value=None):
    method process_update (line 695) | def process_update(self, e, value=None):
    method process_button (line 706) | def process_button(self, e, value=None):
    method process_category (line 720) | def process_category(self, e=None, label=None, value=None):
    method process_location (line 735) | def process_location(self, e=None, label=None, value=None):
    method process_ipncode (line 739) | def process_ipncode(self):
    method process_create_stock (line 746) | def process_create_stock(self, e, value=None):
    method get_code_options (line 760) | def get_code_options(self):
    method get_category_options (line 769) | def get_category_options(self, reload=False):
    method get_stock_location_options (line 775) | def get_stock_location_options(self, reload=False):
    method reload_categories (line 781) | def reload_categories(self, e):
    method reload_stock_locations (line 795) | def reload_stock_locations(self, e):
    method create_ipn_code (line 809) | def create_ipn_code(self, e):
    method build_column (line 822) | def build_column(self):
    method did_mount (line 938) | def did_mount(self):
  class KicadView (line 942) | class KicadView(MainView):
    method build_alert_dialog (line 1000) | def build_alert_dialog(self, symbol: str, footprint: str, download: st...
    method process_enable (line 1035) | def process_enable(self, e, value=None, ignore=['enable']):
    method push_data (line 1041) | def push_data(self, e=None, label=None, value=None):
    method check_snapeda (line 1055) | def check_snapeda(self, e):
    method update_footprint_options (line 1084) | def update_footprint_options(self, library: str):
    method get_footprint_libraries (line 1106) | def get_footprint_libraries(self) -> dict:
    method find_libraries (line 1119) | def find_libraries(self, type: str) -> list:
    method build_library_options (line 1142) | def build_library_options(self, type: str):
    method create_footprint (line 1149) | def create_footprint(self, e):
    method build_column (line 1161) | def build_column(self):
    method did_mount (line 1200) | def did_mount(self):
  class CreateView (line 1227) | class CreateView(MainView):
    method show_dialog (line 1263) | def show_dialog(self, type: DialogType, message: str):
    method enable_create (line 1268) | def enable_create(self, enable=True):
    method enable_cancel (line 1274) | def enable_cancel(self, enable=True):
    method cancel (line 1285) | def cancel(self, e=None):
    method process_cancel (line 1288) | def process_cancel(self):
    method reset_progress_bars (line 1302) | def reset_progress_bars(self):
    method create_part (line 1326) | def create_part(self, e=None):
    method build_column (line 1595) | def build_column(self):
    method did_mount (line 1638) | def did_mount(self):

FILE: kintree/gui/views/settings.py
  class SettingsView (line 359) | class SettingsView(CommonView):
    method __init__ (line 368) | def __init__(self, page: ft.Page):
    method nav_rail_redirect (line 391) | def nav_rail_redirect(self, e):
    method save (line 394) | def save(self, settings_file=None, show_dialog=True):
    method on_dialog_result (line 420) | def on_dialog_result(self, e: ft.FilePickerResultEvent):
    method path_picker (line 426) | def path_picker(self, e: ft.ControlEvent, title: str):
    method init_column (line 438) | def init_column(self) -> ft.Column:
    method update_field (line 448) | def update_field(self, name, field, column):
    method add_buttons (line 512) | def add_buttons(self, column, test=False) -> ft.Row:
    method build_column (line 535) | def build_column(self, ignore=[]):
    method did_mount (line 548) | def did_mount(self):
  class PathSettingsView (line 553) | class PathSettingsView(SettingsView):
    method __init__ (line 556) | def __init__(self, page: ft.Page):
    method build_dialog (line 560) | def build_dialog(self):
    method show_dialog (line 570) | def show_dialog(self, d_type=None, message=None, snackbar=False, open=...
  class UserSettingsView (line 574) | class UserSettingsView(PathSettingsView):
    method save (line 597) | def save(self):
    method increment_cache_value (line 602) | def increment_cache_value(self, inc):
    method build_column (line 614) | def build_column(self):
    method did_mount (line 657) | def did_mount(self):
  class SupplierSettingsView (line 667) | class SupplierSettingsView(SettingsView):
    method __init__ (line 675) | def __init__(self, page: ft.Page):
    method save_s (line 678) | def save_s(self, e: ft.ControlEvent, supplier: str, show_dialog=True):
    method test_s (line 779) | def test_s(self, e: ft.ControlEvent, supplier: str):
    method build_column (line 817) | def build_column(self):
  class InvenTreeSettingsView (line 880) | class InvenTreeSettingsView(SettingsView):
    method save (line 890) | def save(self, file=None, dialog=True):
    method test (line 929) | def test(self):
    method __init__ (line 944) | def __init__(self, page: ft.Page):
    method build_column (line 952) | def build_column(self):
  class KiCadSettingsView (line 1069) | class KiCadSettingsView(PathSettingsView):

FILE: kintree/kicad/kicad_interface.py
  function inventree_to_kicad (line 4) | def inventree_to_kicad(part_data: dict, library_path: str, template_path...

FILE: kintree/kicad/kicad_symbol.py
  class ComponentLibManager (line 10) | class ComponentLibManager(object):
    method __init__ (line 11) | def __init__(self, library_path):
    method is_symbol_in_library (line 25) | def is_symbol_in_library(self, symbol_id):
    method add_symbol_to_library_from_inventree (line 35) | def add_symbol_to_library_from_inventree(self, symbol_data, template_p...

FILE: kintree/kintree_gui.py
  function main (line 6) | def main(view='flet_app'):

FILE: kintree/search/automationdirect_api.py
  function get_default_search_keys (line 38) | def get_default_search_keys():
  function find_categories (line 54) | def find_categories(part_details: str):
  function fetch_part_info (line 62) | def fetch_part_info(part_number: str, silent=False) -> dict:
  function test_api (line 234) | def test_api() -> bool:

FILE: kintree/search/digikey_api.py
  function disable_api_logger (line 37) | def disable_api_logger():
  function check_environment (line 44) | def check_environment() -> bool:
  function setup_environment (line 54) | def setup_environment(force=False) -> bool:
  function get_default_search_keys (line 66) | def get_default_search_keys():
  function find_categories (line 81) | def find_categories(part_details: str):
  function fetch_part_info (line 93) | def fetch_part_info(part_number: str) -> dict:
  function test_api (line 204) | def test_api(check_content=False) -> bool:

FILE: kintree/search/element14_api.py
  function get_default_search_keys (line 135) | def get_default_search_keys():
  function get_default_store_url (line 150) | def get_default_store_url(supplier: str) -> str:
  function build_api_url (line 164) | def build_api_url(part_number: str, supplier: str, store_url=None, silen...
  function build_image_url (line 196) | def build_image_url(image_data: dict, supplier: str, store_url=None) -> ...
  function fetch_part_info (line 216) | def fetch_part_info(part_number: str, supplier: str, store_url=None, sil...
  function test_api (line 314) | def test_api(store_url=None) -> bool:

FILE: kintree/search/jameco_api.py
  function get_default_search_keys (line 26) | def get_default_search_keys():
  function find_categories (line 42) | def find_categories(part_details: str):
  function fetch_part_info (line 50) | def fetch_part_info(part_number: str) -> dict:
  function test_api (line 149) | def test_api() -> bool:

FILE: kintree/search/lcsc_api.py
  function get_default_search_keys (line 25) | def get_default_search_keys():
  function find_categories (line 40) | def find_categories(part_details: str):
  function fetch_part_info (line 48) | def fetch_part_info(part_number: str) -> dict:
  function test_api (line 131) | def test_api() -> bool:

FILE: kintree/search/mouser_api.py
  function get_default_search_keys (line 30) | def get_default_search_keys():
  function setup_environment (line 45) | def setup_environment(force=False):
  function find_categories (line 57) | def find_categories(part_details: str):
  function fetch_part_info (line 66) | def fetch_part_info(part_number: str) -> dict:
  function test_api (line 156) | def test_api() -> bool:

FILE: kintree/search/search_api.py
  function load_from_file (line 7) | def load_from_file(search_file, test_mode=False) -> dict:
  function save_to_file (line 31) | def save_to_file(part_info, search_file, update_ts=True):

FILE: kintree/search/snapeda_api.py
  function fetch_snapeda_part_info (line 8) | def fetch_snapeda_part_info(part_number: str) -> dict:
  function parse_snapeda_response (line 16) | def parse_snapeda_response(response: dict) -> dict:
  function download_snapeda_images (line 65) | def download_snapeda_images(snapeda_data: dict, silent=False) -> dict:
  function test_snapeda_api (line 118) | def test_snapeda_api() -> bool:

FILE: kintree/search/tme_api.py
  function get_default_search_keys (line 21) | def get_default_search_keys():
  function check_environment (line 36) | def check_environment() -> bool:
  function setup_environment (line 46) | def setup_environment(force=False) -> bool:
  function tme_api_request (line 57) | def tme_api_request(endpoint, tme_api_settings, params, api_host='https:...
  function tme_api_query (line 91) | def tme_api_query(request: urllib.request.Request) -> dict:
  function fetch_part_info (line 102) | def fetch_part_info(part_number: str) -> dict:
  function test_api (line 196) | def test_api(check_content=False) -> bool:

FILE: kintree/setup_inventree.py
  function setup_inventree (line 9) | def setup_inventree():

FILE: run_tests.py
  function pretty_test_print (line 53) | def pretty_test_print(message: str):
  function check_result (line 58) | def check_result(status: str, new_part: bool) -> bool:

FILE: tasks.py
  function install (line 8) | def install(c, is_install=True):
  function update (line 22) | def update(c):
  function clean (line 31) | def clean(c):
  function build (line 56) | def build(c):
  function setup_inventree (line 71) | def setup_inventree(c):
  function coverage_report (line 80) | def coverage_report(c, open_browser=True):
  function test (line 93) | def test(c, enable_api=0):
  function python_badge (line 116) | def python_badge(c):
  function style (line 133) | def style(c):
  function gui (line 147) | def gui(c, browser=False):
Condensed preview — 103 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (534K chars).
[
  {
    "path": ".coveragerc",
    "chars": 209,
    "preview": "[run]\nomit =\n    # Do not run coverage on environment files\n    *env*\n    # Skip GUI coverage\n    kintree/kintree_gui.py"
  },
  {
    "path": ".github/workflows/test_deploy.yaml",
    "chars": 6408,
    "preview": "name: tests | linting | publishing\n\non:\n  push:\n    branches:\n      - main\n    tags:\n      - \"*.*.*\"\n    paths-ignore:\n "
  },
  {
    "path": ".gitignore",
    "chars": 147,
    "preview": "# Build files\ndist/\nbuild/\n*.spec\n# Cache and backup files\n*__pycache__*\n*.bck\n# Test files\nkintree/tests/*\n.coverage\nht"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 17827,
    "preview": "# <img src=\"https://raw.githubusercontent.com/sparkmicro/Ki-nTree/main/images/logo.png\" width=\"auto\" height=\"32\"> Ki-nTr"
  },
  {
    "path": "invoke.yaml",
    "chars": 32,
    "preview": "debug: true\nrun:\n    echo: false"
  },
  {
    "path": "kintree/__init__.py",
    "chars": 291,
    "preview": "# WARNING: This file is overwriten when publishing to PyPI\n# __version__ refers to the tag version instead\n\n# VERSION IN"
  },
  {
    "path": "kintree/common/part_tools.py",
    "chars": 5449,
    "preview": "import re\n\nfrom ..config import settings\nfrom ..config import config_interface\nfrom .tools import cprint\n\n\ndef generate_"
  },
  {
    "path": "kintree/common/progress.py",
    "chars": 1214,
    "preview": "import time\n\nCREATE_PART_PROGRESS: float\nMAX_PROGRESS = 1.0\nDEFAULT_PROGRESS = 0.1\n\n\ndef reset_progress_bar(progress_bar"
  },
  {
    "path": "kintree/common/tools.py",
    "chars": 8202,
    "preview": "import builtins\nimport json\nimport os\nfrom shutil import copyfile\n\n\n# CUSTOM PRINT METHOD\nclass pcolors:\n    HEADER = '\\"
  },
  {
    "path": "kintree/config/automationdirect/automationdirect_api.yaml",
    "chars": 577,
    "preview": "AUTOMATIONDIRECT_API_ROOT_URL: \"https://www.automationdirect.com\"\nAUTOMATIONDIRECT_API_URL: \"https://www.automationdirec"
  },
  {
    "path": "kintree/config/automationdirect/automationdirect_config.yaml",
    "chars": 256,
    "preview": "SUPPLIER_DATABASE_NAME: Automation Direct\nSEARCH_NAME: null\nSEARCH_DESCRIPTION: null\nSEARCH_REVISION: null\nSEARCH_KEYWOR"
  },
  {
    "path": "kintree/config/config_interface.py",
    "chars": 18058,
    "preview": "import base64\nimport copy\nimport os\nfrom sys import platform\n\nimport yaml\nfrom ..common.tools import cprint\n\nFUNCTION_FI"
  },
  {
    "path": "kintree/config/digikey/digikey_api.yaml",
    "chars": 47,
    "preview": "DIGIKEY_CLIENT_ID: ''\nDIGIKEY_CLIENT_SECRET: ''"
  },
  {
    "path": "kintree/config/digikey/digikey_categories.yaml",
    "chars": 2745,
    "preview": "Capacitors:\n  Aluminium:\n  - Aluminum Electrolytic Capacitors\n  Ceramic:\n  - Ceramic Capacitors\n  - Ceramic\n  Polymer:\n "
  },
  {
    "path": "kintree/config/digikey/digikey_config.yaml",
    "chars": 248,
    "preview": "SUPPLIER_INVENTREE_NAME: Digi-Key\nSEARCH_NAME: null\nSEARCH_DESCRIPTION: null\nSEARCH_REVISION: null\nSEARCH_KEYWORDS: null"
  },
  {
    "path": "kintree/config/element14/element14_api.yaml",
    "chars": 99,
    "preview": "ELEMENT14_PRODUCT_SEARCH_API_KEY: null\nFARNELL_STORE: null\nNEWARK_STORE: null\nELEMENT14_STORE: null"
  },
  {
    "path": "kintree/config/element14/element14_config.yaml",
    "chars": 244,
    "preview": "SUPPLIER_INVENTREE_NAME: null\nSEARCH_NAME: null\nSEARCH_DESCRIPTION: null\nSEARCH_REVISION: null\nSEARCH_KEYWORDS: null\nSEA"
  },
  {
    "path": "kintree/config/inventree/categories.yaml",
    "chars": 1633,
    "preview": "CATEGORIES:\n  Assemblies:\n    Printed-Circuit Board Assembly: null\n    Product: null\n  Capacitors:\n    Aluminium: null\n "
  },
  {
    "path": "kintree/config/inventree/inventree_dev.yaml",
    "chars": 128,
    "preview": "ENABLE: true\nENABLE_PROXY: false\nPASSWORD: !!binary |\n  ''\nPROXIES: null\nSERVER_ADDRESS: ''\nUSERNAME: ''\nDATASHEET_UPLOA"
  },
  {
    "path": "kintree/config/inventree/inventree_prod.yaml",
    "chars": 128,
    "preview": "ENABLE: true\nENABLE_PROXY: false\nPASSWORD: !!binary |\n  ''\nPROXIES: null\nSERVER_ADDRESS: ''\nUSERNAME: ''\nDATASHEET_UPLOA"
  },
  {
    "path": "kintree/config/inventree/parameters.yaml",
    "chars": 1034,
    "preview": "# Parameters\n# Name: Unit\nMin Output Voltage: V\nAntenna Type: null\nB Constant: K\nBreakdown Voltage: V\nCapacitance: nF\nCl"
  },
  {
    "path": "kintree/config/inventree/parameters_filters.yaml",
    "chars": 553,
    "preview": "Capacitors:\n- Value\n- Rated Voltage\n- Tolerance\n- Package Type\n- Temperature Grade\nCircuit Protections:\n- Value\nConnecto"
  },
  {
    "path": "kintree/config/inventree/stock_locations.yaml",
    "chars": 21,
    "preview": "STOCK_LOCATIONS: null"
  },
  {
    "path": "kintree/config/inventree/supplier_parameters.yaml",
    "chars": 5372,
    "preview": "# Parameter Mapping between InvenTree parameter template and suppliers parameters naming\n# Each template parameter can m"
  },
  {
    "path": "kintree/config/inventree/suppliers.yaml",
    "chars": 364,
    "preview": "Digi-Key:\n  enable: true\n  name: Digi-Key\nMouser:\n  enable: true\n  name: Mouser\nElement14:\n  enable: true\n  name: Elemen"
  },
  {
    "path": "kintree/config/jameco/jameco_api.yaml",
    "chars": 124,
    "preview": "JAMECO_API_URL: https://ahzbkf.a.searchspring.io/api/search/search.json?ajaxCatalog=v3&resultsFormat=native&siteId=ahzbk"
  },
  {
    "path": "kintree/config/jameco/jameco_config.yaml",
    "chars": 258,
    "preview": "SUPPLIER_INVENTREE_NAME: Jameco Electronics\nSEARCH_NAME: null\nSEARCH_DESCRIPTION: null\nSEARCH_REVISION: null\nSEARCH_KEYW"
  },
  {
    "path": "kintree/config/kicad/kicad.yaml",
    "chars": 95,
    "preview": "KICAD_SYMBOLS_PATH: ''\nKICAD_TEMPLATES_PATH: kintree/kicad/templates/\nKICAD_FOOTPRINTS_PATH: ''"
  },
  {
    "path": "kintree/config/kicad/kicad_map.yaml",
    "chars": 1161,
    "preview": "KICAD_FOOTPRINTS:\nKICAD_LIBRARIES:\nKICAD_TEMPLATES:\n  Capacitors:\n    Aluminium: capacitor-polarized\n    Ceramic: capaci"
  },
  {
    "path": "kintree/config/lcsc/lcsc_api.yaml",
    "chars": 72,
    "preview": "LCSC_API_URL: https://wmsc.lcsc.com/ftps/wm/product/detail?productCode=\n"
  },
  {
    "path": "kintree/config/lcsc/lcsc_config.yaml",
    "chars": 256,
    "preview": "SUPPLIER_INVENTREE_NAME: LCSC Electronics\nSEARCH_NAME: null\nSEARCH_DESCRIPTION: null\nSEARCH_REVISION: null\nSEARCH_KEYWOR"
  },
  {
    "path": "kintree/config/mouser/mouser_api.yaml",
    "chars": 25,
    "preview": "MOUSER_PART_API_KEY: null"
  },
  {
    "path": "kintree/config/mouser/mouser_config.yaml",
    "chars": 258,
    "preview": "SUPPLIER_INVENTREE_NAME: Mouser Electronics\nSEARCH_NAME: null\nSEARCH_DESCRIPTION: null\nSEARCH_REVISION: null\nSEARCH_KEYW"
  },
  {
    "path": "kintree/config/settings.py",
    "chars": 13592,
    "preview": "import os\nimport sys\nimport platform\nfrom enum import Enum\n\nfrom ..common.tools import cprint\nfrom .import config_interf"
  },
  {
    "path": "kintree/config/tme/tme_api.yaml",
    "chars": 81,
    "preview": "TME_API_TOKEN: NULL\nTME_API_SECRET: NULL\nTME_API_COUNTRY: US\nTME_API_LANGUAGE: EN"
  },
  {
    "path": "kintree/config/tme/tme_config.yaml",
    "chars": 224,
    "preview": "SUPPLIER_INVENTREE_NAME: TME\nSEARCH_NAME: null\nSEARCH_DESCRIPTION: null\nSEARCH_REVISION: null\nSEARCH_KEYWORDS: null\nSEAR"
  },
  {
    "path": "kintree/config/user/general.yaml",
    "chars": 255,
    "preview": "DATASHEET_SAVE_ENABLED: false\nDATASHEET_SAVE_PATH: null\nDATASHEET_INVENTREE_ENABLED: false\nAUTOMATIC_BROWSER_OPEN: true\n"
  },
  {
    "path": "kintree/config/user/internal_part_number.yaml",
    "chars": 223,
    "preview": "IPN_ENABLE_CREATE: true\nIPN_USE_MANUFACTURER_PART_NUMBER: false\nIPN_PREFIX: null\nIPN_CATEGORY_CODE: true\nIPN_UNIQUE_ID_L"
  },
  {
    "path": "kintree/config/user/search_api.yaml",
    "chars": 73,
    "preview": "CATEGORY_MATCH_RATIO_LIMIT: 100\nCACHE_ENABLED: true\nCACHE_VALID_DAYS: '7'"
  },
  {
    "path": "kintree/database/inventree_api.py",
    "chars": 30795,
    "preview": "from ..config import settings\nimport validators\nfrom ..common import part_tools\nfrom ..common.tools import cprint, downl"
  },
  {
    "path": "kintree/database/inventree_interface.py",
    "chars": 41738,
    "preview": "import copy\n\nfrom ..config import settings\nfrom ..common import part_tools, progress\nfrom ..common.tools import cprint\nf"
  },
  {
    "path": "kintree/gui/gui.py",
    "chars": 3282,
    "preview": "import os\nimport flet as ft\n\nfrom ..config import settings\n\nfrom .views.common import update_theme, handle_transition\nfr"
  },
  {
    "path": "kintree/gui/views/common.py",
    "chars": 12731,
    "preview": "from enum import Enum\nfrom typing import Optional, List\n\nimport flet as ft\n\nGUI_PARAMS = {\n    'nav_rail_min_width': 100"
  },
  {
    "path": "kintree/gui/views/main.py",
    "chars": 62954,
    "preview": "import os\nimport copy\nimport flet as ft\n\n# Version\nfrom ... import __version__\n# Common view\nfrom .common import GUI_PAR"
  },
  {
    "path": "kintree/gui/views/settings.py",
    "chars": 40474,
    "preview": "import flet as ft\n\n# Common view\nfrom .common import DialogType\nfrom .common import CommonView\nfrom .common import Switc"
  },
  {
    "path": "kintree/kicad/kicad_interface.py",
    "chars": 416,
    "preview": "from . import kicad_symbol\n\n\ndef inventree_to_kicad(part_data: dict, library_path: str, template_path=None, show_progres"
  },
  {
    "path": "kintree/kicad/kicad_symbol.py",
    "chars": 4465,
    "preview": "import os\n\nfrom ..config import settings\nfrom ..common import progress\nfrom ..common.tools import cprint\nfrom kiutils.sy"
  },
  {
    "path": "kintree/kicad/templates/LICENSE",
    "chars": 7048,
    "preview": "Creative Commons Legal Code\n\nCC0 1.0 Universal\n\n    CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE\n"
  },
  {
    "path": "kintree/kicad/templates/capacitor-polarized.kicad_sym",
    "chars": 3077,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/capacitor.kicad_sym",
    "chars": 2786,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/connector.kicad_sym",
    "chars": 1089,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/crystal-2p.kicad_sym",
    "chars": 2540,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/default.kicad_sym",
    "chars": 1091,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/diode-led.kicad_sym",
    "chars": 2647,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/diode-schottky.kicad_sym",
    "chars": 2453,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/diode-standard.kicad_sym",
    "chars": 2251,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/diode-zener.kicad_sym",
    "chars": 2445,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/eeprom-sot23.kicad_sym",
    "chars": 2116,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (in_bom yes) (on_board yes)\n    (pr"
  },
  {
    "path": "kintree/kicad/templates/ferrite-bead.kicad_sym",
    "chars": 2445,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/fuse.kicad_sym",
    "chars": 2249,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/inductor.kicad_sym",
    "chars": 2258,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/integrated-circuit.kicad_sym",
    "chars": 1089,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/library_template.kicad_sym",
    "chars": 65,
    "preview": "(kicad_symbol_lib (version 20211014) (generator kicad_converter))"
  },
  {
    "path": "kintree/kicad/templates/oscillator-4p.kicad_sym",
    "chars": 2140,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (in_bom yes) (on_board yes)\n    (pr"
  },
  {
    "path": "kintree/kicad/templates/protection-unidir.kicad_sym",
    "chars": 2451,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/resistor-sm.kicad_sym",
    "chars": 2233,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/resistor.kicad_sym",
    "chars": 2233,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/transistor-nfet.kicad_sym",
    "chars": 4683,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/transistor-npn.kicad_sym",
    "chars": 2795,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/transistor-pfet.kicad_sym",
    "chars": 4986,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates/transistor-pnp.kicad_sym",
    "chars": 2800,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"IPN\" (pin_numbers hide) (pin_names (offs"
  },
  {
    "path": "kintree/kicad/templates_project/templates_project.kicad_pcb",
    "chars": 1981,
    "preview": "(kicad_pcb (version 20221018) (generator pcbnew)\n\n  (general\n    (thickness 1.6)\n  )\n\n  (paper \"A4\")\n  (layers\n    (0 \"F"
  },
  {
    "path": "kintree/kicad/templates_project/templates_project.kicad_prl",
    "chars": 1201,
    "preview": "{\n  \"board\": {\n    \"active_layer\": 0,\n    \"active_layer_preset\": \"\",\n    \"auto_track_width\": true,\n    \"hidden_netclasse"
  },
  {
    "path": "kintree/kicad/templates_project/templates_project.kicad_pro",
    "chars": 6077,
    "preview": "{\n  \"board\": {\n    \"3dviewports\": [],\n    \"design_settings\": {\n      \"defaults\": {\n        \"board_outline_line_width\": 0"
  },
  {
    "path": "kintree/kicad/templates_project/templates_project.kicad_sch",
    "chars": 187,
    "preview": "(kicad_sch (version 20230121) (generator eeschema)\n\n  (uuid b588025f-8c23-406b-a049-ad8593913ab0)\n\n  (paper \"A4\")\n\n  (li"
  },
  {
    "path": "kintree/kintree_gui.py",
    "chars": 243,
    "preview": "import flet as ft\n\nfrom .gui.gui import kintree_gui\n\n\ndef main(view='flet_app'):\n    if view == 'browser':\n        ft.ap"
  },
  {
    "path": "kintree/search/automationdirect_api.py",
    "chars": 11824,
    "preview": "from ..common.tools import download\n\n# These are the 'keys' we want to pull out response\nSEARCH_HEADERS = [\n    'item_co"
  },
  {
    "path": "kintree/search/digikey_api.py",
    "chars": 7741,
    "preview": "import logging\nimport os\nimport digikey\n\nfrom ..config import settings, config_interface\n\nSEARCH_HEADERS = [\n    'descri"
  },
  {
    "path": "kintree/search/element14_api.py",
    "chars": 12711,
    "preview": "from ..config import settings, config_interface\nfrom ..common.tools import download\n\nELEMENT14_API_URL = 'https://api.el"
  },
  {
    "path": "kintree/search/jameco_api.py",
    "chars": 5350,
    "preview": "import html\nimport re\nfrom ..common.tools import download\n\nSEARCH_HEADERS = [\n    'title',\n    'name',\n    'prod_id',\n  "
  },
  {
    "path": "kintree/search/lcsc_api.py",
    "chars": 4110,
    "preview": "from ..common.tools import download\n\nSEARCH_HEADERS = [\n    'productDescEn',\n    'productIntroEn',\n    'productCode',\n  "
  },
  {
    "path": "kintree/search/mouser_api.py",
    "chars": 4797,
    "preview": "import os\n\nfrom ..config import settings, config_interface\nfrom mouser.api import MouserPartSearchRequest\n\nSEARCH_HEADER"
  },
  {
    "path": "kintree/search/search_api.py",
    "chars": 1243,
    "preview": "import os\nimport time\n\nfrom ..config import settings, config_interface\n\n\ndef load_from_file(search_file, test_mode=False"
  },
  {
    "path": "kintree/search/snapeda_api.py",
    "chars": 4345,
    "preview": "from ..config import settings\nfrom ..common.tools import download, download_with_retry\n\nAPI_BASE_URL = 'https://snapeda."
  },
  {
    "path": "kintree/search/tme_api.py",
    "chars": 7679,
    "preview": "import base64\nimport collections\nimport hashlib\nimport hmac\nimport os\nimport urllib.parse\nimport urllib.request\nimport j"
  },
  {
    "path": "kintree/setup_inventree.py",
    "chars": 2114,
    "preview": "import sys\n\nfrom .config import settings\nfrom .common.tools import cprint\nfrom .config import config_interface\nfrom .dat"
  },
  {
    "path": "kintree_gui.py",
    "chars": 176,
    "preview": "import sys\nfrom kintree.kintree_gui import main\n\nif __name__ == '__main__':\n    if len(sys.argv) > 1:\n        main(view="
  },
  {
    "path": "poetry.toml",
    "chars": 32,
    "preview": "[virtualenvs]\nin-project = true\n"
  },
  {
    "path": "pyproject.toml",
    "chars": 1161,
    "preview": "[tool.poetry]\nname = \"kintree\"\nversion = \"1.2.1\" # placeholder\ndescription = \"Fast part creation in KiCad and InvenTree\""
  },
  {
    "path": "requirements.txt",
    "chars": 327,
    "preview": "cloudscraper==1.2.71\nsetuptools==75.2.0\nhttps://github.com/hurricaneJoef/digikey-api/archive/refs/heads/master.zip\nFlet>"
  },
  {
    "path": "run_tests.py",
    "chars": 22762,
    "preview": "import os\nimport sys\n\nimport kintree.config.settings as settings\nfrom kintree.common.tools import cprint, create_library"
  },
  {
    "path": "setup.cfg",
    "chars": 443,
    "preview": "[flake8]\nignore =\n\t# - W191 - indentation contains tab\n\t# W191,\n\t# - W293 - blank lines contain whitespace\n\tW293,\n\tW605,"
  },
  {
    "path": "tasks.py",
    "chars": 3692,
    "preview": "import webbrowser\n\nfrom kintree.common.tools import cprint\nfrom invoke import UnexpectedExit, task\n\n\n@task\ndef install(c"
  },
  {
    "path": "tests/files/FOOTPRINTS/RF.pretty/Skyworks_SKY13575_639LF.kicad_mod",
    "chars": 5144,
    "preview": "(module \"Skyworks_SKY13575_639LF\" (layer F.Cu) (tedit 5D6EEFCB)\n  (descr \"http://www.skyworksinc.com/uploads/documents/S"
  },
  {
    "path": "tests/files/FOOTPRINTS/RF.pretty/Skyworks_SKY65404-31.kicad_mod",
    "chars": 2530,
    "preview": "(module Skyworks_SKY65404-31 (layer F.Cu) (tedit 5C4622B0)\n  (descr http://www.skyworksinc.com/uploads/documents/SKY6540"
  },
  {
    "path": "tests/files/SYMBOLS/TEST.kicad_sym",
    "chars": 14152,
    "preview": "(kicad_symbol_lib (version 20220914) (generator kicad_symbol_editor)\n  (symbol \"C0402C100J3GACTU\" (pin_numbers hide) (pi"
  },
  {
    "path": "tests/files/digikey_config.yaml",
    "chars": 248,
    "preview": "EXTRA_FIELDS: null\nSEARCH_DATASHEET: null\nSEARCH_DESCRIPTION: null\nSEARCH_KEYWORDS: null\nSEARCH_MANUFACTURER: null\nSEARC"
  },
  {
    "path": "tests/files/inventree_dev.yaml",
    "chars": 161,
    "preview": "DATASHEET_UPLOAD: true\nENABLE: true\nENABLE_PROXY: false\nPASSWORD: !!binary |\n  WVdSdGFXND0=\nSERVER_ADDRESS: http://127.0"
  },
  {
    "path": "tests/files/kicad_map.yaml",
    "chars": 2102,
    "preview": "KICAD_FOOTPRINTS:\n  Capacitors:\n  - Capacitors\n  Circuit Protections:\n  - Fuses\n  Connectors:\n  - Connectors\n  Crystals "
  },
  {
    "path": "tests/test_samples.yaml",
    "chars": 2882,
    "preview": "Capacitors:\n  ## 0402 0.1u 16V X7R\n  0402B104K160CT: original\n  # Equivalent\n  CL05B104KO5NNNC: alternate_mpn\n  # 'Fake'"
  }
]

// ... and 2 more files (download for full content)

About this extraction

This page contains the full source code of the sparkmicro/Ki-nTree GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 103 files (497.4 KB), approximately 128.9k tokens, and a symbol index with 287 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!