diff --git a/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/PKG-INFO b/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..40fbefb0b5446958db8e1b3a936aed78134ad802 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/PKG-INFO @@ -0,0 +1,50 @@ +Metadata-Version: 2.4 +Name: babel +Version: 2.16.0 +Summary: Internationalization utilities +Home-page: https://babel.pocoo.org/ +Author: Armin Ronacher +Author-email: armin.ronacher@active-4.com +Maintainer: Aarni Koskela +Maintainer-email: akx@iki.fi +License: BSD-3-Clause +Project-URL: Source, https://github.com/python-babel/babel +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.8 +License-File: LICENSE +Requires-Dist: pytz>=2015.7; python_version < "3.9" +Provides-Extra: dev +Requires-Dist: pytest>=6.0; extra == "dev" +Requires-Dist: pytest-cov; extra == "dev" +Requires-Dist: freezegun~=1.0; extra == "dev" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: maintainer +Dynamic: maintainer-email +Dynamic: project-url +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +A collection of tools for internationalizing Python applications. diff --git a/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/SOURCES.txt b/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..79b5fb8700e0f507b507304db42f86d889c51072 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/SOURCES.txt @@ -0,0 +1,160 @@ +AUTHORS +CHANGES.rst +LICENSE +MANIFEST.in +Makefile +README.rst +conftest.py +pyproject.toml +setup.cfg +setup.py +tox.ini +babel/__init__.py +babel/core.py +babel/dates.py +babel/languages.py +babel/lists.py +babel/localedata.py +babel/numbers.py +babel/plural.py +babel/py.typed +babel/support.py +babel/units.py +babel/util.py +babel.egg-info/PKG-INFO +babel.egg-info/SOURCES.txt +babel.egg-info/dependency_links.txt +babel.egg-info/entry_points.txt +babel.egg-info/not-zip-safe +babel.egg-info/requires.txt +babel.egg-info/top_level.txt +babel/locale-data/LICENSE.unicode +babel/localtime/__init__.py +babel/localtime/_fallback.py +babel/localtime/_helpers.py +babel/localtime/_unix.py +babel/localtime/_win32.py +babel/messages/__init__.py +babel/messages/_compat.py +babel/messages/catalog.py +babel/messages/checkers.py +babel/messages/extract.py +babel/messages/frontend.py +babel/messages/jslexer.py +babel/messages/mofile.py +babel/messages/plurals.py +babel/messages/pofile.py +babel/messages/setuptools_frontend.py +docs/Makefile +docs/changelog.rst +docs/cmdline.rst +docs/conf.py +docs/dates.rst +docs/dev.rst +docs/index.rst +docs/installation.rst +docs/intro.rst +docs/license.rst +docs/locale.rst +docs/make.bat +docs/messages.rst +docs/numbers.rst +docs/requirements.txt +docs/setup.rst +docs/support.rst +docs/_static/logo.pdf +docs/_static/logo.png +docs/_static/logo_small.png +docs/_templates/sidebar-about.html +docs/_templates/sidebar-links.html +docs/_templates/sidebar-logo.html +docs/_themes/LICENSE +docs/_themes/README +docs/_themes/babel/layout.html +docs/_themes/babel/relations.html +docs/_themes/babel/theme.conf +docs/_themes/babel/static/babel.css_t +docs/_themes/babel/static/small_babel.css +docs/api/core.rst +docs/api/dates.rst +docs/api/index.rst +docs/api/languages.rst +docs/api/lists.rst +docs/api/numbers.rst +docs/api/plural.rst +docs/api/support.rst +docs/api/units.rst +docs/api/messages/catalog.rst +docs/api/messages/extract.rst +docs/api/messages/index.rst +docs/api/messages/mofile.rst +docs/api/messages/pofile.rst +scripts/download_import_cldr.py +scripts/dump_data.py +scripts/dump_global.py +scripts/generate_authors.py +scripts/import_cldr.py +tests/__init__.py +tests/conftest.py +tests/test_core.py +tests/test_date_intervals.py +tests/test_dates.py +tests/test_day_periods.py +tests/test_languages.py +tests/test_lists.py +tests/test_localedata.py +tests/test_localtime.py +tests/test_numbers.py +tests/test_plural.py +tests/test_smoke.py +tests/test_support.py +tests/test_util.py +tests/interop/__init__.py +tests/interop/test_jinja2_interop.py +tests/interop/jinja2_data/hello.html +tests/interop/jinja2_data/mapping.cfg +tests/messages/__init__.py +tests/messages/consts.py +tests/messages/test_catalog.py +tests/messages/test_checkers.py +tests/messages/test_extract.py +tests/messages/test_frontend.py +tests/messages/test_js_extract.py +tests/messages/test_jslexer.py +tests/messages/test_mofile.py +tests/messages/test_normalized_string.py +tests/messages/test_plurals.py +tests/messages/test_pofile.py +tests/messages/test_setuptools_frontend.py +tests/messages/test_toml_config.py +tests/messages/data/mapping.cfg +tests/messages/data/setup.cfg +tests/messages/data/setup.py +tests/messages/data/project/__init__.py +tests/messages/data/project/file1.py +tests/messages/data/project/file2.py +tests/messages/data/project/_hidden_by_default/hidden_file.py +tests/messages/data/project/i18n/messages.pot +tests/messages/data/project/i18n/messages_non_fuzzy.pot +tests/messages/data/project/i18n/de/LC_MESSAGES/messages.mo +tests/messages/data/project/i18n/de/LC_MESSAGES/messages.po +tests/messages/data/project/i18n/de_DE/LC_MESSAGES/bar.po +tests/messages/data/project/i18n/de_DE/LC_MESSAGES/foo.po +tests/messages/data/project/i18n/de_DE/LC_MESSAGES/messages.po +tests/messages/data/project/i18n/fi_BUGGY/LC_MESSAGES/messages.po +tests/messages/data/project/i18n/ru_RU/LC_MESSAGES/messages.po +tests/messages/data/project/ignored/a_test_file.txt +tests/messages/data/project/ignored/an_example.txt +tests/messages/data/project/ignored/this_wont_normally_be_here.py +tests/messages/toml-test-cases/bad.extractor.toml +tests/messages/toml-test-cases/bad.extractors-not-a-dict.toml +tests/messages/toml-test-cases/bad.just-a-mapping.toml +tests/messages/toml-test-cases/bad.mapping-not-a-dict.toml +tests/messages/toml-test-cases/bad.mappings-not-a-list.toml +tests/messages/toml-test-cases/bad.missing-extraction-method.toml +tests/messages/toml-test-cases/bad.multiple-mappings-not-a-list.toml +tests/messages/toml-test-cases/bad.non-string-extraction-method.toml +tests/messages/toml-test-cases/bad.pattern-type-2.toml +tests/messages/toml-test-cases/bad.pattern-type.toml +tests/messages/toml-test-cases/bad.pyproject-without-tool-babel.toml +tests/messages/toml-test-cases/bad.standalone-with-babel-prefix.toml \ No newline at end of file diff --git a/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/dependency_links.txt b/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/entry_points.txt b/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..95235a5552bfe080a8908011a30be422dd2ca39e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/entry_points.txt @@ -0,0 +1,20 @@ +[babel.checkers] +num_plurals = babel.messages.checkers:num_plurals +python_format = babel.messages.checkers:python_format + +[babel.extractors] +ignore = babel.messages.extract:extract_nothing +javascript = babel.messages.extract:extract_javascript +python = babel.messages.extract:extract_python + +[console_scripts] +pybabel = babel.messages.frontend:main + +[distutils.commands] +compile_catalog = babel.messages.setuptools_frontend:compile_catalog +extract_messages = babel.messages.setuptools_frontend:extract_messages +init_catalog = babel.messages.setuptools_frontend:init_catalog +update_catalog = babel.messages.setuptools_frontend:update_catalog + +[distutils.setup_keywords] +message_extractors = babel.messages.setuptools_frontend:check_message_extractors diff --git a/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/not-zip-safe b/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/not-zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/not-zip-safe @@ -0,0 +1 @@ + diff --git a/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/requires.txt b/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/requires.txt new file mode 100644 index 0000000000000000000000000000000000000000..43e03b018fd0abdb5f4f4792091c22e333789d78 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/requires.txt @@ -0,0 +1,8 @@ + +[:python_version < "3.9"] +pytz>=2015.7 + +[dev] +pytest>=6.0 +pytest-cov +freezegun~=1.0 diff --git a/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/top_level.txt b/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..98f65931c4c84991b6fa555a19e7674cdf70c761 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/babel.egg-info/top_level.txt @@ -0,0 +1 @@ +babel diff --git a/SPFsmartGATE/LIVE/TMP/babel/cldr/.gitignore b/SPFsmartGATE/LIVE/TMP/babel/cldr/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..72e8ffc0db8aad71a934dd11e5968bd5109e54b4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/cldr/.gitignore @@ -0,0 +1 @@ +* diff --git a/SPFsmartGATE/LIVE/TMP/babel/docs/changelog.rst b/SPFsmartGATE/LIVE/TMP/babel/docs/changelog.rst new file mode 100644 index 0000000000000000000000000000000000000000..d9e113ec685b92b018297dd2f200341d1fba01f9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/docs/changelog.rst @@ -0,0 +1 @@ +.. include:: ../CHANGES.rst diff --git a/SPFsmartGATE/LIVE/TMP/babel/docs/index.rst b/SPFsmartGATE/LIVE/TMP/babel/docs/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..082174133c226a383a34f0e9cf720e1e56afa7e8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/docs/index.rst @@ -0,0 +1,47 @@ +.. -*- mode: rst; encoding: utf-8 -*- + +Babel +===== + +Babel is an integrated collection of utilities that assist in +internationalizing and localizing Python applications, with an emphasis on +web-based applications. + +User Documentation +------------------ + +The user documentation explains some core concept of the library and gives +some information about how it can be used. + +.. toctree:: + :maxdepth: 1 + + intro + installation + locale + dates + numbers + messages + cmdline + setup + support + +API Reference +------------- + +The API reference lists the full public API that Babel provides. + +.. toctree:: + :maxdepth: 2 + + api/index + +Additional Notes +---------------- + +.. toctree:: + :maxdepth: 2 + + dev + changelog + license diff --git a/SPFsmartGATE/LIVE/TMP/babel/docs/installation.rst b/SPFsmartGATE/LIVE/TMP/babel/docs/installation.rst new file mode 100644 index 0000000000000000000000000000000000000000..8bf614cb6e8f283bb361c618534b5b95bb7f8674 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/docs/installation.rst @@ -0,0 +1,99 @@ +.. _installation: + +Installation +============ + +Babel is distributed as a standard Python package fully set up with all +the dependencies it needs. On Python versions where the standard library +`zoneinfo`_ module is not available, `pytz`_ needs to be installed for +timezone support. If `pytz`_ is installed, it is preferred over the +standard library `zoneinfo`_ module where possible. + +.. _pytz: https://pythonhosted.org/pytz/ + +.. _zoneinfo: https://docs.python.org/3/library/zoneinfo.html + +.. _virtualenv: + +virtualenv +---------- + +Virtualenv is probably what you want to use during development, and if you +have shell access to your production machines, you'll probably want to use +it there, too. Use ``pip`` to install it:: + + $ sudo pip install virtualenv + +If you're on Windows, run it in a command-prompt window with administrator +privileges, and leave out ``sudo``. + +Once you have virtualenv installed, just fire up a shell and create +your own environment. I usually create a project folder and a `venv` +folder within:: + + $ mkdir myproject + $ cd myproject + $ virtualenv venv + New python executable in venv/bin/python + Installing distribute............done. + +Now, whenever you want to work on a project, you only have to activate the +corresponding environment. On OS X and Linux, do the following:: + + $ . venv/bin/activate + +If you are a Windows user, the following command is for you:: + + $ venv\scripts\activate + +Either way, you should now be using your virtualenv (notice how the prompt of +your shell has changed to show the active environment). + +Now you can just enter the following command to get Babel installed in your +virtualenv:: + + $ pip install Babel + +A few seconds later and you are good to go. + +System-Wide Installation +------------------------ + +This is possible as well, though I do not recommend it. Just run `pip` +with root privileges:: + + $ sudo pip install Babel + +(On Windows systems, run it in a command-prompt window with administrator +privileges, and leave out `sudo`.) + + +Living on the Edge +------------------ + +If you want to work with the latest version of Babel, you will need to +use a git checkout. + +Get the git checkout in a new virtualenv and run in development mode:: + + $ git clone https://github.com/python-babel/babel + Initialized empty Git repository in ~/dev/babel/.git/ + $ cd babel + $ virtualenv venv + New python executable in venv/bin/python + Installing distribute............done. + $ . venv/bin/activate + $ python setup.py import_cldr + $ pip install --editable . + ... + Finished processing dependencies for Babel + +Make sure to not forget about the ``import_cldr`` step because otherwise +you will be missing the locale data. +The custom setup command will download the most appropriate CLDR release from the +official website and convert it for Babel. + +This will pull also in the dependencies and activate the git head as the +current version inside the virtualenv. Then all you have to do is run +``git pull origin`` to update to the latest version. If the CLDR data +changes you will have to re-run ``python setup.py import_cldr``. diff --git a/SPFsmartGATE/LIVE/TMP/babel/docs/numbers.rst b/SPFsmartGATE/LIVE/TMP/babel/docs/numbers.rst new file mode 100644 index 0000000000000000000000000000000000000000..cbe05cdef1fc53625a5eb4d48747cfeedf45ffb1 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/docs/numbers.rst @@ -0,0 +1,183 @@ +.. -*- mode: rst; encoding: utf-8 -*- + +.. _numbers: + +================= +Number Formatting +================= + + +Support for locale-specific formatting and parsing of numbers is provided by +the ``babel.numbers`` module: + +.. code-block:: pycon + + >>> from babel.numbers import format_number, format_decimal, format_compact_decimal, format_percent + +Examples: + +.. code-block:: pycon + + # Numbers with decimal places + >>> format_decimal(1.2345, locale='en_US') + u'1.234' + >>> format_decimal(1.2345, locale='sv_SE') + u'1,234' + # Integers with thousand grouping + >>> format_decimal(12345, locale='de_DE') + u'12.345' + >>> format_decimal(12345678, locale='de_DE') + u'12.345.678' + +Pattern Syntax +============== + +While Babel makes it simple to use the appropriate number format for a given +locale, you can also force it to use custom patterns. As with date/time +formatting patterns, the patterns Babel supports for number formatting are +based on the `Locale Data Markup Language specification`_ (LDML). + +Examples: + +.. code-block:: pycon + + >>> format_decimal(-1.2345, format='#,##0.##;-#', locale='en') + u'-1.23' + >>> format_decimal(-1.2345, format='#,##0.##;(#)', locale='en') + u'(1.23)' + +The syntax for custom number format patterns is described in detail in the +the specification. The following table is just a relatively brief overview. + + .. _`Locale Data Markup Language specification`: + https://unicode.org/reports/tr35/#Number_Format_Patterns + + +----------+-----------------------------------------------------------------+ + | Symbol | Description | + +==========+=================================================================+ + | ``0`` | Digit | + +----------+-----------------------------------------------------------------+ + | ``1-9`` | '1' through '9' indicate rounding. | + +----------+-----------------------------------------------------------------+ + | ``@`` | Significant digit | + +----------+-----------------------------------------------------------------+ + | ``#`` | Digit, zero shows as absent | + +----------+-----------------------------------------------------------------+ + | ``.`` | Decimal separator or monetary decimal separator | + +----------+-----------------------------------------------------------------+ + | ``-`` | Minus sign | + +----------+-----------------------------------------------------------------+ + | ``,`` | Grouping separator | + +----------+-----------------------------------------------------------------+ + | ``E`` | Separates mantissa and exponent in scientific notation | + +----------+-----------------------------------------------------------------+ + | ``+`` | Prefix positive exponents with localized plus sign | + +----------+-----------------------------------------------------------------+ + | ``;`` | Separates positive and negative subpatterns | + +----------+-----------------------------------------------------------------+ + | ``%`` | Multiply by 100 and show as percentage | + +----------+-----------------------------------------------------------------+ + | ``‰`` | Multiply by 1000 and show as per mille | + +----------+-----------------------------------------------------------------+ + | ``¤`` | Currency sign, replaced by currency symbol. If doubled, | + | | replaced by international currency symbol. If tripled, uses the | + | | long form of the decimal symbol. | + +----------+-----------------------------------------------------------------+ + | ``'`` | Used to quote special characters in a prefix or suffix | + +----------+-----------------------------------------------------------------+ + | ``*`` | Pad escape, precedes pad character | + +----------+-----------------------------------------------------------------+ + + +Rounding Modes +============== + +Since Babel makes full use of Python's `Decimal`_ type to perform number +rounding before formatting, users have the chance to control the rounding mode +and other configurable parameters through the active `Context`_ instance. + +By default, Python rounding mode is ``ROUND_HALF_EVEN`` which complies with +`UTS #35 section 3.3`_. Yet, the caller has the opportunity to tweak the +current context before formatting a number or currency: + +.. code-block:: pycon + + >>> from babel.numbers import decimal, format_decimal + >>> with decimal.localcontext(decimal.Context(rounding=decimal.ROUND_DOWN)): + >>> txt = format_decimal(123.99, format='#', locale='en_US') + >>> txt + u'123' + +It is also possible to use ``decimal.setcontext`` or directly modifying the +instance returned by ``decimal.getcontext``. However, using a context manager +is always more convenient due to the automatic restoration and the ability to +nest them. + +Whatever mechanism is chosen, always make use of the ``decimal`` module imported +from ``babel.numbers``. For efficiency reasons, Babel uses the fastest decimal +implementation available, such as `cdecimal`_. These various implementation +offer an identical API, but their types and instances do **not** interoperate +with each other. + +For example, the previous example can be slightly modified to generate +unexpected results on Python 2.7, with the `cdecimal`_ module installed: + +.. code-block:: pycon + + >>> from decimal import localcontext, Context, ROUND_DOWN + >>> from babel.numbers import format_decimal + >>> with localcontext(Context(rounding=ROUND_DOWN)): + >>> txt = format_decimal(123.99, format='#', locale='en_US') + >>> txt + u'124' + +Changing other parameters such as the precision may also alter the results of +the number formatting functions. Remember to test your code to make sure it +behaves as desired. + +.. _Decimal: https://docs.python.org/3/library/decimal.html#decimal-objects +.. _Context: https://docs.python.org/3/library/decimal.html#context-objects +.. _`UTS #35 section 3.3`: https://www.unicode.org/reports/tr35/tr35-numbers.html#Formatting +.. _cdecimal: https://pypi.org/project/cdecimal/ + + +Parsing Numbers +=============== + +Babel can also parse numeric data in a locale-sensitive manner: + +.. code-block:: pycon + + >>> from babel.numbers import parse_decimal, parse_number + +Examples: + +.. code-block:: pycon + + >>> parse_decimal('1,099.98', locale='en_US') + 1099.98 + >>> parse_decimal('1.099,98', locale='de') + 1099.98 + >>> parse_decimal('2,109,998', locale='de') + Traceback (most recent call last): + ... + NumberFormatError: '2,109,998' is not a valid decimal number + +Note: as of version 2.8.0, the ``parse_number`` function has limited +functionality. It can remove group symbols of certain locales from numeric +strings, but may behave unexpectedly until its logic handles more encoding +issues and other special cases. + +Examples: + +.. code-block:: pycon + + >>> parse_number('1,099', locale='en_US') + 1099 + >>> parse_number('1.099.024', locale='de') + 1099024 + >>> parse_number('123' + u'\xa0' + '4567', locale='ru') + 1234567 + >>> parse_number('123 4567', locale='ru') + ... + NumberFormatError: '123 4567' is not a valid number diff --git a/SPFsmartGATE/LIVE/TMP/babel/docs/requirements.txt b/SPFsmartGATE/LIVE/TMP/babel/docs/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..c133306c70ffb973f6e31d61a56ba347c32a85e1 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/docs/requirements.txt @@ -0,0 +1 @@ +Sphinx~=5.3.0 diff --git a/SPFsmartGATE/LIVE/TMP/babel/scripts/download_import_cldr.py b/SPFsmartGATE/LIVE/TMP/babel/scripts/download_import_cldr.py new file mode 100644 index 0000000000000000000000000000000000000000..cf670ed98c47e12de7dc8d7109a641bd85d5ea42 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/scripts/download_import_cldr.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 + +import contextlib +import hashlib +import os +import shutil +import subprocess +import sys +import zipfile +from urllib.request import urlretrieve + +URL = 'https://unicode.org/Public/cldr/45/cldr-common-45.0.zip' +FILENAME = 'cldr-common-45.0.zip' +# Via https://unicode.org/Public/cldr/45/hashes/SHASUM512.txt +FILESUM = '638123882bd29911fc9492ec152926572fec48eb6c1f5dd706aee3e59cad8be4963a334bb7a09a645dbedc3356f60ef7ac2ef7ab4ccf2c8926b547782175603c' +BLKSIZE = 131072 + + +def reporthook(block_count, block_size, total_size): + bytes_transmitted = block_count * block_size + cols = shutil.get_terminal_size().columns + buffer = 6 + percent = float(bytes_transmitted) / (total_size or 1) + done = int(percent * (cols - buffer)) + bar = ('=' * done).ljust(cols - buffer) + sys.stdout.write(f'\r{bar}{int(percent * 100): 4d}%') + sys.stdout.flush() + + +def log(message): + sys.stderr.write(f'{message}\n') + + +def is_good_file(filename): + if not os.path.isfile(filename): + log(f"Local copy '{filename}' not found") + return False + h = hashlib.sha512() + with open(filename, 'rb') as f: + while True: + blk = f.read(BLKSIZE) + if not blk: + break + h.update(blk) + digest = h.hexdigest() + if digest != FILESUM: + raise RuntimeError(f'Checksum mismatch: {digest!r} != {FILESUM!r}') + else: + return True + + +def main(): + scripts_path = os.path.dirname(os.path.abspath(__file__)) + repo = os.path.dirname(scripts_path) + cldr_dl_path = os.path.join(repo, 'cldr') + cldr_path = os.path.join(repo, 'cldr', os.path.splitext(FILENAME)[0]) + zip_path = os.path.join(cldr_dl_path, FILENAME) + changed = False + show_progress = (False if os.environ.get("BABEL_CLDR_NO_DOWNLOAD_PROGRESS") else sys.stdout.isatty()) + + while not is_good_file(zip_path): + log(f"Downloading '{FILENAME}' from {URL}") + tmp_path = f"{zip_path}.tmp" + urlretrieve(URL, tmp_path, (reporthook if show_progress else None)) + os.replace(tmp_path, zip_path) + changed = True + print() + common_path = os.path.join(cldr_path, 'common') + + if changed or not os.path.isdir(common_path): + if os.path.isdir(common_path): + log(f"Deleting old CLDR checkout in '{cldr_path}'") + shutil.rmtree(common_path) + + log(f"Extracting CLDR to '{cldr_path}'") + with contextlib.closing(zipfile.ZipFile(zip_path)) as z: + z.extractall(cldr_path) + + subprocess.check_call([ + sys.executable, + os.path.join(scripts_path, 'import_cldr.py'), + common_path, + *sys.argv[1:], + ]) + + +if __name__ == '__main__': + main() diff --git a/SPFsmartGATE/LIVE/TMP/babel/scripts/dump_data.py b/SPFsmartGATE/LIVE/TMP/babel/scripts/dump_data.py new file mode 100644 index 0000000000000000000000000000000000000000..639c14d43befbd9ba613125c499647521309cca5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/scripts/dump_data.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python +# +# Copyright (C) 2007-2011 Edgewall Software, 2013-2024 the Babel team +# All rights reserved. +# +# This software is licensed as described in the file LICENSE, which +# you should have received as part of this distribution. The terms +# are also available at http://babel.edgewall.org/wiki/License. +# +# This software consists of voluntary contributions made by many +# individuals. For the exact contribution history, see the revision +# history and logs, available at http://babel.edgewall.org/log/. + +from optparse import OptionParser +from pprint import pprint + +from babel.localedata import LocaleDataDict, load + + +def main(): + parser = OptionParser(usage='%prog [options] locale [path]') + parser.add_option('--noinherit', action='store_false', dest='inherit', + help='do not merge inherited data into locale data') + parser.add_option('--resolve', action='store_true', dest='resolve', + help='resolve aliases in locale data') + parser.set_defaults(inherit=True, resolve=False) + options, args = parser.parse_args() + if len(args) not in (1, 2): + parser.error('incorrect number of arguments') + + data = load(args[0], merge_inherited=options.inherit) + if options.resolve: + data = LocaleDataDict(data) + if len(args) > 1: + for key in args[1].split('.'): + data = data[key] + if isinstance(data, dict): + data = dict(data.items()) + pprint(data) + + +if __name__ == '__main__': + main() diff --git a/SPFsmartGATE/LIVE/TMP/babel/scripts/dump_global.py b/SPFsmartGATE/LIVE/TMP/babel/scripts/dump_global.py new file mode 100644 index 0000000000000000000000000000000000000000..8b8294014d79754e0fcc6ac620e39b8f8e87b061 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/scripts/dump_global.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +# +# Copyright (C) 2007-2011 Edgewall Software, 2013-2024 the Babel team +# All rights reserved. +# +# This software is licensed as described in the file LICENSE, which +# you should have received as part of this distribution. The terms +# are also available at http://babel.edgewall.org/wiki/License. +# +# This software consists of voluntary contributions made by many +# individuals. For the exact contribution history, see the revision +# history and logs, available at http://babel.edgewall.org/log/. + +import os +import sys +from pprint import pprint + +import cPickle as pickle + +import babel + +dirname = os.path.join(os.path.dirname(babel.__file__)) +filename = os.path.join(dirname, 'global.dat') +with open(filename, 'rb') as fileobj: + data = pickle.load(fileobj) + +if len(sys.argv) > 1: + pprint(data.get(sys.argv[1])) +else: + pprint(data) diff --git a/SPFsmartGATE/LIVE/TMP/babel/scripts/generate_authors.py b/SPFsmartGATE/LIVE/TMP/babel/scripts/generate_authors.py new file mode 100644 index 0000000000000000000000000000000000000000..a5443b91e3194fb1ba8614ce1d5bb63f9b944211 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/scripts/generate_authors.py @@ -0,0 +1,39 @@ +import os +from collections import Counter +from subprocess import check_output + +root_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..')) + + +def get_sorted_authors_list(): + authors = check_output(['git', 'log', '--format=%aN'], cwd=root_path).decode('UTF-8') + counts = Counter(authors.splitlines()) + return [author for (author, count) in counts.most_common()] + + +def get_authors_file_content(): + author_list = "\n".join(f"- {a}" for a in get_sorted_authors_list()) + + return f''' +Babel is written and maintained by the Babel team and various contributors: + +{author_list} + +Babel was previously developed under the Copyright of Edgewall Software. The +following copyright notice holds true for releases before 2013: "Copyright (c) +2007 - 2011 by Edgewall Software" + +In addition to the regular contributions Babel includes a fork of Lennart +Regebro's tzlocal that originally was licensed under the CC0 license. The +original copyright of that project is "Copyright 2013 by Lennart Regebro". +''' + + +def write_authors_file(): + content = get_authors_file_content() + with open(os.path.join(root_path, 'AUTHORS'), 'w', encoding='UTF-8') as fp: + fp.write(content) + + +if __name__ == '__main__': + write_authors_file() diff --git a/SPFsmartGATE/LIVE/TMP/babel/scripts/import_cldr.py b/SPFsmartGATE/LIVE/TMP/babel/scripts/import_cldr.py new file mode 100644 index 0000000000000000000000000000000000000000..e8cc03106cf224638820e71b5c4c38a68d98c510 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/babel/scripts/import_cldr.py @@ -0,0 +1,1042 @@ +#!/usr/bin/env python +# +# Copyright (C) 2007-2011 Edgewall Software, 2013-2024 the Babel team +# All rights reserved. +# +# This software is licensed as described in the file LICENSE, which +# you should have received as part of this distribution. The terms +# are also available at http://babel.edgewall.org/wiki/License. +# +# This software consists of voluntary contributions made by many +# individuals. For the exact contribution history, see the revision +# history and logs, available at http://babel.edgewall.org/log/. + +import collections +import logging +import os +import pickle +import re +import sys +from optparse import OptionParser +from xml.etree import ElementTree + +# Make sure we're using Babel source, and not some previously installed version +CHECKOUT_ROOT = os.path.abspath(os.path.join( + os.path.dirname(__file__), + '..', +)) +BABEL_PACKAGE_ROOT = os.path.join(CHECKOUT_ROOT, "babel") +sys.path.insert(0, CHECKOUT_ROOT) + +from babel import dates, numbers +from babel.dates import split_interval_pattern +from babel.localedata import Alias +from babel.plural import PluralRule + +parse = ElementTree.parse +weekdays = {'mon': 0, 'tue': 1, 'wed': 2, 'thu': 3, 'fri': 4, 'sat': 5, + 'sun': 6} + + +def _text(elem): + buf = [elem.text or ''] + for child in elem: + buf.append(_text(child)) + buf.append(elem.tail or '') + return ''.join(filter(None, buf)).strip() + + +NAME_RE = re.compile(r"^\w+$") +TYPE_ATTR_RE = re.compile(r"^\w+\[@type='(.*?)'\]$") + +NAME_MAP = { + 'dateFormats': 'date_formats', + 'dateTimeFormats': 'datetime_formats', + 'eraAbbr': 'abbreviated', + 'eraNames': 'wide', + 'eraNarrow': 'narrow', + 'timeFormats': 'time_formats', +} + +log = logging.getLogger("import_cldr") + + +def need_conversion(dst_filename, data_dict, source_filename): + with open(source_filename, 'rb') as f: + blob = f.read(4096) + version_match = re.search(b'version number="\\$Revision: (\\d+)', blob) + if not version_match: # CLDR 36.0 was shipped without proper revision numbers + return True + version = int(version_match.group(1)) + + data_dict['_version'] = version + if not os.path.isfile(dst_filename): + return True + + with open(dst_filename, 'rb') as f: + data = pickle.load(f) + return data.get('_version') != version + + +def _translate_alias(ctxt, path): + parts = path.split('/') + keys = ctxt[:] + for part in parts: + if part == '..': + keys.pop() + else: + match = TYPE_ATTR_RE.match(part) + if match: + keys.append(match.group(1)) + else: + assert NAME_RE.match(part) + keys.append(NAME_MAP.get(part, part)) + return keys + + +def _parse_currency_date(s): + if not s: + return None + parts = s.split('-', 2) + return tuple(map(int, parts + [1] * (3 - len(parts)))) + + +def _currency_sort_key(tup): + code, start, end, tender = tup + return int(not tender), start or (1, 1, 1) + + +def _extract_plural_rules(file_path): + rule_dict = {} + prsup = parse(file_path) + for elem in prsup.findall('.//plurals/pluralRules'): + rules = [] + for rule in elem.findall('pluralRule'): + rules.append((rule.attrib['count'], str(rule.text))) + pr = PluralRule(rules) + for locale in elem.attrib['locales'].split(): + rule_dict[locale] = pr + return rule_dict + + +def _time_to_seconds_past_midnight(time_expr): + """ + Parse a time expression to seconds after midnight. + :param time_expr: Time expression string (H:M or H:M:S) + :rtype: int + """ + if time_expr is None: + return None + if time_expr.count(":") == 1: + time_expr += ":00" + hour, minute, second = (int(p, 10) for p in time_expr.split(":")) + return hour * 60 * 60 + minute * 60 + second + + +def _compact_dict(dict): + """ + "Compact" the given dict by removing items whose value is None or False. + """ + out_dict = {} + for key, value in dict.items(): + if value is not None and value is not False: + out_dict[key] = value + return out_dict + + +def debug_repr(obj): + if isinstance(obj, PluralRule): + return obj.abstract + return repr(obj) + + +def write_datafile(path, data, dump_json=False): + with open(path, 'wb') as outfile: + pickle.dump(data, outfile, 2) + if dump_json: + import json + + with open(f"{path}.json", "w") as outfile: + json.dump(data, outfile, indent=4, default=debug_repr) + + +def main(): + parser = OptionParser(usage='%prog path/to/cldr') + parser.add_option( + '-f', '--force', dest='force', action='store_true', default=False, + help='force import even if destination file seems up to date', + ) + parser.add_option( + '-j', '--json', dest='dump_json', action='store_true', default=False, + help='also export debugging JSON dumps of locale data', + ) + parser.add_option( + '-q', '--quiet', dest='quiet', action='store_true', default=bool(os.environ.get('BABEL_CLDR_QUIET')), + help='quiesce info/warning messages', + ) + + options, args = parser.parse_args() + if len(args) != 1: + parser.error('incorrect number of arguments') + + logging.basicConfig( + level=(logging.ERROR if options.quiet else logging.INFO), + ) + + return process_data( + srcdir=args[0], + destdir=BABEL_PACKAGE_ROOT, + force=bool(options.force), + dump_json=bool(options.dump_json), + ) + + +def process_data(srcdir, destdir, force=False, dump_json=False): + sup_filename = os.path.join(srcdir, 'supplemental', 'supplementalData.xml') + sup = parse(sup_filename) + + # Import global data from the supplemental files + global_path = os.path.join(destdir, 'global.dat') + global_data = {} + if force or need_conversion(global_path, global_data, sup_filename): + global_data.update(parse_global(srcdir, sup)) + write_datafile(global_path, global_data, dump_json=dump_json) + _process_local_datas(sup, srcdir, destdir, force=force, dump_json=dump_json) + + +def parse_global(srcdir, sup): + global_data = {} + sup_dir = os.path.join(srcdir, 'supplemental') + territory_zones = global_data.setdefault('territory_zones', {}) + zone_aliases = global_data.setdefault('zone_aliases', {}) + zone_territories = global_data.setdefault('zone_territories', {}) + win_mapping = global_data.setdefault('windows_zone_mapping', {}) + language_aliases = global_data.setdefault('language_aliases', {}) + territory_aliases = global_data.setdefault('territory_aliases', {}) + script_aliases = global_data.setdefault('script_aliases', {}) + variant_aliases = global_data.setdefault('variant_aliases', {}) + likely_subtags = global_data.setdefault('likely_subtags', {}) + territory_currencies = global_data.setdefault('territory_currencies', {}) + parent_exceptions = global_data.setdefault('parent_exceptions', {}) + all_currencies = collections.defaultdict(set) + currency_fractions = global_data.setdefault('currency_fractions', {}) + territory_languages = global_data.setdefault('territory_languages', {}) + bcp47_timezone = parse(os.path.join(srcdir, 'bcp47', 'timezone.xml')) + sup_windows_zones = parse(os.path.join(sup_dir, 'windowsZones.xml')) + sup_metadata = parse(os.path.join(sup_dir, 'supplementalMetadata.xml')) + sup_likely = parse(os.path.join(sup_dir, 'likelySubtags.xml')) + # create auxiliary zone->territory map from the windows zones (we don't set + # the 'zones_territories' map directly here, because there are some zones + # aliases listed and we defer the decision of which ones to choose to the + # 'bcp47' data + _zone_territory_map = {} + for map_zone in sup_windows_zones.findall('.//windowsZones/mapTimezones/mapZone'): + if map_zone.attrib.get('territory') == '001': + win_mapping[map_zone.attrib['other']] = map_zone.attrib['type'].split()[0] + for tzid in str(map_zone.attrib['type']).split(): + _zone_territory_map[tzid] = str(map_zone.attrib['territory']) + for key_elem in bcp47_timezone.findall('.//keyword/key'): + if key_elem.attrib['name'] == 'tz': + for elem in key_elem.findall('type'): + if 'deprecated' not in elem.attrib: + aliases = str(elem.attrib['alias']).split() + tzid = aliases.pop(0) + territory = _zone_territory_map.get(tzid, '001') + territory_zones.setdefault(territory, []).append(tzid) + zone_territories[tzid] = territory + for alias in aliases: + zone_aliases[alias] = tzid + break + + # Import Metazone mapping + meta_zones = global_data.setdefault('meta_zones', {}) + tzsup = parse(os.path.join(srcdir, 'supplemental', 'metaZones.xml')) + for elem in tzsup.findall('.//timezone'): + for child in elem.findall('usesMetazone'): + if 'to' not in child.attrib: # FIXME: support old mappings + meta_zones[elem.attrib['type']] = child.attrib['mzone'] + + # Language aliases + for alias in sup_metadata.findall('.//alias/languageAlias'): + # We don't have a use for those at the moment. They don't + # pass our parser anyways. + if '_' in alias.attrib['type']: + continue + language_aliases[alias.attrib['type']] = alias.attrib['replacement'] + + # Territory aliases + for alias in sup_metadata.findall('.//alias/territoryAlias'): + territory_aliases[alias.attrib['type']] = alias.attrib['replacement'].split() + + # Script aliases + for alias in sup_metadata.findall('.//alias/scriptAlias'): + script_aliases[alias.attrib['type']] = alias.attrib['replacement'] + + # Variant aliases + for alias in sup_metadata.findall('.//alias/variantAlias'): + repl = alias.attrib.get('replacement') + if repl: + variant_aliases[alias.attrib['type']] = repl + + # Likely subtags + for likely_subtag in sup_likely.findall('.//likelySubtags/likelySubtag'): + likely_subtags[likely_subtag.attrib['from']] = likely_subtag.attrib['to'] + + # Currencies in territories + for region in sup.findall('.//currencyData/region'): + region_code = region.attrib['iso3166'] + region_currencies = [] + for currency in region.findall('./currency'): + cur_code = currency.attrib['iso4217'] + cur_start = _parse_currency_date(currency.attrib.get('from')) + cur_end = _parse_currency_date(currency.attrib.get('to')) + cur_tender = currency.attrib.get('tender', 'true') == 'true' + # Tie region to currency. + region_currencies.append((cur_code, cur_start, cur_end, cur_tender)) + # Keep a reverse index of currencies to territorie. + all_currencies[cur_code].add(region_code) + region_currencies.sort(key=_currency_sort_key) + territory_currencies[region_code] = region_currencies + global_data['all_currencies'] = { + currency: tuple(sorted(regions)) for currency, regions in all_currencies.items()} + + # Explicit parent locales + # Since CLDR-43, there are multiple statements, some of them with a `component="collations"` or + # `component="segmentations"` attribute; these indicate that only some language aspects should be inherited. + # (https://cldr.unicode.org/index/downloads/cldr-43) + # + # Ignore these for now, as one of them even points to a locale that doesn't have a corresponding XML file (sr_ME) + # and we crash trying to load it. + # There is no XPath support to test for an absent attribute, so use Python to filter + for parentBlock in sup.findall('.//parentLocales'): + if parentBlock.attrib.get('component'): + # Consider only unqualified parent declarations + continue + + for paternity in parentBlock.findall('./parentLocale'): + parent = paternity.attrib['parent'] + if parent == 'root': + # Since CLDR-45, the 'root' parent locale uses 'localeRules="nonlikelyScript"' instead of + # 'locales'. This special case is handled in babel when loading locale data + # (https://cldr.unicode.org/index/downloads/cldr-45#h.5rbkhkncdqi9) + continue + for child in paternity.attrib['locales'].split(): + parent_exceptions[child] = parent + + # Currency decimal and rounding digits + for fraction in sup.findall('.//currencyData/fractions/info'): + cur_code = fraction.attrib['iso4217'] + cur_digits = int(fraction.attrib['digits']) + cur_rounding = int(fraction.attrib['rounding']) + cur_cdigits = int(fraction.attrib.get('cashDigits', cur_digits)) + cur_crounding = int(fraction.attrib.get('cashRounding', cur_rounding)) + currency_fractions[cur_code] = (cur_digits, cur_rounding, cur_cdigits, cur_crounding) + + # Languages in territories + for territory in sup.findall('.//territoryInfo/territory'): + languages = {} + for language in territory.findall('./languagePopulation'): + languages[language.attrib['type']] = { + 'population_percent': float(language.attrib['populationPercent']), + 'official_status': language.attrib.get('officialStatus'), + } + territory_languages[territory.attrib['type']] = languages + return global_data + + +def _process_local_datas(sup, srcdir, destdir, force=False, dump_json=False): + day_period_rules = parse_day_period_rules(parse(os.path.join(srcdir, 'supplemental', 'dayPeriods.xml'))) + # build a territory containment mapping for inheritance + regions = {} + for elem in sup.findall('.//territoryContainment/group'): + regions[elem.attrib['type']] = elem.attrib['contains'].split() + + # Resolve territory containment + territory_containment = {} + region_items = sorted(regions.items()) + for group, territory_list in region_items: + for territory in territory_list: + containers = territory_containment.setdefault(territory, set()) + if group in territory_containment: + containers |= territory_containment[group] + containers.add(group) + + # prepare the per-locale plural rules definitions + plural_rules = _extract_plural_rules(os.path.join(srcdir, 'supplemental', 'plurals.xml')) + ordinal_rules = _extract_plural_rules(os.path.join(srcdir, 'supplemental', 'ordinals.xml')) + + filenames = os.listdir(os.path.join(srcdir, 'main')) + filenames.remove('root.xml') + filenames.sort(key=len) + filenames.insert(0, 'root.xml') + + for filename in filenames: + stem, ext = os.path.splitext(filename) + if ext != '.xml': + continue + + full_filename = os.path.join(srcdir, "main", filename) + data_filename = os.path.join(destdir, "locale-data", f"{stem}.dat") + + data = {} + if not (force or need_conversion(data_filename, data, full_filename)): + continue + + tree = parse(full_filename) + + language = None + elem = tree.find('.//identity/language') + if elem is not None: + language = elem.attrib['type'] + + territory = None + elem = tree.find('.//identity/territory') + if elem is not None: + territory = elem.attrib['type'] + else: + territory = '001' # world + regions = territory_containment.get(territory, []) + + log.info( + 'Processing %s (Language = %s; Territory = %s)', + filename, language, territory, + ) + + locale_id = '_'.join(filter(None, [ + language, + territory != '001' and territory or None, + ])) + + data['locale_id'] = locale_id + data['unsupported_number_systems'] = set() + + if locale_id in plural_rules: + data['plural_form'] = plural_rules[locale_id] + if locale_id in ordinal_rules: + data['ordinal_form'] = ordinal_rules[locale_id] + if locale_id in day_period_rules: + data["day_period_rules"] = day_period_rules[locale_id] + + is_global = ("_" not in locale_id) + parse_locale_display_names(data, tree, is_global=is_global) + parse_list_patterns(data, tree) + parse_dates(data, tree, sup, regions, territory) + + for calendar in tree.findall('.//calendars/calendar'): + if calendar.attrib['type'] != 'gregorian': + # TODO: support other calendar types + continue + + parse_calendar_months(data, calendar) + parse_calendar_days(data, calendar) + parse_calendar_quarters(data, calendar) + parse_calendar_eras(data, calendar) + parse_calendar_periods(data, calendar) + parse_calendar_date_formats(data, calendar) + parse_calendar_time_formats(data, calendar) + parse_calendar_datetime_skeletons(data, calendar) + parse_interval_formats(data, calendar) + + parse_number_symbols(data, tree) + parse_numbering_systems(data, tree) + parse_decimal_formats(data, tree) + parse_scientific_formats(data, tree) + parse_percent_formats(data, tree) + + parse_currency_formats(data, tree) + parse_currency_unit_patterns(data, tree) + parse_currency_names(data, tree) + parse_unit_patterns(data, tree) + parse_date_fields(data, tree) + parse_character_order(data, tree) + parse_measurement_systems(data, tree) + + unsupported_number_systems_string = ', '.join(sorted(data.pop('unsupported_number_systems'))) + if unsupported_number_systems_string: + log.warning( + f"{locale_id}: unsupported number systems were ignored: " + f"{unsupported_number_systems_string}", + ) + + write_datafile(data_filename, data, dump_json=dump_json) + + +def _should_skip_number_elem(data, elem): + """ + Figure out whether the numbering-containing element `elem` is in a currently + non-supported (i.e. currently non-Latin) numbering system. + + :param data: The root data element, for stashing the warning. + :param elem: Element with `numberSystem` key + :return: Boolean + """ + number_system = elem.get('numberSystem', 'latn') + + if number_system != 'latn': + data['unsupported_number_systems'].add(number_system) + return True + + return False + + +def _should_skip_elem(elem, type=None, dest=None): + """ + Check whether the given element should be skipped. + + Elements are skipped if they are drafts or alternates of data that already exists in `dest`. + + :param elem: XML element + :param type: Type string. May be elided if the dest dict is elided. + :param dest: Destination dict. May be elided to skip the dict check. + :return: skip boolean + """ + if _is_draft_or_alt(elem): + if dest is None or type in dest: + return True + + +def _is_draft_or_alt(elem) -> bool: + return 'draft' in elem.attrib or 'alt' in elem.attrib + + +def _import_type_text(dest, elem, type=None, *, allow_variant_and_draft_fallback=True) -> None: + """ + Conditionally import the element's inner text(s) into the `dest` dict. + + If `allow_variant_and_draft_fallback` is True, then the element may be imported + if there otherwise isn't a pre-existing element of the same type. + + :param dest: Destination dict + :param elem: XML element. + :param type: Override type. (By default, the `type` attr of the element.) + :param allow_variant_and_draft_fallback: See above. + :return: Nothing. + """ + if type is None: + type = elem.attrib['type'] + + # Already have this, nothing to do. + if type in dest: + return + + if not allow_variant_and_draft_fallback and _is_draft_or_alt(elem): + # Not allowed to use a draft/alternate here. + return + dest[type] = _text(elem) + + +def parse_locale_display_names(data, tree, *, is_global: bool): + territories = data.setdefault('territories', {}) + for elem in tree.findall('.//territories/territory'): + _import_type_text(territories, elem, allow_variant_and_draft_fallback=is_global) + languages = data.setdefault('languages', {}) + for elem in tree.findall('.//languages/language'): + _import_type_text(languages, elem, allow_variant_and_draft_fallback=is_global) + variants = data.setdefault('variants', {}) + for elem in tree.findall('.//variants/variant'): + _import_type_text(variants, elem, allow_variant_and_draft_fallback=is_global) + scripts = data.setdefault('scripts', {}) + for elem in tree.findall('.//scripts/script'): + _import_type_text(scripts, elem, allow_variant_and_draft_fallback=is_global) + + +def parse_list_patterns(data, tree): + list_patterns = data.setdefault('list_patterns', {}) + for list_pattern_el in tree.findall('.//listPatterns/listPattern'): + pattern_type = list_pattern_el.attrib.get('type', 'standard') + for pattern_part_el in list_pattern_el.findall('listPatternPart'): + pattern_part_type = pattern_part_el.attrib['type'] + list_patterns.setdefault(pattern_type, {})[pattern_part_type] = _text(pattern_part_el) + + +def parse_dates(data, tree, sup, regions, territory): + week_data = data.setdefault('week_data', {}) + supelem = sup.find('.//weekData') + for elem in supelem.findall('minDays'): + if _should_skip_elem(elem): + continue + territories = elem.attrib['territories'].split() + if territory in territories or any(r in territories for r in regions): + week_data['min_days'] = int(elem.attrib['count']) + for elem in supelem.findall('firstDay'): + if _should_skip_elem(elem): + continue + territories = elem.attrib['territories'].split() + if territory in territories or any(r in territories for r in regions): + week_data['first_day'] = weekdays[elem.attrib['day']] + for elem in supelem.findall('weekendStart'): + if _should_skip_elem(elem): + continue + territories = elem.attrib['territories'].split() + if territory in territories or any(r in territories for r in regions): + week_data['weekend_start'] = weekdays[elem.attrib['day']] + for elem in supelem.findall('weekendEnd'): + if _should_skip_elem(elem): + continue + territories = elem.attrib['territories'].split() + if territory in territories or any(r in territories for r in regions): + week_data['weekend_end'] = weekdays[elem.attrib['day']] + zone_formats = data.setdefault('zone_formats', {}) + for elem in tree.findall('.//timeZoneNames/gmtFormat'): + if not _should_skip_elem(elem): + zone_formats['gmt'] = str(elem.text).replace('{0}', '%s') + break + for elem in tree.findall('.//timeZoneNames/regionFormat'): + if not _should_skip_elem(elem): + zone_formats['region'] = str(elem.text).replace('{0}', '%s') + break + for elem in tree.findall('.//timeZoneNames/fallbackFormat'): + if not _should_skip_elem(elem): + zone_formats['fallback'] = ( + str(elem.text).replace('{0}', '%(0)s').replace('{1}', '%(1)s') + ) + break + for elem in tree.findall('.//timeZoneNames/fallbackRegionFormat'): + if not _should_skip_elem(elem): + zone_formats['fallback_region'] = ( + str(elem.text).replace('{0}', '%(0)s').replace('{1}', '%(1)s') + ) + break + time_zones = data.setdefault('time_zones', {}) + for elem in tree.findall('.//timeZoneNames/zone'): + info = {} + city = elem.findtext('exemplarCity') + if city: + info['city'] = str(city) + for child in elem.findall('long/*'): + info.setdefault('long', {})[child.tag] = str(child.text) + for child in elem.findall('short/*'): + info.setdefault('short', {})[child.tag] = str(child.text) + time_zones[elem.attrib['type']] = info + meta_zones = data.setdefault('meta_zones', {}) + for elem in tree.findall('.//timeZoneNames/metazone'): + info = {} + city = elem.findtext('exemplarCity') + if city: + info['city'] = str(city) + for child in elem.findall('long/*'): + info.setdefault('long', {})[child.tag] = str(child.text) + for child in elem.findall('short/*'): + info.setdefault('short', {})[child.tag] = str(child.text) + meta_zones[elem.attrib['type']] = info + + +def parse_calendar_months(data, calendar): + months = data.setdefault('months', {}) + for ctxt in calendar.findall('months/monthContext'): + ctxt_type = ctxt.attrib['type'] + ctxts = months.setdefault(ctxt_type, {}) + for width in ctxt.findall('monthWidth'): + width_type = width.attrib['type'] + widths = ctxts.setdefault(width_type, {}) + for elem in width: + if elem.tag == 'month': + _import_type_text(widths, elem, int(elem.attrib['type'])) + elif elem.tag == 'alias': + ctxts[width_type] = Alias( + _translate_alias(['months', ctxt_type, width_type], + elem.attrib['path']), + ) + + +def parse_calendar_days(data, calendar): + days = data.setdefault('days', {}) + for ctxt in calendar.findall('days/dayContext'): + ctxt_type = ctxt.attrib['type'] + ctxts = days.setdefault(ctxt_type, {}) + for width in ctxt.findall('dayWidth'): + width_type = width.attrib['type'] + widths = ctxts.setdefault(width_type, {}) + for elem in width: + if elem.tag == 'day': + _import_type_text(widths, elem, weekdays[elem.attrib['type']]) + elif elem.tag == 'alias': + ctxts[width_type] = Alias( + _translate_alias(['days', ctxt_type, width_type], + elem.attrib['path']), + ) + + +def parse_calendar_quarters(data, calendar): + quarters = data.setdefault('quarters', {}) + for ctxt in calendar.findall('quarters/quarterContext'): + ctxt_type = ctxt.attrib['type'] + ctxts = quarters.setdefault(ctxt.attrib['type'], {}) + for width in ctxt.findall('quarterWidth'): + width_type = width.attrib['type'] + widths = ctxts.setdefault(width_type, {}) + for elem in width: + if elem.tag == 'quarter': + _import_type_text(widths, elem, int(elem.attrib['type'])) + elif elem.tag == 'alias': + ctxts[width_type] = Alias( + _translate_alias(['quarters', ctxt_type, + width_type], + elem.attrib['path'])) + + +def parse_calendar_eras(data, calendar): + eras = data.setdefault('eras', {}) + for width in calendar.findall('eras/*'): + width_type = NAME_MAP[width.tag] + widths = eras.setdefault(width_type, {}) + for elem in width: + if elem.tag == 'era': + _import_type_text(widths, elem, type=int(elem.attrib.get('type'))) + elif elem.tag == 'alias': + eras[width_type] = Alias( + _translate_alias(['eras', width_type], + elem.attrib['path']), + ) + + +def parse_calendar_periods(data, calendar): + # Day periods (AM/PM/others) + periods = data.setdefault('day_periods', {}) + for day_period_ctx in calendar.findall('dayPeriods/dayPeriodContext'): + ctx_type = day_period_ctx.attrib["type"] + for day_period_width in day_period_ctx.findall('dayPeriodWidth'): + width_type = day_period_width.attrib["type"] + dest_dict = periods.setdefault(ctx_type, {}).setdefault(width_type, {}) + for day_period in day_period_width.findall('dayPeriod'): + period_type = day_period.attrib['type'] + if 'alt' not in day_period.attrib: + dest_dict[period_type] = str(day_period.text) + + +def parse_calendar_date_formats(data, calendar): + date_formats = data.setdefault('date_formats', {}) + for format in calendar.findall('dateFormats'): + for elem in format: + if elem.tag == 'dateFormatLength': + type = elem.attrib.get('type') + if _should_skip_elem(elem, type, date_formats): + continue + try: + date_formats[type] = dates.parse_pattern( + str(elem.findtext('dateFormat/pattern')), + ) + except ValueError as e: + log.error(e) + elif elem.tag == 'alias': + date_formats = Alias(_translate_alias( + ['date_formats'], elem.attrib['path']), + ) + + +def parse_calendar_time_formats(data, calendar): + time_formats = data.setdefault('time_formats', {}) + for format in calendar.findall('timeFormats'): + for elem in format: + if elem.tag == 'timeFormatLength': + type = elem.attrib.get('type') + if _should_skip_elem(elem, type, time_formats): + continue + try: + time_formats[type] = dates.parse_pattern( + str(elem.findtext('timeFormat/pattern')), + ) + except ValueError as e: + log.error(e) + elif elem.tag == 'alias': + time_formats = Alias(_translate_alias( + ['time_formats'], elem.attrib['path']), + ) + + +def parse_calendar_datetime_skeletons(data, calendar): + datetime_formats = data.setdefault('datetime_formats', {}) + datetime_skeletons = data.setdefault('datetime_skeletons', {}) + for format in calendar.findall('dateTimeFormats'): + for elem in format: + if elem.tag == 'dateTimeFormatLength': + type = elem.attrib.get('type') + if _should_skip_elem(elem, type, datetime_formats): + continue + try: + datetime_formats[type] = str(elem.findtext('dateTimeFormat/pattern')) + except ValueError as e: + log.error(e) + elif elem.tag == 'alias': + datetime_formats = Alias(_translate_alias( + ['datetime_formats'], elem.attrib['path']), + ) + elif elem.tag == 'availableFormats': + for datetime_skeleton in elem.findall('dateFormatItem'): + datetime_skeletons[datetime_skeleton.attrib['id']] = ( + dates.parse_pattern(str(datetime_skeleton.text)) + ) + + +def parse_number_symbols(data, tree): + number_symbols = data.setdefault('number_symbols', {}) + for symbol_system_elem in tree.findall('.//numbers/symbols'): + number_system = symbol_system_elem.get('numberSystem') + if not number_system: + continue + + for symbol_element in symbol_system_elem.findall('./*'): + if _should_skip_elem(symbol_element): + continue + + number_symbols.setdefault(number_system, {})[symbol_element.tag] = str(symbol_element.text) + + +def parse_numbering_systems(data, tree): + default_number_system_node = tree.find('.//numbers/defaultNumberingSystem') + if default_number_system_node is not None: + data['default_numbering_system'] = default_number_system_node.text + + numbering_systems = data.setdefault('numbering_systems', {}) + other_numbering_systems_node = tree.find('.//numbers/otherNumberingSystems') or [] + for system in other_numbering_systems_node: + numbering_systems[system.tag] = system.text + + +def parse_decimal_formats(data, tree): + decimal_formats = data.setdefault('decimal_formats', {}) + for df_elem in tree.findall('.//decimalFormats'): + if _should_skip_number_elem(data, df_elem): # TODO: Support other number systems + continue + for elem in df_elem.findall('./decimalFormatLength'): + length_type = elem.attrib.get('type') + if _should_skip_elem(elem, length_type, decimal_formats): + continue + if elem.findall('./alias'): + # TODO map the alias to its target + continue + for pattern_el in elem.findall('./decimalFormat/pattern'): + pattern_type = pattern_el.attrib.get('type') + pattern = numbers.parse_pattern(str(pattern_el.text)) + if pattern_type: + # This is a compact decimal format, see: + # https://www.unicode.org/reports/tr35/tr35-45/tr35-numbers.html#Compact_Number_Formats + + # These are mapped into a `compact_decimal_formats` dictionary + # with the format {length: {count: {multiplier: pattern}}}. + compact_decimal_formats = data.setdefault('compact_decimal_formats', {}) + length_map = compact_decimal_formats.setdefault(length_type, {}) + length_count_map = length_map.setdefault(pattern_el.attrib['count'], {}) + length_count_map[pattern_type] = pattern + else: + # Regular decimal format. + decimal_formats[length_type] = pattern + + +def parse_scientific_formats(data, tree): + scientific_formats = data.setdefault('scientific_formats', {}) + for sf_elem in tree.findall('.//scientificFormats'): + if _should_skip_number_elem(data, sf_elem): # TODO: Support other number systems + continue + for elem in sf_elem.findall('./scientificFormatLength'): + type = elem.attrib.get('type') + if _should_skip_elem(elem, type, scientific_formats): + continue + pattern = str(elem.findtext('scientificFormat/pattern')) + scientific_formats[type] = numbers.parse_pattern(pattern) + + +def parse_percent_formats(data, tree): + percent_formats = data.setdefault('percent_formats', {}) + + for pf_elem in tree.findall('.//percentFormats'): + if _should_skip_number_elem(data, pf_elem): # TODO: Support other number systems + continue + for elem in pf_elem.findall('.//percentFormatLength'): + type = elem.attrib.get('type') + if _should_skip_elem(elem, type, percent_formats): + continue + pattern = str(elem.findtext('percentFormat/pattern')) + percent_formats[type] = numbers.parse_pattern(pattern) + + +def parse_currency_names(data, tree): + currency_names = data.setdefault('currency_names', {}) + currency_names_plural = data.setdefault('currency_names_plural', {}) + currency_symbols = data.setdefault('currency_symbols', {}) + for elem in tree.findall('.//currencies/currency'): + code = elem.attrib['type'] + for name in elem.findall('displayName'): + if ('draft' in name.attrib) and code in currency_names: + continue + if 'count' in name.attrib: + currency_names_plural.setdefault(code, {})[ + name.attrib['count']] = str(name.text) + else: + currency_names[code] = str(name.text) + for symbol in elem.findall('symbol'): + if 'draft' in symbol.attrib or 'choice' in symbol.attrib: # Skip drafts and choice-patterns + continue + if symbol.attrib.get('alt'): # Skip alternate forms + continue + currency_symbols[code] = str(symbol.text) + + +def parse_unit_patterns(data, tree): + unit_patterns = data.setdefault('unit_patterns', {}) + compound_patterns = data.setdefault('compound_unit_patterns', {}) + unit_display_names = data.setdefault('unit_display_names', {}) + + for elem in tree.findall('.//units/unitLength'): + unit_length_type = elem.attrib['type'] + for unit in elem.findall('unit'): + unit_type = unit.attrib['type'] + unit_and_length_patterns = unit_patterns.setdefault(unit_type, {}).setdefault(unit_length_type, {}) + for pattern in unit.findall('unitPattern'): + if pattern.attrib.get('case', 'nominative') != 'nominative': + # Skip non-nominative cases. + continue + unit_and_length_patterns[pattern.attrib['count']] = _text(pattern) + + per_unit_pat = unit.find('perUnitPattern') + if per_unit_pat is not None: + unit_and_length_patterns['per'] = _text(per_unit_pat) + + display_name = unit.find('displayName') + if display_name is not None: + unit_display_names.setdefault(unit_type, {})[unit_length_type] = _text(display_name) + + for unit in elem.findall('compoundUnit'): + unit_type = unit.attrib['type'] + compound_unit_info = {} + compound_variations = {} + for child in unit: + if child.attrib.get('case', 'nominative') != 'nominative': + # Skip non-nominative cases. + continue + if child.tag == "unitPrefixPattern": + compound_unit_info['prefix'] = _text(child) + elif child.tag == "compoundUnitPattern": + compound_variations[None] = _text(child) + elif child.tag == "compoundUnitPattern1": + compound_variations[child.attrib.get('count')] = _text(child) + if compound_variations: + compound_variation_values = set(compound_variations.values()) + if len(compound_variation_values) == 1: + # shortcut: if all compound variations are the same, only store one + compound_unit_info['compound'] = next(iter(compound_variation_values)) + else: + compound_unit_info['compound_variations'] = compound_variations + compound_patterns.setdefault(unit_type, {})[unit_length_type] = compound_unit_info + + +def parse_date_fields(data, tree): + date_fields = data.setdefault('date_fields', {}) + for elem in tree.findall('.//dates/fields/field'): + field_type = elem.attrib['type'] + date_fields.setdefault(field_type, {}) + for rel_time in elem.findall('relativeTime'): + rel_time_type = rel_time.attrib['type'] + for pattern in rel_time.findall('relativeTimePattern'): + type_dict = date_fields[field_type].setdefault(rel_time_type, {}) + type_dict[pattern.attrib['count']] = str(pattern.text) + + +def parse_interval_formats(data, tree): + # https://www.unicode.org/reports/tr35/tr35-dates.html#intervalFormats + interval_formats = data.setdefault("interval_formats", {}) + for elem in tree.findall("dateTimeFormats/intervalFormats/*"): + if 'draft' in elem.attrib: + continue + if elem.tag == "intervalFormatFallback": + interval_formats[None] = elem.text + elif elem.tag == "intervalFormatItem": + skel_data = interval_formats.setdefault(elem.attrib["id"], {}) + for item_sub in elem: + if item_sub.tag == "greatestDifference": + skel_data[item_sub.attrib["id"]] = split_interval_pattern(item_sub.text) + else: + raise NotImplementedError(f"Not implemented: {item_sub.tag}({item_sub.attrib!r})") + + +def parse_currency_formats(data, tree): + currency_formats = data.setdefault('currency_formats', {}) + for currency_format in tree.findall('.//currencyFormats'): + if _should_skip_number_elem(data, currency_format): # TODO: Support other number systems + continue + + for length_elem in currency_format.findall('./currencyFormatLength'): + curr_length_type = length_elem.attrib.get('type') + for elem in length_elem.findall('currencyFormat'): + type = elem.attrib.get('type') + if _should_skip_elem(elem, type, currency_formats): + continue + for child in elem.iter(): + if child.tag == 'alias': + currency_formats[type] = Alias( + _translate_alias(['currency_formats', elem.attrib['type']], + child.attrib['path']), + ) + elif child.tag == 'pattern': + pattern_type = child.attrib.get('type') + if child.attrib.get('draft') or child.attrib.get('alt'): + # Skip drafts and alternates. + # The `noCurrency` alternate for currencies was added in CLDR 42. + continue + pattern = numbers.parse_pattern(str(child.text)) + if pattern_type: + # This is a compact currency format, see: + # https://www.unicode.org/reports/tr35/tr35-45/tr35-numbers.html#Compact_Number_Formats + + # These are mapped into a `compact_currency_formats` dictionary + # with the format {length: {count: {multiplier: pattern}}}. + compact_currency_formats = data.setdefault('compact_currency_formats', {}) + length_map = compact_currency_formats.setdefault(curr_length_type, {}) + length_count_map = length_map.setdefault(child.attrib['count'], {}) + length_count_map[pattern_type] = pattern + else: + # Regular currency format + currency_formats[type] = pattern + + +def parse_currency_unit_patterns(data, tree): + currency_unit_patterns = data.setdefault('currency_unit_patterns', {}) + for currency_formats_elem in tree.findall('.//currencyFormats'): + if _should_skip_number_elem(data, currency_formats_elem): # TODO: Support other number systems + continue + for unit_pattern_elem in currency_formats_elem.findall('./unitPattern'): + count = unit_pattern_elem.attrib['count'] + pattern = str(unit_pattern_elem.text) + currency_unit_patterns[count] = pattern + + +def parse_day_period_rules(tree): + """ + Parse dayPeriodRule data into a dict. + + :param tree: ElementTree + """ + day_periods = {} + for ruleset in tree.findall(".//dayPeriodRuleSet"): + ruleset_type = ruleset.attrib.get("type") # None|"selection" + for rules in ruleset.findall("dayPeriodRules"): + locales = rules.attrib["locales"].split() + for rule in rules.findall("dayPeriodRule"): + type = rule.attrib["type"] + if type in ("am", "pm"): # These fixed periods are handled separately by `get_period_id` + continue + rule = _compact_dict({ + key: _time_to_seconds_past_midnight(rule.attrib.get(key)) + for key in ("after", "at", "before", "from", "to") + }) + for locale in locales: + dest_list = day_periods.setdefault(locale, {}).setdefault(ruleset_type, {}).setdefault(type, []) + dest_list.append(rule) + return day_periods + + +def parse_character_order(data, tree): + for elem in tree.findall('.//layout/orientation/characterOrder'): + data['character_order'] = elem.text + + +def parse_measurement_systems(data, tree): + measurement_systems = data.setdefault('measurement_systems', {}) + for measurement_system in tree.findall('.//measurementSystemNames/measurementSystemName'): + type = measurement_system.attrib['type'] + if not _should_skip_elem(measurement_system, type=type, dest=measurement_systems): + _import_type_text(measurement_systems, measurement_system, type=type) + + +if __name__ == '__main__': + main() diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/ISSUE_TEMPLATE/breaking-change-proposal.md b/SPFsmartGATE/LIVE/TMP/haystack/.github/ISSUE_TEMPLATE/breaking-change-proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..312243cb4072436e300d279e81d84cb36c8c3b1b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/ISSUE_TEMPLATE/breaking-change-proposal.md @@ -0,0 +1,27 @@ +--- +name: Breaking change proposal +about: Track a breaking change in Haystack +title: '' +labels: breaking change +assignees: '' + +--- + +## Summary and motivation + +Briefly explain how the change is breaking and why it is needed. + +## Checklist + +```[tasklist] +### Tasks +- [ ] The changes are merged in the `main` branch (Code + Docstrings) +- [ ] Release notes have documented the breaking change +- [ ] A new version of `haystack-ai` has been released on PyPI +- [ ] Docs at https://docs.haystack.deepset.ai/ were updated +- [ ] Integrations on [haystack-core-integrations](https://github.com/deepset-ai/haystack-core-integrations) were updated (if needed) - This step might require a [Breaking change proposal](https://github.com/deepset-ai/haystack-core-integrations/issues/new?assignees=&labels=breaking+change&projects=&template=breaking-change-proposal.md&title=) on the repo +- [ ] Notebooks on https://github.com/deepset-ai/haystack-cookbook were updated (if needed) +- [ ] Tutorials on https://github.com/deepset-ai/haystack-tutorials were updated (if needed) +- [ ] Articles on https://github.com/deepset-ai/haystack-home/tree/main/content were updated (if needed) +- [ ] Integration tile on https://github.com/deepset-ai/haystack-integrations was updated (if needed) +``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/ISSUE_TEMPLATE/bug_report.md b/SPFsmartGATE/LIVE/TMP/haystack/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000000000000000000000000000000000000..ecfae37a685ca1c90e578d5997009ec3aa81320f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,34 @@ +--- +name: Bug report +about: Errors you encountered +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**Error message** +Error that was thrown (if available) + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Additional context** +Add any other context about the problem here, like document types / preprocessing steps / settings of reader etc. + +**To Reproduce** +Steps to reproduce the behavior + +**FAQ Check** +- [ ] Have you had a look at [our new FAQ page](https://docs.haystack.deepset.ai/docs/faq)? + +**System:** + - OS: + - GPU/CPU: + - Haystack version (commit or version number): + - DocumentStore: + - Reader: + - Retriever: diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/ISSUE_TEMPLATE/config.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..9d36944740c974d365593b74e693f13341514bc1 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Something unclear? Just ask :) + url: https://github.com/deepset-ai/haystack/discussions/new + about: Start a Github discussion with your question diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/ISSUE_TEMPLATE/feature_request.md b/SPFsmartGATE/LIVE/TMP/haystack/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000000000000000000000000000000000000..bbcbbe7d61558adde3cbfd0c7a63a67c27ed6d30 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/create_unstable_docs.py b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/create_unstable_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..a60d0328c922ada1ec637d45471565b39151aefc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/create_unstable_docs.py @@ -0,0 +1,54 @@ +import re +import sys +import argparse + +from readme_api import get_versions, create_new_unstable + + +VERSION_VALIDATOR = re.compile(r"^[0-9]+\.[0-9]+$") + + +def calculate_new_unstable(version: str): + # version must be formatted like so . + major, minor = version.split(".") + return f"{major}.{int(minor) + 1}-unstable" + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "-v", "--new-version", help="The new unstable version that is being created (e.g. 1.9).", required=True + ) + args = parser.parse_args() + + if VERSION_VALIDATOR.match(args.new_version) is None: + sys.exit("Version must be formatted like so .") + + # This two are the version that we must have published in the end + new_stable = f"{args.new_version}" + new_unstable = calculate_new_unstable(args.new_version) + + versions = get_versions() + new_stable_is_published = new_stable in versions + new_unstable_is_published = new_unstable in versions + + if new_stable_is_published and new_unstable_is_published: + # If both versions are published there's nothing to do. + # We fail gracefully. + print(f"Both new version {new_stable} and {new_unstable} are already published.") + sys.exit(0) + elif new_stable_is_published or new_unstable_is_published: + # Either new stable or unstable is already published, it's to risky to + # proceed so we abort the publishing process. + sys.exit(f"Either version {new_stable} or {new_unstable} are already published. Too risky to proceed.") + + # This version must exist since it's the one we're trying to promote + # to stable. + current_unstable = f"{new_stable}-unstable" + + if current_unstable not in versions: + sys.exit(f"Can't find version {current_unstable} to promote to {new_stable}") + + # Create create new unstable from the currently existing one. + # The new unstable will be made stable at a later time by another workflow + create_new_unstable(current_unstable, new_unstable) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/delete_outdated_docs.py b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/delete_outdated_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..1d88c1169df2e283539e1becb56d4dc996d0911e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/delete_outdated_docs.py @@ -0,0 +1,72 @@ +import argparse +import base64 +import os +import re +from pathlib import Path +from typing import List + +import requests +import yaml + +VERSION_VALIDATOR = re.compile(r"^[0-9]+\.[0-9]+$") + + +def readme_token(): + api_key = os.getenv("README_API_KEY", None) + if not api_key: + raise Exception("README_API_KEY env var is not set") + + api_key = f"{api_key}:" + return base64.b64encode(api_key.encode("utf-8")).decode("utf-8") + + +def create_headers(version: str): + return {"authorization": f"Basic {readme_token()}", "x-readme-version": version} + + +def get_docs_in_category(category_slug: str, version: str) -> List[str]: + """ + Returns the slugs of all documents in a category for the specific version. + """ + url = f"https://dash.readme.com/api/v1/categories/{category_slug}/docs" + headers = create_headers(version) + res = requests.get(url, headers=headers, timeout=10) + return [doc["slug"] for doc in res.json()] + + +def delete_doc(slug: str, version: str): + url = f"https://dash.readme.com/api/v1/docs/{slug}" + headers = create_headers(version) + res = requests.delete(url, headers=headers, timeout=10) + res.raise_for_status() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Delete outdated documentation from Readme.io. " + "It will delete all documents that are not present in the current config files." + ) + parser.add_argument( + "-c", "--config-path", help="Path to folder containing YAML documentation configs", required=True, type=Path + ) + parser.add_argument("-v", "--version", help="The version that will have its documents deleted", required=True) + args = parser.parse_args() + + configs = [yaml.safe_load(c.read_text()) for c in args.config_path.glob("*.yml")] + + remote_docs = {} + for config in configs: + category_slug = config["renderer"]["category_slug"] + if category_slug in remote_docs: + continue + docs = get_docs_in_category(category_slug, args.version) + + remote_docs[category_slug] = docs + + for config in configs: + doc_slug = config["renderer"]["slug"] + category_slug = config["renderer"]["category_slug"] + if doc_slug in remote_docs[category_slug]: + continue + + delete_doc(doc_slug, args.version) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/docstrings_checksum.py b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/docstrings_checksum.py new file mode 100644 index 0000000000000000000000000000000000000000..75eefb0b6e92471dd1afa3000f5089732d15c4dd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/docstrings_checksum.py @@ -0,0 +1,49 @@ +from pathlib import Path +from typing import Iterator + +import ast +import hashlib + + +def docstrings_checksum(python_files: Iterator[Path]): + files_content = (f.read_text() for f in python_files) + trees = (ast.parse(c) for c in files_content) + + # Get all docstrings from async functions, functions, + # classes and modules definitions + docstrings = [] + for tree in trees: + for node in ast.walk(tree): + if not isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef, ast.ClassDef, ast.Module)): + # Skip all node types that can't have docstrings to prevent failures + continue + docstring = ast.get_docstring(node) + if docstring: + docstrings.append(docstring) + + # Sort them to be safe, since ast.walk() returns + # nodes in no specified order. + # See https://docs.python.org/3/library/ast.html#ast.walk + docstrings.sort() + + return hashlib.md5(str(docstrings).encode("utf-8")).hexdigest() + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument("--root", help="Haystack root folder", required=True, type=Path) + args = parser.parse_args() + + # Get all Haystack and rest_api python files + root: Path = args.root.absolute() + haystack_files = root.glob("haystack/**/*.py") + rest_api_files = root.glob("rest_api/**/*.py") + + import itertools + + python_files = itertools.chain(haystack_files, rest_api_files) + + md5 = docstrings_checksum(python_files) + print(md5) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/generate_openapi_specs.py b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/generate_openapi_specs.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b14a894389c96edab7a001bc200c7b3baec741 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/generate_openapi_specs.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 + +import json +from pathlib import Path +import os +import sys + +import logging + +logging.basicConfig(level=logging.INFO) + + +sys.path.append(".") +from rest_api.utils import get_openapi_specs, get_app, get_pipelines # pylint: disable=wrong-import-position +from haystack import __version__ # pylint: disable=wrong-import-position + +REST_PATH = Path("./rest_api/rest_api").absolute() +PIPELINE_PATH = str(REST_PATH / "pipeline" / "pipeline_empty.haystack-pipeline.yml") +APP_PATH = str(REST_PATH / "application.py") + +os.environ["PIPELINE_YAML_PATH"] = PIPELINE_PATH + +logging.info("Loading OpenAPI specs from %s with pipeline at %s", APP_PATH, PIPELINE_PATH) + +# To initialize the app and the pipelines +get_app() +get_pipelines() + +# Generate the openapi specs +specs = get_openapi_specs() +# Add `x-readme` to disable proxy and limit sample languages on documentation (see https://docs.readme.com/main/docs/openapi-extensions) +specs.update({"x-readme": {"proxy-enabled": False, "samples-languages": ["curl", "python"]}}) + +# Dump the specs into a JSON file +with open("openapi.json", "w") as f: + json.dump(specs, f, indent=4) + f.write("\n") # We need to add a newline, otherwise there will be a conflict with end-of-file-fixer pre-commit hook diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/promote_unstable_docs.py b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/promote_unstable_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..52df7940515fb90160129ee735d02a8df89ea804 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/promote_unstable_docs.py @@ -0,0 +1,29 @@ +import re +import sys +import argparse + +from readme_api import get_versions, promote_unstable_to_stable + +VERSION_VALIDATOR = re.compile(r"^[0-9]+\.[0-9]+$") + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "-v", "--version", help="The version to promote to stable (e.g. 2.1).", required=True + ) + args = parser.parse_args() + + if VERSION_VALIDATOR.match(args.version) is None: + sys.exit("Version must be formatted like so .") + + unstable_version = f"{args.version}-unstable" + stable_version = args.version + + versions = get_versions() + if stable_version in versions: + sys.exit(f"Version {stable_version} is already published.") + + if unstable_version not in versions: + sys.exit(f"Can't find version {unstable_version} to promote to {stable_version}") + + promote_unstable_to_stable(unstable_version, stable_version) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/pydoc-markdown.sh b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/pydoc-markdown.sh new file mode 100644 index 0000000000000000000000000000000000000000..670bd09697f7e693afc611e025875de50aca1ad8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/pydoc-markdown.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +set -e # Fails on any error in the following loop +cd docs/pydoc +rm -rf temp && mkdir temp +cd temp +for file in ../config/* ; do + echo "Converting $file..." + pydoc-markdown "$file" +done diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/pyproject_to_requirements.py b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/pyproject_to_requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..b6c8b9781739d9c2d5eec2f53b9ef70e0f0be544 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/pyproject_to_requirements.py @@ -0,0 +1,47 @@ +import argparse +import re +import sys +from pathlib import Path + +import toml + +matcher = re.compile(r"farm-haystack\[(.+)\]") +parser = argparse.ArgumentParser( + prog="pyproject_to_requirements.py", description="Convert pyproject.toml to requirements.txt" +) +parser.add_argument("pyproject_path") +parser.add_argument("--extra", default="") + + +def resolve(target: str, extras: dict, results: set): + if target not in extras: + results.add(target) + return + + for t in extras[target]: + m = matcher.match(t) + if m: + for i in m.group(1).split(","): + resolve(i, extras, results) + else: + resolve(t, extras, results) + + +def main(pyproject_path: Path, extra: str = ""): + content = toml.load(pyproject_path) + # basic set of dependencies + deps = set(content["project"]["dependencies"]) + + if extra: + extras = content["project"]["optional-dependencies"] + resolve(extra, extras, deps) + + sys.stdout.write("\n".join(sorted(deps))) + sys.stdout.write("\n") + + +if __name__ == "__main__": + args = parser.parse_args() + pyproject_path = Path(args.pyproject_path).absolute() + + main(pyproject_path, args.extra) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/readme_api.py b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/readme_api.py new file mode 100644 index 0000000000000000000000000000000000000000..617a2b1397c6e81c7992404981ab8c7a91031b03 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/utils/readme_api.py @@ -0,0 +1,55 @@ +import os +import base64 +import requests + + + +class ReadmeAuth(requests.auth.AuthBase): + def __call__(self, r): + r.headers["authorization"] = f"Basic {readme_token()}" + return r + + +def readme_token(): + api_key = os.getenv("RDME_API_KEY", None) + if not api_key: + raise Exception("RDME_API_KEY env var is not set") + + api_key = f"{api_key}:" + return base64.b64encode(api_key.encode("utf-8")).decode("utf-8") + + +def get_versions(): + """ + Return all versions currently published in Readme.io. + """ + url = "https://dash.readme.com/api/v1/version" + res = requests.get(url, auth=ReadmeAuth(), timeout=30) + res.raise_for_status() + return [v["version"] for v in res.json()] + + +def create_new_unstable(current: str, new: str): + """ + Create new version by copying current. + + :param current: Existing current unstable version + :param new: Non existing new unstable version + """ + url = "https://dash.readme.com/api/v1/version/" + payload = {"is_beta": False, "version": new, "from": current, "is_hidden": False, "is_stable": False} + res = requests.post(url, json=payload, auth=ReadmeAuth(), timeout=30) + res.raise_for_status() + + +def promote_unstable_to_stable(unstable: str, stable: str): + """ + Rename the current unstable to stable and set it as stable. + + :param unstable: Existing unstable version + :param stable: Non existing new stable version + """ + url = f"https://dash.readme.com/api/v1/version/{unstable}" + payload = {"is_beta": False, "version": stable, "from": unstable, "is_hidden": False, "is_stable": True} + res = requests.put(url, json=payload, auth=ReadmeAuth(), timeout=30) + res.raise_for_status() diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/ci_metrics.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/ci_metrics.yml new file mode 100644 index 0000000000000000000000000000000000000000..fa6aa86fb09d3a1ea18147722099c282d4558197 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/ci_metrics.yml @@ -0,0 +1,23 @@ +name: CI Metrics + +on: + workflow_run: + workflows: + - "end-to-end" + - "Linting" + - "Tests" + types: + - completed + pull_request: + types: + - opened + - closed +jobs: + send: + runs-on: ubuntu-latest + steps: + - uses: int128/datadog-actions-metrics@v1 + with: + datadog-api-key: ${{ secrets.DATADOG_API_KEY }} + datadog-site: "datadoghq.eu" + collect-job-metrics: true diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/docker_release.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/docker_release.yml new file mode 100644 index 0000000000000000000000000000000000000000..6eee4d42caf25898de6233568790e136557ce602 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/docker_release.yml @@ -0,0 +1,69 @@ +name: Docker image release + +on: + workflow_dispatch: + push: + branches: + - main + tags: + - "v2.[0-9]+.[0-9]+*" + +env: + DOCKER_REPO_NAME: deepset/haystack + +jobs: + build-and-push: + name: Build base image + runs-on: ubuntu-latest + if: github.repository_owner == 'deepset-ai' + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_HUB_USER }} + password: ${{ secrets.DOCKER_HUB_TOKEN }} + + - name: Docker meta + id: meta + uses: docker/metadata-action@v5 + with: + images: $DOCKER_REPO_NAME + + - name: Build base images + uses: docker/bake-action@v5 + env: + IMAGE_TAG_SUFFIX: ${{ steps.meta.outputs.version }} + HAYSTACK_VERSION: ${{ steps.meta.outputs.version }} + with: + workdir: docker + targets: base + push: true + + - name: Test base image + run: | + EXPECTED_VERSION=$(cat VERSION.txt) + if [[ $EXPECTED_VERSION == *"-"* ]]; then + EXPECTED_VERSION=$(cut -d '-' -f 1 < VERSION.txt)$(cut -d '-' -f 2 < VERSION.txt) + fi + TAG="base-${{ steps.meta.outputs.version }}" + + PLATFORM="linux/amd64" + VERSION=$(docker run --platform "$PLATFORM" --rm "deepset/haystack:$TAG" python -c"from haystack.version import __version__; print(__version__)") + [[ "$VERSION" = "$EXPECTED_VERSION" ]] || echo "::error 'Haystack version in deepset/haystack:$TAG image for $PLATFORM is different from expected'" + + PLATFORM="linux/arm64" + VERSION=$(docker run --platform "$PLATFORM" --rm "deepset/haystack:$TAG" python -c"from haystack.version import __version__; print(__version__)") + [[ "$VERSION" = "$EXPECTED_VERSION" ]] || echo "::error 'Haystack version in deepset/haystack:$TAG image for $PLATFORM is different from expected'" + + # Remove image after test to avoid filling the GitHub runner and prevent its failure + docker rmi "deepset/haystack:$TAG" diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/docstring_labeler.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/docstring_labeler.yml new file mode 100644 index 0000000000000000000000000000000000000000..1dc5ddd9dc394c78f7a7243b042029d6d4270492 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/docstring_labeler.yml @@ -0,0 +1,59 @@ +name: Add label on docstrings edit + +on: + pull_request_target: + paths: + - "haystack/**/*.py" + +env: + PYTHON_VERSION: "3.11" + +jobs: + label: + runs-on: ubuntu-latest + + steps: + - name: Checkout base commit + uses: actions/checkout@v4 + with: + ref: ${{ github.base_ref }} + + - name: Copy file + # We copy our script after base ref checkout so we keep executing + # the same version even after checking out the HEAD ref. + # This is done to prevent executing malicious code in forks' PRs. + run: cp .github/utils/docstrings_checksum.py "${{ runner.temp }}/docstrings_checksum.py" + + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: "${{ env.PYTHON_VERSION }}" + + - name: Get docstrings + id: base-docstrings + run: | + CHECKSUM=$(python "${{ runner.temp }}/docstrings_checksum.py" --root "${{ github.workspace }}") + echo "checksum=$CHECKSUM" >> "$GITHUB_OUTPUT" + + - name: Checkout HEAD commit + uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.ref }} + # This must be set to correctly checkout a fork + repository: ${{ github.event.pull_request.head.repo.full_name }} + + - name: Get docstrings + id: head-docstrings + run: | + CHECKSUM=$(python "${{ runner.temp }}/docstrings_checksum.py" --root "${{ github.workspace }}") + echo "checksum=$CHECKSUM" >> "$GITHUB_OUTPUT" + + - name: Check if we should label + id: run-check + run: echo "should_run=${{ steps.base-docstrings.outputs.checksum != steps.head-docstrings.outputs.checksum }}" >> "$GITHUB_OUTPUT" + + - name: Add label + if: ${{ steps.run-check.outputs.should_run == 'true' }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: gh pr edit ${{ github.event.pull_request.html_url }} --add-label "type:documentation" diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/docstrings_linting.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/docstrings_linting.yml new file mode 100644 index 0000000000000000000000000000000000000000..beb18facc71465370dc99dbbf36c56c7508aaa0d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/docstrings_linting.yml @@ -0,0 +1,28 @@ +name: run docstrings linting + +on: + pull_request: + types: + - opened + - reopened + - synchronize + - ready_for_review + paths: + - "**.py" + +env: + HATCH_VERSION: "1.13.0" + +jobs: + docstrings-linting: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install Hatch + run: pip install hatch==${{ env.HATCH_VERSION }} + + - name: ruff docstrings linting + run: hatch run ruff check haystack diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/e2e.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/e2e.yml new file mode 100644 index 0000000000000000000000000000000000000000..b0911ea3bc9b3cd091599a0cd2da16d584a401e9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/e2e.yml @@ -0,0 +1,58 @@ +# If you change this name also do it in ci_metrics.yml +name: end-to-end + +on: + workflow_dispatch: # Activate this workflow manually + schedule: + - cron: "0 0 * * *" + pull_request: + types: + - opened + - reopened + - synchronize + - ready_for_review + paths: + - "e2e/**/*.py" + - ".github/workflows/e2e.yml" + +env: + PYTHON_VERSION: "3.8" + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + HATCH_VERSION: "1.13.0" + +jobs: + run: + timeout-minutes: 60 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "${{ env.PYTHON_VERSION }}" + + - name: Install Hatch + run: pip install hatch==${{ env.HATCH_VERSION }} + + - name: Run tests + run: hatch run test:e2e + + - name: Send event to Datadog + if: failure() && github.event_name == 'schedule' + uses: masci/datadog@v1 + with: + api-key: ${{ secrets.CORE_DATADOG_API_KEY }} + api-url: https://api.datadoghq.eu + events: | + - title: "${{ github.workflow }} workflow" + text: "Job ${{ github.job }} in branch ${{ github.ref_name }}" + alert_type: "error" + source_type_name: "Github" + host: ${{ github.repository_owner }} + tags: + - "project:${{ github.repository }}" + - "job:${{ github.job }}" + - "run_id:${{ github.run_id }}" + - "workflow:${{ github.workflow }}" + - "branch:${{ github.ref_name }}" + - "url:https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/github_release.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/github_release.yml new file mode 100644 index 0000000000000000000000000000000000000000..4a6a00eb01acc8221ddb17b5140a4f48ae151f45 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/github_release.yml @@ -0,0 +1,74 @@ +name: Project release on Github + +on: + workflow_dispatch: # this is useful to re-generate the release page without a new tag being pushed + push: + tags: + - "v2.[0-9]+.[0-9]+*" + # Ignore release versions tagged with -rc0 suffix + - "!v2.[0-9]+.[0-9]-rc0" + +jobs: + generate-notes: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-tags: true + fetch-depth: 0 # slow but needed by reno + + - name: Parse version + id: version + run: | + echo "current_release=$(awk -F \\- '{print $1}' < VERSION.txt)" >> "$GITHUB_OUTPUT" + echo "current_pre_release=$(awk -F \\- '{print $2}' < VERSION.txt)" >> "$GITHUB_OUTPUT" + + - name: Install reno + run: | + python -m pip install --upgrade pip + pip install "reno<5" + + - name: Generate release notes for release candidates - minor releases + if: steps.version.outputs.current_pre_release != '' && endsWith(steps.version.outputs.current_release, '.0') + env: + # When generating notes for release candidates of minor versions, pick every vX.Y.Z-rcN but + # stop when encounter vX.Y.Z-rc0. The -rc0 tag is added automatically when + # we create the release branch, so we can assume it's always there. + EARLIEST_VERSION: v${{ steps.version.outputs.current_release }}-rc0 + run: | + reno report --no-show-source --ignore-cache --earliest-version "$EARLIEST_VERSION" -o relnotes.rst + + - name: Generate release notes for release candidates - bugfix releases + if: steps.version.outputs.current_pre_release != '' && !endsWith(steps.version.outputs.current_release, '.0') + env: + # When generating notes for release candidates of bugfix releases, pick every vX.Y.Z-rcN but + # stop when encounter vX.Y.Z-rc1. + # In this case, we don't have the -rc0 tag, because we don't need to go through commits on main, + # as we cherry-pick them into the release branch. + EARLIEST_VERSION: v${{ steps.version.outputs.current_release }}-rc1 + run: | + reno report --no-show-source --ignore-cache --earliest-version "$EARLIEST_VERSION" -o relnotes.rst + + - name: Generate release notes for the final release + if: steps.version.outputs.current_pre_release == '' + # When generating notes for the final release vX.Y.Z, we just pass --version and reno + # will automatically collapse all the vX.Y.Z-rcN. + run: | + reno report --no-show-source --ignore-cache --version v${{ steps.version.outputs.current_release }} -o relnotes.rst + + - name: Convert to Markdown + uses: docker://pandoc/core:3.1 + with: + args: "--from rst --to markdown_github --no-highlight relnotes.rst -o relnotes.md --wrap=none" + + - name: Debug + run: | + cat relnotes.md + + - uses: ncipollo/release-action@v1 + with: + bodyFile: "relnotes.md" + prerelease: ${{ steps.version.outputs.current_pre_release }} + allowUpdates: true diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/labeler.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/labeler.yml new file mode 100644 index 0000000000000000000000000000000000000000..2af558297ef107bb37d632577729e510cb1dc964 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/labeler.yml @@ -0,0 +1,15 @@ +name: "Labeler" +on: +- pull_request_target + +permissions: + contents: read + pull-requests: write + +jobs: + triage: + runs-on: ubuntu-latest + steps: + - uses: actions/labeler@v5 + with: + repo-token: "${{ secrets.GITHUB_TOKEN }}" diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/license_compliance.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/license_compliance.yml new file mode 100644 index 0000000000000000000000000000000000000000..1bf55ee536b107dc9fc7df32e45b1e3b2343f110 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/license_compliance.yml @@ -0,0 +1,92 @@ +name: License Compliance + +on: + pull_request: + paths: + - "**/pyproject.toml" + # Since we test PRs, there is no need to run the workflow at each + # merge on `main`. Let's use a cron job instead. + schedule: + - cron: "0 0 * * *" # every day at midnight + +env: + CORE_DATADOG_API_KEY: ${{ secrets.CORE_DATADOG_API_KEY }} + PYTHON_VERSION: "3.10" + +jobs: + license_check_direct: + name: Direct dependencies only + env: + REQUIREMENTS_FILE: requirements_direct.txt + runs-on: ubuntu-latest + steps: + - name: Checkout the code + uses: actions/checkout@v4 + + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: "${{ env.PYTHON_VERSION }}" + + - name: Get direct dependencies + run: | + pip install toml + python .github/utils/pyproject_to_requirements.py pyproject.toml > ${{ env.REQUIREMENTS_FILE }} + + - name: Check Licenses + id: license_check_report + uses: pilosus/action-pip-license-checker@v2 + with: + github-token: ${{ secrets.GH_ACCESS_TOKEN }} + requirements: ${{ env.REQUIREMENTS_FILE }} + fail: "Copyleft,Other,Error" + # Exclusions in the vanilla distribution must be explicitly motivated + # + # - tqdm is MLP but there are no better alternatives + exclude: "(?i)^(tqdm).*" + + # We keep the license inventory on FOSSA + - name: Send license report to Fossa + uses: fossas/fossa-action@v1.4.0 + continue-on-error: true # not critical + with: + api-key: ${{ secrets.FOSSA_LICENSE_SCAN_TOKEN }} + + - name: Print report + if: ${{ always() }} + run: echo "${{ steps.license_check_report.outputs.report }}" + + - name: Calculate alert data + id: calculator + shell: bash + if: (success() || failure()) + run: | + if [ "${{ job.status }}" = "success" ]; then + echo "alert_type=success" >> "$GITHUB_OUTPUT"; + else + echo "alert_type=error" >> "$GITHUB_OUTPUT"; + fi + + - name: Send event to Datadog + # This step would fail when running in PRs opened from forks since + # secrets are not accessible. + # To prevent showing bogus failures in those PRs we skip the step. + # The workflow will fail in any case if the actual check fails in the previous steps. + if: (success() || failure()) && env.CORE_DATADOG_API_KEY != '' + uses: masci/datadog@v1 + with: + api-key: ${{ env.CORE_DATADOG_API_KEY }} + api-url: https://api.datadoghq.eu + events: | + - title: "${{ github.job }} in ${{ github.workflow }} workflow" + text: "License compliance check: direct dependencies only." + alert_type: "${{ steps.calculator.outputs.alert_type }}" + source_type_name: "Github" + host: ${{ github.repository_owner }} + tags: + - "project:${{ github.repository }}" + - "job:${{ github.job }}" + - "run_id:${{ github.run_id }}" + - "workflow:${{ github.workflow }}" + - "branch:${{ github.ref_name }}" + - "url:https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/minor_version_release.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/minor_version_release.yml new file mode 100644 index 0000000000000000000000000000000000000000..f569c46de3d19593d698ae02554ffcdcb0e10e6f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/minor_version_release.yml @@ -0,0 +1,79 @@ +name: Minor Version Release + +on: + workflow_dispatch: + +env: + PYTHON_VERSION: "3.8" + +jobs: + sync: + runs-on: ubuntu-latest + steps: + - name: Checkout this repo + uses: actions/checkout@v4 + with: + ref: main + + - name: Define all versions + id: versions + shell: bash + # We only need `major.minor` in Readme so we cut the full version string to the first two tokens + run: | + echo "current_release_minor=$(cut -d "." -f 1,2 < VERSION.txt)" >> "$GITHUB_OUTPUT" + + - name: Bump version on main + shell: bash + env: + # We use the HAYSTACK_BOT_TOKEN here so the PR created by the step will + # trigger required workflows and can be merged by anyone + GITHUB_TOKEN: ${{ secrets.HAYSTACK_BOT_TOKEN }} + run: | + git config --global user.name "github-actions[bot]" + git config --global user.email "github-actions[bot]@users.noreply.github.com" + + git checkout main + + # Create the release branch from the current unstable + git checkout -b v${{ steps.versions.outputs.current_release_minor }}.x + git push -u origin v${{ steps.versions.outputs.current_release_minor }}.x + + # Tag the base with X.Y.Z-rc0. + # At this point VERSION.txt still contains the previous version and not + # the one specified by the tag. + # This is good though as we just need this to make reno work properly. + NEW_VERSION=$(awk -F. '/[0-9]+\./{$2++;print}' OFS=. < VERSION.txt) + echo "$NEW_VERSION" > VERSION.txt + VERSION_TAG="v$NEW_VERSION" + git tag "$VERSION_TAG" -m"$VERSION_TAG" + git push --tags + + # Create the branch that bump version in dev branch + cat VERSION.txt + git checkout -b bump-version + git add . + git commit -m "Update unstable version to $NEW_VERSION" + git push -u origin bump-version + + # Create the PR + gh pr create -B main \ + -H bump-version \ + --title "Bump unstable version" \ + --body "This PR bumps the unstable version for \`v2.x\`. \ + The release branch \`v${{ steps.versions.outputs.current_release_minor }}.x\` has been correctly created. \ + Verify documentation on Readme has been correctly updated before approving and merging this PR." \ + --label "ignore-for-release-notes" + + - uses: actions/setup-python@v5 + with: + python-version: "${{ env.PYTHON_VERSION }}" + + - name: Install create_unstable_docs.py dependencies + run: pip install requests + + - name: Release Readme version + env: + RDME_API_KEY: ${{ secrets.README_API_KEY }} + run: | + git checkout main + python ./.github/utils/create_unstable_docs.py --new-version ${{ steps.versions.outputs.current_release_minor }} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/project.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/project.yml new file mode 100644 index 0000000000000000000000000000000000000000..45a8ca5f3b2cb531dedb26477f61e10ea658eff5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/project.yml @@ -0,0 +1,16 @@ +name: Track issues with Github project + +on: + issues: + types: + - opened + +jobs: + add-to-project: + name: Add new issues to project for triage + runs-on: ubuntu-latest + steps: + - uses: actions/add-to-project@v1.0.2 + with: + project-url: https://github.com/orgs/deepset-ai/projects/5 + github-token: ${{ secrets.GH_PROJECT_PAT }} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/promote_unstable_docs.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/promote_unstable_docs.yml new file mode 100644 index 0000000000000000000000000000000000000000..838dcd145d1b4a8f37497f2caeefc728b4c4a482 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/promote_unstable_docs.yml @@ -0,0 +1,38 @@ +name: Release new minor version docs + +on: + push: + tags: + # Trigger this only for the first patch release of the new minor + - "v[0-9]+.[0-9]+.0" + # Exclude 1.x tags + - "!v1.[0-9]+.[0-9]+" +env: + PYTHON_VERSION: "3.8" + +jobs: + promote: + runs-on: ubuntu-latest + steps: + - name: Checkout this repo + uses: actions/checkout@v4 + + - name: Get version to release + id: version + shell: bash + # We only need `major.minor` in Readme so we cut the full version string to the first two tokens + run: | + echo "version=$(cut -d "." -f 1,2 < VERSION.txt)" >> "$GITHUB_OUTPUT" + + - uses: actions/setup-python@v5 + with: + python-version: "${{ env.PYTHON_VERSION }}" + + - name: Install promote_unstable_docs.py dependencies + run: pip install requests + + - name: Release Readme version + env: + RDME_API_KEY: ${{ secrets.README_API_KEY }} + run: | + python ./.github/utils/promote_unstable_docs.py --version ${{ steps.version.outputs.version }} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/pypi_release.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/pypi_release.yml new file mode 100644 index 0000000000000000000000000000000000000000..807adff22625ff5c5b824751e0aa5c62474ef8e2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/pypi_release.yml @@ -0,0 +1,31 @@ +name: Project release on PyPi + +on: + push: + tags: + - "v[0-9]+.[0-9]+.[0-9]+*" + # We must not release versions tagged with -rc0 suffix + - "!v[0-9]+.[0-9]+.[0-9]-rc0" + +env: + HATCH_VERSION: "1.13.0" + +jobs: + release-on-pypi: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install Hatch + run: pip install hatch==${{ env.HATCH_VERSION }} + + - name: Build Haystack + run: hatch build + + - name: Publish on PyPi + env: + HATCH_INDEX_USER: __token__ + HATCH_INDEX_AUTH: ${{ secrets.HAYSTACK_AI_PYPI_TOKEN }} + run: hatch publish -y diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/readme_sync.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/readme_sync.yml new file mode 100644 index 0000000000000000000000000000000000000000..b387dbb6220738759ee562edc5dc0c0500c2f607 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/readme_sync.yml @@ -0,0 +1,65 @@ +name: Sync docs with Readme + +on: + pull_request: + paths: + - "docs/pydoc/**" + push: + branches: + - main + # release branches have the form v1.9.x + - "v[0-9]+.[0-9]+.x" + # Exclude 1.x release branches, there's another workflow handling those + - "!v1.[0-9]+.x" + +env: + HATCH_VERSION: "1.13.0" + PYTHON_VERSION: "3.10" + +jobs: + sync: + runs-on: ubuntu-latest + steps: + - name: Checkout this repo + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "${{ env.PYTHON_VERSION }}" + + - name: Install Hatch + run: pip install hatch==${{ env.HATCH_VERSION }} + + - name: Generate API docs + env: + # This is necessary to fetch the documentation categories + # from Readme.io as we need them to associate the slug + # in config files with their id. + README_API_KEY: ${{ secrets.README_API_KEY }} + # The command is a bit misleading, we're not actually syncing anything here, + # we're just generating the markdown files from the yaml configs. + run: hatch run readme:sync + + - name: Get version + id: version-getter + run: | + VERSION="$(hatch version | cut -d '.' -f 1,2)" + CURRENT_BRANCH="${{ github.ref_name }}" + # If we're on `main` branch we should push docs to the unstable version + if [ "$CURRENT_BRANCH" = "main" ]; then + VERSION="$VERSION-unstable" + fi + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + + - name: Sync docs + if: github.event_name == 'push' + uses: readmeio/rdme@v8 + with: + rdme: docs ./docs/pydoc/temp --key=${{ secrets.README_API_KEY }} --version=${{ steps.version-getter.outputs.version }} + + - name: Delete outdated + if: github.event_name == 'push' + env: + README_API_KEY: ${{ secrets.README_API_KEY }} + run: hatch run readme:delete-outdated --version="${{ steps.version-getter.outputs.version }}" --config-path ./docs/pydoc/config diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/release_notes.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/release_notes.yml new file mode 100644 index 0000000000000000000000000000000000000000..5203c0837c6d980ddea8d624f50bec0c0ca6b433 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/release_notes.yml @@ -0,0 +1,48 @@ +name: Check Release Notes + +on: + pull_request: + types: + - opened + - reopened + - synchronize + - ready_for_review + - labeled + - unlabeled + paths: + - "**.py" + - "pyproject.toml" + - "!.github/**/*.py" + +jobs: + reno: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + # With the default value of 1, there are corner cases where tj-actions/changed-files + # fails with a `no merge base` error + fetch-depth: 0 + + - name: Get release note files + id: changed-files + uses: tj-actions/changed-files@v45 + with: + files: releasenotes/notes/*.yaml + + - name: Check release notes + if: steps.changed-files.outputs.any_changed == 'false' && !contains( github.event.pull_request.labels.*.name, 'ignore-for-release-notes') + run: | + # Check if any of the commit messages contain tags ci/docs/test + if git log --pretty=%s origin/main..HEAD | grep -E '^(ci:|docs:|test:)' > /dev/null; then + echo "Skipping release note check for commits with 'ci:', 'docs:', or 'test:' tags." + else + echo "::error::The release notes file is missing, please add one or attach the label 'ignore-for-release-notes' to this PR." + exit 1 + fi + + - name: Verify release notes formatting + if: steps.changed-files.outputs.any_changed == 'true' && !contains( github.event.pull_request.labels.*.name, 'ignore-for-release-notes') + run: | + yamllint -d "{extends: default, rules: {line-length: {max: 1200}}}" ${{ steps.changed-files.outputs.all_changed_files }} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/release_notes_skipper.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/release_notes_skipper.yml new file mode 100644 index 0000000000000000000000000000000000000000..41c9be1e81e24556655fd40a94b1d72a93827998 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/release_notes_skipper.yml @@ -0,0 +1,22 @@ +name: Check Release Notes + +on: + pull_request: + types: + - opened + - reopened + - synchronize + - ready_for_review + - labeled + - unlabeled + paths-ignore: + - "**.py" + - "pyproject.toml" + - "!.github/**/*.py" + +jobs: + reno: + runs-on: ubuntu-latest + steps: + - name: Skip mandatory job + run: echo "Skipped!" diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/stale.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/stale.yml new file mode 100644 index 0000000000000000000000000000000000000000..4ac6c92fcd05bfc58043f60d7a22231f6dfb248b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/stale.yml @@ -0,0 +1,15 @@ +name: 'Stalebot' +on: + schedule: + - cron: '30 1 * * *' + +jobs: + makestale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v9 + with: + any-of-labels: 'proposal,community-triage' + stale-pr-message: 'This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 10 days.' + days-before-stale: 30 + days-before-close: 10 diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/tests.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..4f9df1a3fe13e40c3e8c793c8c3e01023999cb8e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/tests.yml @@ -0,0 +1,442 @@ +# If you change this name also do it in tests_skipper.yml and ci_metrics.yml +name: Tests + +on: + workflow_dispatch: # Activate this workflow manually + push: + branches: + - main + # release branches have the form v1.9.x + - "v[0-9].*[0-9].x" + pull_request: + types: + - opened + - reopened + - synchronize + - ready_for_review + paths: + # Keep the list in sync with the paths defined in the `tests_skipper.yml` workflow + - "haystack/**/*.py" + - "haystack/core/pipeline/predefined/*" + - "test/**/*.py" + - "pyproject.toml" + +env: + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + CORE_AZURE_CS_ENDPOINT: ${{ secrets.CORE_AZURE_CS_ENDPOINT }} + CORE_AZURE_CS_API_KEY: ${{ secrets.CORE_AZURE_CS_API_KEY }} + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} + AZURE_OPENAI_ENDPOINT: ${{ secrets.AZURE_OPENAI_ENDPOINT }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + HF_API_TOKEN: ${{ secrets.HUGGINGFACE_API_KEY }} + PYTHON_VERSION: "3.8" + HATCH_VERSION: "1.13.0" + +jobs: + format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "${{ env.PYTHON_VERSION }}" + + - name: Install Hatch + run: pip install hatch==${{ env.HATCH_VERSION }} + + - name: Check file format + run: hatch run format-check + + - name: Check linting + run: hatch run check + + - name: Check presence of license header + run: docker run --rm -v "$(pwd):/github/workspace" ghcr.io/korandoru/hawkeye check + + - name: Calculate alert data + id: calculator + shell: bash + if: (success() || failure()) && github.ref_name == 'main' + run: | + if [ "${{ job.status }}" = "success" ]; then + echo "alert_type=success" >> "$GITHUB_OUTPUT"; + else + echo "alert_type=error" >> "$GITHUB_OUTPUT"; + fi + + - name: Send event to Datadog + if: (success() || failure()) && github.ref_name == 'main' + uses: masci/datadog@v1 + with: + api-key: ${{ secrets.CORE_DATADOG_API_KEY }} + api-url: https://api.datadoghq.eu + events: | + - title: "${{ github.workflow }} workflow" + text: "Job ${{ github.job }} in branch ${{ github.ref_name }}" + alert_type: "${{ steps.calculator.outputs.alert_type }}" + source_type_name: "Github" + host: ${{ github.repository_owner }} + tags: + - "project:${{ github.repository }}" + - "job:${{ github.job }}" + - "run_id:${{ github.run_id }}" + - "workflow:${{ github.workflow }}" + - "branch:${{ github.ref_name }}" + - "url:https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" + + unit-tests: + name: Unit / ${{ matrix.os }} + needs: format + strategy: + fail-fast: false + matrix: + os: + - ubuntu-latest + - windows-latest + - macos-latest + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "${{ env.PYTHON_VERSION }}" + + - name: Install Hatch + id: hatch + shell: bash + run: | + pip install hatch==${{ env.HATCH_VERSION }} + echo "env=$(hatch env find test)" >> "$GITHUB_OUTPUT" + + - name: Run + run: hatch run test:unit + + - uses: actions/cache/save@v4 + id: cache + with: + path: ${{ steps.hatch.outputs.env }} + key: ${{ runner.os }}-${{ github.sha }} + + - name: Coveralls + # We upload only coverage for ubuntu as handling both os + # complicates the workflow too much for little to no gain + if: matrix.os == 'ubuntu-latest' + uses: coverallsapp/github-action@v2 + with: + path-to-lcov: coverage.xml + + - name: Calculate alert data + id: calculator + shell: bash + if: (success() || failure()) && github.ref_name == 'main' + run: | + if [ "${{ job.status }}" = "success" ]; then + echo "alert_type=success" >> "$GITHUB_OUTPUT"; + else + echo "alert_type=error" >> "$GITHUB_OUTPUT"; + fi + + - name: Send event to Datadog + if: (success() || failure()) && github.ref_name == 'main' + uses: masci/datadog@v1 + with: + api-key: ${{ secrets.CORE_DATADOG_API_KEY }} + api-url: https://api.datadoghq.eu + events: | + - title: "${{ github.workflow }} workflow" + text: "Job ${{ github.job }} in branch ${{ github.ref_name }}" + alert_type: "${{ steps.calculator.outputs.alert_type }}" + source_type_name: "Github" + host: ${{ github.repository_owner }} + tags: + - "project:${{ github.repository }}" + - "job:${{ github.job }}" + - "run_id:${{ github.run_id }}" + - "workflow:${{ github.workflow }}" + - "branch:${{ github.ref_name }}" + - "url:https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" + + lint: + needs: unit-tests + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + # With the default value of 1, there are corner cases where tj-actions/changed-files + # fails with a `no merge base` error + fetch-depth: 0 + + - name: Get changed files + id: files + uses: tj-actions/changed-files@v45 + with: + files: | + **/*.py + files_ignore: | + test/** + + - uses: actions/setup-python@v5 + with: + python-version: "${{ env.PYTHON_VERSION }}" + + - name: Install Hatch + id: hatch + run: | + pip install hatch==${{ env.HATCH_VERSION }} + echo "env=$(hatch env find test)" >> "$GITHUB_OUTPUT" + + - uses: actions/cache/restore@v4 + id: cache + with: + path: ${{ steps.hatch.outputs.env }} + key: ${{ runner.os }}-${{ github.sha }} + + - name: Mypy + if: steps.files.outputs.any_changed == 'true' + run: | + mkdir .mypy_cache + hatch run test:types ${{ steps.files.outputs.all_changed_files }} + + - name: Pylint + if: steps.files.outputs.any_changed == 'true' + run: | + hatch run test:lint ${{ steps.files.outputs.all_changed_files }} + + - name: Calculate alert data + id: calculator + shell: bash + if: (success() || failure()) && github.ref_name == 'main' + run: | + if [ "${{ job.status }}" = "success" ]; then + echo "alert_type=success" >> "$GITHUB_OUTPUT"; + else + echo "alert_type=error" >> "$GITHUB_OUTPUT"; + fi + + - name: Send event to Datadog + if: (success() || failure()) && github.ref_name == 'main' + uses: masci/datadog@v1 + with: + api-key: ${{ secrets.CORE_DATADOG_API_KEY }} + api-url: https://api.datadoghq.eu + events: | + - title: "${{ github.workflow }} workflow" + text: "Job ${{ github.job }} in branch ${{ github.ref_name }}" + alert_type: "${{ steps.calculator.outputs.alert_type }}" + source_type_name: "Github" + host: ${{ github.repository_owner }} + tags: + - "project:${{ github.repository }}" + - "job:${{ github.job }}" + - "run_id:${{ github.run_id }}" + - "workflow:${{ github.workflow }}" + - "branch:${{ github.ref_name }}" + - "url:https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" + + integration-tests-linux: + name: Integration / ubuntu-latest + needs: unit-tests + runs-on: ubuntu-latest + services: + tika: + image: apache/tika:2.9.0.0 + ports: + - 9998:9998 + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "${{ env.PYTHON_VERSION }}" + + - name: Install Hatch + id: hatch + shell: bash + run: | + pip install hatch==${{ env.HATCH_VERSION }} + echo "env=$(hatch env find test)" >> "$GITHUB_OUTPUT" + + - uses: actions/cache/restore@v4 + id: cache + with: + path: ${{ steps.hatch.outputs.env }} + key: ${{ runner.os }}-${{ github.sha }} + + - name: Install dependencies + run: | + sudo apt update + sudo apt install ffmpeg # for local Whisper tests + + - name: Run + run: hatch run test:integration + + - name: Calculate alert data + id: calculator + shell: bash + if: (success() || failure()) && github.ref_name == 'main' + run: | + if [ "${{ job.status }}" = "success" ]; then + echo "alert_type=success" >> "$GITHUB_OUTPUT"; + else + echo "alert_type=error" >> "$GITHUB_OUTPUT"; + fi + + - name: Send event to Datadog + if: (success() || failure()) && github.ref_name == 'main' + uses: masci/datadog@v1 + with: + api-key: ${{ secrets.CORE_DATADOG_API_KEY }} + api-url: https://api.datadoghq.eu + events: | + - title: "${{ github.workflow }} workflow" + text: "Job ${{ github.job }} in branch ${{ github.ref_name }}" + alert_type: "${{ steps.calculator.outputs.alert_type }}" + source_type_name: "Github" + host: ${{ github.repository_owner }} + tags: + - "project:${{ github.repository }}" + - "job:${{ github.job }}" + - "run_id:${{ github.run_id }}" + - "workflow:${{ github.workflow }}" + - "branch:${{ github.ref_name }}" + - "url:https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" + + integration-tests-macos: + name: Integration / macos-latest + needs: unit-tests + runs-on: macos-latest + env: + HAYSTACK_MPS_ENABLED: false + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "${{ env.PYTHON_VERSION }}" + + - name: Install Hatch + id: hatch + shell: bash + run: | + pip install hatch==${{ env.HATCH_VERSION }} + echo "env=$(hatch env find test)" >> "$GITHUB_OUTPUT" + + - uses: actions/cache/restore@v4 + id: cache + with: + path: ${{ steps.hatch.outputs.env }} + key: ${{ runner.os }}-${{ github.sha }} + + - name: Install dependencies + run: | + brew install ffmpeg # for local Whisper tests + + - name: Run + run: hatch run test:integration-mac + + - name: Calculate alert data + id: calculator + shell: bash + if: (success() || failure()) && github.ref_name == 'main' + run: | + if [ "${{ job.status }}" = "success" ]; then + echo "alert_type=success" >> "$GITHUB_OUTPUT"; + else + echo "alert_type=error" >> "$GITHUB_OUTPUT"; + fi + + - name: Send event to Datadog + if: (success() || failure()) && github.ref_name == 'main' + uses: masci/datadog@v1 + with: + api-key: ${{ secrets.CORE_DATADOG_API_KEY }} + api-url: https://api.datadoghq.eu + events: | + - title: "${{ github.workflow }} workflow" + text: "Job ${{ github.job }} in branch ${{ github.ref_name }}" + alert_type: "${{ steps.calculator.outputs.alert_type }}" + source_type_name: "Github" + host: ${{ github.repository_owner }} + tags: + - "project:${{ github.repository }}" + - "job:${{ github.job }}" + - "run_id:${{ github.run_id }}" + - "workflow:${{ github.workflow }}" + - "branch:${{ github.ref_name }}" + - "url:https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" + + integration-tests-windows: + name: Integration / windows-latest + needs: unit-tests + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "${{ env.PYTHON_VERSION }}" + + - name: Install Hatch + id: hatch + shell: bash + run: | + pip install hatch==${{ env.HATCH_VERSION }} + echo "env=$(hatch env find test)" >> "$GITHUB_OUTPUT" + + - uses: actions/cache/restore@v4 + id: cache + with: + path: ${{ steps.hatch.outputs.env }} + key: ${{ runner.os }}-${{ github.sha }} + + - name: Run + run: hatch run test:integration-windows + + - name: Calculate alert data + id: calculator + shell: bash + if: (success() || failure()) && github.ref_name == 'main' + run: | + if [ "${{ job.status }}" = "success" ]; then + echo "alert_type=success" >> "$GITHUB_OUTPUT"; + else + echo "alert_type=error" >> "$GITHUB_OUTPUT"; + fi + + - name: Send event to Datadog + if: (success() || failure()) && github.ref_name == 'main' + uses: masci/datadog@v1 + with: + api-key: ${{ secrets.CORE_DATADOG_API_KEY }} + api-url: https://api.datadoghq.eu + events: | + - title: "${{ github.workflow }} workflow" + text: "Job ${{ github.job }} in branch ${{ github.ref_name }}" + alert_type: "${{ steps.calculator.outputs.alert_type }}" + source_type_name: "Github" + host: ${{ github.repository_owner }} + tags: + - "project:${{ github.repository }}" + - "job:${{ github.job }}" + - "run_id:${{ github.run_id }}" + - "workflow:${{ github.workflow }}" + - "branch:${{ github.ref_name }}" + - "url:https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" + + trigger-catch-all: + name: Tests completed + # This job will be executed only after all the other tests + # are successful. + # This way we'll be able to mark only this test as required + # and skip it accordingly. + needs: + - integration-tests-linux + - integration-tests-macos + - integration-tests-windows + uses: ./.github/workflows/tests_skipper_workflow.yml + with: + tests_were_skipped: false diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/tests_skipper_trigger.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/tests_skipper_trigger.yml new file mode 100644 index 0000000000000000000000000000000000000000..b2974539768bb70d2b31fb44c1a05b34486ae2db --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/tests_skipper_trigger.yml @@ -0,0 +1,48 @@ +# If you change this name also do it in tests.yml and ci_metrics.yml +name: Tests + +on: + pull_request: + types: + - opened + - reopened + - synchronize + - ready_for_review + paths-ignore: + # we skip the tests unless the code changes. The problem is that GitHub will run the check anyway if any other + # file outside the code changed (e.g. the release notes). Hence, we need a second filter down below. + # keep the list in sync with the paths defined in the `tests.yml` workflow + - "haystack/**/*.py" + - "haystack/core/pipeline/predefined/*" + - "test/**/*.py" + +jobs: + check_if_changed: + name: Check if changed + runs-on: ubuntu-latest + permissions: + pull-requests: read + outputs: + code_changes: ${{ steps.changes.outputs.code_changes }} + steps: + - uses: actions/checkout@v4 + - name: Check for changed code + id: changes + uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 + with: + # keep the list in sync with the paths defined in the `tests.yml` workflow + filters: | + code_changes: + - haystack/**/*.py + - "haystack/templates/predefined/*" + - test/**/*.py + - "pyproject.toml" + + trigger-catch-all: + name: Tests completed + # Don't run this check if the PR contains both code and non-code changes (e.g. release notes) + needs: check_if_changed + if: needs.check_if_changed.outputs.code_changes == 'false' + uses: ./.github/workflows/tests_skipper_workflow.yml + with: + tests_were_skipped: true diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/tests_skipper_workflow.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/tests_skipper_workflow.yml new file mode 100644 index 0000000000000000000000000000000000000000..4554c8275f34cbaa2ec5c6502a45af214e0ca1c5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/tests_skipper_workflow.yml @@ -0,0 +1,24 @@ +# If you change this name also do it in tests.yml and ci_metrics.yml +# We use a separate workflow to skip the tests if the PR contains both code and non-code changes (e.g. release notes). +# Skipping the job unfortunately doesn't work because GitHub will treat these jobs as successful even if they are +# skipped. Hence, we need to revert to a separate workflow. +name: Tests +on: + workflow_call: + inputs: + tests_were_skipped: + type: boolean + required: true + +jobs: + catch-all: + # Don't run this check if the PR contains both code and non-code changes (e.g. release notes) + name: Mark tests as completed + runs-on: ubuntu-latest + steps: + - name: Skip tests + if: ${{ github.event.inputs.tests_were_skipped }} + run: echo "Skipped!" + - name: Tests completed successfully + if: ${{ !github.event.inputs.tests_were_skipped }} + run: echo "Tests completed!" diff --git a/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/workflows_linting.yml b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/workflows_linting.yml new file mode 100644 index 0000000000000000000000000000000000000000..7b5c021184c198e4fe52aad85ee6b989f5f10d6d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/.github/workflows/workflows_linting.yml @@ -0,0 +1,23 @@ +name: Github workflows linter + +on: + pull_request: + paths: + - ".github/workflows/**" + +jobs: + lint-workflows: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - uses: actions/setup-go@v5 + + - name: Install actionlint + run: go install github.com/rhysd/actionlint/cmd/actionlint@latest + + - name: Run actionlint + env: + SHELLCHECK_OPTS: --exclude=SC2102 + run: actionlint diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/audio_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/audio_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..8c6a6708866db2c6e5b49b102a5c4d17a70f744e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/audio_api.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/audio] + modules: ["whisper_local", "whisper_remote"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Transcribes audio files. + category_slug: haystack-api + title: Audio + slug: audio-api + order: 3 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: audio_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/builders_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/builders_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..d16085b0c42107eeda21aa03a0385730a34b29d8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/builders_api.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/builders] + modules: ["answer_builder", "prompt_builder", "chat_prompt_builder"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Extract the output of a Generator to an Answer format, and build prompts. + category_slug: haystack-api + title: Builders + slug: builders-api + order: 5 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: builders_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/caching_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/caching_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..a38a5ba9381ff40cb6d382b7ae1343da66d2e661 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/caching_api.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/caching] + modules: ["cache_checker"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Checks if any document coming from the given URL is already present in the store. + category_slug: haystack-api + title: Caching + slug: caching-api + order: 7 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: cachings_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/classifiers_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/classifiers_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..14a97ee7bd38a33297961a29e06cce2c954539d2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/classifiers_api.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/classifiers] + modules: ["document_language_classifier", "zero_shot_document_classifier"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Classify documents based on the provided labels. + category_slug: haystack-api + title: Classifiers + slug: classifiers-api + order: 10 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: classifiers_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/connectors.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/connectors.yml new file mode 100644 index 0000000000000000000000000000000000000000..b53b4bb80f9b138ac4d3468779b54c4f3a3ac421 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/connectors.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/connectors] + modules: ["openapi_service"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Various connectors to integrate with external services. + category_slug: haystack-api + title: Connectors + slug: connectors-api + order: 15 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: connectors_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/converters_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/converters_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..6c89138c98fd2c93cb72c4bf20ef3117a9f00657 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/converters_api.yml @@ -0,0 +1,42 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/converters] + modules: + [ + "azure", + "csv", + "docx", + "html", + "json", + "markdown", + "openapi_functions", + "output_adapter", + "pdfminer", + "pptx", + "pypdf", + "tika", + "txt", + ] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Various converters to transform data from one format to another. + category_slug: haystack-api + title: Converters + slug: converters-api + order: 20 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: converters_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/data_classess_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/data_classess_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..a67f28db9d4412faa315d6964a074ab261904f1c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/data_classess_api.yml @@ -0,0 +1,28 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/dataclasses] + modules: + ["answer", "byte_stream", "chat_message", "document", "streaming_chunk", "sparse_embedding"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Core classes that carry data through the system. + category_slug: haystack-api + title: Data Classes + slug: data-classes-api + order: 30 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: data_classess_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/document_stores_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/document_stores_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..f9744e197723ef7f9ed42f31543cec17c774cfad --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/document_stores_api.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/document_stores/in_memory] + modules: ["document_store"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Stores your texts and meta data and provides them to the Retriever at query time. + category_slug: haystack-api + title: Document Stores + slug: document-stores-api + order: 40 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: document_stores_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/document_writers_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/document_writers_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..1d16ae84a4df1c55dd8604faedd3cb9e565d8c9e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/document_writers_api.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/writers] + modules: ["document_writer"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Writes Documents to a DocumentStore. + category_slug: haystack-api + title: Document Writers + slug: document-writers-api + order: 50 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: document_writers_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/embedders_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/embedders_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..9528039aa0c236fc2833850d17f6856632732489 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/embedders_api.yml @@ -0,0 +1,37 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/embedders] + modules: + [ + "azure_document_embedder", + "azure_text_embedder", + "hugging_face_api_document_embedder", + "hugging_face_api_text_embedder", + "openai_document_embedder", + "openai_text_embedder", + "sentence_transformers_document_embedder", + "sentence_transformers_text_embedder", + ] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Transforms queries into vectors to look for similar or relevant Documents. + category_slug: haystack-api + title: Embedders + slug: embedders-api + order: 60 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: embedders_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/evaluation_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/evaluation_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..e445e9a56802c593ce22f80a0275a36a15ace76b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/evaluation_api.yml @@ -0,0 +1,31 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/evaluation] + modules: + [ + "base", + "eval_run_result", + ] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Represents the results of evaluation. + category_slug: haystack-api + title: Evaluation + slug: evaluation-api + order: 61 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: evaluation_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/evaluators_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/evaluators_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..9a8460b94ad6ab272bd0074a7afecb19eb21f269 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/evaluators_api.yml @@ -0,0 +1,38 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/evaluators] + modules: + [ + "answer_exact_match", + "context_relevance", + "document_map", + "document_mrr", + "document_ndcg", + "document_recall", + "faithfulness", + "llm_evaluator", + "sas_evaluator", + ] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Evaluate your pipelines or individual components. + category_slug: haystack-api + title: Evaluators + slug: evaluators-api + order: 63 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: evaluators_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/extractors_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/extractors_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..76ee7f0b15a77f3322eadb816fc04c91abfc059b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/extractors_api.yml @@ -0,0 +1,29 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/extractors] + modules: ["named_entity_extractor"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: filter + expression: "name not in ['_BackendEnumMeta', '_NerBackend', '_HfBackend', '_SpacyBackend']" + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Extracts predefined entities out of a piece of text. + category_slug: haystack-api + title: Extractors + slug: extractors-api + order: 65 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: extractors_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/fetchers_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/fetchers_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..9e021d3ef4527f3e502dfd90b558061628a7305c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/fetchers_api.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/fetchers] + modules: ["link_content"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Fetches content from a list of URLs and returns a list of extracted content streams. + category_slug: haystack-api + title: Fetchers + slug: fetchers-api + order: 80 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: fetchers_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/generators_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/generators_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..4fcfa74879922375ef2a7a6d7d4f3d051546e0fc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/generators_api.yml @@ -0,0 +1,37 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/generators] + modules: + [ + "azure", + "hugging_face_local", + "hugging_face_api", + "openai", + "chat/azure", + "chat/hugging_face_local", + "chat/hugging_face_api", + "chat/openai", + ] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Enables text generation using LLMs. + category_slug: haystack-api + title: Generators + slug: generators-api + order: 70 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: generators_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/joiners_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/joiners_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..6b7d422166641c493af45ab5ef6c0b1af8a10b96 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/joiners_api.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/joiners] + modules: ["document_joiner", "branch", "answer_joiner"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Components that join list of different objects + category_slug: haystack-api + title: Joiners + slug: joiners-api + order: 75 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: joiners_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/pipeline_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/pipeline_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..d720152510ae3b06f367fbc593991882084cb744 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/pipeline_api.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/core/pipeline] + modules: ["pipeline"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Arranges components and integrations in flow. + category_slug: haystack-api + title: Pipeline + slug: pipeline-api + order: 90 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: pipeline_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/preprocessors_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/preprocessors_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..c27e01be340f3cfb1eeb618a86c45278ba2e1690 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/preprocessors_api.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/preprocessors] + modules: ["document_cleaner", "document_splitter", "text_cleaner", "nltk_document_splitter"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Preprocess your Documents and texts. Clean, split, and more. + category_slug: haystack-api + title: PreProcessors + slug: preprocessors-api + order: 100 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: preprocessors_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/rankers_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/rankers_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..31dc468ad863357e39822e3f8f9f74646b04022f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/rankers_api.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/rankers] + modules: ["lost_in_the_middle", "meta_field", "transformers_similarity", "sentence_transformers_diversity"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Reorders a set of Documents based on their relevance to the query. + category_slug: haystack-api + title: Rankers + slug: rankers-api + order: 110 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: rankers_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/readers_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/readers_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..ef0974b78ae19473c812d124497c9a9c94678e64 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/readers_api.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/readers] + modules: ["extractive"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Takes a query and a set of Documents as input and returns ExtractedAnswers by selecting a text span within the Documents. + category_slug: haystack-api + title: Readers + slug: readers-api + order: 120 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: readers_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/retrievers_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/retrievers_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..c7f0e8ebd1ca70a09890629311c4b6adb099ff16 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/retrievers_api.yml @@ -0,0 +1,33 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/retrievers] + modules: + [ + "in_memory/bm25_retriever", + "in_memory/embedding_retriever", + "filter_retriever", + "sentence_window_retriever", + ] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Sweeps through a Document Store and returns a set of candidate Documents that are relevant to the query. + category_slug: haystack-api + title: Retrievers + slug: retrievers-api + order: 130 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: retrievers_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/routers_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/routers_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..126d08d7ea1fdf5f16b51bb1849b54f1959c43ef --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/routers_api.yml @@ -0,0 +1,35 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/routers] + modules: + [ + "conditional_router", + "file_type_router", + "metadata_router", + "text_language_router", + "transformers_text_router", + "zero_shot_text_router", + ] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Routers is a group of components that route queries or Documents to other components that can handle them best. + category_slug: haystack-api + title: Routers + slug: routers-api + order: 140 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: routers_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/samplers_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/samplers_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..f0a5bdbca98ff96fa7f3418456ff5ec87a19b1a2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/samplers_api.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/samplers] + modules: ["top_p"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Filters documents based on their similarity scores using top-p sampling. + category_slug: haystack-api + title: Samplers + slug: samplers-api + order: 150 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: samplers_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/utils_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/utils_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..3b32a0276d5a71cf6b05cb238802ae2f4f67ecbd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/utils_api.yml @@ -0,0 +1,28 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/utils] + ignore_when_discovered: ["__init__", "hf"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: filter + expression: "name not in ['TokenSecret', 'EnvVarSecret','_get_default_device', '_split_device_string', 'convert']" + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Utility functions and classes used across the library. + category_slug: haystack-api + title: Utils + slug: utils-api + order: 153 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: utils_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/validators_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/validators_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..48b452eeeb5a4d4fec1f4a36ee47fd36f8040d1e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/validators_api.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/validators] + modules: ["json_schema"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Validators validate LLM outputs + category_slug: haystack-api + title: Validators + slug: validators-api + order: 155 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: validators_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/websearch_api.yml b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/websearch_api.yml new file mode 100644 index 0000000000000000000000000000000000000000..daa08fd5f1bcbb28c823db2992668d5d439d755c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/docs/pydoc/config/websearch_api.yml @@ -0,0 +1,27 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../../../haystack/components/websearch] + modules: ["serper_dev", "searchapi"] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeCoreRenderer + excerpt: Web search engine for Haystack. + category_slug: haystack-api + title: Websearch + slug: websearch-api + order: 170 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: websearch_api.md diff --git a/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_dense_doc_search.py b/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_dense_doc_search.py new file mode 100644 index 0000000000000000000000000000000000000000..39a587a10624049544039a46fd252596fc04d238 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_dense_doc_search.py @@ -0,0 +1,85 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json + +from haystack import Pipeline +from haystack.components.converters import PyPDFToDocument, TextFileToDocument +from haystack.components.embedders import SentenceTransformersDocumentEmbedder, SentenceTransformersTextEmbedder +from haystack.components.joiners import DocumentJoiner +from haystack.components.preprocessors import DocumentCleaner, DocumentSplitter +from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever +from haystack.components.routers import FileTypeRouter +from haystack.components.writers import DocumentWriter +from haystack.document_stores.in_memory import InMemoryDocumentStore + + +def test_dense_doc_search_pipeline(tmp_path, samples_path): + # Create the indexing pipeline + indexing_pipeline = Pipeline() + indexing_pipeline.add_component( + instance=FileTypeRouter(mime_types=["text/plain", "application/pdf"]), name="file_type_router" + ) + indexing_pipeline.add_component(instance=TextFileToDocument(), name="text_file_converter") + indexing_pipeline.add_component(instance=PyPDFToDocument(), name="pdf_file_converter") + indexing_pipeline.add_component(instance=DocumentJoiner(), name="joiner") + indexing_pipeline.add_component(instance=DocumentCleaner(), name="cleaner") + indexing_pipeline.add_component( + instance=DocumentSplitter(split_by="sentence", split_length=250, split_overlap=30), name="splitter" + ) + indexing_pipeline.add_component( + instance=SentenceTransformersDocumentEmbedder(model="sentence-transformers/all-MiniLM-L6-v2"), name="embedder" + ) + indexing_pipeline.add_component(instance=DocumentWriter(document_store=InMemoryDocumentStore()), name="writer") + + indexing_pipeline.connect("file_type_router.text/plain", "text_file_converter.sources") + indexing_pipeline.connect("file_type_router.application/pdf", "pdf_file_converter.sources") + indexing_pipeline.connect("text_file_converter.documents", "joiner.documents") + indexing_pipeline.connect("pdf_file_converter.documents", "joiner.documents") + indexing_pipeline.connect("joiner.documents", "cleaner.documents") + indexing_pipeline.connect("cleaner.documents", "splitter.documents") + indexing_pipeline.connect("splitter.documents", "embedder.documents") + indexing_pipeline.connect("embedder.documents", "writer.documents") + + # Draw the indexing pipeline + indexing_pipeline.draw(tmp_path / "test_dense_doc_search_indexing_pipeline.png") + + # Serialize the indexing pipeline to YAML. + with open(tmp_path / "test_dense_doc_search_indexing_pipeline.yaml", "w") as f: + indexing_pipeline.dump(f) + + # Load the indexing pipeline back + with open(tmp_path / "test_dense_doc_search_indexing_pipeline.yaml", "r") as f: + indexing_pipeline = Pipeline.load(f) + + indexing_result = indexing_pipeline.run({"file_type_router": {"sources": list(samples_path.iterdir())}}) + filled_document_store = indexing_pipeline.get_component("writer").document_store + + assert indexing_result["writer"]["documents_written"] == 2 + assert filled_document_store.count_documents() == 2 + + # Create the querying pipeline + query_pipeline = Pipeline() + query_pipeline.add_component( + instance=SentenceTransformersTextEmbedder(model="sentence-transformers/all-MiniLM-L6-v2"), name="text_embedder" + ) + query_pipeline.add_component( + instance=InMemoryEmbeddingRetriever(document_store=filled_document_store, top_k=20), name="embedding_retriever" + ) + query_pipeline.connect("text_embedder", "embedding_retriever") + + querying_result = query_pipeline.run({"text_embedder": {"text": "Who lives in Rome?"}}) + assert querying_result["embedding_retriever"]["documents"][0].content == "My name is Giorgio and I live in Rome." + + # Draw the querying pipeline + query_pipeline.draw(tmp_path / "test_dense_doc_search_query_pipeline.png") + + # Serialize the querying pipeline to JSON + with open(tmp_path / "test_dense_doc_search_query_pipeline.json", "w") as f: + print(json.dumps(query_pipeline.to_dict(), indent=4)) + json.dump(query_pipeline.to_dict(), f) + + # Load the querying pipeline back + with open(tmp_path / "test_dense_doc_search_query_pipeline.json", "r") as f: + query_pipeline = Pipeline.from_dict(json.load(f)) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_evaluation_pipeline.py b/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_evaluation_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..1cd41fa4d8b7b0cc9caa4b92dca013ba4b12c8b4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_evaluation_pipeline.py @@ -0,0 +1,292 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +from typing import List + +import pytest + +from haystack import Document, Pipeline +from haystack.components.builders import AnswerBuilder, PromptBuilder +from haystack.components.embedders import SentenceTransformersDocumentEmbedder, SentenceTransformersTextEmbedder +from haystack.components.evaluators import ( + ContextRelevanceEvaluator, + DocumentMAPEvaluator, + DocumentMRREvaluator, + DocumentRecallEvaluator, + FaithfulnessEvaluator, + SASEvaluator, +) +from haystack.components.evaluators.document_recall import RecallMode +from haystack.components.generators import OpenAIGenerator +from haystack.components.retrievers import InMemoryEmbeddingRetriever +from haystack.components.writers import DocumentWriter +from haystack.document_stores.in_memory import InMemoryDocumentStore +from haystack.document_stores.types import DuplicatePolicy +from haystack.evaluation import EvaluationRunResult + +EMBEDDINGS_MODEL = "sentence-transformers/all-MiniLM-L6-v2" + + +def indexing_pipeline(documents: List[Document]): + """Indexing the documents""" + document_store = InMemoryDocumentStore() + doc_writer = DocumentWriter(document_store=document_store, policy=DuplicatePolicy.SKIP) + doc_embedder = SentenceTransformersDocumentEmbedder(model=EMBEDDINGS_MODEL, progress_bar=False) + ingestion_pipe = Pipeline() + ingestion_pipe.add_component(instance=doc_embedder, name="doc_embedder") # type: ignore + ingestion_pipe.add_component(instance=doc_writer, name="doc_writer") # type: ignore + ingestion_pipe.connect("doc_embedder.documents", "doc_writer.documents") + ingestion_pipe.run({"doc_embedder": {"documents": documents}}) + return document_store + + +def rag_pipeline(document_store: InMemoryDocumentStore, top_k: int): # type: ignore + """RAG pipeline""" + template = """ + You have to answer the following question based on the given context information only. + + Context: + {% for document in documents %} + {{ document.content }} + {% endfor %} + + Question: {{question}} + Answer: + """ + rag = Pipeline() + rag.add_component("embedder", SentenceTransformersTextEmbedder(model=EMBEDDINGS_MODEL, progress_bar=False)) # type: ignore + rag.add_component("retriever", InMemoryEmbeddingRetriever(document_store, top_k=top_k)) # type: ignore + rag.add_component("prompt_builder", PromptBuilder(template=template)) # type: ignore + rag.add_component("generator", OpenAIGenerator(model="gpt-4o-mini")) # type: ignore + rag.add_component("answer_builder", AnswerBuilder()) # type: ignore + rag.connect("embedder", "retriever.query_embedding") + rag.connect("retriever", "prompt_builder.documents") + rag.connect("prompt_builder", "generator") + rag.connect("generator.replies", "answer_builder.replies") + rag.connect("generator.meta", "answer_builder.meta") + rag.connect("retriever", "answer_builder.documents") + + return rag + + +def evaluation_pipeline(): + """ + Create an evaluation pipeline with the following evaluators: + + - DocumentMRREvaluator + - FaithfulnessEvaluator + - SASEvaluator + - DocumentMAPEvaluator + - DocumentRecallEvaluator + - ContextRelevanceEvaluator + """ + eval_pipeline = Pipeline() + eval_pipeline.add_component("doc_mrr", DocumentMRREvaluator()) + eval_pipeline.add_component("groundedness", FaithfulnessEvaluator()) + eval_pipeline.add_component("sas", SASEvaluator(model=EMBEDDINGS_MODEL)) + eval_pipeline.add_component("doc_map", DocumentMAPEvaluator()) + eval_pipeline.add_component("doc_recall_single_hit", DocumentRecallEvaluator(mode=RecallMode.SINGLE_HIT)) + eval_pipeline.add_component("doc_recall_multi_hit", DocumentRecallEvaluator(mode=RecallMode.MULTI_HIT)) + eval_pipeline.add_component("relevance", ContextRelevanceEvaluator()) + + return eval_pipeline + + +def built_eval_input(questions, truth_docs, truth_answers, retrieved_docs, contexts, pred_answers): + """Helper function to build the input for the evaluation pipeline""" + return { + "doc_mrr": {"ground_truth_documents": truth_docs, "retrieved_documents": retrieved_docs}, + "groundedness": {"questions": questions, "contexts": contexts, "predicted_answers": pred_answers}, + "sas": {"predicted_answers": pred_answers, "ground_truth_answers": truth_answers}, + "doc_map": {"ground_truth_documents": truth_docs, "retrieved_documents": retrieved_docs}, + "doc_recall_single_hit": {"ground_truth_documents": truth_docs, "retrieved_documents": retrieved_docs}, + "doc_recall_multi_hit": {"ground_truth_documents": truth_docs, "retrieved_documents": retrieved_docs}, + "relevance": {"questions": questions, "contexts": contexts}, + } + + +def run_rag_pipeline(documents, evaluation_questions, rag_pipeline_a): + """ + Run the RAG pipeline and return the contexts, predicted answers, retrieved documents and ground truth documents + """ + + truth_docs = [] + retrieved_docs = [] + contexts = [] + predicted_answers = [] + + for q in evaluation_questions: + response = rag_pipeline_a.run( + { + "embedder": {"text": q["question"]}, + "prompt_builder": {"question": q["question"]}, + "answer_builder": {"query": q["question"]}, + } + ) + truth_docs.append([doc for doc in documents if doc.meta["name"] in q["ground_truth_doc"] and doc.content]) + retrieved_docs.append(response["answer_builder"]["answers"][0].documents) + contexts.append([doc.content for doc in response["answer_builder"]["answers"][0].documents]) + predicted_answers.append(response["answer_builder"]["answers"][0].data) + + return contexts, predicted_answers, retrieved_docs, truth_docs + + +def built_input_for_results_eval(rag_results): + """Helper function to build the input for the results evaluation""" + return { + "Mean Reciprocal Rank": { + "individual_scores": rag_results["doc_mrr"]["individual_scores"], + "score": rag_results["doc_mrr"]["score"], + }, + "Semantic Answer Similarity": { + "individual_scores": rag_results["sas"]["individual_scores"], + "score": rag_results["sas"]["score"], + }, + "Faithfulness": { + "individual_scores": rag_results["groundedness"]["individual_scores"], + "score": rag_results["groundedness"]["score"], + }, + "Document MAP": { + "individual_scores": rag_results["doc_map"]["individual_scores"], + "score": rag_results["doc_map"]["score"], + }, + "Document Recall Single Hit": { + "individual_scores": rag_results["doc_recall_single_hit"]["individual_scores"], + "score": rag_results["doc_recall_single_hit"]["score"], + }, + "Document Recall Multi Hit": { + "individual_scores": rag_results["doc_recall_multi_hit"]["individual_scores"], + "score": rag_results["doc_recall_multi_hit"]["score"], + }, + "Contextual Relevance": { + "individual_scores": rag_results["relevance"]["individual_scores"], + "score": rag_results["relevance"]["score"], + }, + } + + +@pytest.mark.skipif( + not os.environ.get("OPENAI_API_KEY", None), + reason="Export an env var called OPENAI_API_KEY containing the OpenAI API key to run this test.", +) +def test_evaluation_pipeline(samples_path): + """Test an evaluation pipeline""" + eval_questions = [ + { + "question": 'What falls within the term "cultural anthropology"?', + "answer": "the ideology and analytical stance of cultural relativism", + "ground_truth_doc": ["Culture.txt"], + }, + { + "question": "Who was the spiritual guide during the Protestant Reformation?", + "answer": "Martin Bucer", + "ground_truth_doc": ["Strasbourg.txt"], + }, + { + "question": "What is materialism?", + "answer": "a form of philosophical monism", + "ground_truth_doc": ["Materialism.txt"], + }, + ] + + questions = [q["question"] for q in eval_questions] + truth_answers = [q["answer"] for q in eval_questions] + + # indexing documents + docs = [] + full_path = os.path.join(str(samples_path) + "/test_documents/") + for article in os.listdir(full_path): + with open(f"{full_path}/{article}", "r") as f: + for text in f.read().split("\n"): + if doc := Document(content=text, meta={"name": article}) if text else None: + docs.append(doc) + doc_store = indexing_pipeline(docs) + + # running the RAG pipeline A + evaluation pipeline + rag_pipeline_a = rag_pipeline(doc_store, top_k=2) + contexts_a, pred_answers_a, retrieved_docs_a, truth_docs = run_rag_pipeline(docs, eval_questions, rag_pipeline_a) + eval_pipeline = evaluation_pipeline() + eval_input = built_eval_input(questions, truth_docs, truth_answers, retrieved_docs_a, contexts_a, pred_answers_a) + results_rag_a = eval_pipeline.run(eval_input) + + # running the evaluation EvaluationRunResult + inputs_a = { + "question": questions, + "contexts": contexts_a, + "answer": truth_answers, + "predicted_answer": pred_answers_a, + } + results_a = built_input_for_results_eval(results_rag_a) + evaluation_result_a = EvaluationRunResult(run_name="rag_pipeline_a", results=results_a, inputs=inputs_a) + df_score_report = evaluation_result_a.score_report() + + # assert the score report has all the metrics + assert len(df_score_report) == 7 + assert list(df_score_report.columns) == ["metrics", "score"] + assert list(df_score_report.metrics) == [ + "Mean Reciprocal Rank", + "Semantic Answer Similarity", + "Faithfulness", + "Document MAP", + "Document Recall Single Hit", + "Document Recall Multi Hit", + "Contextual Relevance", + ] + + # assert the evaluation result has all the metrics, inputs and questions + df = evaluation_result_a.to_pandas() + assert list(df.columns) == [ + "question", + "contexts", + "answer", + "predicted_answer", + "Mean Reciprocal Rank", + "Semantic Answer Similarity", + "Faithfulness", + "Document MAP", + "Document Recall Single Hit", + "Document Recall Multi Hit", + "Contextual Relevance", + ] + assert len(df) == 3 + + # running the RAG pipeline B + rag_pipeline_b = rag_pipeline(doc_store, top_k=4) + contexts_b, pred_answers_b, retrieved_docs_b, truth_docs = run_rag_pipeline(docs, eval_questions, rag_pipeline_b) + eval_input = built_eval_input(questions, truth_docs, truth_answers, retrieved_docs_b, contexts_b, pred_answers_b) + results_rag_b = eval_pipeline.run(eval_input) + + inputs_b = { + "question": questions, + "contexts": contexts_b, + "answer": truth_answers, + "predicted_answer": pred_answers_b, + } + results_b = built_input_for_results_eval(results_rag_b) + evaluation_result_b = EvaluationRunResult(run_name="rag_pipeline_b", results=results_b, inputs=inputs_b) + df_comparative = evaluation_result_a.comparative_individual_scores_report(evaluation_result_b) + + # assert the comparative score report has all the metrics, inputs and questions + assert len(df_comparative) == 3 + assert list(df_comparative.columns) == [ + "question", + "contexts", + "answer", + "predicted_answer", + "rag_pipeline_a_Mean Reciprocal Rank", + "rag_pipeline_a_Semantic Answer Similarity", + "rag_pipeline_a_Faithfulness", + "rag_pipeline_a_Document MAP", + "rag_pipeline_a_Document Recall Single Hit", + "rag_pipeline_a_Document Recall Multi Hit", + "rag_pipeline_a_Contextual Relevance", + "rag_pipeline_b_Mean Reciprocal Rank", + "rag_pipeline_b_Semantic Answer Similarity", + "rag_pipeline_b_Faithfulness", + "rag_pipeline_b_Document MAP", + "rag_pipeline_b_Document Recall Single Hit", + "rag_pipeline_b_Document Recall Multi Hit", + "rag_pipeline_b_Contextual Relevance", + ] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_extractive_qa_pipeline.py b/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_extractive_qa_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..d30f69cef3d0c5ed268b02437650fc067f1e5e7f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_extractive_qa_pipeline.py @@ -0,0 +1,73 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json + +from haystack import Document, Pipeline +from haystack.components.readers import ExtractiveReader +from haystack.components.retrievers.in_memory import InMemoryBM25Retriever +from haystack.document_stores.in_memory import InMemoryDocumentStore + + +def test_extractive_qa_pipeline(tmp_path): + # Create the pipeline + qa_pipeline = Pipeline() + qa_pipeline.add_component(instance=InMemoryBM25Retriever(document_store=InMemoryDocumentStore()), name="retriever") + qa_pipeline.add_component(instance=ExtractiveReader(model="deepset/tinyroberta-squad2"), name="reader") + qa_pipeline.connect("retriever", "reader") + + # Draw the pipeline + qa_pipeline.draw(tmp_path / "test_extractive_qa_pipeline.png") + + # Serialize the pipeline to YAML + with open(tmp_path / "test_bm25_rag_pipeline.yaml", "w") as f: + qa_pipeline.dump(f) + + # Load the pipeline back + with open(tmp_path / "test_bm25_rag_pipeline.yaml", "r") as f: + qa_pipeline = Pipeline.load(f) + + # Populate the document store + documents = [ + Document(content="My name is Jean and I live in Paris."), + Document(content="My name is Mark and I live in Berlin."), + Document(content="My name is Giorgio and I live in Rome."), + ] + qa_pipeline.get_component("retriever").document_store.write_documents(documents) + + # Query and assert + questions = ["Who lives in Paris?", "Who lives in Berlin?", "Who lives in Rome?"] + answers_spywords = ["Jean", "Mark", "Giorgio"] + + for question, spyword, doc in zip(questions, answers_spywords, documents): + result = qa_pipeline.run({"retriever": {"query": question}, "reader": {"query": question}}) + + extracted_answers = result["reader"]["answers"] + + # we expect at least one real answer and no_answer + assert len(extracted_answers) > 1 + + # the best answer should contain the spyword + assert spyword in extracted_answers[0].data + + # no_answer + assert extracted_answers[-1].data is None + + # since these questions are easily answerable, the best answer should have higher score than no_answer + assert extracted_answers[0].score >= extracted_answers[-1].score + + for answer in extracted_answers: + assert answer.query == question + + assert hasattr(answer, "score") + assert hasattr(answer, "document_offset") + + assert hasattr(answer, "document") + + # the top answer is extracted from the correct document + top_answer = extracted_answers[0] + if top_answer.document is not None: + if top_answer.document.id != doc.id: + print(top_answer.document.id, doc.id) + assert top_answer.document.id == doc.id diff --git a/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_hybrid_doc_search_pipeline.py b/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_hybrid_doc_search_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..2e4da6f449433c765e57d53a6ef7f80ded9f56d4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_hybrid_doc_search_pipeline.py @@ -0,0 +1,61 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + + +from haystack import Document, Pipeline +from haystack.components.embedders import SentenceTransformersDocumentEmbedder, SentenceTransformersTextEmbedder +from haystack.components.joiners.document_joiner import DocumentJoiner +from haystack.components.rankers import TransformersSimilarityRanker +from haystack.components.retrievers.in_memory import InMemoryBM25Retriever, InMemoryEmbeddingRetriever +from haystack.document_stores.in_memory import InMemoryDocumentStore + + +def test_hybrid_doc_search_pipeline(tmp_path): + # Create the pipeline + document_store = InMemoryDocumentStore() + hybrid_pipeline = Pipeline() + hybrid_pipeline.add_component(instance=InMemoryBM25Retriever(document_store=document_store), name="bm25_retriever") + hybrid_pipeline.add_component( + instance=SentenceTransformersTextEmbedder(model="sentence-transformers/all-MiniLM-L6-v2"), name="text_embedder" + ) + hybrid_pipeline.add_component( + instance=InMemoryEmbeddingRetriever(document_store=document_store), name="embedding_retriever" + ) + hybrid_pipeline.add_component(instance=DocumentJoiner(), name="joiner") + hybrid_pipeline.add_component(instance=TransformersSimilarityRanker(top_k=20), name="ranker") + + hybrid_pipeline.connect("bm25_retriever", "joiner") + hybrid_pipeline.connect("text_embedder", "embedding_retriever") + hybrid_pipeline.connect("embedding_retriever", "joiner") + hybrid_pipeline.connect("joiner", "ranker") + + # Draw the pipeline + hybrid_pipeline.draw(tmp_path / "test_hybrid_doc_search_pipeline.png") + + # Serialize the pipeline to YAML + with open(tmp_path / "test_hybrid_doc_search_pipeline.yaml", "w") as f: + hybrid_pipeline.dump(f) + + # Load the pipeline back + with open(tmp_path / "test_hybrid_doc_search_pipeline.yaml", "r") as f: + hybrid_pipeline = Pipeline.load(f) + + # Populate the document store + documents = [ + Document(content="My name is Jean and I live in Paris."), + Document(content="My name is Mark and I live in Berlin."), + Document(content="My name is Mario and I live in the capital of Italy."), + Document(content="My name is Giorgio and I live in Rome."), + ] + doc_embedder = SentenceTransformersDocumentEmbedder(model="sentence-transformers/all-MiniLM-L6-v2") + doc_embedder.warm_up() + embedded_documents = doc_embedder.run(documents=documents)["documents"] + hybrid_pipeline.get_component("embedding_retriever").document_store.write_documents(embedded_documents) + + query = "Who lives in Rome?" + result = hybrid_pipeline.run( + {"bm25_retriever": {"query": query}, "text_embedder": {"text": query}, "ranker": {"query": query}} + ) + assert result["ranker"]["documents"][0].content == "My name is Giorgio and I live in Rome." + assert result["ranker"]["documents"][1].content == "My name is Mario and I live in the capital of Italy." diff --git a/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_named_entity_extractor.py b/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_named_entity_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc15a9a1a29c9e3d7ca77180e4f8b4fe3457190 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_named_entity_extractor.py @@ -0,0 +1,108 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import pytest + +from haystack import Document, Pipeline +from haystack.components.extractors import NamedEntityAnnotation, NamedEntityExtractor, NamedEntityExtractorBackend + + +@pytest.fixture +def raw_texts(): + return [ + "My name is Clara and I live in Berkeley, California.", + "I'm Merlin, the happy pig!", + "New York State declared a state of emergency after the announcement of the end of the world.", + "", # Intentionally empty. + ] + + +@pytest.fixture +def hf_annotations(): + return [ + [ + NamedEntityAnnotation(entity="PER", start=11, end=16), + NamedEntityAnnotation(entity="LOC", start=31, end=39), + NamedEntityAnnotation(entity="LOC", start=41, end=51), + ], + [NamedEntityAnnotation(entity="PER", start=4, end=10)], + [NamedEntityAnnotation(entity="LOC", start=0, end=14)], + [], + ] + + +@pytest.fixture +def spacy_annotations(): + return [ + [ + NamedEntityAnnotation(entity="PERSON", start=11, end=16), + NamedEntityAnnotation(entity="GPE", start=31, end=39), + NamedEntityAnnotation(entity="GPE", start=41, end=51), + ], + [NamedEntityAnnotation(entity="PERSON", start=4, end=10)], + [NamedEntityAnnotation(entity="GPE", start=0, end=14)], + [], + ] + + +def test_ner_extractor_init(): + extractor = NamedEntityExtractor(backend=NamedEntityExtractorBackend.HUGGING_FACE, model="dslim/bert-base-NER") + + with pytest.raises(RuntimeError, match=r"not warmed up"): + extractor.run(documents=[]) + + assert not extractor.initialized + extractor.warm_up() + assert extractor.initialized + + +@pytest.mark.parametrize("batch_size", [1, 3]) +def test_ner_extractor_hf_backend(raw_texts, hf_annotations, batch_size): + extractor = NamedEntityExtractor(backend=NamedEntityExtractorBackend.HUGGING_FACE, model="dslim/bert-base-NER") + extractor.warm_up() + + _extract_and_check_predictions(extractor, raw_texts, hf_annotations, batch_size) + + +@pytest.mark.parametrize("batch_size", [1, 3]) +def test_ner_extractor_spacy_backend(raw_texts, spacy_annotations, batch_size): + extractor = NamedEntityExtractor(backend=NamedEntityExtractorBackend.SPACY, model="en_core_web_trf") + extractor.warm_up() + + _extract_and_check_predictions(extractor, raw_texts, spacy_annotations, batch_size) + + +@pytest.mark.parametrize("batch_size", [1, 3]) +def test_ner_extractor_in_pipeline(raw_texts, hf_annotations, batch_size): + pipeline = Pipeline() + pipeline.add_component( + name="ner_extractor", + instance=NamedEntityExtractor(backend=NamedEntityExtractorBackend.HUGGING_FACE, model="dslim/bert-base-NER"), + ) + + outputs = pipeline.run( + {"ner_extractor": {"documents": [Document(content=text) for text in raw_texts], "batch_size": batch_size}} + )["ner_extractor"]["documents"] + predicted = [NamedEntityExtractor.get_stored_annotations(doc) for doc in outputs] + _check_predictions(predicted, hf_annotations) + + +def _extract_and_check_predictions(extractor, texts, expected, batch_size): + docs = [Document(content=text) for text in texts] + outputs = extractor.run(documents=docs, batch_size=batch_size)["documents"] + assert all(id(a) == id(b) for a, b in zip(docs, outputs)) + predicted = [NamedEntityExtractor.get_stored_annotations(doc) for doc in outputs] + + _check_predictions(predicted, expected) + + +def _check_predictions(predicted, expected): + assert len(predicted) == len(expected) + for pred, exp in zip(predicted, expected): + assert len(pred) == len(exp) + + for a, b in zip(pred, exp): + assert a.entity == b.entity + assert a.start == b.start + assert a.end == b.end diff --git a/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_preprocessing_pipeline.py b/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_preprocessing_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..82375f89d8ed0381a21d3a3db279c5fd7c587222 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_preprocessing_pipeline.py @@ -0,0 +1,91 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json + +from haystack import Pipeline +from haystack.components.classifiers import DocumentLanguageClassifier +from haystack.components.converters import TextFileToDocument +from haystack.components.embedders import SentenceTransformersDocumentEmbedder +from haystack.components.preprocessors import DocumentCleaner, DocumentSplitter +from haystack.components.routers import FileTypeRouter, MetadataRouter +from haystack.components.writers import DocumentWriter +from haystack.document_stores.in_memory import InMemoryDocumentStore + + +def test_preprocessing_pipeline(tmp_path): + # Create the pipeline and its components + document_store = InMemoryDocumentStore() + preprocessing_pipeline = Pipeline() + preprocessing_pipeline.add_component(instance=FileTypeRouter(mime_types=["text/plain"]), name="file_type_router") + preprocessing_pipeline.add_component(instance=TextFileToDocument(), name="text_file_converter") + preprocessing_pipeline.add_component(instance=DocumentLanguageClassifier(), name="language_classifier") + preprocessing_pipeline.add_component( + instance=MetadataRouter(rules={"en": {"field": "language", "operator": "==", "value": "en"}}), name="router" + ) + preprocessing_pipeline.add_component(instance=DocumentCleaner(), name="cleaner") + preprocessing_pipeline.add_component( + instance=DocumentSplitter(split_by="sentence", split_length=1), name="splitter" + ) + preprocessing_pipeline.add_component( + instance=SentenceTransformersDocumentEmbedder(model="sentence-transformers/all-MiniLM-L6-v2"), name="embedder" + ) + preprocessing_pipeline.add_component(instance=DocumentWriter(document_store=document_store), name="writer") + preprocessing_pipeline.connect("file_type_router.text/plain", "text_file_converter.sources") + preprocessing_pipeline.connect("text_file_converter.documents", "language_classifier.documents") + preprocessing_pipeline.connect("language_classifier.documents", "router.documents") + preprocessing_pipeline.connect("router.en", "cleaner.documents") + preprocessing_pipeline.connect("cleaner.documents", "splitter.documents") + preprocessing_pipeline.connect("splitter.documents", "embedder.documents") + preprocessing_pipeline.connect("embedder.documents", "writer.documents") + + # Draw the pipeline + preprocessing_pipeline.draw(tmp_path / "test_preprocessing_pipeline.png") + + # Serialize the pipeline to YAML + with open(tmp_path / "test_preprocessing_pipeline.yaml", "w") as f: + preprocessing_pipeline.dump(f) + + # Load the pipeline back + with open(tmp_path / "test_preprocessing_pipeline.yaml", "r") as f: + preprocessing_pipeline = Pipeline.load(f) + + # Write a txt file + with open(tmp_path / "test_file_english.txt", "w") as f: + f.write( + "This is an english sentence. There is more to it. It's a long text." + "Spans multiple lines." + "" + "Even contains empty lines. And extra whitespaces." + ) + + # Write a txt file + with open(tmp_path / "test_file_german.txt", "w") as f: + f.write("Ein deutscher Satz ohne Verb.") + + # Add two txt files and one non-txt file + paths = [ + tmp_path / "test_file_english.txt", + tmp_path / "test_file_german.txt", + tmp_path / "test_preprocessing_pipeline.json", + ] + + result = preprocessing_pipeline.run({"file_type_router": {"sources": paths}}) + + assert result["writer"]["documents_written"] == 6 + filled_document_store = preprocessing_pipeline.get_component("writer").document_store + assert filled_document_store.count_documents() == 6 + + # Check preprocessed texts + stored_documents = filled_document_store.filter_documents() + expected_texts = [ + "This is an english sentence.", + " There is more to it.", + " It's a long text.", + "Spans multiple lines.", + "Even contains empty lines.", + " And extra whitespaces.", + ] + assert expected_texts == [document.content for document in stored_documents] + assert all(document.meta["language"] == "en" for document in stored_documents) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_rag_pipelines_e2e.py b/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_rag_pipelines_e2e.py new file mode 100644 index 0000000000000000000000000000000000000000..5727e9ee0ba00a31dac09345f1efbd665551cce8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/e2e/pipelines/test_rag_pipelines_e2e.py @@ -0,0 +1,163 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +import os + +import pytest + +from haystack import Document, Pipeline +from haystack.components.builders.answer_builder import AnswerBuilder +from haystack.components.builders.prompt_builder import PromptBuilder +from haystack.components.embedders import SentenceTransformersDocumentEmbedder, SentenceTransformersTextEmbedder +from haystack.components.generators import OpenAIGenerator +from haystack.components.retrievers.in_memory import InMemoryBM25Retriever, InMemoryEmbeddingRetriever +from haystack.components.writers import DocumentWriter +from haystack.document_stores.in_memory import InMemoryDocumentStore + + +@pytest.mark.skipif( + not os.environ.get("OPENAI_API_KEY", None), + reason="Export an env var called OPENAI_API_KEY containing the OpenAI API key to run this test.", +) +def test_bm25_rag_pipeline(tmp_path): + # Create the RAG pipeline + prompt_template = """ + Given these documents, answer the question.\nDocuments: + {% for doc in documents %} + {{ doc.content }} + {% endfor %} + + \nQuestion: {{question}} + \nAnswer: + """ + rag_pipeline = Pipeline() + rag_pipeline.add_component(instance=InMemoryBM25Retriever(document_store=InMemoryDocumentStore()), name="retriever") + rag_pipeline.add_component(instance=PromptBuilder(template=prompt_template), name="prompt_builder") + rag_pipeline.add_component(instance=OpenAIGenerator(), name="llm") + rag_pipeline.add_component(instance=AnswerBuilder(), name="answer_builder") + rag_pipeline.connect("retriever", "prompt_builder.documents") + rag_pipeline.connect("prompt_builder", "llm") + rag_pipeline.connect("llm.replies", "answer_builder.replies") + rag_pipeline.connect("llm.meta", "answer_builder.meta") + rag_pipeline.connect("retriever", "answer_builder.documents") + + # Draw the pipeline + rag_pipeline.draw(tmp_path / "test_bm25_rag_pipeline.png") + + # Serialize the pipeline to YAML + with open(tmp_path / "test_bm25_rag_pipeline.yaml", "w") as f: + rag_pipeline.dump(f) + + # Load the pipeline back + with open(tmp_path / "test_bm25_rag_pipeline.yaml", "r") as f: + rag_pipeline = Pipeline.load(f) + + # Populate the document store + documents = [ + Document(content="My name is Jean and I live in Paris."), + Document(content="My name is Mark and I live in Berlin."), + Document(content="My name is Giorgio and I live in Rome."), + ] + rag_pipeline.get_component("retriever").document_store.write_documents(documents) + + # Query and assert + questions = ["Who lives in Paris?", "Who lives in Berlin?", "Who lives in Rome?"] + answers_spywords = ["Jean", "Mark", "Giorgio"] + + for question, spyword in zip(questions, answers_spywords): + result = rag_pipeline.run( + { + "retriever": {"query": question}, + "prompt_builder": {"question": question}, + "answer_builder": {"query": question}, + } + ) + + assert len(result["answer_builder"]["answers"]) == 1 + generated_answer = result["answer_builder"]["answers"][0] + assert spyword in generated_answer.data + assert generated_answer.query == question + assert hasattr(generated_answer, "documents") + assert hasattr(generated_answer, "meta") + + +@pytest.mark.skipif( + not os.environ.get("OPENAI_API_KEY", None), + reason="Export an env var called OPENAI_API_KEY containing the OpenAI API key to run this test.", +) +def test_embedding_retrieval_rag_pipeline(tmp_path): + # Create the RAG pipeline + prompt_template = """ + Given these documents, answer the question.\nDocuments: + {% for doc in documents %} + {{ doc.content }} + {% endfor %} + + \nQuestion: {{question}} + \nAnswer: + """ + rag_pipeline = Pipeline() + rag_pipeline.add_component( + instance=SentenceTransformersTextEmbedder(model="sentence-transformers/all-MiniLM-L6-v2"), name="text_embedder" + ) + rag_pipeline.add_component( + instance=InMemoryEmbeddingRetriever(document_store=InMemoryDocumentStore()), name="retriever" + ) + rag_pipeline.add_component(instance=PromptBuilder(template=prompt_template), name="prompt_builder") + rag_pipeline.add_component(instance=OpenAIGenerator(), name="llm") + rag_pipeline.add_component(instance=AnswerBuilder(), name="answer_builder") + rag_pipeline.connect("text_embedder", "retriever") + rag_pipeline.connect("retriever", "prompt_builder.documents") + rag_pipeline.connect("prompt_builder", "llm") + rag_pipeline.connect("llm.replies", "answer_builder.replies") + rag_pipeline.connect("llm.meta", "answer_builder.meta") + rag_pipeline.connect("retriever", "answer_builder.documents") + + # Draw the pipeline + rag_pipeline.draw(tmp_path / "test_embedding_rag_pipeline.png") + + # Serialize the pipeline to JSON + with open(tmp_path / "test_embedding_rag_pipeline.json", "w") as f: + json.dump(rag_pipeline.to_dict(), f) + + # Load the pipeline back + with open(tmp_path / "test_embedding_rag_pipeline.json", "r") as f: + rag_pipeline = Pipeline.from_dict(json.load(f)) + + # Populate the document store + documents = [ + Document(content="My name is Jean and I live in Paris."), + Document(content="My name is Mark and I live in Berlin."), + Document(content="My name is Giorgio and I live in Rome."), + ] + document_store = rag_pipeline.get_component("retriever").document_store + indexing_pipeline = Pipeline() + indexing_pipeline.add_component( + instance=SentenceTransformersDocumentEmbedder(model="sentence-transformers/all-MiniLM-L6-v2"), + name="document_embedder", + ) + indexing_pipeline.add_component(instance=DocumentWriter(document_store=document_store), name="document_writer") + indexing_pipeline.connect("document_embedder", "document_writer") + indexing_pipeline.run({"document_embedder": {"documents": documents}}) + + # Query and assert + questions = ["Who lives in Paris?", "Who lives in Berlin?", "Who lives in Rome?"] + answers_spywords = ["Jean", "Mark", "Giorgio"] + + for question, spyword in zip(questions, answers_spywords): + result = rag_pipeline.run( + { + "text_embedder": {"text": question}, + "prompt_builder": {"question": question}, + "answer_builder": {"query": question}, + } + ) + + assert len(result["answer_builder"]["answers"]) == 1 + generated_answer = result["answer_builder"]["answers"][0] + assert spyword in generated_answer.data + assert generated_answer.query == question + assert hasattr(generated_answer, "documents") + assert hasattr(generated_answer, "meta") diff --git a/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/doc_1.txt b/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/doc_1.txt new file mode 100644 index 0000000000000000000000000000000000000000..1d3da15eb978b2a3108d8c06fa9ae55d65bd072d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/doc_1.txt @@ -0,0 +1 @@ +My name is Giorgio and I live in Rome. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/sample_pdf_1.pdf b/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/sample_pdf_1.pdf new file mode 100644 index 0000000000000000000000000000000000000000..87259b897f83b462f521276bf32d210ea008bcd3 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/sample_pdf_1.pdf differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/test_documents/Culture.txt b/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/test_documents/Culture.txt new file mode 100644 index 0000000000000000000000000000000000000000..64843b52c0657435b8233ebd44a2e62f4f98d7ae --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/test_documents/Culture.txt @@ -0,0 +1,24 @@ +Cambridge English Dictionary states that culture is, "the way of life, especially the general customs and beliefs, of a particular group of people at a particular time." Terror Management Theory posits that culture is a series of activities and worldviews that provide humans with the illusion of being individuals of value in a world meaning—raising themselves above the merely physical aspects of existence, in order to deny the animal insignificance and death that Homo Sapiens became aware of when they acquired a larger brain. +As a defining aspect of what it means to be human, culture is a central concept in anthropology, encompassing the range of phenomena that are transmitted through social learning in human societies. The word is used in a general sense as the evolved ability to categorize and represent experiences with symbols and to act imaginatively and creatively. This ability arose with the evolution of behavioral modernity in humans around 50,000 years ago.[citation needed] This capacity is often thought to be unique to humans, although some other species have demonstrated similar, though much less complex abilities for social learning. It is also used to denote the complex networks of practices and accumulated knowledge and ideas that is transmitted through social interaction and exist in specific human groups, or cultures, using the plural form. Some aspects of human behavior, such as language, social practices such as kinship, gender and marriage, expressive forms such as art, music, dance, ritual, religion, and technologies such as cooking, shelter, clothing are said to be cultural universals, found in all human societies. The concept material culture covers the physical expressions of culture, such as technology, architecture and art, whereas the immaterial aspects of culture such as principles of social organization (including, practices of political organization and social institutions), mythology, philosophy, literature (both written and oral), and science make up the intangible cultural heritage of a society. +In the humanities, one sense of culture, as an attribute of the individual, has been the degree to which they have cultivated a particular level of sophistication, in the arts, sciences, education, or manners. The level of cultural sophistication has also sometimes been seen to distinguish civilizations from less complex societies. Such hierarchical perspectives on culture are also found in class-based distinctions between a high culture of the social elite and a low culture, popular culture or folk culture of the lower classes, distinguished by the stratified access to cultural capital. In common parlance, culture is often used to refer specifically to the symbolic markers used by ethnic groups to distinguish themselves visibly from each other such as body modification, clothing or jewelry.[dubious – discuss] Mass culture refers to the mass-produced and mass mediated forms of consumer culture that emerged in the 20th century. Some schools of philosophy, such as Marxism and critical theory, have argued that culture is often used politically as a tool of the elites to manipulate the lower classes and create a false consciousness, such perspectives common in the discipline of cultural studies. In the wider social sciences, the theoretical perspective of cultural materialism holds that human symbolic culture arises from the material conditions of human life, as humans create the conditions for physical survival, and that the basis of culture is found in evolved biological dispositions. +When used as a count noun "a culture", is the set of customs, traditions and values of a society or community, such as an ethnic group or nation. In this sense, multiculturalism is a concept that values the peaceful coexistence and mutual respect between different cultures inhabiting the same territory. Sometimes "culture" is also used to describe specific practices within a subgroup of a society, a subculture (e.g. "bro culture"), or a counter culture. Within cultural anthropology, the ideology and analytical stance of cultural relativism holds that cultures cannot easily be objectively ranked or evaluated because any evaluation is necessarily situated within the value system of a given culture. +The modern term "culture" is based on a term used by the Ancient Roman orator Cicero in his Tusculanae Disputationes, where he wrote of a cultivation of the soul or "cultura animi", using an agricultural metaphor for the development of a philosophical soul, understood teleologically as the highest possible ideal for human development. Samuel Pufendorf took over this metaphor in a modern context, meaning something similar, but no longer assuming that philosophy was man's natural perfection. His use, and that of many writers after him "refers to all the ways in which human beings overcome their original barbarism, and through artifice, become fully human". +Social conflict and the development of technologies can produce changes within a society by altering social dynamics and promoting new cultural models, and spurring or enabling generative action. These social shifts may accompany ideological shifts and other types of cultural change. For example, the U.S. feminist movement involved new practices that produced a shift in gender relations, altering both gender and economic structures. Environmental conditions may also enter as factors. For example, after tropical forests returned at the end of the last ice age, plants suitable for domestication were available, leading to the invention of agriculture, which in turn brought about many cultural innovations and shifts in social dynamics. +Cultures are externally affected via contact between societies, which may also produce—or inhibit—social shifts and changes in cultural practices. War or competition over resources may impact technological development or social dynamics. Additionally, cultural ideas may transfer from one society to another, through diffusion or acculturation. In diffusion, the form of something (though not necessarily its meaning) moves from one culture to another. For example, hamburgers, fast food in the United States, seemed exotic when introduced into China. "Stimulus diffusion" (the sharing of ideas) refers to an element of one culture leading to an invention or propagation in another. "Direct Borrowing" on the other hand tends to refer to technological or tangible diffusion from one culture to another. Diffusion of innovations theory presents a research-based model of why and when individuals and cultures adopt new ideas, practices, and products. +Immanuel Kant (1724–1804) has formulated an individualist definition of "enlightenment" similar to the concept of bildung: "Enlightenment is man's emergence from his self-incurred immaturity." He argued that this immaturity comes not from a lack of understanding, but from a lack of courage to think independently. Against this intellectual cowardice, Kant urged: Sapere aude, "Dare to be wise!" In reaction to Kant, German scholars such as Johann Gottfried Herder (1744–1803) argued that human creativity, which necessarily takes unpredictable and highly diverse forms, is as important as human rationality. Moreover, Herder proposed a collective form of bildung: "For Herder, Bildung was the totality of experiences that provide a coherent identity, and sense of common destiny, to a people." +In 1795, the Prussian linguist and philosopher Wilhelm von Humboldt (1767–1835) called for an anthropology that would synthesize Kant's and Herder's interests. During the Romantic era, scholars in Germany, especially those concerned with nationalist movements—such as the nationalist struggle to create a "Germany" out of diverse principalities, and the nationalist struggles by ethnic minorities against the Austro-Hungarian Empire—developed a more inclusive notion of culture as "worldview" (Weltanschauung). According to this school of thought, each ethnic group has a distinct worldview that is incommensurable with the worldviews of other groups. Although more inclusive than earlier views, this approach to culture still allowed for distinctions between "civilized" and "primitive" or "tribal" cultures. +In 1860, Adolf Bastian (1826–1905) argued for "the psychic unity of mankind". He proposed that a scientific comparison of all human societies would reveal that distinct worldviews consisted of the same basic elements. According to Bastian, all human societies share a set of "elementary ideas" (Elementargedanken); different cultures, or different "folk ideas" (Völkergedanken), are local modifications of the elementary ideas. This view paved the way for the modern understanding of culture. Franz Boas (1858–1942) was trained in this tradition, and he brought it with him when he left Germany for the United States. +In practice, culture referred to an élite ideal and was associated with such activities as art, classical music, and haute cuisine. As these forms were associated with urban life, "culture" was identified with "civilization" (from lat. civitas, city). Another facet of the Romantic movement was an interest in folklore, which led to identifying a "culture" among non-elites. This distinction is often characterized as that between high culture, namely that of the ruling social group, and low culture. In other words, the idea of "culture" that developed in Europe during the 18th and early 19th centuries reflected inequalities within European societies. +Matthew Arnold contrasted "culture" with anarchy; other Europeans, following philosophers Thomas Hobbes and Jean-Jacques Rousseau, contrasted "culture" with "the state of nature". According to Hobbes and Rousseau, the Native Americans who were being conquered by Europeans from the 16th centuries on were living in a state of nature; this opposition was expressed through the contrast between "civilized" and "uncivilized." According to this way of thinking, one could classify some countries and nations as more civilized than others and some people as more cultured than others. This contrast led to Herbert Spencer's theory of Social Darwinism and Lewis Henry Morgan's theory of cultural evolution. Just as some critics have argued that the distinction between high and low cultures is really an expression of the conflict between European elites and non-elites, some critics have argued that the distinction between civilized and uncivilized people is really an expression of the conflict between European colonial powers and their colonial subjects. +Other 19th-century critics, following Rousseau have accepted this differentiation between higher and lower culture, but have seen the refinement and sophistication of high culture as corrupting and unnatural developments that obscure and distort people's essential nature. These critics considered folk music (as produced by "the folk", i.e., rural, illiterate, peasants) to honestly express a natural way of life, while classical music seemed superficial and decadent. Equally, this view often portrayed indigenous peoples as "noble savages" living authentic and unblemished lives, uncomplicated and uncorrupted by the highly stratified capitalist systems of the West. +Although anthropologists worldwide refer to Tylor's definition of culture, in the 20th century "culture" emerged as the central and unifying concept of American anthropology, where it most commonly refers to the universal human capacity to classify and encode human experiences symbolically, and to communicate symbolically encoded experiences socially.[citation needed] American anthropology is organized into four fields, each of which plays an important role in research on culture: biological anthropology, linguistic anthropology, cultural anthropology, and archaeology. +The sociology of culture concerns culture—usually understood as the ensemble of symbolic codes used by a society—as manifested in society. For Georg Simmel (1858–1918), culture referred to "the cultivation of individuals through the agency of external forms which have been objectified in the course of history". Culture in the sociological field can be defined as the ways of thinking, the ways of acting, and the material objects that together shape a people's way of life. Culture can be any of two types, non-material culture or material culture. Non-material culture refers to the non physical ideas that individuals have about their culture, including values, belief system, rules, norms, morals, language, organizations, and institutions. While Material culture is the physical evidence of a culture in the objects and architecture they make, or have made. The term tends to be relevant only in archeological and anthropological studies, but it specifically means all material evidence which can be attributed to culture past or present. +Cultural sociology first emerged in Weimar Germany (1918–1933), where sociologists such as Alfred Weber used the term Kultursoziologie (cultural sociology). Cultural sociology was then "reinvented" in the English-speaking world as a product of the "cultural turn" of the 1960s, which ushered in structuralist and postmodern approaches to social science. This type of cultural sociology may loosely be regarded as an approach incorporating cultural analysis and critical theory. Cultural sociologists tend to reject scientific methods,[citation needed] instead hermeneutically focusing on words, artifacts and symbols. "Culture" has since become an important concept across many branches of sociology, including resolutely scientific fields like social stratification and social network analysis. As a result, there has been a recent influx of quantitative sociologists to the field. Thus there is now a growing group of sociologists of culture who are, confusingly, not cultural sociologists. These scholars reject the abstracted postmodern aspects of cultural sociology, and instead look for a theoretical backing in the more scientific vein of social psychology and cognitive science. "Cultural sociology" is one of the largest sections of the American Sociological Association. The British establishment of cultural studies means the latter is often taught as a loosely distinct discipline in the UK. +The sociology of culture grew from the intersection between sociology (as shaped by early theorists like Marx, Durkheim, and Weber) with the growing discipline of anthropology, where in researchers pioneered ethnographic strategies for describing and analyzing a variety of cultures around the world. Part of the legacy of the early development of the field lingers in the methods (much of cultural sociological research is qualitative), in the theories (a variety of critical approaches to sociology are central to current research communities), and in the substantive focus of the field. For instance, relationships between popular culture, political control, and social class were early and lasting concerns in the field. +In the United Kingdom, sociologists and other scholars influenced by Marxism, such as Stuart Hall (1932–2014) and Raymond Williams (1921–1988), developed cultural studies. Following nineteenth-century Romantics, they identified "culture" with consumption goods and leisure activities (such as art, music, film, food, sports, and clothing). Nevertheless, they saw patterns of consumption and leisure as determined by relations of production, which led them to focus on class relations and the organization of production. +In the United States, "Cultural Studies" focuses largely on the study of popular culture, that is, on the social meanings of mass-produced consumer and leisure goods. Richard Hoggart coined the term in 1964 when he founded the Birmingham Centre for Contemporary Cultural Studies or CCCS. It has since become strongly associated with Stuart Hall, who succeeded Hoggart as Director. Cultural studies in this sense, then, can be viewed as a limited concentration scoped on the intricacies of consumerism, which belongs to a wider culture sometimes referred to as "Western Civilization" or as "Globalism." +From the 1970s onward, Stuart Hall's pioneering work, along with that of his colleagues Paul Willis, Dick Hebdige, Tony Jefferson, and Angela McRobbie, created an international intellectual movement. As the field developed it began to combine political economy, communication, sociology, social theory, literary theory, media theory, film/video studies, cultural anthropology, philosophy, museum studies and art history to study cultural phenomena or cultural texts. In this field researchers often concentrate on how particular phenomena relate to matters of ideology, nationality, ethnicity, social class, and/or gender.[citation needed] Cultural studies has a concern with the meaning and practices of everyday life. These practices comprise the ways people do particular things (such as watching television, or eating out) in a given culture. This field studies the meanings and uses people attribute to various objects and practices. Specifically, culture involves those meanings and practices held independently of reason. Watching television in order to view a public perspective on a historical event should not be thought of as culture, unless referring to the medium of television itself, which may have been selected culturally; however, schoolchildren watching television after school with their friends in order to "fit in" certainly qualifies, since there is no grounded reason for one's participation in this practice. Recently, as capitalism has spread throughout the world (a process called globalization), cultural studies has begun[when?] to analyze local and global forms of resistance to Western hegemony.[citation needed] Globalization in this context can be defined as western civilization in other ways, it undermines the cultural integrity of other culture and it is therefore repressive, exploitative and harmful to most people in different places. +In the context of cultural studies, the idea of a text includes not only written language, but also films, photographs, fashion or hairstyles: the texts of cultural studies comprise all the meaningful artifacts of culture.[citation needed] Similarly, the discipline widens the concept of "culture". "Culture" for a cultural-studies researcher not only includes traditional high culture (the culture of ruling social groups) and popular culture, but also everyday meanings and practices. The last two, in fact, have become the main focus of cultural studies. A further and recent approach is comparative cultural studies, based on the disciplines of comparative literature and cultural studies.[citation needed] +Scholars in the United Kingdom and the United States developed somewhat different versions of cultural studies after the late 1970s. The British version of cultural studies had originated in the 1950s and 1960s, mainly under the influence first of Richard Hoggart, E. P. Thompson, and Raymond Williams, and later that of Stuart Hall and others at the Centre for Contemporary Cultural Studies at the University of Birmingham. This included overtly political, left-wing views, and criticisms of popular culture as "capitalist" mass culture; it absorbed some of the ideas of the Frankfurt School critique of the "culture industry" (i.e. mass culture). This emerges in the writings of early British cultural-studies scholars and their influences: see the work of (for example) Raymond Williams, Stuart Hall, Paul Willis, and Paul Gilroy. +In the United States, Lindlof and Taylor write, "Cultural studies [were] grounded in a pragmatic, liberal-pluralist tradition". The American version of cultural studies initially concerned itself more with understanding the subjective and appropriative side of audience reactions to, and uses of, mass culture; for example, American cultural-studies advocates wrote about the liberatory aspects of fandom.[citation needed] The distinction between American and British strands, however, has faded.[citation needed] Some researchers, especially in early British cultural studies, apply a Marxist model to the field. This strain of thinking has some influence from the Frankfurt School, but especially from the structuralist Marxism of Louis Althusser and others. The main focus of an orthodox Marxist approach concentrates on the production of meaning. This model assumes a mass production of culture and identifies power as residing with those producing cultural artifacts. In a Marxist view, those who control the means of production (the economic base) essentially control a culture.[citation needed] Other approaches to cultural studies, such as feminist cultural studies and later American developments of the field, distance themselves from this view. They criticize the Marxist assumption of a single, dominant meaning, shared by all, for any cultural product. The non-Marxist approaches suggest that different ways of consuming cultural artifacts affect the meaning of the product. This view comes through in the book Doing Cultural Studies: The Story of the Sony Walkman (by Paul du Gay et al.), which seeks to challenge the notion that those who produce commodities control the meanings that people attribute to them. Feminist cultural analyst, theorist and art historian Griselda Pollock contributed to cultural studies from viewpoints of art history and psychoanalysis. The writer Julia Kristeva is among influential voices at the turn of the century, contributing to cultural studies from the field of art and psychoanalytical French feminism.[citation needed] +Raimon Panikkar pointed out 29 ways in which cultural change can be brought about. Some of these are: growth, development, evolution, involution, renovation, reconception, reform, innovation, revivalism, revolution, mutation, progress, diffusion, osmosis, borrowing, eclecticism, syncretism, modernization, indigenization, and transformation. Hence Modernization could be similar or related to the enlightenment but a 'looser' term set to ideal and values that flourish. a belief in objectivity progress. Also seen as a belief in a secular society (free from religious influences) example objective and rational, science vs religion and finally been modern means not being religious. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/test_documents/Materialism.txt b/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/test_documents/Materialism.txt new file mode 100644 index 0000000000000000000000000000000000000000..5d5ff8a3de290416ec83cd0e504bafb9f1494001 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/test_documents/Materialism.txt @@ -0,0 +1,27 @@ +Materialism is a form of philosophical monism which holds that matter is the fundamental substance in nature, and that all phenomena, including mental phenomena and consciousness, are identical with material interactions. +Materialism is closely related to physicalism, the view that all that exists is ultimately physical. Philosophical physicalism has evolved from materialism with the discoveries of the physical sciences to incorporate more sophisticated notions of physicality than mere ordinary matter, such as: spacetime, physical energies and forces, dark matter, and so on. Thus the term "physicalism" is preferred over "materialism" by some, while others use the terms as if they are synonymous. +Materialism belongs to the class of monist ontology. As such, it is different from ontological theories based on dualism or pluralism. For singular explanations of the phenomenal reality, materialism would be in contrast to idealism, neutral monism, and spiritualism. +Despite the large number of philosophical schools and subtle nuances between many, all philosophies are said to fall into one of two primary categories, which are defined in contrast to each other: Idealism, and materialism.[a] The basic proposition of these two categories pertains to the nature of reality, and the primary distinction between them is the way they answer two fundamental questions: "what does reality consist of?" and "how does it originate?" To idealists, spirit or mind or the objects of mind (ideas) are primary, and matter secondary. To materialists, matter is primary, and mind or spirit or ideas are secondary, the product of matter acting upon matter. +The materialist view is perhaps best understood in its opposition to the doctrines of immaterial substance applied to the mind historically, famously by René Descartes. However, by itself materialism says nothing about how material substance should be characterized. In practice, it is frequently assimilated to one variety of physicalism or another. +During the 19th century, Karl Marx and Friedrich Engels extended the concept of materialism to elaborate a materialist conception of history centered on the roughly empirical world of human activity (practice, including labor) and the institutions created, reproduced, or destroyed by that activity (see materialist conception of history). Later Marxists developed the notion of dialectical materialism which characterized later Marxist philosophy and method. +Materialism developed, possibly independently, in several geographically separated regions of Eurasia during what Karl Jaspers termed the Axial Age (approximately 800 to 200 BC). +In Ancient Indian philosophy, materialism developed around 600 BC with the works of Ajita Kesakambali, Payasi, Kanada, and the proponents of the Cārvāka school of philosophy. Kanada became one of the early proponents of atomism. The Nyaya–Vaisesika school (600 BC - 100 BC) developed one of the earliest forms of atomism, though their proofs of God and their positing that the consciousness was not material precludes labelling them as materialists. Buddhist atomism and the Jaina school continued the atomic tradition. +Materialism is often associated with reductionism, according to which the objects or phenomena individuated at one level of description, if they are genuine, must be explicable in terms of the objects or phenomena at some other level of description — typically, at a more reduced level. Non-reductive materialism explicitly rejects this notion, however, taking the material constitution of all particulars to be consistent with the existence of real objects, properties, or phenomena not explicable in the terms canonically used for the basic material constituents. Jerry Fodor influentially argues this view, according to which empirical laws and explanations in "special sciences" like psychology or geology are invisible from the perspective of basic physics. A lot of vigorous literature has grown up around the relation between these views. +Ancient Greek philosophers like Thales, Anaxagoras (ca. 500 BC – 428 BC), Epicurus and Democritus prefigure later materialists. The Latin poem De Rerum Natura by Lucretius (ca. 99 BC – ca. 55 BC) reflects the mechanistic philosophy of Democritus and Epicurus. According to this view, all that exists is matter and void, and all phenomena result from different motions and conglomerations of base material particles called "atoms" (literally: "indivisibles"). De Rerum Natura provides mechanistic explanations for phenomena such as erosion, evaporation, wind, and sound. Famous principles like "nothing can touch body but body" first appeared in the works of Lucretius. Democritus and Epicurus however did not hold to a monist ontology since they held to the ontological separation of matter and space i.e. space being "another kind" of being, indicating that the definition of "materialism" is wider than given scope for in this article. +Later Indian materialist Jayaraashi Bhatta (6th century) in his work Tattvopaplavasimha ("The upsetting of all principles") refuted the Nyaya Sutra epistemology. The materialistic Cārvāka philosophy appears to have died out some time after 1400. When Madhavacharya compiled Sarva-darśana-samgraha (a digest of all philosophies) in the 14th century, he had no Cārvāka/Lokāyata text to quote from, or even refer to. +In early 12th-century al-Andalus, the Arabian philosopher, Ibn Tufail (Abubacer), wrote discussions on materialism in his philosophical novel, Hayy ibn Yaqdhan (Philosophus Autodidactus), while vaguely foreshadowing the idea of a historical materialism. +The French cleric Pierre Gassendi (1592-1665) represented the materialist tradition in opposition to the attempts of René Descartes (1596-1650) to provide the natural sciences with dualist foundations. There followed the materialist and atheist abbé Jean Meslier (1664-1729), Julien Offray de La Mettrie, the German-French Paul-Henri Thiry Baron d'Holbach (1723-1789), the Encyclopedist Denis Diderot (1713-1784), and other French Enlightenment thinkers; as well as (in England) John "Walking" Stewart (1747-1822), whose insistence in seeing matter as endowed with a moral dimension had a major impact on the philosophical poetry of William Wordsworth (1770-1850). +Arthur Schopenhauer (1788-1860) wrote that "...materialism is the philosophy of the subject who forgets to take account of himself". He claimed that an observing subject can only know material objects through the mediation of the brain and its particular organization. That is, the brain itself is the "determiner" of how material objects will be experienced or perceived: +The German materialist and atheist anthropologist Ludwig Feuerbach would signal a new turn in materialism through his book, The Essence of Christianity (1841), which provided a humanist account of religion as the outward projection of man's inward nature. Feuerbach's materialism would later heavily influence Karl Marx. +Many current and recent philosophers—e.g., Daniel Dennett, Willard Van Orman Quine, Donald Davidson, and Jerry Fodor—operate within a broadly physicalist or materialist framework, producing rival accounts of how best to accommodate mind, including functionalism, anomalous monism, identity theory, and so on. +The nature and definition of matter - like other key concepts in science and philosophy - have occasioned much debate. Is there a single kind of matter (hyle) which everything is made of, or multiple kinds? Is matter a continuous substance capable of expressing multiple forms (hylomorphism), or a number of discrete, unchanging constituents (atomism)? Does it have intrinsic properties (substance theory), or is it lacking them (prima materia)? +One challenge to the traditional concept of matter as tangible "stuff" came with the rise of field physics in the 19th century. Relativity shows that matter and energy (including the spatially distributed energy of fields) are interchangeable. This enables the ontological view that energy is prima materia and matter is one of its forms. On the other hand, the Standard Model of Particle physics uses quantum field theory to describe all interactions. On this view it could be said that fields are prima materia and the energy is a property of the field. +According to the dominant cosmological model, the Lambda-CDM model, less than 5% of the universe's energy density is made up of the "matter" described by the Standard Model of Particle Physics, and the majority of the universe is composed of dark matter and dark energy - with little agreement amongst scientists about what these are made of. +With the advent of quantum physics, some scientists believed the concept of matter had merely changed, while others believed the conventional position could no longer be maintained. For instance Werner Heisenberg said "The ontology of materialism rested upon the illusion that the kind of existence, the direct 'actuality' of the world around us, can be extrapolated into the atomic range. This extrapolation, however, is impossible... atoms are not things." Likewise, some philosophers[which?] feel that these dichotomies necessitate a switch from materialism to physicalism. Others use the terms "materialism" and "physicalism" interchangeably. +Some modern day physicists and science writers—such as Paul Davies and John Gribbin—have argued that materialism has been disproven by certain scientific findings in physics, such as quantum mechanics and chaos theory. In 1991, Gribbin and Davies released their book The Matter Myth, the first chapter of which, "The Death of Materialism", contained the following passage: +Davies' and Gribbin's objections are shared by proponents of digital physics who view information rather than matter to be fundamental. Their objections were also shared by some founders of quantum theory, such as Max Planck, who wrote: +According to the Catholic Encyclopedia of 1907-1912, materialism, defined as "a philosophical system which regards matter as the only reality in the world [...] denies the existence of God and the soul". Materialism, in this view, therefore becomes incompatible with most world religions, including Christianity, Judaism, and Islam. In such a context one can conflate materialism with atheism. Most of Hinduism and transcendentalism regards all matter as an illusion called Maya, blinding humans from knowing "the truth". Maya is the limited, purely physical and mental reality in which our everyday consciousness has become entangled. Maya gets destroyed for a person when s/he perceives Brahman with transcendental knowledge. +In contrast, Joseph Smith, the founder of the Latter Day Saint movement, taught: "There is no such thing as immaterial matter. All spirit is matter, but it is more fine or pure, and can only be discerned by purer eyes; We cannot see it; but when our bodies are purified we shall see that it is all matter." This spirit element has always existed; it is co-eternal with God. It is also called "intelligence" or "the light of truth", which like all observable matter "was not created or made, neither indeed can be". Members of the Church of Jesus Christ of Latter-day Saints view the revelations of Joseph Smith as a restoration of original Christian doctrine, which they believe post-apostolic theologians began to corrupt in the centuries after Christ. The writings of many[quantify] of these theologians indicate a clear influence of Greek metaphysical philosophies such as Neoplatonism, which characterized divinity as an utterly simple, immaterial, formless, substance/essence (ousia) that transcended all that was physical. Despite strong opposition from many Christians, this metaphysical depiction of God eventually became incorporated into the doctrine of the Christian church, displacing the original Judeo-Christian concept of a physical, corporeal God who created humans in His image and likeness. +An argument for idealism, such as those of Hegel and Berkeley, is ipso facto an argument against materialism. Matter can be argued to be redundant, as in bundle theory, and mind-independent properties can in turn be reduced to subjective percepts. Berkeley presents an example of the latter by pointing out that it is impossible to gather direct evidence of matter, as there is no direct experience of matter; all that is experienced is perception, whether internal or external. As such, the existence of matter can only be assumed from the apparent (perceived) stability of perceptions; it finds absolutely no evidence in direct experience. +If matter and energy are seen as necessary to explain the physical world, but incapable of explaining mind, dualism results. Emergence, holism, and process philosophy seek to ameliorate the perceived shortcomings of traditional (especially mechanistic) materialism without abandoning materialism entirely. +Some critics object to materialism as part of an overly skeptical, narrow or reductivist approach to theorizing, rather than to the ontological claim that matter is the only substance. Particle physicist and Anglican theologian John Polkinghorne objects to what he calls promissory materialism — claims that materialistic science will eventually succeed in explaining phenomena it has not so far been able to explain. Polkinghorne prefers "dual-aspect monism" to faith in materialism. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/test_documents/Strasbourg.txt b/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/test_documents/Strasbourg.txt new file mode 100644 index 0000000000000000000000000000000000000000..bf64384234a9fe5b20151a17b98f20a45924e231 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/test_documents/Strasbourg.txt @@ -0,0 +1,34 @@ +Strasbourg (/ˈstræzbɜːrɡ/, French pronunciation: ​[stʁaz.buʁ, stʁas.buʁ]; Alsatian: Strossburi; German: Straßburg, [ˈʃtʁaːsbʊɐ̯k]) is the capital and largest city of the Alsace-Champagne-Ardenne-Lorraine (ACAL) region in eastern France and is the official seat of the European Parliament. Located close to the border with Germany, it is the capital of the Bas-Rhin département. The city and the region of Alsace were historically predominantly Alemannic-speaking, hence the city's Germanic name. In 2013, the city proper had 275,718 inhabitants, Eurométropole de Strasbourg (Greater Strasbourg) had 475,934 inhabitants and the Arrondissement of Strasbourg had 482,384 inhabitants. With a population of 768,868 in 2012, Strasbourg's metropolitan area (only the part of the metropolitan area on French territory) is the ninth largest in France and home to 13% of the ACAL region's inhabitants. The transnational Eurodistrict Strasbourg-Ortenau had a population of 915,000 inhabitants in 2014. +Strasbourg's historic city centre, the Grande Île (Grand Island), was classified a World Heritage site by UNESCO in 1988, the first time such an honour was placed on an entire city centre. Strasbourg is immersed in the Franco-German culture and although violently disputed throughout history, has been a bridge of unity between France and Germany for centuries, especially through the University of Strasbourg, currently the second largest in France, and the coexistence of Catholic and Protestant culture. The largest Islamic place of worship in France, the Strasbourg Grand Mosque, was inaugurated by French Interior Minister Manuel Valls on 27 September 2012. +Strasbourg is situated on the eastern border of France with Germany. This border is formed by the River Rhine, which also forms the eastern border of the modern city, facing across the river to the German town Kehl. The historic core of Strasbourg however lies on the Grande Île in the River Ill, which here flows parallel to, and roughly 4 kilometres (2.5 mi) from, the Rhine. The natural courses of the two rivers eventually join some distance downstream of Strasbourg, although several artificial waterways now connect them within the city. +The Romans under Nero Claudius Drusus established a military outpost belonging to the Germania Superior Roman province at Strasbourg's current location, and named it Argentoratum. (Hence the town is commonly called Argentina in medieval Latin.) The name "Argentoratum" was first mentioned in 12 BC and the city celebrated its 2,000th birthday in 1988. "Argentorate" as the toponym of the Gaulish settlement preceded it before being Latinized, but it is not known by how long. The Roman camp was destroyed by fire and rebuilt six times between the first and the fifth centuries AD: in 70, 97, 235, 355, in the last quarter of the fourth century, and in the early years of the fifth century. It was under Trajan and after the fire of 97 that Argentoratum received its most extended and fortified shape. From the year 90 on, the Legio VIII Augusta was permanently stationed in the Roman camp of Argentoratum. It then included a cavalry section and covered an area of approximately 20 hectares. Other Roman legions temporarily stationed in Argentoratum were the Legio XIV Gemina and the Legio XXI Rapax, the latter during the reign of Nero. +The centre of Argentoratum proper was situated on the Grande Île (Cardo: current Rue du Dôme, Decumanus: current Rue des Hallebardes). The outline of the Roman "castrum" is visible in the street pattern in the Grande Ile. Many Roman artifacts have also been found along the current Route des Romains, the road that led to Argentoratum, in the suburb of Kœnigshoffen. This was where the largest burial places were situated, as well as the densest concentration of civilian dwelling places and commerces next to the camp. Among the most outstanding finds in Kœnigshoffen were (found in 1911–12) the fragments of a grand Mithraeum that had been shattered by early Christians in the fourth century. From the fourth century, Strasbourg was the seat of the Bishopric of Strasbourg (made an Archbishopric in 1988). Archaeological excavations below the current Église Saint-Étienne in 1948 and 1956 unearthed the apse of a church dating back to the late fourth or early fifth century, considered to be the oldest church in Alsace. It is supposed that this was the first seat of the Roman Catholic Diocese of Strasbourg. +In the fifth century Strasbourg was occupied successively by Alemanni, Huns, and Franks. In the ninth century it was commonly known as Strazburg in the local language, as documented in 842 by the Oaths of Strasbourg. This trilingual text contains, alongside texts in Latin and Old High German (teudisca lingua), the oldest written variety of Gallo-Romance (lingua romana) clearly distinct from Latin, the ancestor of Old French. The town was also called Stratisburgum or Strateburgus in Latin, from which later came Strossburi in Alsatian and Straßburg in Standard German, and then Strasbourg in French. The Oaths of Strasbourg is considered as marking the birth of the two countries of France and Germany with the division of the Carolingian Empire. +A revolution in 1332 resulted in a broad-based city government with participation of the guilds, and Strasbourg declared itself a free republic. The deadly bubonic plague of 1348 was followed on 14 February 1349 by one of the first and worst pogroms in pre-modern history: over a thousand Jews were publicly burnt to death, with the remainder of the Jewish population being expelled from the city. Until the end of the 18th century, Jews were forbidden to remain in town after 10 pm. The time to leave the city was signalled by a municipal herald blowing the Grüselhorn (see below, Museums, Musée historique);. A special tax, the Pflastergeld (pavement money), was furthermore to be paid for any horse that a Jew would ride or bring into the city while allowed to. +In the 1520s during the Protestant Reformation, the city, under the political guidance of Jacob Sturm von Sturmeck and the spiritual guidance of Martin Bucer embraced the religious teachings of Martin Luther. Their adherents established a Gymnasium, headed by Johannes Sturm, made into a University in the following century. The city first followed the Tetrapolitan Confession, and then the Augsburg Confession. Protestant iconoclasm caused much destruction to churches and cloisters, notwithstanding that Luther himself opposed such a practice. Strasbourg was a centre of humanist scholarship and early book-printing in the Holy Roman Empire, and its intellectual and political influence contributed much to the establishment of Protestantism as an accepted denomination in the southwest of Germany. (John Calvin spent several years as a political refugee in the city). The Strasbourg Councillor Sturm and guildmaster Matthias represented the city at the Imperial Diet of Speyer (1529), where their protest led to the schism of the Catholic Church and the evolution of Protestantism. Together with four other free cities, Strasbourg presented the confessio tetrapolitana as its Protestant book of faith at the Imperial Diet of Augsburg in 1530, where the slightly different Augsburg Confession was also handed over to Charles V, Holy Roman Emperor. +Louis' advisors believed that, as long as Strasbourg remained independent, it would endanger the King's newly annexed territories in Alsace, and, that to defend these large rural lands effectively, a garrison had to be placed in towns such as Strasbourg. Indeed, the bridge over the Rhine at Strasbourg had been used repeatedly by Imperial (Holy Roman Empire) forces, and three times during the Franco-Dutch War Strasbourg had served as a gateway for Imperial invasions into Alsace. In September 1681 Louis' forces, though lacking a clear casus belli, surrounded the city with overwhelming force. After some negotiation, Louis marched into the city unopposed on 30 September 1681 and proclaimed its annexation. +This annexation was one of the direct causes of the brief and bloody War of the Reunions whose outcome left the French in possession. The French annexation was recognized by the Treaty of Ryswick (1697). The official policy of religious intolerance which drove most Protestants from France after the revocation of the Edict of Nantes in 1685 was not applied in Strasbourg and in Alsace, because both had a special status as a province à l'instar de l'étranger effectif (a kind of foreign province of the king of France). Strasbourg Cathedral, however, was taken from the Lutherans to be returned to the Catholics as the French authorities tried to promote Catholicism wherever they could (some other historic churches remained in Protestant hands). Its language also remained overwhelmingly German: the German Lutheran university persisted until the French Revolution. Famous students included Goethe and Herder. +Strasbourg's status as a free city was revoked by the French Revolution. Enragés, most notoriously Eulogius Schneider, ruled the city with an increasingly iron hand. During this time, many churches and monasteries were either destroyed or severely damaged. The cathedral lost hundreds of its statues (later replaced by copies in the 19th century) and in April 1794, there was talk of tearing its spire down, on the grounds that it was against the principle of equality. The tower was saved, however, when in May of the same year citizens of Strasbourg crowned it with a giant tin Phrygian cap. This artifact was later kept in the historical collections of the city until it was destroyed by the Germans in 1870 during the Franco-Prussian war. +During the Franco-Prussian War and the Siege of Strasbourg, the city was heavily bombarded by the Prussian army. The bombardment of the city was meant to break the morale of the people of Strasbourg. On 24 and 26 August 1870, the Museum of Fine Arts was destroyed by fire, as was the Municipal Library housed in the Gothic former Dominican church, with its unique collection of medieval manuscripts (most famously the Hortus deliciarum), rare Renaissance books, archeological finds and historical artifacts. The gothic cathedral was damaged as well as the medieval church of Temple Neuf, the theatre, the city hall, the court of justice and many houses. At the end of the siege 10,000 inhabitants were left without shelter; over 600 died, including 261 civilians, and 3200 were injured, including 1,100 civilians. +In 1871, after the end of the war, the city was annexed to the newly established German Empire as part of the Reichsland Elsass-Lothringen under the terms of the Treaty of Frankfurt. As part of Imperial Germany, Strasbourg was rebuilt and developed on a grand and representative scale, such as the Neue Stadt, or "new city" around the present Place de la République. Historian Rodolphe Reuss and Art historian Wilhelm von Bode were in charge of rebuilding the municipal archives, libraries and museums. The University, founded in 1567 and suppressed during the French Revolution as a stronghold of German sentiment,[citation needed] was reopened in 1872 under the name Kaiser-Wilhelms-Universität. +A belt of massive fortifications was established around the city, most of which still stands today, renamed after French generals and generally classified as Monuments historiques; most notably Fort Roon (now Fort Desaix) and Fort Podbielski (now Fort Ducrot) in Mundolsheim, Fort von Moltke (now Fort Rapp) in Reichstett, Fort Bismarck (now Fort Kléber) in Wolfisheim, Fort Kronprinz (now Fort Foch) in Niederhausbergen, Fort Kronprinz von Sachsen (now Fort Joffre) in Holtzheim and Fort Großherzog von Baden (now Fort Frère) in Oberhausbergen. +Following the defeat of the German empire in World War I and the abdication of the German Emperor, some revolutionary insurgents declared Alsace-Lorraine as an independent Republic, without preliminary referendum or vote. On 11 November 1918 (Armistice Day), communist insurgents proclaimed a "soviet government" in Strasbourg, following the example of Kurt Eisner in Munich as well as other German towns. French troops commanded by French general Henri Gouraud entered triumphantly in the city on 22 November. A major street of the city now bears the name of that date (Rue du 22 Novembre) which celebrates the entry of the French in the city. Viewing the massive cheering crowd gathered under the balcony of Strasbourg's town hall, French President Raymond Poincaré stated that "the plebiscite is done". +In 1919, following the Treaty of Versailles, the city was restituted to France in accordance with U.S. President Woodrow Wilson's "Fourteen Points" without a referendum. The date of the assignment was retroactively established on Armistice Day. It is doubtful whether a referendum in Strasbourg would have ended in France's favour since the political parties striving for an autonomous Alsace or a connection to France accounted only for a small proportion of votes in the last Reichstag as well as in the local elections. The Alsatian autonomists who were pro French had won many votes in the more rural parts of the region and other towns since the annexation of the region by Germany in 1871. The movement started with the first election for the Reichstag; those elected were called "les députés protestataires", and until the fall of Bismarck in 1890, they were the only deputies elected by the Alsatians to the German parliament demanding the return of those territories to France. At the last Reichstag election in Strasbourg and its periphery, the clear winners were the Social Democrats; the city was the administrative capital of the region, was inhabited by many Germans appointed by the central government in Berlin and its flourishing economy attracted many Germans. This could explain the difference between the rural vote and the one in Strasbourg. After the war, many Germans left Strasbourg and went back to Germany; some of them were denounced by the locals or expelled by the newly appointed authorities. The Saverne Affair was vivid in the memory among the Alsatians. +Between the German invasion of Poland on 1 September 1939 and the Anglo-French declaration of War against the German Reich on 3 September 1939, the entire city (a total of 120,000 people) was evacuated, like other border towns as well. Until the arrival of the Wehrmacht troops mid-June 1940, the city was, for ten months, completely empty, with the exception of the garrisoned soldiers. The Jews of Strasbourg had been evacuated to Périgueux and Limoges, the University had been evacuated to Clermont-Ferrand. +After the ceasefire following the Fall of France in June 1940, Alsace was annexed to Germany and a rigorous policy of Germanisation was imposed upon it by the Gauleiter Robert Heinrich Wagner. When, in July 1940, the first evacuees were allowed to return, only residents of Alsatian origin were admitted. The last Jews were deported on 15 July 1940 and the main synagogue, a huge Romanesque revival building that had been a major architectural landmark with its 54-metre-high dome since its completion in 1897, was set ablaze, then razed. +In September 1940 the first Alsatian resistance movement led by Marcel Weinum called La main noire (The black hand) was created. It was composed by a group of 25 young men aged from 14 to 18 years old who led several attacks against the German occupation. The actions culminated with the attack of the Gauleiter Robert Wagner, the highest commander of Alsace directly under the order of Hitler. In March 1942, Marcel Weinum was prosecuted by the Gestapo and sentenced to be beheaded at the age of 18 in April 1942 in Stuttgart, Germany. His last words will be: "If I have to die, I shall die but with a pure heart". From 1943 the city was bombarded by Allied aircraft. While the First World War had not notably damaged the city, Anglo-American bombing caused extensive destruction in raids of which at least one was allegedly carried out by mistake. In August 1944, several buildings in the Old Town were damaged by bombs, particularly the Palais Rohan, the Old Customs House (Ancienne Douane) and the Cathedral. On 23 November 1944, the city was officially liberated by the 2nd French Armoured Division under General Leclerc. He achieved the oath that he made with his soldiers, after the decisive Capture of Kufra. With the Oath of Kuffra, they swore to keep up the fight until the French flag flew over the Cathedral of Strasbourg. +Many people from Strasbourg were incorporated in the German Army against their will, and were sent to the eastern front, those young men and women were called Malgré-nous. Many tried to escape from the incorporation, join the French Resistance, or desert the Wehrmacht but many couldn't because they were running the risk of having their families sent to work or concentration camps by the Germans. Many of these men, especially those who did not answer the call immediately, were pressured to "volunteer" for service with the SS, often by direct threats on their families. This threat obliged the majority of them to remain in the German army. After the war, the few that survived were often accused of being traitors or collaborationists, because this tough situation was not known in the rest of France, and they had to face the incomprehension of many. In July 1944, 1500 malgré-nous were released from Soviet captivity and sent to Algiers, where they joined the Free French Forces. Nowadays history recognizes the suffering of those people, and museums, public discussions and memorials have been built to commemorate this terrible period of history of this part of Eastern France (Alsace and Moselle). Liberation of Strasbourg took place on 23 November 1944. +In 1949, the city was chosen to be the seat of the Council of Europe with its European Court of Human Rights and European Pharmacopoeia. Since 1952, the European Parliament has met in Strasbourg, which was formally designated its official 'seat' at the Edinburgh meeting of the European Council of EU heads of state and government in December 1992. (This position was reconfirmed and given treaty status in the 1997 Treaty of Amsterdam). However, only the (four-day) plenary sessions of the Parliament are held in Strasbourg each month, with all other business being conducted in Brussels and Luxembourg. Those sessions take place in the Immeuble Louise Weiss, inaugurated in 1999, which houses the largest parliamentary assembly room in Europe and of any democratic institution in the world. Before that, the EP sessions had to take place in the main Council of Europe building, the Palace of Europe, whose unusual inner architecture had become a familiar sight to European TV audiences. In 1992, Strasbourg became the seat of the Franco-German TV channel and movie-production society Arte. +In addition to the cathedral, Strasbourg houses several other medieval churches that have survived the many wars and destructions that have plagued the city: the Romanesque Église Saint-Étienne, partly destroyed in 1944 by Allied bombing raids, the part Romanesque, part Gothic, very large Église Saint-Thomas with its Silbermann organ on which Wolfgang Amadeus Mozart and Albert Schweitzer played, the Gothic Église protestante Saint-Pierre-le-Jeune with its crypt dating back to the seventh century and its cloister partly from the eleventh century, the Gothic Église Saint-Guillaume with its fine early-Renaissance stained glass and furniture, the Gothic Église Saint-Jean, the part Gothic, part Art Nouveau Église Sainte-Madeleine, etc. The Neo-Gothic church Saint-Pierre-le-Vieux Catholique (there is also an adjacent church Saint-Pierre-le-Vieux Protestant) serves as a shrine for several 15th-century wood worked and painted altars coming from other, now destroyed churches and installed there for public display. Among the numerous secular medieval buildings, the monumental Ancienne Douane (old custom-house) stands out. +The German Renaissance has bequeathed the city some noteworthy buildings (especially the current Chambre de commerce et d'industrie, former town hall, on Place Gutenberg), as did the French Baroque and Classicism with several hôtels particuliers (i.e. palaces), among which the Palais Rohan (1742, now housing three museums) is the most spectacular. Other buildings of its kind are the "Hôtel de Hanau" (1736, now the city hall), the Hôtel de Klinglin (1736, now residence of the préfet), the Hôtel des Deux-Ponts (1755, now residence of the military governor), the Hôtel d'Andlau-Klinglin (1725, now seat of the administration of the Port autonome de Strasbourg) etc. The largest baroque building of Strasbourg though is the 150 m (490 ft) long 1720s main building of the Hôpital civil. As for French Neo-classicism, it is the Opera House on Place Broglie that most prestigiously represents this style. +Strasbourg also offers high-class eclecticist buildings in its very extended German district, the Neustadt, being the main memory of Wilhelmian architecture since most of the major cities in Germany proper suffered intensive damage during World War II. Streets, boulevards and avenues are homogeneous, surprisingly high (up to seven stories) and broad examples of German urban lay-out and of this architectural style that summons and mixes up five centuries of European architecture as well as Neo-Egyptian, Neo-Greek and Neo-Babylonian styles. The former imperial palace Palais du Rhin, the most political and thus heavily criticized of all German Strasbourg buildings epitomizes the grand scale and stylistic sturdiness of this period. But the two most handsome and ornate buildings of these times are the École internationale des Pontonniers (the former Höhere Mädchenschule, girls college) with its towers, turrets and multiple round and square angles and the École des Arts décoratifs with its lavishly ornate façade of painted bricks, woodwork and majolica. +As for modern and contemporary architecture, Strasbourg possesses some fine Art Nouveau buildings (such as the huge Palais des Fêtes and houses and villas like Villa Schutzenberger and Hôtel Brion), good examples of post-World War II functional architecture (the Cité Rotterdam, for which Le Corbusier did not succeed in the architectural contest) and, in the very extended Quartier Européen, some spectacular administrative buildings of sometimes utterly large size, among which the European Court of Human Rights building by Richard Rogers is arguably the finest. Other noticeable contemporary buildings are the new Music school Cité de la Musique et de la Danse, the Musée d'Art moderne et contemporain and the Hôtel du Département facing it, as well as, in the outskirts, the tramway-station Hoenheim-Nord designed by Zaha Hadid. +Strasbourg features a number of prominent parks, of which several are of cultural and historical interest: the Parc de l'Orangerie, laid out as a French garden by André le Nôtre and remodeled as an English garden on behalf of Joséphine de Beauharnais, now displaying noteworthy French gardens, a neo-classical castle and a small zoo; the Parc de la Citadelle, built around impressive remains of the 17th-century fortress erected close to the Rhine by Vauban; the Parc de Pourtalès, laid out in English style around a baroque castle (heavily restored in the 19th century) that now houses a small three-star hotel, and featuring an open-air museum of international contemporary sculpture. The Jardin botanique de l'Université de Strasbourg (botanical garden) was created under the German administration next to the Observatory of Strasbourg, built in 1881, and still owns some greenhouses of those times. The Parc des Contades, although the oldest park of the city, was completely remodeled after World War II. The futuristic Parc des Poteries is an example of European park-conception in the late 1990s. The Jardin des deux Rives, spread over Strasbourg and Kehl on both sides of the Rhine opened in 2004 and is the most extended (60-hectare) park of the agglomeration. The most recent park is Parc du Heyritz (8,7 ha), opened in 2014 along a canal facing the hôpital civil. +Unlike most other cities, Strasbourg's collections of European art are divided into several museums according not only to type and area, but also to epoch. Old master paintings from the Germanic Rhenish territories and until 1681 are displayed in the Musée de l'Œuvre Notre-Dame, old master paintings from all the rest of Europe (including the Dutch Rhenish territories) and until 1871 as well as old master paintings from the Germanic Rhenish territories between 1681 and 1871 are displayed in the Musée des Beaux-Arts. Old master graphic arts until 1871 is displayed in the Cabinet des estampes et dessins. Decorative arts until 1681 ("German period") are displayed in the Musée de l'Œuvre Notre-Dame, decorative arts from 1681 to 1871 ("French period") are displayed in the Musée des Arts décoratifs. International art (painting, sculpture, graphic arts) and decorative art since 1871 is displayed in the Musée d'art moderne et contemporain. The latter museum also displays the city's photographic library. +Strasbourg, well known as centre of humanism, has a long history of excellence in higher-education, at the crossroads of French and German intellectual traditions. Although Strasbourg had been annexed by the Kingdom of France in 1683, it still remained connected to the German-speaking intellectual world throughout the 18th century and the university attracted numerous students from the Holy Roman Empire, including Goethe, Metternich and Montgelas, who studied law in Strasbourg, among the most prominent. Nowadays, Strasbourg is known to offer among the best university courses in France, after Paris. +The Bibliothèque nationale et universitaire (BNU) is, with its collection of more than 3,000,000 titles, the second largest library in France after the Bibliothèque nationale de France. It was founded by the German administration after the complete destruction of the previous municipal library in 1871 and holds the unique status of being simultaneously a students' and a national library. The Strasbourg municipal library had been marked erroneously as "City Hall" in a French commercial map, which had been captured and used by the German artillery to lay their guns. A librarian from Munich later pointed out "...that the destruction of the precious collection was not the fault of a German artillery officer, who used the French map, but of the slovenly and inaccurate scholarship of a Frenchman." +As one of the earliest centers of book-printing in Europe (see above: History), Strasbourg for a long time held a large number of incunabula—documents printed before 1500—in her library as one of her most precious heritages. After the total destruction of this institution in 1870, however, a new collection had to be reassembled from scratch. Today, Strasbourg's different public and institutional libraries again display a sizable total number of incunabula, distributed as follows: Bibliothèque nationale et universitaire, ca. 2 098 Médiathèque de la ville et de la communauté urbaine de Strasbourg, 394 Bibliothèque du Grand Séminaire, 238 Médiathèque protestante, 94 and Bibliothèque alsatique du Crédit Mutuel, 5. +City transportation in Strasbourg includes the futurist-looking Strasbourg tramway that opened in 1994 and is operated by the regional transit company Compagnie des Transports Strasbourgeois (CTS), consisting of 6 lines with a total length of 55.8 km (34.7 mi). The CTS also operates a comprehensive bus network throughout the city that is integrated with the trams. With more than 500 km (311 mi) of bicycle paths, biking in the city is convenient and the CTS operates a cheap bike-sharing scheme named Vélhop'. The CTS, and its predecessors, also operated a previous generation of tram system between 1878 and 1960, complemented by trolleybus routes between 1939 and 1962. +Being a city on the Ill and close to the Rhine, Strasbourg has always been an important centre of fluvial navigation, as is attested by archeological findings. In 1682 the Canal de la Bruche was added to the river navigations, initially to provide transport for sandstone from quarries in the Vosges for use in the fortification of the city. That canal has since closed, but the subsequent Canal du Rhone au Rhine, Canal de la Marne au Rhin and Grand Canal d'Alsace are still in use, as is the important activity of the Port autonome de Strasbourg. Water tourism inside the city proper attracts hundreds of thousands of tourists yearly. +The tram system that now criss-crosses the historic city centre complements walking and biking in it. The centre has been transformed into a pedestrian priority zone that enables and invites walking and biking by making these active modes of transport comfortable, safe and enjoyable. These attributes are accomplished by applying the principle of "filtered permeability" to the existing irregular network of streets. It means that the network adaptations favour active transportation and, selectively, "filter out" the car by reducing the number of streets that run through the centre. While certain streets are discontinuous for cars, they connect to a network of pedestrian and bike paths which permeate the entire centre. In addition, these paths go through public squares and open spaces increasing the enjoyment of the trip. This logic of filtering a mode of transport is fully expressed in a comprehensive model for laying out neighbourhoods and districts – the Fused Grid. +At present the A35 autoroute, which parallels the Rhine between Karlsruhe and Basel, and the A4 autoroute, which links Paris with Strasbourg, penetrate close to the centre of the city. The Grand contournement ouest (GCO) project, programmed since 1999, plans to construct a 24 km (15 mi) long highway connection between the junctions of the A4 and the A35 autoroutes in the north and of the A35 and A352 autoroutes in the south. This routes well to the west of the city and is meant to divest a significant portion of motorized traffic from the unité urbaine. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/test_documents/War_on_Terror.txt b/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/test_documents/War_on_Terror.txt new file mode 100644 index 0000000000000000000000000000000000000000..1601e747ba0ea6fee4280742e3eb35233e54135c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/e2e/samples/test_documents/War_on_Terror.txt @@ -0,0 +1,31 @@ +On 16 September 2001, at Camp David, President George W. Bush used the phrase war on terrorism in an unscripted and controversial comment when he said, "This crusade – this war on terrorism – is going to take a while, ... " Bush later apologized for this remark due to the negative connotations the term crusade has to people, e.g. of Muslim faith. The word crusade was not used again. On 20 September 2001, during a televised address to a joint session of congress, Bush stated that, "(o)ur 'war on terror' begins with al-Qaeda, but it does not end there. It will not end until every terrorist group of global reach has been found, stopped, and defeated." +U.S. President Barack Obama has rarely used the term, but in his inaugural address on 20 January 2009, he stated "Our nation is at war, against a far-reaching network of violence and hatred." In March 2009 the Defense Department officially changed the name of operations from "Global War on Terror" to "Overseas Contingency Operation" (OCO). In March 2009, the Obama administration requested that Pentagon staff members avoid use of the term, instead using "Overseas Contingency Operation". Basic objectives of the Bush administration "war on terror", such as targeting al Qaeda and building international counterterrorism alliances, remain in place. In December 2012, Jeh Johnson, the General Counsel of the Department of Defense, stated that the military fight will be replaced by a law enforcement operation when speaking at Oxford University, predicting that al Qaeda will be so weakened to be ineffective, and has been "effectively destroyed", and thus the conflict will not be an armed conflict under international law. In May 2013, Obama stated that the goal is "to dismantle specific networks of violent extremists that threaten America"; which coincided with the U.S. Office of Management and Budget having changed the wording from "Overseas Contingency Operations" to "Countering Violent Extremism" in 2010. +Because the actions involved in the "war on terrorism" are diffuse, and the criteria for inclusion are unclear, political theorist Richard Jackson has argued that "the 'war on terrorism' therefore, is simultaneously a set of actual practices—wars, covert operations, agencies, and institutions—and an accompanying series of assumptions, beliefs, justifications, and narratives—it is an entire language or discourse." Jackson cites among many examples a statement by John Ashcroft that "the attacks of September 11 drew a bright line of demarcation between the civil and the savage". Administration officials also described "terrorists" as hateful, treacherous, barbarous, mad, twisted, perverted, without faith, parasitical, inhuman, and, most commonly, evil. Americans, in contrast, were described as brave, loving, generous, strong, resourceful, heroic, and respectful of human rights. +The origins of al-Qaeda can be traced to the Soviet war in Afghanistan (December 1979 – February 1989). The United States, United Kingdom, Saudi Arabia, Pakistan, and the People's Republic of China supported the Islamist Afghan mujahadeen guerillas against the military forces of the Soviet Union and the Democratic Republic of Afghanistan. A small number of "Afghan Arab" volunteers joined the fight against the Soviets, including Osama bin Laden, but there is no evidence they received any external assistance. In May 1996 the group World Islamic Front for Jihad Against Jews and Crusaders (WIFJAJC), sponsored by bin Laden (and later re-formed as al-Qaeda), started forming a large base of operations in Afghanistan, where the Islamist extremist regime of the Taliban had seized power earlier in the year. In February 1998, Osama bin Laden signed a fatwā, as head of al-Qaeda, declaring war on the West and Israel, later in May of that same year al-Qaeda released a video declaring war on the U.S. and the West. +On 7 August 1998, al-Qaeda struck the U.S. embassies in Kenya and Tanzania, killing 224 people, including 12 Americans. In retaliation, U.S. President Bill Clinton launched Operation Infinite Reach, a bombing campaign in Sudan and Afghanistan against targets the U.S. asserted were associated with WIFJAJC, although others have questioned whether a pharmaceutical plant in Sudan was used as a chemical warfare plant. The plant produced much of the region's antimalarial drugs and around 50% of Sudan's pharmaceutical needs. The strikes failed to kill any leaders of WIFJAJC or the Taliban. +On the morning of 11 September 2001, 19 men affiliated with al-Qaeda hijacked four airliners all bound for California. Once the hijackers assumed control of the airliners, they told the passengers that they had the bomb on board and would spare the lives of passengers and crew once their demands were met – no passenger and crew actually suspected that they would use the airliners as suicide weapons since it had never happened before in history. The hijackers – members of al-Qaeda's Hamburg cell – intentionally crashed two airliners into the Twin Towers of the World Trade Center in New York City. Both buildings collapsed within two hours from fire damage related to the crashes, destroying nearby buildings and damaging others. The hijackers crashed a third airliner into the Pentagon in Arlington County, Virginia, just outside Washington D.C. The fourth plane crashed into a field near Shanksville, Pennsylvania, after some of its passengers and flight crew attempted to retake control of the plane, which the hijackers had redirected toward Washington D.C., to target the White House, or the U.S. Capitol. No flights had survivors. A total of 2,977 victims and the 19 hijackers perished in the attacks. +The Authorization for Use of Military Force Against Terrorists or "AUMF" was made law on 14 September 2001, to authorize the use of United States Armed Forces against those responsible for the attacks on 11 September 2001. It authorized the President to use all necessary and appropriate force against those nations, organizations, or persons he determines planned, authorized, committed, or aided the terrorist attacks that occurred on 11 September 2001, or harbored such organizations or persons, in order to prevent any future acts of international terrorism against the United States by such nations, organizations or persons. Congress declares this is intended to constitute specific statutory authorization within the meaning of section 5(b) of the War Powers Resolution of 1973. +Subsequently, in October 2001, U.S. forces (with UK and coalition allies) invaded Afghanistan to oust the Taliban regime. On 7 October 2001, the official invasion began with British and U.S. forces conducting airstrike campaigns over enemy targets. Kabul, the capital city of Afghanistan, fell by mid-November. The remaining al-Qaeda and Taliban remnants fell back to the rugged mountains of eastern Afghanistan, mainly Tora Bora. In December, Coalition forces (the U.S. and its allies) fought within that region. It is believed that Osama bin Laden escaped into Pakistan during the battle. +The Taliban regrouped in western Pakistan and began to unleash an insurgent-style offensive against Coalition forces in late 2002. Throughout southern and eastern Afghanistan, firefights broke out between the surging Taliban and Coalition forces. Coalition forces responded with a series of military offensives and an increase in the amount of troops in Afghanistan. In February 2010, Coalition forces launched Operation Moshtarak in southern Afghanistan along with other military offensives in the hopes that they would destroy the Taliban insurgency once and for all. Peace talks are also underway between Taliban affiliated fighters and Coalition forces. In September 2014, Afghanistan and the United States signed a security agreement, which permits United States and NATO forces to remain in Afghanistan until at least 2024. The United States and other NATO and non-NATO forces are planning to withdraw; with the Taliban claiming it has defeated the United States and NATO, and the Obama Administration viewing it as a victory. In December 2014, ISAF encasing its colors, and Resolute Support began as the NATO operation in Afghanistan. Continued United States operations within Afghanistan will continue under the name "Operation Freedom's Sentinel". +In January 2002, the United States Special Operations Command, Pacific deployed to the Philippines to advise and assist the Armed Forces of the Philippines in combating Filipino Islamist groups. The operations were mainly focused on removing the Abu Sayyaf group and Jemaah Islamiyah (JI) from their stronghold on the island of Basilan. The second portion of the operation was conducted as a humanitarian program called "Operation Smiles". The goal of the program was to provide medical care and services to the region of Basilan as part of a "Hearts and Minds" program. Joint Special Operations Task Force – Philippines disbanded in June 2014, ending a 14-year mission. After JSOTF-P disbanded, as late as November 2014, American forces continued to operate in the Philippines under the name "PACOM Augmentation Team". +On 14 September 2009, U.S. Special Forces killed two men and wounded and captured two others near the Somali village of Baarawe. Witnesses claim that helicopters used for the operation launched from French-flagged warships, but that could not be confirmed. A Somali-based al-Qaida affiliated group, the Al-Shabaab, has confirmed the death of "sheik commander" Saleh Ali Saleh Nabhan along with an unspecified number of militants. Nabhan, a Kenyan, was wanted in connection with the 2002 Mombasa attacks. +The conflict in northern Mali began in January 2012 with radical Islamists (affiliated to al-Qaeda) advancing into northern Mali. The Malian government had a hard time maintaining full control over their country. The fledgling government requested support from the international community on combating the Islamic militants. In January 2013, France intervened on behalf of the Malian government's request and deployed troops into the region. They launched Operation Serval on 11 January 2013, with the hopes of dislodging the al-Qaeda affiliated groups from northern Mali. +Following the ceasefire agreement that suspended hostilities (but not officially ended) in the 1991 Gulf War, the United States and its allies instituted and began patrolling Iraqi no-fly zones, to protect Iraq's Kurdish and Shi'a Arab population—both of which suffered attacks from the Hussein regime before and after the Gulf War—in Iraq's northern and southern regions, respectively. U.S. forces continued in combat zone deployments through November 1995 and launched Operation Desert Fox against Iraq in 1998 after it failed to meet U.S. demands of "unconditional cooperation" in weapons inspections. +The first ground attack came at the Battle of Umm Qasr on 21 March 2003 when a combined force of British, American and Polish forces seized control of the port city of Umm Qasr. Baghdad, Iraq's capital city, fell to American forces in April 2003 and Saddam Hussein's government quickly dissolved. On 1 May 2003, Bush announced that major combat operations in Iraq had ended. However, an insurgency arose against the U.S.-led coalition and the newly developing Iraqi military and post-Saddam government. The insurgency, which included al-Qaeda affiliated groups, led to far more coalition casualties than the invasion. Other elements of the insurgency were led by fugitive members of President Hussein's Ba'ath regime, which included Iraqi nationalists and pan-Arabists. Many insurgency leaders are Islamists and claim to be fighting a religious war to reestablish the Islamic Caliphate of centuries past. Iraq's former president, Saddam Hussein was captured by U.S. forces in December 2003. He was executed in 2006. +In a major split in the ranks of Al Qaeda's organization, the Iraqi franchise, known as Al Qaeda in Iraq covertly invaded Syria and the Levant and began participating in the ongoing Syrian Civil War, gaining enough support and strength to re-invade Iraq's western provinces under the name of the Islamic State of Iraq and the Levant (ISIS/ISIL), taking over much of the country in a blitzkrieg-like action and combining the Iraq insurgency and Syrian Civil War into a single conflict. Due to their extreme brutality and a complete change in their overall ideology, Al Qaeda's core organization in Central Asia eventually denounced ISIS and directed their affiliates to cut off all ties with this organization. Many analysts[who?] believe that because of this schism, Al Qaeda and ISIL are now in a competition to retain the title of the world's most powerful terrorist organization. +The Obama administration began to reengage in Iraq with a series of airstrikes aimed at ISIS beginning on 10 August 2014. On 9 September 2014 President Obama said that he had the authority he needed to take action to destroy the militant group known as the Islamic State of Iraq and the Levant, citing the 2001 Authorization for Use of Military Force Against Terrorists, and thus did not require additional approval from Congress. The following day on 10 September 2014 President Barack Obama made a televised speech about ISIL, which he stated "Our objective is clear: We will degrade, and ultimately destroy, ISIL through a comprehensive and sustained counter-terrorism strategy". Obama has authorized the deployment of additional U.S. Forces into Iraq, as well as authorizing direct military operations against ISIL within Syria. On the night of 21/22 September the United States, Saudi Arabia, Bahrain, the UAE, Jordan and Qatar started air attacks against ISIS in Syria.[citation needed] +Following the 11 September 2001 attacks, former President of Pakistan Pervez Musharraf sided with the U.S. against the Taliban government in Afghanistan after an ultimatum by then U.S. President George W. Bush. Musharraf agreed to give the U.S. the use of three airbases for Operation Enduring Freedom. United States Secretary of State Colin Powell and other U.S. administration officials met with Musharraf. On 19 September 2001, Musharraf addressed the people of Pakistan and stated that, while he opposed military tactics against the Taliban, Pakistan risked being endangered by an alliance of India and the U.S. if it did not cooperate. In 2006, Musharraf testified that this stance was pressured by threats from the U.S., and revealed in his memoirs that he had "war-gamed" the United States as an adversary and decided that it would end in a loss for Pakistan. +On 12 January 2002, Musharraf gave a speech against Islamic extremism. He unequivocally condemned all acts of terrorism and pledged to combat Islamic extremism and lawlessness within Pakistan itself. He stated that his government was committed to rooting out extremism and made it clear that the banned militant organizations would not be allowed to resurface under any new name. He said, "the recent decision to ban extremist groups promoting militancy was taken in the national interest after thorough consultations. It was not taken under any foreign influence". +In 2002, the Musharraf-led government took a firm stand against the jihadi organizations and groups promoting extremism, and arrested Maulana Masood Azhar, head of the Jaish-e-Mohammed, and Hafiz Muhammad Saeed, chief of the Lashkar-e-Taiba, and took dozens of activists into custody. An official ban was imposed on the groups on 12 January. Later that year, the Saudi born Zayn al-Abidn Muhammed Hasayn Abu Zubaydah was arrested by Pakistani officials during a series of joint U.S.-Pakistan raids. Zubaydah is said to have been a high-ranking al-Qaeda official with the title of operations chief and in charge of running al-Qaeda training camps. Other prominent al-Qaeda members were arrested in the following two years, namely Ramzi bin al-Shibh, who is known to have been a financial backer of al-Qaeda operations, and Khalid Sheikh Mohammed, who at the time of his capture was the third highest-ranking official in al-Qaeda and had been directly in charge of the planning for the 11 September attacks. +The use of drones by the Central Intelligence Agency in Pakistan to carry out operations associated with the Global War on Terror sparks debate over sovereignty and the laws of war. The U.S. Government uses the CIA rather than the U.S. Air Force for strikes in Pakistan in order to avoid breaching sovereignty through military invasion. The United States was criticized by[according to whom?] a report on drone warfare and aerial sovereignty for abusing the term 'Global War on Terror' to carry out military operations through government agencies without formally declaring war. +In a 'Letter to American People' written by Osama bin Laden in 2002, he stated that one of the reasons he was fighting America is because of its support of India on the Kashmir issue. While on a trip to Delhi in 2002, U.S. Secretary of Defense Donald Rumsfeld suggested that Al-Qaeda was active in Kashmir, though he did not have any hard evidence. An investigation in 2002 unearthed evidence that Al-Qaeda and its affiliates were prospering in Pakistan-administered Kashmir with tacit approval of Pakistan's National Intelligence agency Inter-Services Intelligence. A team of Special Air Service and Delta Force was sent into Indian-administered Kashmir in 2002 to hunt for Osama bin Laden after reports that he was being sheltered by the Kashmiri militant group Harkat-ul-Mujahideen. U.S. officials believed that Al-Qaeda was helping organize a campaign of terror in Kashmir in order to provoke conflict between India and Pakistan. Fazlur Rehman Khalil, the leader of the Harkat-ul-Mujahideen, signed al-Qaeda's 1998 declaration of holy war, which called on Muslims to attack all Americans and their allies. Indian sources claimed that In 2006, Al-Qaeda claimed they had established a wing in Kashmir; this worried the Indian government. India also claimed that Al-Qaeda has strong ties with the Kashmir militant groups Lashkar-e-Taiba and Jaish-e-Mohammed in Pakistan. While on a visit to Pakistan in January 2010, U.S. Defense secretary Robert Gates stated that Al-Qaeda was seeking to destabilize the region and planning to provoke a nuclear war between India and Pakistan. +In September 2009, a U.S. Drone strike reportedly killed Ilyas Kashmiri, who was the chief of Harkat-ul-Jihad al-Islami, a Kashmiri militant group associated with Al-Qaeda. Kashmiri was described by Bruce Riedel as a 'prominent' Al-Qaeda member, while others described him as the head of military operations for Al-Qaeda. Waziristan had now become the new battlefield for Kashmiri militants, who were now fighting NATO in support of Al-Qaeda. On 8 July 2012, Al-Badar Mujahideen, a breakaway faction of Kashmir centric terror group Hizbul Mujahideen, on conclusion of their two-day Shuhada Conference called for mobilisation of resources for continuation of jihad in Kashmir. +In the following months, NATO took a wide range of measures to respond to the threat of terrorism. On 22 November 2002, the member states of the Euro-Atlantic Partnership Council (EAPC) decided on a Partnership Action Plan against Terrorism, which explicitly states, "EAPC States are committed to the protection and promotion of fundamental freedoms and human rights, as well as the rule of law, in combating terrorism." NATO started naval operations in the Mediterranean Sea designed to prevent the movement of terrorists or weapons of mass destruction as well as to enhance the security of shipping in general called Operation Active Endeavour. +Support for the U.S. cooled when America made clear its determination to invade Iraq in late 2002. Even so, many of the "coalition of the willing" countries that unconditionally supported the U.S.-led military action have sent troops to Afghanistan, particular neighboring Pakistan, which has disowned its earlier support for the Taliban and contributed tens of thousands of soldiers to the conflict. Pakistan was also engaged in the War in North-West Pakistan (Waziristan War). Supported by U.S. intelligence, Pakistan was attempting to remove the Taliban insurgency and al-Qaeda element from the northern tribal areas. +The British 16th Air Assault Brigade (later reinforced by Royal Marines) formed the core of the force in southern Afghanistan, along with troops and helicopters from Australia, Canada and the Netherlands. The initial force consisted of roughly 3,300 British, 2,000 Canadian, 1,400 from the Netherlands and 240 from Australia, along with special forces from Denmark and Estonia and small contingents from other nations. The monthly supply of cargo containers through Pakistani route to ISAF in Afghanistan is over 4,000 costing around 12 billion in Pakistani Rupees. +In addition to military efforts abroad, in the aftermath of 9/11 the Bush Administration increased domestic efforts to prevent future attacks. Various government bureaucracies that handled security and military functions were reorganized. A new cabinet-level agency called the United States Department of Homeland Security was created in November 2002 to lead and coordinate the largest reorganization of the U.S. federal government since the consolidation of the armed forces into the Department of Defense.[citation needed] +The USA PATRIOT Act of October 2001 dramatically reduces restrictions on law enforcement agencies' ability to search telephone, e-mail communications, medical, financial, and other records; eases restrictions on foreign intelligence gathering within the United States; expands the Secretary of the Treasury's authority to regulate financial transactions, particularly those involving foreign individuals and entities; and broadens the discretion of law enforcement and immigration authorities in detaining and deporting immigrants suspected of terrorism-related acts. The act also expanded the definition of terrorism to include domestic terrorism, thus enlarging the number of activities to which the USA PATRIOT Act's expanded law enforcement powers could be applied. A new Terrorist Finance Tracking Program monitored the movements of terrorists' financial resources (discontinued after being revealed by The New York Times). Global telecommunication usage, including those with no links to terrorism, is being collected and monitored through the NSA electronic surveillance program. The Patriot Act is still in effect. +Political interest groups have stated that these laws remove important restrictions on governmental authority, and are a dangerous encroachment on civil liberties, possible unconstitutional violations of the Fourth Amendment. On 30 July 2003, the American Civil Liberties Union (ACLU) filed the first legal challenge against Section 215 of the Patriot Act, claiming that it allows the FBI to violate a citizen's First Amendment rights, Fourth Amendment rights, and right to due process, by granting the government the right to search a person's business, bookstore, and library records in a terrorist investigation, without disclosing to the individual that records were being searched. Also, governing bodies in a number of communities have passed symbolic resolutions against the act. +In 2005, the UN Security Council adopted Resolution 1624 concerning incitement to commit acts of terrorism and the obligations of countries to comply with international human rights laws. Although both resolutions require mandatory annual reports on counter-terrorism activities by adopting nations, the United States and Israel have both declined to submit reports. In the same year, the United States Department of Defense and the Chairman of the Joint Chiefs of Staff issued a planning document, by the name "National Military Strategic Plan for the War on Terrorism", which stated that it constituted the "comprehensive military plan to prosecute the Global War on Terror for the Armed Forces of the United States...including the findings and recommendations of the 9/11 Commission and a rigorous examination with the Department of Defense". +Criticism of the War on Terror addresses the issues, morality, efficiency, economics, and other questions surrounding the War on Terror and made against the phrase itself, calling it a misnomer. The notion of a "war" against "terrorism" has proven highly contentious, with critics charging that it has been exploited by participating governments to pursue long-standing policy/military objectives, reduce civil liberties, and infringe upon human rights. It is argued that the term war is not appropriate in this context (as in War on Drugs), since there is no identifiable enemy, and that it is unlikely international terrorism can be brought to an end by military means. +Other critics, such as Francis Fukuyama, note that "terrorism" is not an enemy, but a tactic; calling it a "war on terror", obscures differences between conflicts such as anti-occupation insurgents and international mujahideen. With a military presence in Iraq and Afghanistan and its associated collateral damage Shirley Williams maintains this increases resentment and terrorist threats against the West. There is also perceived U.S. hypocrisy, media-induced hysteria, and that differences in foreign and security policy have damaged America's image in most of the world. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/__pycache__/__init__.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be4a7ff8e15517250d9f3994ed37bfe6fec16f13 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/__pycache__/__init__.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/__pycache__/lazy_imports.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/__pycache__/lazy_imports.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cbbf3ddc2f72bb06a2aa6f582f75a83c9ab7486 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/__pycache__/lazy_imports.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/__pycache__/logging.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/__pycache__/logging.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dda864ba97d10980e42c6158311c51d709db3584 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/__pycache__/logging.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/audio/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/audio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c25e2ddeb81f90ab2e5835ce3608517629eea48b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/audio/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.audio.whisper_local import LocalWhisperTranscriber +from haystack.components.audio.whisper_remote import RemoteWhisperTranscriber + +__all__ = ["LocalWhisperTranscriber", "RemoteWhisperTranscriber"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/audio/whisper_local.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/audio/whisper_local.py new file mode 100644 index 0000000000000000000000000000000000000000..79ac83b144139764fd68d9d45d6ae4771d281455 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/audio/whisper_local.py @@ -0,0 +1,197 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import tempfile +from pathlib import Path +from typing import Any, Dict, List, Literal, Optional, Union, get_args + +from haystack import Document, component, default_from_dict, default_to_dict, logging +from haystack.dataclasses import ByteStream +from haystack.lazy_imports import LazyImport +from haystack.utils import ComponentDevice + +with LazyImport("Run 'pip install \"openai-whisper>=20231106\"' to install whisper.") as whisper_import: + import whisper + + +logger = logging.getLogger(__name__) +WhisperLocalModel = Literal[ + "base", + "base.en", + "large", + "large-v1", + "large-v2", + "large-v3", + "medium", + "medium.en", + "small", + "small.en", + "tiny", + "tiny.en", +] + + +@component +class LocalWhisperTranscriber: + """ + Transcribes audio files using OpenAI's Whisper model on your local machine. + + For the supported audio formats, languages, and other parameters, see the + [Whisper API documentation](https://platform.openai.com/docs/guides/speech-to-text) and the official Whisper + [GitHub repository](https://github.com/openai/whisper). + + ### Usage example + + ```python + from haystack.components.audio import LocalWhisperTranscriber + + whisper = LocalWhisperTranscriber(model="small") + whisper.warm_up() + transcription = whisper.run(sources=["path/to/audio/file"]) + ``` + """ + + def __init__( + self, + model: WhisperLocalModel = "large", + device: Optional[ComponentDevice] = None, + whisper_params: Optional[Dict[str, Any]] = None, + ): + """ + Creates an instance of the LocalWhisperTranscriber component. + + :param model: + The name of the model to use. Set to one of the following models: + "tiny", "base", "small", "medium", "large" (default). + For details on the models and their modifications, see the + [Whisper documentation](https://github.com/openai/whisper?tab=readme-ov-file#available-models-and-languages). + :param device: + The device for loading the model. If `None`, automatically selects the default device. + """ + whisper_import.check() + if model not in get_args(WhisperLocalModel): + raise ValueError( + f"Model name '{model}' not recognized. Choose one among: " f"{', '.join(get_args(WhisperLocalModel))}." + ) + self.model = model + self.whisper_params = whisper_params or {} + self.device = ComponentDevice.resolve_device(device) + self._model = None + + def warm_up(self) -> None: + """ + Loads the model in memory. + """ + if not self._model: + self._model = whisper.load_model(self.model, device=self.device.to_torch()) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict(self, model=self.model, device=self.device.to_dict(), whisper_params=self.whisper_params) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "LocalWhisperTranscriber": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + init_params = data["init_parameters"] + if init_params.get("device") is not None: + init_params["device"] = ComponentDevice.from_dict(init_params["device"]) + return default_from_dict(cls, data) + + @component.output_types(documents=List[Document]) + def run(self, sources: List[Union[str, Path, ByteStream]], whisper_params: Optional[Dict[str, Any]] = None): + """ + Transcribes a list of audio files into a list of documents. + + For the supported audio formats, languages, and other parameters, see the + [Whisper API documentation](https://platform.openai.com/docs/guides/speech-to-text) and the official Whisper + [GitHup repo](https://github.com/openai/whisper). + + :param sources: + A list of paths or binary streams to transcribe. + + :returns: A dictionary with the following keys: + - `documents`: A list of documents where each document is a transcribed audio file. The content of + the document is the transcription text, and the document's metadata contains the values returned by + the Whisper model, such as the alignment data and the path to the audio file used + for the transcription. + """ + if self._model is None: + raise RuntimeError( + "The component LocalWhisperTranscriber was not warmed up. Run 'warm_up()' before calling 'run()'." + ) + + if whisper_params is None: + whisper_params = self.whisper_params + + documents = self.transcribe(sources, **whisper_params) + return {"documents": documents} + + def transcribe(self, sources: List[Union[str, Path, ByteStream]], **kwargs) -> List[Document]: + """ + Transcribes the audio files into a list of Documents, one for each input file. + + For the supported audio formats, languages, and other parameters, see the + [Whisper API documentation](https://platform.openai.com/docs/guides/speech-to-text) and the official Whisper + [github repo](https://github.com/openai/whisper). + + :param sources: + A list of paths or binary streams to transcribe. + :returns: + A list of Documents, one for each file. + """ + transcriptions = self._raw_transcribe(sources, **kwargs) + documents = [] + for path, transcript in transcriptions.items(): + content = transcript.pop("text") + doc = Document(content=content, meta={"audio_file": path, **transcript}) + documents.append(doc) + return documents + + def _raw_transcribe(self, sources: List[Union[str, Path, ByteStream]], **kwargs) -> Dict[Path, Any]: + """ + Transcribes the given audio files. Returns the output of the model, a dictionary, for each input file. + + For the supported audio formats, languages, and other parameters, see the + [Whisper API documentation](https://platform.openai.com/docs/guides/speech-to-text) and the official Whisper + [github repo](https://github.com/openai/whisper). + + :param sources: + A list of paths or binary streams to transcribe. + :returns: + A dictionary mapping 'file_path' to 'transcription'. + """ + if self._model is None: + raise RuntimeError("Model is not loaded, please run 'warm_up()' before calling 'run()'") + + return_segments = kwargs.pop("return_segments", False) + transcriptions = {} + + for source in sources: + path = Path(source) if not isinstance(source, ByteStream) else source.meta.get("file_path") + + if isinstance(source, ByteStream) and path is None: + with tempfile.NamedTemporaryFile(delete=False) as fp: + path = Path(fp.name) + source.to_file(path) + + transcription = self._model.transcribe(str(path), **kwargs) + + if not return_segments: + transcription.pop("segments", None) + + transcriptions[path] = transcription + + return transcriptions diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/audio/whisper_remote.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/audio/whisper_remote.py new file mode 100644 index 0000000000000000000000000000000000000000..da794be349e5933edaed989a7f028bdf984f167e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/audio/whisper_remote.py @@ -0,0 +1,153 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import io +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from openai import OpenAI + +from haystack import Document, component, default_from_dict, default_to_dict, logging +from haystack.dataclasses import ByteStream +from haystack.utils import Secret, deserialize_secrets_inplace + +logger = logging.getLogger(__name__) + + +@component +class RemoteWhisperTranscriber: + """ + Transcribes audio files using the OpenAI's Whisper API. + + The component requires an OpenAI API key, see the + [OpenAI documentation](https://platform.openai.com/docs/api-reference/authentication) for more details. + For the supported audio formats, languages, and other parameters, see the + [Whisper API documentation](https://platform.openai.com/docs/guides/speech-to-text). + + ### Usage example + + ```python + from haystack.components.audio import RemoteWhisperTranscriber + + whisper = RemoteWhisperTranscriber(api_key=Secret.from_token(""), model="tiny") + transcription = whisper.run(sources=["path/to/audio/file"]) + ``` + """ + + def __init__( + self, + api_key: Secret = Secret.from_env_var("OPENAI_API_KEY"), + model: str = "whisper-1", + api_base_url: Optional[str] = None, + organization: Optional[str] = None, + **kwargs, + ): + """ + Creates an instance of the RemoteWhisperTranscriber component. + + :param api_key: + OpenAI API key. + You can set it with an environment variable `OPENAI_API_KEY`, or pass with this parameter + during initialization. + :param model: + Name of the model to use. Currently accepts only `whisper-1`. + :param organization: + Your OpenAI organization ID. See OpenAI's documentation on + [Setting Up Your Organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization). + :param api_base: + An optional URL to use as the API base. For details, see the + OpenAI [documentation](https://platform.openai.com/docs/api-reference/audio). + :param kwargs: + Other optional parameters for the model. These are sent directly to the OpenAI + endpoint. See OpenAI [documentation](https://platform.openai.com/docs/api-reference/audio) for more details. + Some of the supported parameters are: + - `language`: The language of the input audio. + Provide the input language in ISO-639-1 format + to improve transcription accuracy and latency. + - `prompt`: An optional text to guide the model's + style or continue a previous audio segment. + The prompt should match the audio language. + - `response_format`: The format of the transcript + output. This component only supports `json`. + - `temperature`: The sampling temperature, between 0 + and 1. Higher values like 0.8 make the output more + random, while lower values like 0.2 make it more + focused and deterministic. If set to 0, the model + uses log probability to automatically increase the + temperature until certain thresholds are hit. + """ + + self.organization = organization + self.model = model + self.api_base_url = api_base_url + self.api_key = api_key + + # Only response_format = "json" is supported + whisper_params = kwargs + response_format = whisper_params.get("response_format", "json") + if response_format != "json": + logger.warning( + "RemoteWhisperTranscriber only supports 'response_format: json'. This parameter will be overwritten." + ) + whisper_params["response_format"] = "json" + self.whisper_params = whisper_params + self.client = OpenAI(api_key=api_key.resolve_value(), organization=organization, base_url=api_base_url) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + api_key=self.api_key.to_dict(), + model=self.model, + organization=self.organization, + api_base_url=self.api_base_url, + **self.whisper_params, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "RemoteWhisperTranscriber": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + return default_from_dict(cls, data) + + @component.output_types(documents=List[Document]) + def run(self, sources: List[Union[str, Path, ByteStream]]): + """ + Transcribes the list of audio files into a list of documents. + + :param sources: + A list of file paths or `ByteStream` objects containing the audio files to transcribe. + + :returns: A dictionary with the following keys: + - `documents`: A list of documents, one document for each file. + The content of each document is the transcribed text. + """ + documents = [] + + for source in sources: + if not isinstance(source, ByteStream): + path = source + source = ByteStream.from_file_path(Path(source)) + source.meta["file_path"] = path + + file = io.BytesIO(source.data) + file.name = str(source.meta["file_path"]) if "file_path" in source.meta else "__fallback__.wav" + + content = self.client.audio.transcriptions.create(file=file, model=self.model, **self.whisper_params) + doc = Document(content=content.text, meta=source.meta) + documents.append(doc) + + return {"documents": documents} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/builders/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/builders/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5e1ebf6d1152eac0e38b6ce8edf320f3ffe93091 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/builders/__init__.py @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.builders.answer_builder import AnswerBuilder +from haystack.components.builders.chat_prompt_builder import ChatPromptBuilder +from haystack.components.builders.prompt_builder import PromptBuilder + +__all__ = ["AnswerBuilder", "PromptBuilder", "ChatPromptBuilder"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/builders/answer_builder.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/builders/answer_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..1577fb3e99b89417dbbbd5f9297187e230a0d787 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/builders/answer_builder.py @@ -0,0 +1,176 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import re +from typing import Any, Dict, List, Optional, Union + +from haystack import Document, GeneratedAnswer, component, logging +from haystack.dataclasses.chat_message import ChatMessage + +logger = logging.getLogger(__name__) + + +@component +class AnswerBuilder: + """ + Converts a query and Generator replies into a `GeneratedAnswer` object. + + AnswerBuilder parses Generator replies using custom regular expressions. + Check out the usage example below to see how it works. + Optionally, it can also take documents and metadata from the Generator to add to the `GeneratedAnswer` object. + AnswerBuilder works with both non-chat and chat Generators. + + ### Usage example + + ```python + from haystack.components.builders import AnswerBuilder + + builder = AnswerBuilder(pattern="Answer: (.*)") + builder.run(query="What's the answer?", replies=["This is an argument. Answer: This is the answer."]) + ``` + """ + + def __init__(self, pattern: Optional[str] = None, reference_pattern: Optional[str] = None): + """ + Creates an instance of the AnswerBuilder component. + + :param pattern: + The regular expression pattern to extract the answer text from the Generator. + If not specified, the entire response is used as the answer. + The regular expression can have one capture group at most. + If present, the capture group text + is used as the answer. If no capture group is present, the whole match is used as the answer. + Examples: + `[^\\n]+$` finds "this is an answer" in a string "this is an argument.\\nthis is an answer". + `Answer: (.*)` finds "this is an answer" in a string "this is an argument. Answer: this is an answer". + + :param reference_pattern: + The regular expression pattern used for parsing the document references. + If not specified, no parsing is done, and all documents are referenced. + References need to be specified as indices of the input documents and start at [1]. + Example: `\\[(\\d+)\\]` finds "1" in a string "this is an answer[1]". + """ + if pattern: + AnswerBuilder._check_num_groups_in_regex(pattern) + + self.pattern = pattern + self.reference_pattern = reference_pattern + + @component.output_types(answers=List[GeneratedAnswer]) + def run( + self, + query: str, + replies: Union[List[str], List[ChatMessage]], + meta: Optional[List[Dict[str, Any]]] = None, + documents: Optional[List[Document]] = None, + pattern: Optional[str] = None, + reference_pattern: Optional[str] = None, + ): + """ + Turns the output of a Generator into `GeneratedAnswer` objects using regular expressions. + + :param query: + The input query used as the Generator prompt. + :param replies: + The output of the Generator. Can be a list of strings or a list of `ChatMessage` objects. + :param meta: + The metadata returned by the Generator. If not specified, the generated answer will contain no metadata. + :param documents: + The documents used as the Generator inputs. If specified, they are added to + the`GeneratedAnswer` objects. + If both `documents` and `reference_pattern` are specified, the documents referenced in the + Generator output are extracted from the input documents and added to the `GeneratedAnswer` objects. + :param pattern: + The regular expression pattern to extract the answer text from the Generator. + If not specified, the entire response is used as the answer. + The regular expression can have one capture group at most. + If present, the capture group text + is used as the answer. If no capture group is present, the whole match is used as the answer. + Examples: + `[^\\n]+$` finds "this is an answer" in a string "this is an argument.\\nthis is an answer". + `Answer: (.*)` finds "this is an answer" in a string + "this is an argument. Answer: this is an answer". + :param reference_pattern: + The regular expression pattern used for parsing the document references. + If not specified, no parsing is done, and all documents are referenced. + References need to be specified as indices of the input documents and start at [1]. + Example: `\\[(\\d+)\\]` finds "1" in a string "this is an answer[1]". + + :returns: A dictionary with the following keys: + - `answers`: The answers received from the output of the Generator. + """ + if not meta: + meta = [{}] * len(replies) + elif len(replies) != len(meta): + raise ValueError(f"Number of replies ({len(replies)}), and metadata ({len(meta)}) must match.") + + if pattern: + AnswerBuilder._check_num_groups_in_regex(pattern) + + pattern = pattern or self.pattern + reference_pattern = reference_pattern or self.reference_pattern + all_answers = [] + for reply, metadata in zip(replies, meta): + # Extract content from ChatMessage objects if reply is a ChatMessages, else use the string as is + extracted_reply: str = reply.content if isinstance(reply, ChatMessage) else reply # type: ignore + extracted_metadata = reply.meta if isinstance(reply, ChatMessage) else metadata + referenced_docs = [] + if documents: + if reference_pattern: + reference_idxs = AnswerBuilder._extract_reference_idxs(extracted_reply, reference_pattern) + else: + reference_idxs = [doc_idx for doc_idx, _ in enumerate(documents)] + + for idx in reference_idxs: + try: + referenced_docs.append(documents[idx]) + except IndexError: + logger.warning( + "Document index '{index}' referenced in Generator output is out of range. ", index=idx + 1 + ) + + answer_string = AnswerBuilder._extract_answer_string(extracted_reply, pattern) + answer = GeneratedAnswer( + data=answer_string, query=query, documents=referenced_docs, meta=extracted_metadata + ) + all_answers.append(answer) + + return {"answers": all_answers} + + @staticmethod + def _extract_answer_string(reply: str, pattern: Optional[str] = None) -> str: + """ + Extract the answer string from the generator output using the specified pattern. + + If no pattern is specified, the whole string is used as the answer. + + :param reply: + The output of the Generator. A string. + :param pattern: + The regular expression pattern to use to extract the answer text from the generator output. + """ + if pattern is None: + return reply + + if match := re.search(pattern, reply): + # No capture group in pattern -> use the whole match as answer + if not match.lastindex: + return match.group(0) + # One capture group in pattern -> use the capture group as answer + return match.group(1) + return "" + + @staticmethod + def _extract_reference_idxs(reply: str, reference_pattern: str) -> List[int]: + document_idxs = re.findall(reference_pattern, reply) + return [int(idx) - 1 for idx in document_idxs] + + @staticmethod + def _check_num_groups_in_regex(pattern: str): + num_groups = re.compile(pattern).groups + if num_groups > 1: + raise ValueError( + f"Pattern '{pattern}' contains multiple capture groups. " + f"Please specify a pattern with at most one capture group." + ) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/builders/chat_prompt_builder.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/builders/chat_prompt_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..a8824dffcadb59503ea29ae5c881afca123c5641 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/builders/chat_prompt_builder.py @@ -0,0 +1,254 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from copy import deepcopy +from typing import Any, Dict, List, Optional, Set + +from jinja2 import meta +from jinja2.sandbox import SandboxedEnvironment + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.dataclasses.chat_message import ChatMessage, ChatRole + +logger = logging.getLogger(__name__) + + +@component +class ChatPromptBuilder: + """ + Renders a chat prompt from a template string using Jinja2 syntax. + + It constructs prompts using static or dynamic templates, which you can update for each pipeline run. + + Template variables in the template are optional unless specified otherwise. + If an optional variable isn't provided, it defaults to an empty string. Use `variable` and `required_variables` + to define input types and required variables. + + ### Usage examples + + #### With static prompt template + + ```python + template = [ChatMessage.from_user("Translate to {{ target_language }}. Context: {{ snippet }}; Translation:")] + builder = ChatPromptBuilder(template=template) + builder.run(target_language="spanish", snippet="I can't speak spanish.") + ``` + + #### Overriding static template at runtime + + ```python + template = [ChatMessage.from_user("Translate to {{ target_language }}. Context: {{ snippet }}; Translation:")] + builder = ChatPromptBuilder(template=template) + builder.run(target_language="spanish", snippet="I can't speak spanish.") + + msg = "Translate to {{ target_language }} and summarize. Context: {{ snippet }}; Summary:" + summary_template = [ChatMessage.from_user(msg)] + builder.run(target_language="spanish", snippet="I can't speak spanish.", template=summary_template) + ``` + + #### With dynamic prompt template + + ```python + from haystack.components.builders import ChatPromptBuilder + from haystack.components.generators.chat import OpenAIChatGenerator + from haystack.dataclasses import ChatMessage + from haystack import Pipeline + from haystack.utils import Secret + + # no parameter init, we don't use any runtime template variables + prompt_builder = ChatPromptBuilder() + llm = OpenAIChatGenerator(api_key=Secret.from_token(""), model="gpt-4o-mini") + + pipe = Pipeline() + pipe.add_component("prompt_builder", prompt_builder) + pipe.add_component("llm", llm) + pipe.connect("prompt_builder.prompt", "llm.messages") + + location = "Berlin" + language = "English" + system_message = ChatMessage.from_system("You are an assistant giving information to tourists in {{language}}") + messages = [system_message, ChatMessage.from_user("Tell me about {{location}}")] + + res = pipe.run(data={"prompt_builder": {"template_variables": {"location": location, "language": language}, + "template": messages}}) + print(res) + + >> {'llm': {'replies': [ChatMessage(content="Berlin is the capital city of Germany and one of the most vibrant + and diverse cities in Europe. Here are some key things to know...Enjoy your time exploring the vibrant and dynamic + capital of Germany!", role=, name=None, meta={'model': 'gpt-4o-mini', + 'index': 0, 'finish_reason': 'stop', 'usage': {'prompt_tokens': 27, 'completion_tokens': 681, 'total_tokens': + 708}})]}} + + + messages = [system_message, ChatMessage.from_user("What's the weather forecast for {{location}} in the next + {{day_count}} days?")] + + res = pipe.run(data={"prompt_builder": {"template_variables": {"location": location, "day_count": "5"}, + "template": messages}}) + + print(res) + >> {'llm': {'replies': [ChatMessage(content="Here is the weather forecast for Berlin in the next 5 + days:\\n\\nDay 1: Mostly cloudy with a high of 22°C (72°F) and...so it's always a good idea to check for updates + closer to your visit.", role=, name=None, meta={'model': 'gpt-4o-mini', + 'index': 0, 'finish_reason': 'stop', 'usage': {'prompt_tokens': 37, 'completion_tokens': 201, + 'total_tokens': 238}})]}} + ``` + + """ + + def __init__( + self, + template: Optional[List[ChatMessage]] = None, + required_variables: Optional[List[str]] = None, + variables: Optional[List[str]] = None, + ): + """ + Constructs a ChatPromptBuilder component. + + :param template: + A list of `ChatMessage` objects. The component looks for Jinja2 template syntax and + renders the prompt with the provided variables. Provide the template in either + the `init` method` or the `run` method. + :param required_variables: + List variables that must be provided as input to ChatPromptBuilder. + If a variable listed as required is not provided, an exception is raised. Optional. + :param variables: + List input variables to use in prompt templates instead of the ones inferred from the + `template` parameter. For example, to use more variables during prompt engineering than the ones present + in the default template, you can provide them here. + """ + self._variables = variables + self._required_variables = required_variables + self.required_variables = required_variables or [] + self.template = template + variables = variables or [] + self._env = SandboxedEnvironment() + if template and not variables: + for message in template: + if message.is_from(ChatRole.USER) or message.is_from(ChatRole.SYSTEM): + # infere variables from template + ast = self._env.parse(message.content) + template_variables = meta.find_undeclared_variables(ast) + variables += list(template_variables) + + # setup inputs + for var in variables: + if var in self.required_variables: + component.set_input_type(self, var, Any) + else: + component.set_input_type(self, var, Any, "") + + @component.output_types(prompt=List[ChatMessage]) + def run( + self, + template: Optional[List[ChatMessage]] = None, + template_variables: Optional[Dict[str, Any]] = None, + **kwargs, + ): + """ + Renders the prompt template with the provided variables. + + It applies the template variables to render the final prompt. You can provide variables with pipeline kwargs. + To overwrite the default template, you can set the `template` parameter. + To overwrite pipeline kwargs, you can set the `template_variables` parameter. + + :param template: + An optional list of `ChatMessage` objects to overwrite ChatPromptBuilder's default template. + If `None`, the default template provided at initialization is used. + :param template_variables: + An optional dictionary of template variables to overwrite the pipeline variables. + :param kwargs: + Pipeline variables used for rendering the prompt. + + :returns: A dictionary with the following keys: + - `prompt`: The updated list of `ChatMessage` objects after rendering the templates. + :raises ValueError: + If `chat_messages` is empty or contains elements that are not instances of `ChatMessage`. + """ + kwargs = kwargs or {} + template_variables = template_variables or {} + template_variables_combined = {**kwargs, **template_variables} + + if template is None: + template = self.template + + if not template: + raise ValueError( + f"The {self.__class__.__name__} requires a non-empty list of ChatMessage instances. " + f"Please provide a valid list of ChatMessage instances to render the prompt." + ) + + if not all(isinstance(message, ChatMessage) for message in template): + raise ValueError( + f"The {self.__class__.__name__} expects a list containing only ChatMessage instances. " + f"The provided list contains other types. Please ensure that all elements in the list " + f"are ChatMessage instances." + ) + + processed_messages = [] + for message in template: + if message.is_from(ChatRole.USER) or message.is_from(ChatRole.SYSTEM): + self._validate_variables(set(template_variables_combined.keys())) + + compiled_template = self._env.from_string(message.content) + rendered_content = compiled_template.render(template_variables_combined) + # deep copy the message to avoid modifying the original message + rendered_message: ChatMessage = deepcopy(message) + rendered_message.content = rendered_content + processed_messages.append(rendered_message) + else: + processed_messages.append(message) + + return {"prompt": processed_messages} + + def _validate_variables(self, provided_variables: Set[str]): + """ + Checks if all the required template variables are provided. + + :param provided_variables: + A set of provided template variables. + :raises ValueError: + If no template is provided or if all the required template variables are not provided. + """ + missing_variables = [var for var in self.required_variables if var not in provided_variables] + if missing_variables: + missing_vars_str = ", ".join(missing_variables) + raise ValueError( + f"Missing required input variables in ChatPromptBuilder: {missing_vars_str}. " + f"Required variables: {self.required_variables}. Provided variables: {provided_variables}." + ) + + def to_dict(self) -> Dict[str, Any]: + """ + Returns a dictionary representation of the component. + + :returns: + Serialized dictionary representation of the component. + """ + if self.template is not None: + template = [m.to_dict() for m in self.template] + else: + template = None + + return default_to_dict( + self, template=template, variables=self._variables, required_variables=self._required_variables + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "ChatPromptBuilder": + """ + Deserialize this component from a dictionary. + + :param data: + The dictionary to deserialize and create the component. + + :returns: + The deserialized component. + """ + init_parameters = data["init_parameters"] + template = init_parameters.get("template") + if template: + init_parameters["template"] = [ChatMessage.from_dict(d) for d in template] + + return default_from_dict(cls, data) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/builders/prompt_builder.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/builders/prompt_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..3cb29e121113d32d3732367aa6372a21f6f52c20 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/builders/prompt_builder.py @@ -0,0 +1,247 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional, Set + +from jinja2 import meta +from jinja2.sandbox import SandboxedEnvironment + +from haystack import component, default_to_dict +from haystack.utils import Jinja2TimeExtension + + +@component +class PromptBuilder: + """ + + Renders a prompt filling in any variables so that it can send it to a Generator. + + The prompt uses Jinja2 template syntax. + The variables in the default template are used as PromptBuilder's input and are all optional. + If they're not provided, they're replaced with an empty string in the rendered prompt. + To try out different prompts, you can replace the prompt template at runtime by + providing a template for each pipeline run invocation. + + ### Usage examples + + #### On its own + + This example uses PromptBuilder to render a prompt template and fill it with `target_language` + and `snippet`. PromptBuilder returns a prompt with the string "Translate the following context to Spanish. + Context: I can't speak Spanish.; Translation:". + ```python + from haystack.components.builders import PromptBuilder + + template = "Translate the following context to {{ target_language }}. Context: {{ snippet }}; Translation:" + builder = PromptBuilder(template=template) + builder.run(target_language="spanish", snippet="I can't speak spanish.") + ``` + + #### In a Pipeline + + This is an example of a RAG pipeline where PromptBuilder renders a custom prompt template and fills it + with the contents of the retrieved documents and a query. The rendered prompt is then sent to a Generator. + ```python + from haystack import Pipeline, Document + from haystack.utils import Secret + from haystack.components.generators import OpenAIGenerator + from haystack.components.builders.prompt_builder import PromptBuilder + + # in a real world use case documents could come from a retriever, web, or any other source + documents = [Document(content="Joe lives in Berlin"), Document(content="Joe is a software engineer")] + prompt_template = \"\"\" + Given these documents, answer the question. + Documents: + {% for doc in documents %} + {{ doc.content }} + {% endfor %} + + Question: {{query}} + Answer: + \"\"\" + p = Pipeline() + p.add_component(instance=PromptBuilder(template=prompt_template), name="prompt_builder") + p.add_component(instance=OpenAIGenerator(api_key=Secret.from_env_var("OPENAI_API_KEY")), name="llm") + p.connect("prompt_builder", "llm") + + question = "Where does Joe live?" + result = p.run({"prompt_builder": {"documents": documents, "query": question}}) + print(result) + ``` + + #### Changing the template at runtime (prompt engineering) + + You can change the prompt template of an existing pipeline, like in this example: + ```python + documents = [ + Document(content="Joe lives in Berlin", meta={"name": "doc1"}), + Document(content="Joe is a software engineer", meta={"name": "doc1"}), + ] + new_template = \"\"\" + You are a helpful assistant. + Given these documents, answer the question. + Documents: + {% for doc in documents %} + Document {{ loop.index }}: + Document name: {{ doc.meta['name'] }} + {{ doc.content }} + {% endfor %} + + Question: {{ query }} + Answer: + \"\"\" + p.run({ + "prompt_builder": { + "documents": documents, + "query": question, + "template": new_template, + }, + }) + ``` + To replace the variables in the default template when testing your prompt, + pass the new variables in the `variables` parameter. + + #### Overwriting variables at runtime + + To overwrite the values of variables, use `template_variables` during runtime: + ```python + language_template = \"\"\" + You are a helpful assistant. + Given these documents, answer the question. + Documents: + {% for doc in documents %} + Document {{ loop.index }}: + Document name: {{ doc.meta['name'] }} + {{ doc.content }} + {% endfor %} + + Question: {{ query }} + Please provide your answer in {{ answer_language | default('English') }} + Answer: + \"\"\" + p.run({ + "prompt_builder": { + "documents": documents, + "query": question, + "template": language_template, + "template_variables": {"answer_language": "German"}, + }, + }) + ``` + Note that `language_template` introduces variable `answer_language` which is not bound to any pipeline variable. + If not set otherwise, it will use its default value 'English'. + This example overwrites its value to 'German'. + Use `template_variables` to overwrite pipeline variables (such as documents) as well. + + """ + + def __init__( + self, template: str, required_variables: Optional[List[str]] = None, variables: Optional[List[str]] = None + ): + """ + Constructs a PromptBuilder component. + + :param template: + A prompt template that uses Jinja2 syntax to add variables. For example: + `"Summarize this document: {{ documents[0].content }}\\nSummary:"` + It's used to render the prompt. + The variables in the default template are input for PromptBuilder and are all optional, + unless explicitly specified. + If an optional variable is not provided, it's replaced with an empty string in the rendered prompt. + :param required_variables: List variables that must be provided as input to PromptBuilder. + If a variable listed as required is not provided, an exception is raised. Optional. + :param variables: + List input variables to use in prompt templates instead of the ones inferred from the + `template` parameter. For example, to use more variables during prompt engineering than the ones present + in the default template, you can provide them here. + """ + self._template_string = template + self._variables = variables + self._required_variables = required_variables + self.required_variables = required_variables or [] + try: + # The Jinja2TimeExtension needs an optional dependency to be installed. + # If it's not available we can do without it and use the PromptBuilder as is. + self._env = SandboxedEnvironment(extensions=[Jinja2TimeExtension]) + except ImportError: + self._env = SandboxedEnvironment() + + self.template = self._env.from_string(template) + if not variables: + # infer variables from template + ast = self._env.parse(template) + template_variables = meta.find_undeclared_variables(ast) + variables = list(template_variables) + + variables = variables or [] + + # setup inputs + for var in variables: + if var in self.required_variables: + component.set_input_type(self, var, Any) + else: + component.set_input_type(self, var, Any, "") + + def to_dict(self) -> Dict[str, Any]: + """ + Returns a dictionary representation of the component. + + :returns: + Serialized dictionary representation of the component. + """ + return default_to_dict( + self, template=self._template_string, variables=self._variables, required_variables=self._required_variables + ) + + @component.output_types(prompt=str) + def run(self, template: Optional[str] = None, template_variables: Optional[Dict[str, Any]] = None, **kwargs): + """ + Renders the prompt template with the provided variables. + + It applies the template variables to render the final prompt. You can provide variables via pipeline kwargs. + In order to overwrite the default template, you can set the `template` parameter. + In order to overwrite pipeline kwargs, you can set the `template_variables` parameter. + + :param template: + An optional string template to overwrite PromptBuilder's default template. If None, the default template + provided at initialization is used. + :param template_variables: + An optional dictionary of template variables to overwrite the pipeline variables. + :param kwargs: + Pipeline variables used for rendering the prompt. + + :returns: A dictionary with the following keys: + - `prompt`: The updated prompt text after rendering the prompt template. + + :raises ValueError: + If any of the required template variables is not provided. + """ + kwargs = kwargs or {} + template_variables = template_variables or {} + template_variables_combined = {**kwargs, **template_variables} + self._validate_variables(set(template_variables_combined.keys())) + + compiled_template = self.template + if template is not None: + compiled_template = self._env.from_string(template) + + result = compiled_template.render(template_variables_combined) + return {"prompt": result} + + def _validate_variables(self, provided_variables: Set[str]): + """ + Checks if all the required template variables are provided. + + :param provided_variables: + A set of provided template variables. + :raises ValueError: + If any of the required template variables is not provided. + """ + missing_variables = [var for var in self.required_variables if var not in provided_variables] + if missing_variables: + missing_vars_str = ", ".join(missing_variables) + raise ValueError( + f"Missing required input variables in PromptBuilder: {missing_vars_str}. " + f"Required variables: {self.required_variables}. Provided variables: {provided_variables}." + ) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/caching/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/caching/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e922713dc469212be43ba32db4fa6e2b74ca9313 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/caching/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.caching.cache_checker import CacheChecker + +__all__ = ["CacheChecker"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/caching/cache_checker.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/caching/cache_checker.py new file mode 100644 index 0000000000000000000000000000000000000000..b67608b07551b4578fded49bb5a6f1fbcfe3b9be --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/caching/cache_checker.py @@ -0,0 +1,102 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List + +from haystack import Document, component, default_from_dict, default_to_dict, logging +from haystack.document_stores.types import DocumentStore +from haystack.utils import deserialize_document_store_in_init_params_inplace + +logger = logging.getLogger(__name__) + + +@component +class CacheChecker: + """ + Checks for the presence of documents in a Document Store based on a specified field in each document's metadata. + + If matching documents are found, they are returned as "hits". If not found in the cache, the items + are returned as "misses". + + ### Usage example + + ```python + from haystack import Document + from haystack.document_stores.in_memory import InMemoryDocumentStore + from haystack.components.caching.cache_checker import CacheChecker + + docstore = InMemoryDocumentStore() + documents = [ + Document(content="doc1", meta={"url": "https://example.com/1"}), + Document(content="doc2", meta={"url": "https://example.com/2"}), + Document(content="doc3", meta={"url": "https://example.com/1"}), + Document(content="doc4", meta={"url": "https://example.com/2"}), + ] + docstore.write_documents(documents) + checker = CacheChecker(docstore, cache_field="url") + results = checker.run(items=["https://example.com/1", "https://example.com/5"]) + assert results == {"hits": [documents[0], documents[2]], "misses": ["https://example.com/5"]} + ``` + """ + + def __init__(self, document_store: DocumentStore, cache_field: str): + """ + Creates a CacheChecker component. + + :param document_store: + Document Store to check for the presence of specific documents. + :param cache_field: + Name of the document's metadata field + to check for cache hits. + """ + self.document_store = document_store + self.cache_field = cache_field + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict(self, document_store=self.document_store.to_dict(), cache_field=self.cache_field) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "CacheChecker": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + # deserialize the document store + deserialize_document_store_in_init_params_inplace(data) + + return default_from_dict(cls, data) + + @component.output_types(hits=List[Document], misses=List) + def run(self, items: List[Any]): + """ + Checks if any document associated with the specified cache field is already present in the store. + + :param items: + Values to be checked against the cache field. + :return: + A dictionary with two keys: + - `hits` - Documents that matched with at least one of the items. + - `misses` - Items that were not present in any documents. + """ + found_documents = [] + misses = [] + + for item in items: + filters = {"field": self.cache_field, "operator": "==", "value": item} + found = self.document_store.filter_documents(filters=filters) + if found: + found_documents.extend(found) + else: + misses.append(item) + return {"hits": found_documents, "misses": misses} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/classifiers/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/classifiers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..662df14d82de7578a5938225de5a0d2626e93141 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/classifiers/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.classifiers.document_language_classifier import DocumentLanguageClassifier +from haystack.components.classifiers.zero_shot_document_classifier import TransformersZeroShotDocumentClassifier + +__all__ = ["DocumentLanguageClassifier", "TransformersZeroShotDocumentClassifier"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/classifiers/document_language_classifier.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/classifiers/document_language_classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..ed9b42b5d5472b5b4c77d4ea9bb0dd152925b9c8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/classifiers/document_language_classifier.py @@ -0,0 +1,109 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Dict, List, Optional + +from haystack import Document, component, logging +from haystack.lazy_imports import LazyImport + +logger = logging.getLogger(__name__) + +with LazyImport("Run 'pip install langdetect'") as langdetect_import: + import langdetect + + +@component +class DocumentLanguageClassifier: + """ + Classifies the language of each document and adds it to its metadata. + + Provide a list of languages during initialization. If the document's text doesn't match any of the + specified languages, the metadata value is set to "unmatched". + To route documents based on their language, use the MetadataRouter component after DocumentLanguageClassifier. + For routing plain text, use the TextLanguageRouter component instead. + + ### Usage example + + ```python + from haystack import Document, Pipeline + from haystack.document_stores.in_memory import InMemoryDocumentStore + from haystack.components.classifiers import DocumentLanguageClassifier + from haystack.components.routers import MetadataRouter + from haystack.components.writers import DocumentWriter + + docs = [Document(id="1", content="This is an English document"), + Document(id="2", content="Este es un documento en español")] + + document_store = InMemoryDocumentStore() + + p = Pipeline() + p.add_component(instance=DocumentLanguageClassifier(languages=["en"]), name="language_classifier") + p.add_component(instance=MetadataRouter(rules={"en": {"language": {"$eq": "en"}}}), name="router") + p.add_component(instance=DocumentWriter(document_store=document_store), name="writer") + p.connect("language_classifier.documents", "router.documents") + p.connect("router.en", "writer.documents") + + p.run({"language_classifier": {"documents": docs}}) + + written_docs = document_store.filter_documents() + assert len(written_docs) == 1 + assert written_docs[0] == Document(id="1", content="This is an English document", meta={"language": "en"}) + ``` + """ + + def __init__(self, languages: Optional[List[str]] = None): + """ + Initializes the DocumentLanguageClassifier component. + + :param languages: A list of ISO language codes. + See the supported languages in [`langdetect` documentation](https://github.com/Mimino666/langdetect#languages). + If not specified, defaults to ["en"]. + """ + langdetect_import.check() + if not languages: + languages = ["en"] + self.languages = languages + + @component.output_types(documents=List[Document]) + def run(self, documents: List[Document]): + """ + Classifies the language of each document and adds it to its metadata. + + If the document's text doesn't match any of the languages specified at initialization, + sets the metadata value to "unmatched". + + :param documents: A list of documents for language classification. + + :returns: A dictionary with the following key: + - `documents`: A list of documents with an added `language` metadata field. + + :raises TypeError: if the input is not a list of Documents. + """ + if not isinstance(documents, list) or documents and not isinstance(documents[0], Document): + raise TypeError( + "DocumentLanguageClassifier expects a list of Document as input. " + "In case you want to classify a text, please use the TextLanguageClassifier." + ) + + output: Dict[str, List[Document]] = {language: [] for language in self.languages} + output["unmatched"] = [] + + for document in documents: + detected_language = self._detect_language(document) + if detected_language in self.languages: + document.meta["language"] = detected_language + else: + document.meta["language"] = "unmatched" + + return {"documents": documents} + + def _detect_language(self, document: Document) -> Optional[str]: + try: + language = langdetect.detect(document.content) + except langdetect.LangDetectException: + logger.warning( + "Langdetect cannot detect the language of Document with id: {document_id}", document_id=document.id + ) + language = None + return language diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/classifiers/zero_shot_document_classifier.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/classifiers/zero_shot_document_classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..5aa52fde80fc3c55a1d89f4c3ca68f9fc36566e3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/classifiers/zero_shot_document_classifier.py @@ -0,0 +1,245 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional + +from haystack import Document, component, default_from_dict, default_to_dict, logging +from haystack.lazy_imports import LazyImport +from haystack.utils import ComponentDevice, Secret, deserialize_secrets_inplace +from haystack.utils.hf import deserialize_hf_model_kwargs, resolve_hf_pipeline_kwargs, serialize_hf_model_kwargs + +logger = logging.getLogger(__name__) + + +with LazyImport(message="Run 'pip install transformers[torch,sentencepiece]'") as torch_and_transformers_import: + from transformers import pipeline + + +@component +class TransformersZeroShotDocumentClassifier: + """ + Performs zero-shot classification of documents based on given labels and adds the predicted label to their metadata. + + The component uses a Hugging Face pipeline for zero-shot classification. + Provide the model and the set of labels to be used for categorization during initialization. + Additionally, you can configure the component to allow multiple labels to be true. + + Classification is run on the document's content field by default. If you want it to run on another field, set the + `classification_field` to one of the document's metadata fields. + + Available models for the task of zero-shot-classification include: + - `valhalla/distilbart-mnli-12-3` + - `cross-encoder/nli-distilroberta-base` + - `cross-encoder/nli-deberta-v3-xsmall` + + ### Usage example + + The following is a pipeline that classifies documents based on predefined classification labels + retrieved from a search pipeline: + + ```python + from haystack import Document + from haystack.components.retrievers.in_memory import InMemoryBM25Retriever + from haystack.document_stores.in_memory import InMemoryDocumentStore + from haystack.core.pipeline import Pipeline + from haystack.components.classifiers import TransformersZeroShotDocumentClassifier + + documents = [Document(id="0", content="Today was a nice day!"), + Document(id="1", content="Yesterday was a bad day!")] + + document_store = InMemoryDocumentStore() + retriever = InMemoryBM25Retriever(document_store=document_store) + document_classifier = TransformersZeroShotDocumentClassifier( + model="cross-encoder/nli-deberta-v3-xsmall", + labels=["positive", "negative"], + ) + + document_store.write_documents(documents) + + pipeline = Pipeline() + pipeline.add_component(instance=retriever, name="retriever") + pipeline.add_component(instance=document_classifier, name="document_classifier") + pipeline.connect("retriever", "document_classifier") + + queries = ["How was your day today?", "How was your day yesterday?"] + expected_predictions = ["positive", "negative"] + + for idx, query in enumerate(queries): + result = pipeline.run({"retriever": {"query": query, "top_k": 1}}) + assert result["document_classifier"]["documents"][0].to_dict()["id"] == str(idx) + assert (result["document_classifier"]["documents"][0].to_dict()["classification"]["label"] + == expected_predictions[idx]) + ``` + """ + + def __init__( + self, + model: str, + labels: List[str], + multi_label: bool = False, + classification_field: Optional[str] = None, + device: Optional[ComponentDevice] = None, + token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + huggingface_pipeline_kwargs: Optional[Dict[str, Any]] = None, + ): + """ + Initializes the TransformersZeroShotDocumentClassifier. + + See the Hugging Face [website](https://huggingface.co/models?pipeline_tag=zero-shot-classification&sort=downloads&search=nli) + for the full list of zero-shot classification models (NLI) models. + + :param model: + The name or path of a Hugging Face model for zero shot document classification. + :param labels: + The set of possible class labels to classify each document into, for example, + ["positive", "negative"]. The labels depend on the selected model. + :param multi_label: + Whether or not multiple candidate labels can be true. + If `False`, the scores are normalized such that + the sum of the label likelihoods for each sequence is 1. If `True`, the labels are considered + independent and probabilities are normalized for each candidate by doing a softmax of the entailment + score vs. the contradiction score. + :param classification_field: + Name of document's meta field to be used for classification. + If not set, `Document.content` is used by default. + :param device: + The device on which the model is loaded. If `None`, the default device is automatically + selected. If a device/device map is specified in `huggingface_pipeline_kwargs`, it overrides this parameter. + :param token: + The Hugging Face token to use as HTTP bearer authorization. + Check your HF token in your [account settings](https://huggingface.co/settings/tokens). + :param huggingface_pipeline_kwargs: + Dictionary containing keyword arguments used to initialize the + Hugging Face pipeline for text classification. + """ + + torch_and_transformers_import.check() + + self.classification_field = classification_field + + self.token = token + self.labels = labels + self.multi_label = multi_label + + huggingface_pipeline_kwargs = resolve_hf_pipeline_kwargs( + huggingface_pipeline_kwargs=huggingface_pipeline_kwargs or {}, + model=model, + task="zero-shot-classification", + supported_tasks=["zero-shot-classification"], + device=device, + token=token, + ) + + self.huggingface_pipeline_kwargs = huggingface_pipeline_kwargs + self.pipeline = None + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + if isinstance(self.huggingface_pipeline_kwargs["model"], str): + return {"model": self.huggingface_pipeline_kwargs["model"]} + return {"model": f"[object of type {type(self.huggingface_pipeline_kwargs['model'])}]"} + + def warm_up(self): + """ + Initializes the component. + """ + if self.pipeline is None: + self.pipeline = pipeline(**self.huggingface_pipeline_kwargs) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + serialization_dict = default_to_dict( + self, + labels=self.labels, + model=self.huggingface_pipeline_kwargs["model"], + huggingface_pipeline_kwargs=self.huggingface_pipeline_kwargs, + token=self.token.to_dict() if self.token else None, + ) + + huggingface_pipeline_kwargs = serialization_dict["init_parameters"]["huggingface_pipeline_kwargs"] + huggingface_pipeline_kwargs.pop("token", None) + + serialize_hf_model_kwargs(huggingface_pipeline_kwargs) + return serialization_dict + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "TransformersZeroShotDocumentClassifier": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["token"]) + if data["init_parameters"].get("huggingface_pipeline_kwargs") is not None: + deserialize_hf_model_kwargs(data["init_parameters"]["huggingface_pipeline_kwargs"]) + return default_from_dict(cls, data) + + @component.output_types(documents=List[Document]) + def run(self, documents: List[Document], batch_size: int = 1): + """ + Classifies the documents based on the provided labels and adds them to their metadata. + + The classification results are stored in the `classification` dict within + each document's metadata. If `multi_label` is set to `True`, the scores for each label are available under + the `details` key within the `classification` dictionary. + + :param documents: + Documents to process. + :param batch_size: + Batch size used for processing the content in each document. + :returns: + A dictionary with the following key: + - `documents`: A list of documents with an added metadata field called `classification`. + """ + + if self.pipeline is None: + raise RuntimeError( + "The component TransformerZeroShotDocumentClassifier wasn't warmed up. " + "Run 'warm_up()' before calling 'run()'." + ) + + if not isinstance(documents, list) or documents and not isinstance(documents[0], Document): + raise TypeError( + "DocumentLanguageClassifier expects a list of documents as input. " + "In case you want to classify a text, please use the TextLanguageClassifier." + ) + + invalid_doc_ids = [] + + for doc in documents: + if self.classification_field is not None and self.classification_field not in doc.meta: + invalid_doc_ids.append(doc.id) + + if invalid_doc_ids: + raise ValueError( + f"The following documents do not have the classification field '{self.classification_field}': " + f"{', '.join(invalid_doc_ids)}" + ) + + texts = [ + (doc.content if self.classification_field is None else doc.meta[self.classification_field]) + for doc in documents + ] + + predictions = self.pipeline(texts, self.labels, multi_label=self.multi_label, batch_size=batch_size) + + for prediction, document in zip(predictions, documents): + formatted_prediction = { + "label": prediction["labels"][0], + "score": prediction["scores"][0], + "details": dict(zip(prediction["labels"], prediction["scores"])), + } + document.meta["classification"] = formatted_prediction + + return {"documents": documents} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/connectors/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/connectors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b9fbe418aa57b08bb00c58b62c167e9697e87dae --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/connectors/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.connectors.openapi_service import OpenAPIServiceConnector + +__all__ = ["OpenAPIServiceConnector"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/connectors/openapi_service.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/connectors/openapi_service.py new file mode 100644 index 0000000000000000000000000000000000000000..5238722f7fedce5bdb018c2271a417020d7b30e7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/connectors/openapi_service.py @@ -0,0 +1,270 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +from collections import defaultdict +from copy import copy +from typing import Any, Dict, List, Optional, Union + +from haystack import component, logging +from haystack.dataclasses import ChatMessage, ChatRole +from haystack.lazy_imports import LazyImport + +logger = logging.getLogger(__name__) + +with LazyImport("Run 'pip install openapi3'") as openapi_imports: + from openapi3 import OpenAPI + + +@component +class OpenAPIServiceConnector: + """ + A component which connects the Haystack framework to OpenAPI services. + + The `OpenAPIServiceConnector` component connects the Haystack framework to OpenAPI services, enabling it to call + operations as defined in the OpenAPI specification of the service. + + It integrates with `ChatMessage` dataclass, where the payload in messages is used to determine the method to be + called and the parameters to be passed. The message payload should be an OpenAI JSON formatted function calling + string consisting of the method name and the parameters to be passed to the method. The method name and parameters + are then used to invoke the method on the OpenAPI service. The response from the service is returned as a + `ChatMessage`. + + Before using this component, users usually resolve service endpoint parameters with a help of + `OpenAPIServiceToFunctions` component. + + The example below demonstrates how to use the `OpenAPIServiceConnector` to invoke a method on a https://serper.dev/ + service specified via OpenAPI specification. + + Note, however, that `OpenAPIServiceConnector` is usually not meant to be used directly, but rather as part of a + pipeline that includes the `OpenAPIServiceToFunctions` component and an `OpenAIChatGenerator` component using LLM + with the function calling capabilities. In the example below we use the function calling payload directly, but in a + real-world scenario, the function calling payload would usually be generated by the `OpenAIChatGenerator` component. + + Usage example: + + ```python + import json + import requests + + from haystack.components.connectors import OpenAPIServiceConnector + from haystack.dataclasses import ChatMessage + + + fc_payload = [{'function': {'arguments': '{"q": "Why was Sam Altman ousted from OpenAI?"}', 'name': 'search'}, + 'id': 'call_PmEBYvZ7mGrQP5PUASA5m9wO', 'type': 'function'}] + + serper_token = + serperdev_openapi_spec = json.loads(requests.get("https://bit.ly/serper_dev_spec").text) + service_connector = OpenAPIServiceConnector() + result = service_connector.run(messages=[ChatMessage.from_assistant(json.dumps(fc_payload))], + service_openapi_spec=serperdev_openapi_spec, service_credentials=serper_token) + print(result) + + >> {'service_response': [ChatMessage(content='{"searchParameters": {"q": "Why was Sam Altman ousted from OpenAI?", + >> "type": "search", "engine": "google"}, "answerBox": {"snippet": "Concerns over AI safety and OpenAI\'s role + >> in protecting were at the center of Altman\'s brief ouster from the company."... + ``` + + """ + + def __init__(self): + """ + Initializes the OpenAPIServiceConnector instance + """ + openapi_imports.check() + + @component.output_types(service_response=Dict[str, Any]) + def run( + self, + messages: List[ChatMessage], + service_openapi_spec: Dict[str, Any], + service_credentials: Optional[Union[dict, str]] = None, + ) -> Dict[str, List[ChatMessage]]: + """ + Processes a list of chat messages to invoke a method on an OpenAPI service. + + It parses the last message in the list, expecting it to contain an OpenAI function calling descriptor + (name & parameters) in JSON format. + + :param messages: A list of `ChatMessage` objects containing the messages to be processed. The last message + should contain the function invocation payload in OpenAI function calling format. See the example in the class + docstring for the expected format. + :param service_openapi_spec: The OpenAPI JSON specification object of the service to be invoked. All the refs + should already be resolved. + :param service_credentials: The credentials to be used for authentication with the service. + Currently, only the http and apiKey OpenAPI security schemes are supported. + + :return: A dictionary with the following keys: + - `service_response`: a list of `ChatMessage` objects, each containing the response from the service. The + response is in JSON format, and the `content` attribute of the `ChatMessage` contains + the JSON string. + + :raises ValueError: If the last message is not from the assistant or if it does not contain the correct payload + to invoke a method on the service. + """ + + last_message = messages[-1] + if not last_message.is_from(ChatRole.ASSISTANT): + raise ValueError(f"{last_message} is not from the assistant.") + + function_invocation_payloads = self._parse_message(last_message) + + # instantiate the OpenAPI service for the given specification + openapi_service = OpenAPI(service_openapi_spec) + self._authenticate_service(openapi_service, service_credentials) + + response_messages = [] + for method_invocation_descriptor in function_invocation_payloads: + service_response = self._invoke_method(openapi_service, method_invocation_descriptor) + # openapi3 parses the JSON service response into a model object, which is not our focus at the moment. + # Instead, we require direct access to the raw JSON data of the response, rather than the model objects + # provided by the openapi3 library. This approach helps us avoid issues related to (de)serialization. + # By accessing the raw JSON response through `service_response._raw_data`, we can serialize this data + # into a string. Finally, we use this string to create a ChatMessage object. + response_messages.append(ChatMessage.from_user(json.dumps(service_response._raw_data))) + + return {"service_response": response_messages} + + def _parse_message(self, message: ChatMessage) -> List[Dict[str, Any]]: + """ + Parses the message to extract the method invocation descriptor. + + :param message: ChatMessage containing the tools calls + :return: A list of function invocation payloads + :raises ValueError: If the content is not valid JSON or lacks required fields. + """ + function_payloads = [] + try: + tool_calls = json.loads(message.content) + except json.JSONDecodeError: + raise ValueError("Invalid JSON content, expected OpenAI tools message.", message.content) + + for tool_call in tool_calls: + # this should never happen, but just in case do a sanity check + if "type" not in tool_call: + raise ValueError("Message payload doesn't seem to be a tool invocation descriptor", message.content) + + # In OpenAPIServiceConnector we know how to handle functions tools only + if tool_call["type"] == "function": + function_call = tool_call["function"] + function_payloads.append( + {"arguments": json.loads(function_call["arguments"]), "name": function_call["name"]} + ) + return function_payloads + + def _authenticate_service(self, openapi_service: OpenAPI, credentials: Optional[Union[dict, str]] = None): + """ + Authentication with an OpenAPI service. + + Authenticates with the OpenAPI service if required, supporting both single (str) and multiple + authentication methods (dict). + + OpenAPI spec v3 supports the following security schemes: + http – for Basic, Bearer and other HTTP authentications schemes + apiKey – for API keys and cookie authentication + oauth2 – for OAuth 2 + openIdConnect – for OpenID Connect Discovery + + Currently, only the http and apiKey schemes are supported. Multiple security schemes can be defined in the + OpenAPI spec, and the credentials should be provided as a dictionary with keys matching the security scheme + names. If only one security scheme is defined, the credentials can be provided as a simple string. + + :param openapi_service: The OpenAPI service instance. + :param credentials: Credentials for authentication, which can be either a string (e.g. token) or a dictionary + with keys matching the authentication method names. + :raises ValueError: If authentication fails, is not found, or if appropriate credentials are missing. + """ + if openapi_service.raw_element.get("components", {}).get("securitySchemes"): + service_name = openapi_service.info.title + if not credentials: + raise ValueError(f"Service {service_name} requires authentication but no credentials were provided.") + + # a dictionary of security schemes defined in the OpenAPI spec + # each key is the name of the security scheme, and the value is the scheme definition + security_schemes = openapi_service.components.securitySchemes.raw_element + supported_schemes = ["http", "apiKey"] # todo: add support for oauth2 and openIdConnect + + authenticated = False + for scheme_name, scheme in security_schemes.items(): + if scheme["type"] in supported_schemes: + auth_credentials = None + if isinstance(credentials, str): + auth_credentials = credentials + elif isinstance(credentials, dict) and scheme_name in credentials: + auth_credentials = credentials[scheme_name] + if auth_credentials: + openapi_service.authenticate(scheme_name, auth_credentials) + authenticated = True + break + + raise ValueError( + f"Service {service_name} requires {scheme_name} security scheme but no " + f"credentials were provided for it. Check the service configuration and credentials." + ) + if not authenticated: + raise ValueError( + f"Service {service_name} requires authentication but no credentials were provided " + f"for it. Check the service configuration and credentials." + ) + + def _invoke_method(self, openapi_service: OpenAPI, method_invocation_descriptor: Dict[str, Any]) -> Any: + """ + Invokes the specified method on the OpenAPI service. + + The method name and arguments are passed in the method_invocation_descriptor. + + :param openapi_service: The OpenAPI service instance. + :param method_invocation_descriptor: The method name and arguments to be passed to the method. The payload + should contain the method name (key: "name") and the arguments (key: "arguments"). The name is a string, and + the arguments are a dictionary of key-value pairs. + :return: A service JSON response. + :raises RuntimeError: If the method is not found or invocation fails. + """ + name = method_invocation_descriptor.get("name") + invocation_arguments = copy(method_invocation_descriptor.get("arguments", {})) + if not name or not invocation_arguments: + raise ValueError( + f"Invalid function calling descriptor: {method_invocation_descriptor} . It should contain " + f"a method name and arguments." + ) + + # openapi3 specific method to call the operation, do we have it? + method_to_call = getattr(openapi_service, f"call_{name}", None) + if not callable(method_to_call): + raise RuntimeError(f"Operation {name} not found in OpenAPI specification {openapi_service.info.title}") + + # get the operation reference from the method_to_call + operation = method_to_call.operation.__self__ + operation_dict = operation.raw_element + + # Pack URL/query parameters under "parameters" key + method_call_params: Dict[str, Dict[str, Any]] = defaultdict(dict) + parameters = operation_dict.get("parameters", []) + request_body = operation_dict.get("requestBody", {}) + + for param in parameters: + param_name = param["name"] + param_value = invocation_arguments.get(param_name) + if param_value: + method_call_params["parameters"][param_name] = param_value + else: + if param.get("required", False): + raise ValueError(f"Missing parameter: '{param_name}' required for the '{name}' operation.") + + # Pack request body parameters under "data" key + if request_body: + schema = request_body.get("content", {}).get("application/json", {}).get("schema", {}) + required_params = schema.get("required", []) + for param_name in schema.get("properties", {}): + param_value = invocation_arguments.get(param_name) + if param_value: + method_call_params["data"][param_name] = param_value + else: + if param_name in required_params: + raise ValueError( + f"Missing requestBody parameter: '{param_name}' required for the '{name}' operation." + ) + # call the underlying service REST API with the parameters + return method_to_call(**method_call_params) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4561dd1e0a2d06eae06adbc7ebce92b589d401b8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/__init__.py @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.converters.azure import AzureOCRDocumentConverter +from haystack.components.converters.csv import CSVToDocument +from haystack.components.converters.docx import DOCXMetadata, DOCXToDocument +from haystack.components.converters.html import HTMLToDocument +from haystack.components.converters.json import JSONConverter +from haystack.components.converters.markdown import MarkdownToDocument +from haystack.components.converters.openapi_functions import OpenAPIServiceToFunctions +from haystack.components.converters.output_adapter import OutputAdapter +from haystack.components.converters.pdfminer import PDFMinerToDocument +from haystack.components.converters.pptx import PPTXToDocument +from haystack.components.converters.pypdf import PyPDFToDocument +from haystack.components.converters.tika import TikaDocumentConverter +from haystack.components.converters.txt import TextFileToDocument + +__all__ = [ + "TextFileToDocument", + "TikaDocumentConverter", + "AzureOCRDocumentConverter", + "PyPDFToDocument", + "PDFMinerToDocument", + "HTMLToDocument", + "MarkdownToDocument", + "OpenAPIServiceToFunctions", + "OutputAdapter", + "DOCXToDocument", + "DOCXMetadata", + "PPTXToDocument", + "CSVToDocument", + "JSONConverter", +] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/azure.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/azure.py new file mode 100644 index 0000000000000000000000000000000000000000..94ca9714f3b481eae7e6e90a96852208e1ee4fc3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/azure.py @@ -0,0 +1,497 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import copy +import hashlib +from collections import defaultdict +from pathlib import Path +from typing import Any, Dict, List, Literal, Optional, Union + +import networkx as nx +import pandas as pd + +from haystack import Document, component, default_from_dict, default_to_dict, logging +from haystack.components.converters.utils import get_bytestream_from_source, normalize_metadata +from haystack.dataclasses import ByteStream +from haystack.lazy_imports import LazyImport +from haystack.utils import Secret, deserialize_secrets_inplace + +logger = logging.getLogger(__name__) + +with LazyImport(message="Run 'pip install \"azure-ai-formrecognizer>=3.2.0b2\"'") as azure_import: + from azure.ai.formrecognizer import AnalyzeResult, DocumentAnalysisClient, DocumentLine, DocumentParagraph + from azure.core.credentials import AzureKeyCredential + + +@component +class AzureOCRDocumentConverter: + """ + Converts files to documents using Azure's Document Intelligence service. + + Supported file formats are: PDF, JPEG, PNG, BMP, TIFF, DOCX, XLSX, PPTX, and HTML. + + To use this component, you need an active Azure account + and a Document Intelligence or Cognitive Services resource. For help with setting up your resource, see + [Azure documentation](https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/quickstarts/get-started-sdks-rest-api). + + ### Usage example + + ```python + from haystack.components.converters import AzureOCRDocumentConverter + from haystack.utils import Secret + + converter = AzureOCRDocumentConverter(endpoint="", api_key=Secret.from_token("")) + results = converter.run(sources=["path/to/doc_with_images.pdf"], meta={"date_added": datetime.now().isoformat()}) + documents = results["documents"] + print(documents[0].content) + # 'This is a text from the PDF file.' + ``` + """ + + def __init__( + self, + endpoint: str, + api_key: Secret = Secret.from_env_var("AZURE_AI_API_KEY"), + model_id: str = "prebuilt-read", + preceding_context_len: int = 3, + following_context_len: int = 3, + merge_multiple_column_headers: bool = True, + page_layout: Literal["natural", "single_column"] = "natural", + threshold_y: Optional[float] = 0.05, + ): + """ + Creates an AzureOCRDocumentConverter component. + + :param endpoint: + The endpoint of your Azure resource. + :param api_key: + The API key of your Azure resource. + :param model_id: + The ID of the model you want to use. For a list of available models, see [Azure documentation] + (https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/choose-model-feature). + :param preceding_context_len: Number of lines before a table to include as preceding context + (this will be added to the metadata). + :param following_context_len: Number of lines after a table to include as subsequent context ( + this will be added to the metadata). + :param merge_multiple_column_headers: If `True`, merges multiple column header rows into a single row. + :param page_layout: The type reading order to follow. Possible options: + - `natural`: Uses the natural reading order determined by Azure. + - `single_column`: Groups all lines with the same height on the page based on a threshold + determined by `threshold_y`. + :param threshold_y: Only relevant if `single_column` is set to `page_layout`. + The threshold, in inches, to determine if two recognized PDF elements are grouped into a + single line. This is crucial for section headers or numbers which may be spatially separated + from the remaining text on the horizontal axis. + """ + azure_import.check() + + self.document_analysis_client = DocumentAnalysisClient( + endpoint=endpoint, credential=AzureKeyCredential(api_key.resolve_value() or "") + ) # type: ignore + self.endpoint = endpoint + self.model_id = model_id + self.api_key = api_key + self.preceding_context_len = preceding_context_len + self.following_context_len = following_context_len + self.merge_multiple_column_headers = merge_multiple_column_headers + self.page_layout = page_layout + self.threshold_y = threshold_y + if self.page_layout == "single_column" and self.threshold_y is None: + self.threshold_y = 0.05 + + @component.output_types(documents=List[Document], raw_azure_response=List[Dict]) + def run(self, sources: List[Union[str, Path, ByteStream]], meta: Optional[List[Dict[str, Any]]] = None): + """ + Convert a list of files to Documents using Azure's Document Intelligence service. + + :param sources: + List of file paths or ByteStream objects. + :param meta: + Optional metadata to attach to the Documents. + This value can be either a list of dictionaries or a single dictionary. + If it's a single dictionary, its content is added to the metadata of all produced Documents. + If it's a list, the length of the list must match the number of sources, because the two lists will be + zipped. If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. + + :returns: + A dictionary with the following keys: + - `documents`: List of created Documents + - `raw_azure_response`: List of raw Azure responses used to create the Documents + """ + documents = [] + azure_output = [] + meta_list: List[Dict[str, Any]] = normalize_metadata(meta=meta, sources_count=len(sources)) + for source, metadata in zip(sources, meta_list): + try: + bytestream = get_bytestream_from_source(source=source) + except Exception as e: + logger.warning("Could not read {source}. Skipping it. Error: {error}", source=source, error=e) + continue + + poller = self.document_analysis_client.begin_analyze_document( + model_id=self.model_id, document=bytestream.data + ) + result = poller.result() + azure_output.append(result.to_dict()) + + merged_metadata = {**bytestream.meta, **metadata} + docs = self._convert_tables_and_text(result=result, meta=merged_metadata) + documents.extend(docs) + + return {"documents": documents, "raw_azure_response": azure_output} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + api_key=self.api_key.to_dict(), + endpoint=self.endpoint, + model_id=self.model_id, + preceding_context_len=self.preceding_context_len, + following_context_len=self.following_context_len, + merge_multiple_column_headers=self.merge_multiple_column_headers, + page_layout=self.page_layout, + threshold_y=self.threshold_y, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "AzureOCRDocumentConverter": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + return default_from_dict(cls, data) + + # pylint: disable=line-too-long + def _convert_tables_and_text(self, result: "AnalyzeResult", meta: Optional[Dict[str, Any]]) -> List[Document]: + """ + Converts the tables and text extracted by Azure's Document Intelligence service into Haystack Documents. + + :param result: The AnalyzeResult object returned by the `begin_analyze_document` method. Docs on Analyze result + can be found [here](https://azuresdkdocs.blob.core.windows.net/$web/python/azure-ai-formrecognizer/3.3.0/azure.ai.formrecognizer.html?highlight=read#azure.ai.formrecognizer.AnalyzeResult). + :param meta: Optional dictionary with metadata that shall be attached to all resulting documents. + Can be any custom keys and values. + :returns: List of Documents containing the tables and text extracted from the AnalyzeResult object. + """ + tables = self._convert_tables(result=result, meta=meta) + if self.page_layout == "natural": + text = self._convert_to_natural_text(result=result, meta=meta) + else: + assert isinstance(self.threshold_y, float) + text = self._convert_to_single_column_text(result=result, meta=meta, threshold_y=self.threshold_y) + docs = [*tables, text] + return docs + + def _convert_tables(self, result: "AnalyzeResult", meta: Optional[Dict[str, Any]]) -> List[Document]: + """ + Converts the tables extracted by Azure's Document Intelligence service into Haystack Documents. + + :param result: The AnalyzeResult Azure object + :param meta: Optional dictionary with metadata that shall be attached to all resulting documents. + + :returns: List of Documents containing the tables extracted from the AnalyzeResult object. + """ + converted_tables: List[Document] = [] + + if not result.tables: + return converted_tables + + for table in result.tables: + # Initialize table with empty cells + table_list = [[""] * table.column_count for _ in range(table.row_count)] + additional_column_header_rows = set() + caption = "" + row_idx_start = 0 + + for idx, cell in enumerate(table.cells): + # Remove ':selected:'/':unselected:' tags from cell's content + cell.content = cell.content.replace(":selected:", "") + cell.content = cell.content.replace(":unselected:", "") + + # Check if first row is a merged cell spanning whole table + # -> exclude this row and use as a caption + if idx == 0 and cell.column_span == table.column_count: + caption = cell.content + row_idx_start = 1 + table_list.pop(0) + continue + + column_span = cell.column_span if cell.column_span else 0 + for c in range(column_span): # pylint: disable=invalid-name + row_span = cell.row_span if cell.row_span else 0 + for r in range(row_span): # pylint: disable=invalid-name + if ( + self.merge_multiple_column_headers + and cell.kind == "columnHeader" + and cell.row_index > row_idx_start + ): + # More than one row serves as column header + table_list[0][cell.column_index + c] += f"\n{cell.content}" + additional_column_header_rows.add(cell.row_index - row_idx_start) + else: + table_list[cell.row_index + r - row_idx_start][cell.column_index + c] = cell.content + + # Remove additional column header rows, as these got attached to the first row + for row_idx in sorted(additional_column_header_rows, reverse=True): + del table_list[row_idx] + + # Get preceding context of table + if table.bounding_regions: + table_beginning_page = next( + page for page in result.pages if page.page_number == table.bounding_regions[0].page_number + ) + else: + table_beginning_page = None + table_start_offset = table.spans[0].offset + if table_beginning_page and table_beginning_page.lines: + preceding_lines = [ + line.content for line in table_beginning_page.lines if line.spans[0].offset < table_start_offset + ] + else: + preceding_lines = [] + preceding_context = "\n".join(preceding_lines[-self.preceding_context_len :]) + f"\n{caption}" + preceding_context = preceding_context.strip() + + # Get following context + if table.bounding_regions and len(table.bounding_regions) == 1: + table_end_page = table_beginning_page + elif table.bounding_regions: + table_end_page = next( + page for page in result.pages if page.page_number == table.bounding_regions[-1].page_number + ) + else: + table_end_page = None + + table_end_offset = table_start_offset + table.spans[0].length + if table_end_page and table_end_page.lines: + following_lines = [ + line.content for line in table_end_page.lines if line.spans[0].offset > table_end_offset + ] + else: + following_lines = [] + following_context = "\n".join(following_lines[: self.following_context_len]) + + table_meta = copy.deepcopy(meta) + + if isinstance(table_meta, dict): + table_meta["preceding_context"] = preceding_context + table_meta["following_context"] = following_context + else: + table_meta = {"preceding_context": preceding_context, "following_context": following_context} + + if table.bounding_regions: + table_meta["page"] = table.bounding_regions[0].page_number + + table_df = pd.DataFrame(columns=table_list[0], data=table_list[1:]) + + # Use custom ID for tables, as columns might not be unique and thus failing in the default ID generation + pd_hashes = self._hash_dataframe(table_df) + data = f"{pd_hashes}{table_meta}" + doc_id = hashlib.sha256(data.encode()).hexdigest() + converted_tables.append(Document(id=doc_id, dataframe=table_df, meta=table_meta)) + + return converted_tables + + def _convert_to_natural_text(self, result: "AnalyzeResult", meta: Optional[Dict[str, Any]]) -> Document: + """ + This converts the `AnalyzeResult` object into a single document. + + We add "\f" separators between to differentiate between the text on separate pages. This is the expected format + for the PreProcessor. + + :param result: The AnalyzeResult object returned by the `begin_analyze_document` method. Docs on Analyze result + can be found [here](https://azuresdkdocs.blob.core.windows.net/$web/python/azure-ai-formrecognizer/3.3.0/azure.ai.formrecognizer.html?highlight=read#azure.ai.formrecognizer.AnalyzeResult). + :param meta: Optional dictionary with metadata that shall be attached to all resulting documents. + Can be any custom keys and values. + :returns: A single Document containing all the text extracted from the AnalyzeResult object. + """ + table_spans_by_page = self._collect_table_spans(result=result) + + texts = [] + if result.paragraphs: + paragraphs_to_pages: Dict[int, str] = defaultdict(str) + for paragraph in result.paragraphs: + if paragraph.bounding_regions: + # If paragraph spans multiple pages we group it with the first page number + page_numbers = [b.page_number for b in paragraph.bounding_regions] + else: + # If page_number is not available we put the paragraph onto an existing page + current_last_page_number = sorted(paragraphs_to_pages.keys())[-1] if paragraphs_to_pages else 1 + page_numbers = [current_last_page_number] + tables_on_page = table_spans_by_page[page_numbers[0]] + # Check if paragraph is part of a table and if so skip + if self._check_if_in_table(tables_on_page, line_or_paragraph=paragraph): + continue + paragraphs_to_pages[page_numbers[0]] += paragraph.content + "\n" + + max_page_number: int = max(paragraphs_to_pages) + for page_idx in range(1, max_page_number + 1): + # We add empty strings for missing pages so the preprocessor can still extract the correct page number + # from the original PDF. + page_text = paragraphs_to_pages.get(page_idx, "") + texts.append(page_text) + else: + logger.warning("No text paragraphs were detected by the OCR conversion.") + + all_text = "\f".join(texts) + return Document(content=all_text, meta=meta if meta else {}) + + def _convert_to_single_column_text( + self, result: "AnalyzeResult", meta: Optional[Dict[str, str]], threshold_y: float = 0.05 + ) -> Document: + """ + This converts the `AnalyzeResult` object into a single Haystack Document. + + We add "\f" separators between to differentiate between the text on separate pages. This is the expected format + for the PreProcessor. + + :param result: The AnalyzeResult object returned by the `begin_analyze_document` method. Docs on Analyze result + can be found [here](https://azuresdkdocs.blob.core.windows.net/$web/python/azure-ai-formrecognizer/3.3.0/azure.ai.formrecognizer.html?highlight=read#azure.ai.formrecognizer.AnalyzeResult). + :param meta: Optional dictionary with metadata that shall be attached to all resulting documents. + Can be any custom keys and values. + :param threshold_y: height threshold in inches for PDF and pixels for images + :returns: A single Document containing all the text extracted from the AnalyzeResult object. + """ + table_spans_by_page = self._collect_table_spans(result=result) + + # Find all pairs of lines that should be grouped together based on the y-value of the upper left coordinate + # of their bounding box + pairs_by_page = defaultdict(list) + for page_idx, page in enumerate(result.pages): + lines = page.lines if page.lines else [] + # Only works if polygons is available + if all(line.polygon is not None for line in lines): + for i in range(len(lines)): # pylint: disable=consider-using-enumerate + # left_upi, right_upi, right_lowi, left_lowi = lines[i].polygon + left_upi, _, _, _ = lines[i].polygon # type: ignore + pairs_by_page[page_idx].append([i, i]) + for j in range(i + 1, len(lines)): # pylint: disable=invalid-name + left_upj, _, _, _ = lines[j].polygon # type: ignore + close_on_y_axis = abs(left_upi[1] - left_upj[1]) < threshold_y + if close_on_y_axis: + pairs_by_page[page_idx].append([i, j]) + # Default if polygon is not available + else: + logger.info( + "Polygon information for lines on page {page_idx} is not available so it is not possible " + "to enforce a single column page layout.".format(page_idx=page_idx) + ) + for i in range(len(lines)): + pairs_by_page[page_idx].append([i, i]) + + # merged the line pairs that are connected by page + merged_pairs_by_page = {} + for page_idx in pairs_by_page: + graph = nx.Graph() + graph.add_edges_from(pairs_by_page[page_idx]) + merged_pairs_by_page[page_idx] = [list(a) for a in list(nx.connected_components(graph))] + + # Convert line indices to the DocumentLine objects + merged_lines_by_page = {} + for page_idx, page in enumerate(result.pages): + rows = [] + lines = page.lines if page.lines else [] + # We use .get(page_idx, []) since the page could be empty + for row_of_lines in merged_pairs_by_page.get(page_idx, []): + lines_in_row = [lines[line_idx] for line_idx in row_of_lines] + rows.append(lines_in_row) + merged_lines_by_page[page_idx] = rows + + # Sort the merged pairs in each row by the x-value of the upper left bounding box coordinate + x_sorted_lines_by_page = {} + for page_idx, _ in enumerate(result.pages): + sorted_rows = [] + for row_of_lines in merged_lines_by_page[page_idx]: + sorted_rows.append(sorted(row_of_lines, key=lambda x: x.polygon[0][0])) # type: ignore + x_sorted_lines_by_page[page_idx] = sorted_rows + + # Sort each row within the page by the y-value of the upper left bounding box coordinate + y_sorted_lines_by_page = {} + for page_idx, _ in enumerate(result.pages): + sorted_rows = sorted(x_sorted_lines_by_page[page_idx], key=lambda x: x[0].polygon[0][1]) # type: ignore + y_sorted_lines_by_page[page_idx] = sorted_rows + + # Construct the text to write + texts = [] + for page_idx, page in enumerate(result.pages): + tables_on_page = table_spans_by_page[page.page_number] + page_text = "" + for row_of_lines in y_sorted_lines_by_page[page_idx]: + # Check if line is part of a table and if so skip + if any(self._check_if_in_table(tables_on_page, line_or_paragraph=line) for line in row_of_lines): + continue + page_text += " ".join(line.content for line in row_of_lines) + page_text += "\n" + texts.append(page_text) + all_text = "\f".join(texts) + return Document(content=all_text, meta=meta if meta else {}) + + def _collect_table_spans(self, result: "AnalyzeResult") -> Dict: + """ + Collect the spans of all tables by page number. + + :param result: The AnalyzeResult object returned by the `begin_analyze_document` method. + :returns: A dictionary with the page number as key and a list of table spans as value. + """ + table_spans_by_page = defaultdict(list) + tables = result.tables if result.tables else [] + for table in tables: + if not table.bounding_regions: + continue + table_spans_by_page[table.bounding_regions[0].page_number].append(table.spans[0]) + return table_spans_by_page + + def _check_if_in_table( + self, tables_on_page: dict, line_or_paragraph: Union["DocumentLine", "DocumentParagraph"] + ) -> bool: + """ + Check if a line or paragraph is part of a table. + + :param tables_on_page: A dictionary with the page number as key and a list of table spans as value. + :param line_or_paragraph: The line or paragraph to check. + :returns: True if the line or paragraph is part of a table, False otherwise. + """ + in_table = False + # Check if line is part of a table + for table in tables_on_page: + if table.offset <= line_or_paragraph.spans[0].offset <= table.offset + table.length: + in_table = True + break + return in_table + + def _hash_dataframe(self, df: pd.DataFrame, desired_samples=5, hash_length=4) -> str: + """ + Returns a hash of the DataFrame content. + + The hash is based on the content of the DataFrame. + :param df: The DataFrame to hash. + :param desired_samples: The desired number of samples to hash. + :param hash_length: The length of the hash for each sample. + + :returns: A hash of the DataFrame content. + """ + # take adaptive sample of rows to hash because we can have very large dataframes + hasher = hashlib.md5() + total_rows = len(df) + # sample rate based on DataFrame size and desired number of samples + sample_rate = max(1, total_rows // desired_samples) + + hashes = pd.util.hash_pandas_object(df, index=True) + sampled_hashes = hashes[::sample_rate] + + for hash_value in sampled_hashes: + partial_hash = str(hash_value)[:hash_length].encode("utf-8") + hasher.update(partial_hash) + + return hasher.hexdigest() diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/csv.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/csv.py new file mode 100644 index 0000000000000000000000000000000000000000..721d8cf6257ad5121616b05da5f77910ceb4e294 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/csv.py @@ -0,0 +1,93 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import io +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from haystack import Document, component, logging +from haystack.components.converters.utils import get_bytestream_from_source, normalize_metadata +from haystack.dataclasses import ByteStream + +logger = logging.getLogger(__name__) + + +@component +class CSVToDocument: + """ + Converts CSV files to Documents. + + By default, it uses UTF-8 encoding when converting files but + you can also set a custom encoding. + It can attach metadata to the resulting documents. + + ### Usage example + + ```python + from haystack.components.converters.csv import CSVToDocument + converter = CSVToDocument() + results = converter.run(sources=["sample.csv"], meta={"date_added": datetime.now().isoformat()}) + documents = results["documents"] + print(documents[0].content) + # 'col1,col2\now1,row1\nrow2row2\n' + ``` + """ + + def __init__(self, encoding: str = "utf-8"): + """ + Creates a CSVToDocument component. + + :param encoding: + The encoding of the csv files to convert. + If the encoding is specified in the metadata of a source ByteStream, + it overrides this value. + """ + self.encoding = encoding + + @component.output_types(documents=List[Document]) + def run( + self, + sources: List[Union[str, Path, ByteStream]], + meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, + ): + """ + Converts a CSV file to a Document. + + :param sources: + List of file paths or ByteStream objects. + :param meta: + Optional metadata to attach to the documents. + This value can be either a list of dictionaries or a single dictionary. + If it's a single dictionary, its content is added to the metadata of all produced documents. + If it's a list, the length of the list must match the number of sources, because the two lists will + be zipped. + If `sources` contains ByteStream objects, their `meta` will be added to the output documents. + :returns: + A dictionary with the following keys: + - `documents`: Created documents + """ + documents = [] + + meta_list = normalize_metadata(meta, sources_count=len(sources)) + + for source, metadata in zip(sources, meta_list): + try: + bytestream = get_bytestream_from_source(source) + except Exception as e: + logger.warning("Could not read {source}. Skipping it. Error: {error}", source=source, error=e) + continue + try: + encoding = bytestream.meta.get("encoding", self.encoding) + data = io.BytesIO(bytestream.data).getvalue().decode(encoding=encoding) + except Exception as e: + logger.warning( + "Could not convert file {source}. Skipping it. Error message: {error}", source=source, error=e + ) + continue + + merged_metadata = {**bytestream.meta, **metadata} + document = Document(content=data, meta=merged_metadata) + documents.append(document) + + return {"documents": documents} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/docx.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/docx.py new file mode 100644 index 0000000000000000000000000000000000000000..8ffc3888a8912e28c6762db4fe8d69e0b9f61f60 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/docx.py @@ -0,0 +1,207 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import io +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from haystack import Document, component, logging +from haystack.components.converters.utils import get_bytestream_from_source, normalize_metadata +from haystack.dataclasses import ByteStream +from haystack.lazy_imports import LazyImport + +logger = logging.getLogger(__name__) + +with LazyImport("Run 'pip install python-docx'") as docx_import: + import docx + from docx.document import Document as DocxDocument + from docx.text.paragraph import Paragraph + + +@dataclass +class DOCXMetadata: + """ + Describes the metadata of Docx file. + + :param author: The author + :param category: The category + :param comments: The comments + :param content_status: The content status + :param created: The creation date (ISO formatted string) + :param identifier: The identifier + :param keywords: Available keywords + :param language: The language of the document + :param last_modified_by: User who last modified the document + :param last_printed: The last printed date (ISO formatted string) + :param modified: The last modification date (ISO formatted string) + :param revision: The revision number + :param subject: The subject + :param title: The title + :param version: The version + """ + + author: str + category: str + comments: str + content_status: str + created: Optional[str] + identifier: str + keywords: str + language: str + last_modified_by: str + last_printed: Optional[str] + modified: Optional[str] + revision: int + subject: str + title: str + version: str + + +@component +class DOCXToDocument: + """ + Converts DOCX files to Documents. + + Uses `python-docx` library to convert the DOCX file to a document. + This component does not preserve page breaks in the original document. + + Usage example: + ```python + from haystack.components.converters.docx import DOCXToDocument + + converter = DOCXToDocument() + results = converter.run(sources=["sample.docx"], meta={"date_added": datetime.now().isoformat()}) + documents = results["documents"] + print(documents[0].content) + # 'This is a text from the DOCX file.' + ``` + """ + + def __init__(self): + """ + Create a DOCXToDocument component. + """ + docx_import.check() + + @component.output_types(documents=List[Document]) + def run( + self, + sources: List[Union[str, Path, ByteStream]], + meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, + ): + """ + Converts DOCX files to Documents. + + :param sources: + List of file paths or ByteStream objects. + :param meta: + Optional metadata to attach to the Documents. + This value can be either a list of dictionaries or a single dictionary. + If it's a single dictionary, its content is added to the metadata of all produced Documents. + If it's a list, the length of the list must match the number of sources, because the two lists will + be zipped. + If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. + + :returns: + A dictionary with the following keys: + - `documents`: Created Documents + """ + documents = [] + meta_list = normalize_metadata(meta=meta, sources_count=len(sources)) + + for source, metadata in zip(sources, meta_list): + try: + bytestream = get_bytestream_from_source(source) + except Exception as e: + logger.warning("Could not read {source}. Skipping it. Error: {error}", source=source, error=e) + continue + try: + file = docx.Document(io.BytesIO(bytestream.data)) + paragraphs = self._extract_paragraphs_with_page_breaks(file.paragraphs) + text = "\n".join(paragraphs) + except Exception as e: + logger.warning( + "Could not read {source} and convert it to a DOCX Document, skipping. Error: {error}", + source=source, + error=e, + ) + continue + + docx_metadata = self._get_docx_metadata(document=file) + merged_metadata = {**bytestream.meta, **metadata, "docx": docx_metadata} + document = Document(content=text, meta=merged_metadata) + documents.append(document) + + return {"documents": documents} + + def _extract_paragraphs_with_page_breaks(self, paragraphs: List["Paragraph"]) -> List[str]: + """ + Extracts paragraphs from a DOCX file, including page breaks. + + Page breaks (both soft and hard page breaks) are not automatically extracted by python-docx as '\f' chars. + This means we need to add them in ourselves, as done here. This allows the correct page number + to be associated with each document if the file contents are split, e.g. by DocumentSplitter. + + :param paragraphs: + List of paragraphs from a DOCX file. + + :returns: + List of strings (paragraph text fields) with all page breaks added in as '\f' characters. + """ + paragraph_texts = [] + for para in paragraphs: + if para.contains_page_break: + para_text_w_page_breaks = "" + # Usually, just 1 page break exists, but could be more if paragraph is really long, so we loop over them + for pb_index, page_break in enumerate(para.rendered_page_breaks): + # Can only extract text from first paragraph page break, unfortunately + if pb_index == 0: + if page_break.preceding_paragraph_fragment: + para_text_w_page_breaks += page_break.preceding_paragraph_fragment.text + para_text_w_page_breaks += "\f" + if page_break.following_paragraph_fragment: + # following_paragraph_fragment contains all text for remainder of paragraph. + # However, if the remainder of the paragraph spans multiple page breaks, it won't include + # those later page breaks so we have to add them at end of text in the `else` block below. + # This is not ideal, but this case should be very rare and this is likely good enough. + para_text_w_page_breaks += page_break.following_paragraph_fragment.text + else: + para_text_w_page_breaks += "\f" + + paragraph_texts.append(para_text_w_page_breaks) + else: + paragraph_texts.append(para.text) + + return paragraph_texts + + def _get_docx_metadata(self, document: "DocxDocument") -> DOCXMetadata: + """ + Get all relevant data from the 'core_properties' attribute from a DOCX Document. + + :param document: + The DOCX Document you want to extract metadata from + + :returns: + A `DOCXMetadata` dataclass all the relevant fields from the 'core_properties' + """ + return DOCXMetadata( + author=document.core_properties.author, + category=document.core_properties.category, + comments=document.core_properties.comments, + content_status=document.core_properties.content_status, + created=document.core_properties.created.isoformat() if document.core_properties.created else None, + identifier=document.core_properties.identifier, + keywords=document.core_properties.keywords, + language=document.core_properties.language, + last_modified_by=document.core_properties.last_modified_by, + last_printed=document.core_properties.last_printed.isoformat() + if document.core_properties.last_printed + else None, + modified=document.core_properties.modified.isoformat() if document.core_properties.modified else None, + revision=document.core_properties.revision, + subject=document.core_properties.subject, + title=document.core_properties.title, + version=document.core_properties.version, + ) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/html.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/html.py new file mode 100644 index 0000000000000000000000000000000000000000..b090ec175467d64cd661e93459db5688c4a873bd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/html.py @@ -0,0 +1,121 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from haystack import Document, component, default_from_dict, default_to_dict, logging +from haystack.components.converters.utils import get_bytestream_from_source, normalize_metadata +from haystack.dataclasses import ByteStream +from haystack.lazy_imports import LazyImport + +logger = logging.getLogger(__name__) + +with LazyImport("Run 'pip install trafilatura'") as trafilatura_import: + from trafilatura import extract + + +@component +class HTMLToDocument: + """ + Converts an HTML file to a Document. + + Usage example: + ```python + from haystack.components.converters import HTMLToDocument + + converter = HTMLToDocument() + results = converter.run(sources=["path/to/sample.html"]) + documents = results["documents"] + print(documents[0].content) + # 'This is a text from the HTML file.' + ``` + """ + + def __init__(self, extraction_kwargs: Optional[Dict[str, Any]] = None): + """ + Create an HTMLToDocument component. + + :param extraction_kwargs: A dictionary containing keyword arguments to customize the extraction process. These + are passed to the underlying Trafilatura `extract` function. For the full list of available arguments, see + the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). + """ + trafilatura_import.check() + + self.extraction_kwargs = extraction_kwargs or {} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict(self, extraction_kwargs=self.extraction_kwargs) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "HTMLToDocument": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + return default_from_dict(cls, data) + + @component.output_types(documents=List[Document]) + def run( + self, + sources: List[Union[str, Path, ByteStream]], + meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, + extraction_kwargs: Optional[Dict[str, Any]] = None, + ): + """ + Converts a list of HTML files to Documents. + + :param sources: + List of HTML file paths or ByteStream objects. + :param meta: + Optional metadata to attach to the Documents. + This value can be either a list of dictionaries or a single dictionary. + If it's a single dictionary, its content is added to the metadata of all produced Documents. + If it's a list, the length of the list must match the number of sources, because the two lists will + be zipped. + If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. + :param extraction_kwargs: + Additional keyword arguments to customize the extraction process. + + :returns: + A dictionary with the following keys: + - `documents`: Created Documents + """ + + merged_extraction_kwargs = {**self.extraction_kwargs, **(extraction_kwargs or {})} + + documents = [] + meta_list = normalize_metadata(meta=meta, sources_count=len(sources)) + + for source, metadata in zip(sources, meta_list): + try: + bytestream = get_bytestream_from_source(source=source) + except Exception as e: + logger.warning("Could not read {source}. Skipping it. Error: {error}", source=source, error=e) + continue + + try: + text = extract(bytestream.data.decode("utf-8"), **merged_extraction_kwargs) + except Exception as conversion_e: + logger.warning( + "Failed to extract text from {source}. Skipping it. Error: {error}", + source=source, + error=conversion_e, + ) + continue + + document = Document(content=text, meta={**bytestream.meta, **metadata}) + documents.append(document) + + return {"documents": documents} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/json.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/json.py new file mode 100644 index 0000000000000000000000000000000000000000..966da881b83b627313f751528de0b0b289227203 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/json.py @@ -0,0 +1,277 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +from pathlib import Path +from typing import Any, Dict, List, Literal, Optional, Set, Tuple, Union + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.components.converters.utils import get_bytestream_from_source, normalize_metadata +from haystack.dataclasses import ByteStream, Document +from haystack.lazy_imports import LazyImport + +logger = logging.getLogger(__name__) + +with LazyImport("Run 'pip install jq'") as jq_import: + import jq + + +@component +class JSONConverter: + """ + Converts one or more JSON files into a text document. + + ### Usage examples + + ```python + import json + + from haystack.components.converters import JSONConverter + from haystack.dataclasses import ByteStream + + source = ByteStream.from_string(json.dumps({"text": "This is the content of my document"})) + + converter = JSONConverter(content_key="text") + results = converter.run(sources=[source]) + documents = results["documents"] + print(documents[0].content) + # 'This is the content of my document' + ``` + + Optionally, you can also provide a `jq_schema` string to filter the JSON source files and `extra_meta_fields` + to extract from the filtered data: + + ```python + import json + + from haystack.components.converters import JSONConverter + from haystack.dataclasses import ByteStream + + data = { + "laureates": [ + { + "firstname": "Enrico", + "surname": "Fermi", + "motivation": "for his demonstrations of the existence of new radioactive elements produced " + "by neutron irradiation, and for his related discovery of nuclear reactions brought about by" + " slow neutrons", + }, + { + "firstname": "Rita", + "surname": "Levi-Montalcini", + "motivation": "for their discoveries of growth factors", + }, + ], + } + source = ByteStream.from_string(json.dumps(data)) + converter = JSONConverter( + jq_schema=".laureates[]", content_key="motivation", extra_meta_fields={"firstname", "surname"} + ) + + results = converter.run(sources=[source]) + documents = results["documents"] + print(documents[0].content) + # 'for his demonstrations of the existence of new radioactive elements produced by + # neutron irradiation, and for his related discovery of nuclear reactions brought + # about by slow neutrons' + + print(documents[0].meta) + # {'firstname': 'Enrico', 'surname': 'Fermi'} + + print(documents[1].content) + # 'for their discoveries of growth factors' + + print(documents[1].meta) + # {'firstname': 'Rita', 'surname': 'Levi-Montalcini'} + ``` + + """ + + def __init__( + self, + jq_schema: Optional[str] = None, + content_key: Optional[str] = None, + extra_meta_fields: Optional[Union[Set[str], Literal["*"]]] = None, + ): + """ + Creates a JSONConverter component. + + An optional `jq_schema` can be provided to extract nested data in the JSON source files. + See the [official jq documentation](https://jqlang.github.io/jq/) for more info on the filters syntax. + If `jq_schema` is not set, whole JSON source files will be used to extract content. + + Optionally, you can provide a `content_key` to specify which key in the extracted object must + be set as the document's content. + + If both `jq_schema` and `content_key` are set, the component will search for the `content_key` in + the JSON object extracted by `jq_schema`. If the extracted data is not a JSON object, it will be skipped. + + If only `jq_schema` is set, the extracted data must be a scalar value. If it's a JSON object or array, + it will be skipped. + + If only `content_key` is set, the source JSON file must be a JSON object, else it will be skipped. + + `extra_meta_fields` can either be set to a set of strings or a literal `"*"` string. + If it's a set of strings, it must specify fields in the extracted objects that must be set in + the extracted documents. If a field is not found, the meta value will be `None`. + If set to `"*"`, all fields that are not `content_key` found in the filtered JSON object will + be saved as metadata. + + Initialization will fail if neither `jq_schema` nor `content_key` are set. + + :param jq_schema: + Optional jq filter string to extract content. + If not specified, whole JSON object will be used to extract information. + :param content_key: + Optional key to extract document content. + If `jq_schema` is specified, the `content_key` will be extracted from that object. + :param extra_meta_fields: + An optional set of meta keys to extract from the content. + If `jq_schema` is specified, all keys will be extracted from that object. + """ + self._compiled_filter = None + if jq_schema: + jq_import.check() + self._compiled_filter = jq.compile(jq_schema) + + self._jq_schema = jq_schema + self._content_key = content_key + self._meta_fields = extra_meta_fields + + if self._compiled_filter is None and self._content_key is None: + msg = "No `jq_schema` nor `content_key` specified. Set either or both to extract data." + raise ValueError(msg) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, jq_schema=self._jq_schema, content_key=self._content_key, extra_meta_fields=self._meta_fields + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "JSONConverter": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + return default_from_dict(cls, data) + + def _get_content_and_meta(self, source: ByteStream) -> List[Tuple[str, Dict[str, Any]]]: + """ + Utility function to extract text and metadata from a JSON file. + + :param source: + UTF-8 byte stream. + :returns: + Collection of text and metadata dict tuples, each corresponding + to a different document. + """ + try: + file_content = source.data.decode("utf-8") + except UnicodeError as exc: + logger.warning( + "Failed to extract text from {source}. Skipping it. Error: {error}", + source=source.meta["file_path"], + error=exc, + ) + + meta_fields = self._meta_fields or set() + + if self._compiled_filter is not None: + try: + objects = list(self._compiled_filter.input_text(file_content)) + except Exception as exc: + logger.warning( + "Failed to extract text from {source}. Skipping it. Error: {error}", + source=source.meta["file_path"], + error=exc, + ) + return [] + else: + # We just load the whole file as JSON if the user didn't provide a jq filter. + # We put it in a list even if it's not to ease handling it later on. + objects = [json.loads(file_content)] + + result = [] + if self._content_key is not None: + for obj in objects: + if not isinstance(obj, dict): + logger.warning("Expected a dictionary but got {obj}. Skipping it.", obj=obj) + continue + if self._content_key not in obj: + logger.warning( + "'{content_key}' not found in {obj}. Skipping it.", content_key=self._content_key, obj=obj + ) + continue + + text = obj[self._content_key] + if isinstance(text, (dict, list)): + logger.warning("Expected a scalar value but got {obj}. Skipping it.", obj=obj) + continue + + meta = {} + if meta_fields == "*": + meta = {k: v for k, v in obj.items() if k != self._content_key} + else: + for field in meta_fields: + meta[field] = obj.get(field, None) + result.append((text, meta)) + else: + for obj in objects: + if isinstance(obj, (dict, list)): + logger.warning("Expected a scalar value but got {obj}. Skipping it.", obj=obj) + continue + result.append((str(obj), {})) + + return result + + @component.output_types(documents=List[Document]) + def run( + self, + sources: List[Union[str, Path, ByteStream]], + meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, + ): + """ + Converts a list of JSON files to documents. + + :param sources: + A list of file paths or ByteStream objects. + :param meta: + Optional metadata to attach to the documents. + This value can be either a list of dictionaries or a single dictionary. + If it's a single dictionary, its content is added to the metadata of all produced documents. + If it's a list, the length of the list must match the number of sources. + If `sources` contain ByteStream objects, their `meta` will be added to the output documents. + + :returns: + A dictionary with the following keys: + - `documents`: A list of created documents. + """ + documents = [] + meta_list = normalize_metadata(meta=meta, sources_count=len(sources)) + + for source, metadata in zip(sources, meta_list): + try: + bytestream = get_bytestream_from_source(source) + except Exception as exc: + logger.warning("Could not read {source}. Skipping it. Error: {error}", source=source, error=exc) + continue + + data = self._get_content_and_meta(bytestream) + + for text, extra_meta in data: + merged_metadata = {**bytestream.meta, **metadata, **extra_meta} + document = Document(content=text, meta=merged_metadata) + documents.append(document) + + return {"documents": documents} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/markdown.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/markdown.py new file mode 100644 index 0000000000000000000000000000000000000000..c983ef212fdc452fad1bafa0330e8e518d6e5844 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/markdown.py @@ -0,0 +1,111 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from tqdm import tqdm + +from haystack import Document, component, logging +from haystack.components.converters.utils import get_bytestream_from_source, normalize_metadata +from haystack.dataclasses import ByteStream +from haystack.lazy_imports import LazyImport + +with LazyImport("Run 'pip install markdown-it-py mdit_plain'") as markdown_conversion_imports: + from markdown_it import MarkdownIt + from mdit_plain.renderer import RendererPlain + + +logger = logging.getLogger(__name__) + + +@component +class MarkdownToDocument: + """ + Converts a Markdown file into a text Document. + + Usage example: + ```python + from haystack.components.converters import MarkdownToDocument + from datetime import datetime + + converter = MarkdownToDocument() + results = converter.run(sources=["path/to/sample.md"], meta={"date_added": datetime.now().isoformat()}) + documents = results["documents"] + print(documents[0].content) + # 'This is a text from the markdown file.' + ``` + """ + + def __init__(self, table_to_single_line: bool = False, progress_bar: bool = True): + """ + Create a MarkdownToDocument component. + + :param table_to_single_line: + If True converts table contents into a single line. + :param progress_bar: + If True shows a progress bar when running. + """ + markdown_conversion_imports.check() + + self.table_to_single_line = table_to_single_line + self.progress_bar = progress_bar + + @component.output_types(documents=List[Document]) + def run( + self, + sources: List[Union[str, Path, ByteStream]], + meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, + ): + """ + Converts a list of Markdown files to Documents. + + :param sources: + List of file paths or ByteStream objects. + :param meta: + Optional metadata to attach to the Documents. + This value can be either a list of dictionaries or a single dictionary. + If it's a single dictionary, its content is added to the metadata of all produced Documents. + If it's a list, the length of the list must match the number of sources, because the two lists will + be zipped. + If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. + + :returns: + A dictionary with the following keys: + - `documents`: List of created Documents + """ + parser = MarkdownIt(renderer_cls=RendererPlain) + if self.table_to_single_line: + parser.enable("table") + + documents = [] + meta_list = normalize_metadata(meta=meta, sources_count=len(sources)) + + for source, metadata in tqdm( + zip(sources, meta_list), + total=len(sources), + desc="Converting markdown files to Documents", + disable=not self.progress_bar, + ): + try: + bytestream = get_bytestream_from_source(source) + except Exception as e: + logger.warning("Could not read {source}. Skipping it. Error: {error}", source=source, error=e) + continue + try: + file_content = bytestream.data.decode("utf-8") + text = parser.render(file_content) + except Exception as conversion_e: + logger.warning( + "Failed to extract text from {source}. Skipping it. Error: {error}", + source=source, + error=conversion_e, + ) + continue + + merged_metadata = {**bytestream.meta, **metadata} + document = Document(content=text, meta=merged_metadata) + documents.append(document) + + return {"documents": documents} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/openapi_functions.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/openapi_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..acc5d2a2325d49c5c535c588ae4ebe858ccb3b93 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/openapi_functions.py @@ -0,0 +1,258 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +import os +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +import yaml + +from haystack import component, logging +from haystack.dataclasses.byte_stream import ByteStream +from haystack.lazy_imports import LazyImport + +logger = logging.getLogger(__name__) + +with LazyImport("Run 'pip install jsonref'") as openapi_imports: + import jsonref + + +@component +class OpenAPIServiceToFunctions: + """ + Converts OpenAPI service definitions to a format suitable for OpenAI function calling. + + The definition must respect OpenAPI specification 3.0.0 or higher. + It can be specified in JSON or YAML format. + Each function must have: + - unique operationId + - description + - requestBody and/or parameters + - schema for the requestBody and/or parameters + For more details on OpenAPI specification see the [official documentation](https://github.com/OAI/OpenAPI-Specification). + For more details on OpenAI function calling see the [official documentation](https://platform.openai.com/docs/guides/function-calling). + + Usage example: + ```python + from haystack.components.converters import OpenAPIServiceToFunctions + + converter = OpenAPIServiceToFunctions() + result = converter.run(sources=["path/to/openapi_definition.yaml"]) + assert result["functions"] + ``` + """ + + MIN_REQUIRED_OPENAPI_SPEC_VERSION = 3 + + def __init__(self): + """ + Create an OpenAPIServiceToFunctions component. + """ + openapi_imports.check() + + @component.output_types(functions=List[Dict[str, Any]], openapi_specs=List[Dict[str, Any]]) + def run(self, sources: List[Union[str, Path, ByteStream]]) -> Dict[str, Any]: + """ + Converts OpenAPI definitions in OpenAI function calling format. + + :param sources: + File paths or ByteStream objects of OpenAPI definitions (in JSON or YAML format). + + :returns: + A dictionary with the following keys: + - functions: Function definitions in JSON object format + - openapi_specs: OpenAPI specs in JSON/YAML object format with resolved references + + :raises RuntimeError: + If the OpenAPI definitions cannot be downloaded or processed. + :raises ValueError: + If the source type is not recognized or no functions are found in the OpenAPI definitions. + """ + all_extracted_fc_definitions: List[Dict[str, Any]] = [] + all_openapi_specs = [] + for source in sources: + openapi_spec_content = None + if isinstance(source, (str, Path)): + if os.path.exists(source): + try: + with open(source, "r") as f: + openapi_spec_content = f.read() + except IOError as e: + logger.warning( + "IO error reading OpenAPI specification file: {source}. Error: {e}", source=source, e=e + ) + else: + logger.warning(f"OpenAPI specification file not found: {source}") + elif isinstance(source, ByteStream): + openapi_spec_content = source.data.decode("utf-8") + if not openapi_spec_content: + logger.warning( + "Invalid OpenAPI specification content provided: {openapi_spec_content}", + openapi_spec_content=openapi_spec_content, + ) + else: + logger.warning( + "Invalid source type {source}. Only str, Path, and ByteStream are supported.", source=type(source) + ) + continue + + if openapi_spec_content: + try: + service_openapi_spec = self._parse_openapi_spec(openapi_spec_content) + functions: List[Dict[str, Any]] = self._openapi_to_functions(service_openapi_spec) + all_extracted_fc_definitions.extend(functions) + all_openapi_specs.append(service_openapi_spec) + except Exception as e: + logger.error( + "Error processing OpenAPI specification from source {source}: {error}", source=source, error=e + ) + + if not all_extracted_fc_definitions: + logger.warning("No OpenAI function definitions extracted from the provided OpenAPI specification sources.") + + return {"functions": all_extracted_fc_definitions, "openapi_specs": all_openapi_specs} + + def _openapi_to_functions(self, service_openapi_spec: Dict[str, Any]) -> List[Dict[str, Any]]: + """ + OpenAPI to OpenAI function conversion. + + Extracts functions from the OpenAPI specification of the service and converts them into a format + suitable for OpenAI function calling. + + :param service_openapi_spec: The OpenAPI specification from which functions are to be extracted. + :type service_openapi_spec: Dict[str, Any] + :return: A list of dictionaries, each representing a function. Each dictionary includes the function's + name, description, and a schema of its parameters. + :rtype: List[Dict[str, Any]] + """ + + # Doesn't enforce rigid spec validation because that would require a lot of dependencies + # We check the version and require minimal fields to be present, so we can extract functions + spec_version = service_openapi_spec.get("openapi") + if not spec_version: + raise ValueError(f"Invalid OpenAPI spec provided. Could not extract version from {service_openapi_spec}") + service_openapi_spec_version = int(spec_version.split(".")[0]) + + # Compare the versions + if service_openapi_spec_version < OpenAPIServiceToFunctions.MIN_REQUIRED_OPENAPI_SPEC_VERSION: + raise ValueError( + f"Invalid OpenAPI spec version {service_openapi_spec_version}. Must be " + f"at least {OpenAPIServiceToFunctions.MIN_REQUIRED_OPENAPI_SPEC_VERSION}." + ) + + functions: List[Dict[str, Any]] = [] + for paths in service_openapi_spec["paths"].values(): + for path_spec in paths.values(): + function_dict = self._parse_endpoint_spec(path_spec) + if function_dict: + functions.append(function_dict) + return functions + + def _parse_endpoint_spec(self, resolved_spec: Dict[str, Any]) -> Optional[Dict[str, Any]]: + if not isinstance(resolved_spec, dict): + logger.warning("Invalid OpenAPI spec format provided. Could not extract function.") + return {} + + function_name = resolved_spec.get("operationId") + description = resolved_spec.get("description") or resolved_spec.get("summary", "") + + schema: Dict[str, Any] = {"type": "object", "properties": {}} + + # requestBody section + req_body_schema = ( + resolved_spec.get("requestBody", {}).get("content", {}).get("application/json", {}).get("schema", {}) + ) + if "properties" in req_body_schema: + for prop_name, prop_schema in req_body_schema["properties"].items(): + schema["properties"][prop_name] = self._parse_property_attributes(prop_schema) + + if "required" in req_body_schema: + schema.setdefault("required", []).extend(req_body_schema["required"]) + + # parameters section + for param in resolved_spec.get("parameters", []): + if "schema" in param: + schema_dict = self._parse_property_attributes(param["schema"]) + # these attributes are not in param[schema] level but on param level + useful_attributes = ["description", "pattern", "enum"] + schema_dict.update({key: param[key] for key in useful_attributes if param.get(key)}) + schema["properties"][param["name"]] = schema_dict + if param.get("required", False): + schema.setdefault("required", []).append(param["name"]) + + if function_name and description and schema["properties"]: + return {"name": function_name, "description": description, "parameters": schema} + else: + logger.warning( + "Invalid OpenAPI spec format provided. Could not extract function from {spec}", spec=resolved_spec + ) + return {} + + def _parse_property_attributes( + self, property_schema: Dict[str, Any], include_attributes: Optional[List[str]] = None + ) -> Dict[str, Any]: + """ + Parses the attributes of a property schema. + + Recursively parses the attributes of a property schema, including nested objects and arrays, + and includes specified attributes like description, pattern, etc. + + :param property_schema: The schema of the property to parse. + :param include_attributes: The list of attributes to include in the parsed schema. + :return: The parsed schema of the property including the specified attributes. + """ + include_attributes = include_attributes or ["description", "pattern", "enum"] + + schema_type = property_schema.get("type") + + parsed_schema = {"type": schema_type} if schema_type else {} + for attr in include_attributes: + if attr in property_schema: + parsed_schema[attr] = property_schema[attr] + + if schema_type == "object": + properties = property_schema.get("properties", {}) + parsed_properties = { + prop_name: self._parse_property_attributes(prop, include_attributes) + for prop_name, prop in properties.items() + } + parsed_schema["properties"] = parsed_properties + + if "required" in property_schema: + parsed_schema["required"] = property_schema["required"] + + elif schema_type == "array": + items = property_schema.get("items", {}) + parsed_schema["items"] = self._parse_property_attributes(items, include_attributes) + + return parsed_schema + + def _parse_openapi_spec(self, content: str) -> Dict[str, Any]: + """ + Parses OpenAPI specification content, supporting both JSON and YAML formats. + + :param content: The content of the OpenAPI specification. + :return: The parsed OpenAPI specification. + """ + open_api_spec_content = None + try: + open_api_spec_content = json.loads(content) + return jsonref.replace_refs(open_api_spec_content) + except json.JSONDecodeError as json_error: + # heuristic to confirm that the content is likely malformed JSON + if content.strip().startswith(("{", "[")): + raise json_error + + try: + open_api_spec_content = yaml.safe_load(content) + except yaml.YAMLError: + error_message = ( + "Failed to parse the OpenAPI specification. " + "The content does not appear to be valid JSON or YAML.\n\n" + ) + raise RuntimeError(error_message, content) + + # Replace references in the object with their resolved values, if any + return jsonref.replace_refs(open_api_spec_content) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/output_adapter.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/output_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..50ffd5391914c9b85e2bdf0e7d72d0e493614897 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/output_adapter.py @@ -0,0 +1,184 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import ast +import contextlib +from typing import Any, Callable, Dict, Optional, Set +from warnings import warn + +import jinja2.runtime +from jinja2 import Environment, TemplateSyntaxError, meta +from jinja2.nativetypes import NativeEnvironment +from jinja2.sandbox import SandboxedEnvironment +from typing_extensions import TypeAlias + +from haystack import component, default_from_dict, default_to_dict +from haystack.utils import deserialize_callable, deserialize_type, serialize_callable, serialize_type + + +class OutputAdaptationException(Exception): + """Exception raised when there is an error during output adaptation.""" + + +@component +class OutputAdapter: + """ + Adapts output of a Component using Jinja templates. + + Usage example: + ```python + from haystack import Document + from haystack.components.converters import OutputAdapter + + adapter = OutputAdapter(template="{{ documents[0].content }}", output_type=str) + documents = [Document(content="Test content"] + result = adapter.run(documents=documents) + + assert result["output"] == "Test content" + ``` + """ + + def __init__( + self, + template: str, + output_type: TypeAlias, + custom_filters: Optional[Dict[str, Callable]] = None, + unsafe: bool = False, + ): + """ + Create an OutputAdapter component. + + :param template: + A Jinja template that defines how to adapt the input data. + The variables in the template define the input of this instance. + e.g. + With this template: + ``` + {{ documents[0].content }} + ``` + The Component input will be `documents`. + :param output_type: + The type of output this instance will return. + :param custom_filters: + A dictionary of custom Jinja filters used in the template. + :param unsafe: + Enable execution of arbitrary code in the Jinja template. + This should only be used if you trust the source of the template as it can be lead to remote code execution. + """ + self.custom_filters = {**(custom_filters or {})} + input_types: Set[str] = set() + + self._unsafe = unsafe + + if self._unsafe: + msg = ( + "Unsafe mode is enabled. This allows execution of arbitrary code in the Jinja template. " + "Use this only if you trust the source of the template." + ) + warn(msg) + self._env = ( + NativeEnvironment() if self._unsafe else SandboxedEnvironment(undefined=jinja2.runtime.StrictUndefined) + ) + + try: + self._env.parse(template) # Validate template syntax + self.template = template + except TemplateSyntaxError as e: + raise ValueError(f"Invalid Jinja template '{template}': {e}") from e + + for name, filter_func in self.custom_filters.items(): + self._env.filters[name] = filter_func + + # b) extract variables in the template + route_input_names = self._extract_variables(self._env) + input_types.update(route_input_names) + + # the env is not needed, discarded automatically + component.set_input_types(self, **{var: Any for var in input_types}) + component.set_output_types(self, **{"output": output_type}) + self.output_type = output_type + + def run(self, **kwargs): + """ + Renders the Jinja template with the provided inputs. + + :param kwargs: + Must contain all variables used in the `template` string. + :returns: + A dictionary with the following keys: + - `output`: Rendered Jinja template. + + :raises OutputAdaptationException: If template rendering fails. + """ + # check if kwargs are empty + if not kwargs: + raise ValueError("No input data provided for output adaptation") + for name, filter_func in self.custom_filters.items(): + self._env.filters[name] = filter_func + adapted_outputs = {} + try: + adapted_output_template = self._env.from_string(self.template) + output_result = adapted_output_template.render(**kwargs) + if isinstance(output_result, jinja2.runtime.Undefined): + raise OutputAdaptationException(f"Undefined variable in the template {self.template}; kwargs: {kwargs}") + + # We suppress the exception in case the output is already a string, otherwise + # we try to evaluate it and would fail. + # This must be done cause the output could be different literal structures. + # This doesn't support any user types. + with contextlib.suppress(Exception): + if not self._unsafe: + output_result = ast.literal_eval(output_result) + + adapted_outputs["output"] = output_result + except Exception as e: + raise OutputAdaptationException(f"Error adapting {self.template} with {kwargs}: {e}") from e + return adapted_outputs + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + se_filters = {name: serialize_callable(filter_func) for name, filter_func in self.custom_filters.items()} + return default_to_dict( + self, + template=self.template, + output_type=serialize_type(self.output_type), + custom_filters=se_filters, + unsafe=self._unsafe, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "OutputAdapter": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + init_params = data.get("init_parameters", {}) + init_params["output_type"] = deserialize_type(init_params["output_type"]) + + custom_filters = init_params.get("custom_filters", {}) + if custom_filters: + init_params["custom_filters"] = { + name: deserialize_callable(filter_func) if filter_func else None + for name, filter_func in custom_filters.items() + } + return default_from_dict(cls, data) + + def _extract_variables(self, env: Environment) -> Set[str]: + """ + Extracts all variables from a list of Jinja template strings. + + :param env: A Jinja environment. + :return: A set of variable names extracted from the template strings. + """ + ast = env.parse(self.template) + return meta.find_undeclared_variables(ast) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/pdfminer.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/pdfminer.py new file mode 100644 index 0000000000000000000000000000000000000000..b105e2fca6af6e68635c433bc771eb40e64960c8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/pdfminer.py @@ -0,0 +1,165 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import io +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from haystack import Document, component, logging +from haystack.components.converters.utils import get_bytestream_from_source, normalize_metadata +from haystack.dataclasses import ByteStream +from haystack.lazy_imports import LazyImport + +with LazyImport("Run 'pip install pdfminer.six'") as pdfminer_import: + from pdfminer.high_level import extract_pages + from pdfminer.layout import LAParams, LTTextContainer + +logger = logging.getLogger(__name__) + + +@component +class PDFMinerToDocument: + """ + Converts PDF files to Documents. + + Uses `pdfminer` compatible converters to convert PDF files to Documents. https://pdfminersix.readthedocs.io/en/latest/ + + Usage example: + ```python + from haystack.components.converters.pdfminer import PDFMinerToDocument + + converter = PDFMinerToDocument() + results = converter.run(sources=["sample.pdf"], meta={"date_added": datetime.now().isoformat()}) + documents = results["documents"] + print(documents[0].content) + # 'This is a text from the PDF file.' + ``` + """ + + def __init__( + self, + line_overlap: float = 0.5, + char_margin: float = 2.0, + line_margin: float = 0.5, + word_margin: float = 0.1, + boxes_flow: Optional[float] = 0.5, + detect_vertical: bool = True, + all_texts: bool = False, + ) -> None: + """ + Create a PDFMinerToDocument component. + + :param line_overlap: + This parameter determines whether two characters are considered to be on + the same line based on the amount of overlap between them. + The overlap is calculated relative to the minimum height of both characters. + :param char_margin: + Determines whether two characters are part of the same line based on the distance between them. + If the distance is less than the margin specified, the characters are considered to be on the same line. + The margin is calculated relative to the width of the character. + :param word_margin: + Determines whether two characters on the same line are part of the same word + based on the distance between them. If the distance is greater than the margin specified, + an intermediate space will be added between them to make the text more readable. + The margin is calculated relative to the width of the character. + :param line_margin: + This parameter determines whether two lines are part of the same paragraph based on + the distance between them. If the distance is less than the margin specified, + the lines are considered to be part of the same paragraph. + The margin is calculated relative to the height of a line. + :param boxes_flow: + This parameter determines the importance of horizontal and vertical position when + determining the order of text boxes. A value between -1.0 and +1.0 can be set, + with -1.0 indicating that only horizontal position matters and +1.0 indicating + that only vertical position matters. Setting the value to 'None' will disable advanced + layout analysis, and text boxes will be ordered based on the position of their bottom left corner. + :param detect_vertical: + This parameter determines whether vertical text should be considered during layout analysis. + :param all_texts: + If layout analysis should be performed on text in figures. + """ + + pdfminer_import.check() + + self.layout_params = LAParams( + line_overlap=line_overlap, + char_margin=char_margin, + line_margin=line_margin, + word_margin=word_margin, + boxes_flow=boxes_flow, + detect_vertical=detect_vertical, + all_texts=all_texts, + ) + + def __converter(self, extractor) -> Document: + """ + Extracts text from PDF pages then convert the text into Documents + + :param extractor: + Python generator that yields PDF pages. + + :returns: + PDF text converted to Haystack Document + """ + pages = [] + for page in extractor: + text = "" + for container in page: + # Keep text only + if isinstance(container, LTTextContainer): + text += container.get_text() + pages.append(text) + + # Add a page delimiter + concat = "\f".join(pages) + + return Document(content=concat) + + @component.output_types(documents=List[Document]) + def run( + self, + sources: List[Union[str, Path, ByteStream]], + meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, + ): + """ + Converts PDF files to Documents. + + :param sources: + List of PDF file paths or ByteStream objects. + :param meta: + Optional metadata to attach to the Documents. + This value can be either a list of dictionaries or a single dictionary. + If it's a single dictionary, its content is added to the metadata of all produced Documents. + If it's a list, the length of the list must match the number of sources, because the two lists will + be zipped. + If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. + + :returns: + A dictionary with the following keys: + - `documents`: Created Documents + """ + documents = [] + + meta_list = normalize_metadata(meta, sources_count=len(sources)) + + for source, metadata in zip(sources, meta_list): + try: + bytestream = get_bytestream_from_source(source) + except Exception as e: + logger.warning("Could not read {source}. Skipping it. Error: {error}", source=source, error=e) + continue + try: + pdf_reader = extract_pages(io.BytesIO(bytestream.data), laparams=self.layout_params) + document = self.__converter(pdf_reader) + except Exception as e: + logger.warning( + "Could not read {source} and convert it to Document, skipping. {error}", source=source, error=e + ) + continue + + merged_metadata = {**bytestream.meta, **metadata} + document.meta = merged_metadata + documents.append(document) + + return {"documents": documents} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/pptx.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/pptx.py new file mode 100644 index 0000000000000000000000000000000000000000..b665abc4a7615ff096a38d737d2744f07569d61a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/pptx.py @@ -0,0 +1,102 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import io +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from haystack import Document, component, logging +from haystack.components.converters.utils import get_bytestream_from_source, normalize_metadata +from haystack.dataclasses import ByteStream +from haystack.lazy_imports import LazyImport + +with LazyImport("Run 'pip install python-pptx'") as pptx_import: + from pptx import Presentation + + +logger = logging.getLogger(__name__) + + +@component +class PPTXToDocument: + """ + Converts PPTX files to Documents. + + Usage example: + ```python + from haystack.components.converters.pptx import PPTXToDocument + + converter = PPTXToDocument() + results = converter.run(sources=["sample.pptx"], meta={"date_added": datetime.now().isoformat()}) + documents = results["documents"] + print(documents[0].content) + # 'This is the text from the PPTX file.' + ``` + """ + + def __init__(self): + """ + Create an PPTXToDocument component. + """ + pptx_import.check() + + def _convert(self, file_content: io.BytesIO) -> str: + """ + Converts the PPTX file to text. + """ + pptx_presentation = Presentation(file_content) + text_all_slides = [] + for slide in pptx_presentation.slides: + text_on_slide = [] + for shape in slide.shapes: + if hasattr(shape, "text"): + text_on_slide.append(shape.text) + text_all_slides.append("\n".join(text_on_slide)) + text = "\f".join(text_all_slides) + return text + + @component.output_types(documents=List[Document]) + def run( + self, + sources: List[Union[str, Path, ByteStream]], + meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, + ): + """ + Converts PPTX files to Documents. + + :param sources: + List of file paths or ByteStream objects. + :param meta: + Optional metadata to attach to the Documents. + This value can be either a list of dictionaries or a single dictionary. + If it's a single dictionary, its content is added to the metadata of all produced Documents. + If it's a list, the length of the list must match the number of sources, because the two lists will + be zipped. + If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. + + :returns: + A dictionary with the following keys: + - `documents`: Created Documents + """ + documents = [] + meta_list = normalize_metadata(meta, sources_count=len(sources)) + + for source, metadata in zip(sources, meta_list): + try: + bytestream = get_bytestream_from_source(source) + except Exception as e: + logger.warning("Could not read {source}. Skipping it. Error: {error}", source=source, error=e) + continue + try: + text = self._convert(io.BytesIO(bytestream.data)) + except Exception as e: + logger.warning( + "Could not read {source} and convert it to Document, skipping. {error}", source=source, error=e + ) + continue + + merged_metadata = {**bytestream.meta, **metadata} + documents.append(Document(content=text, meta=merged_metadata)) + + return {"documents": documents} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/pypdf.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/pypdf.py new file mode 100644 index 0000000000000000000000000000000000000000..f6d13ec2755c29a8be914422f38812e114a9a8c6 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/pypdf.py @@ -0,0 +1,180 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import io +import warnings +from pathlib import Path +from typing import Any, Dict, List, Optional, Protocol, Union + +from haystack import Document, component, default_from_dict, default_to_dict, logging +from haystack.components.converters.utils import get_bytestream_from_source, normalize_metadata +from haystack.dataclasses import ByteStream +from haystack.lazy_imports import LazyImport +from haystack.utils.base_serialization import deserialize_class_instance, serialize_class_instance +from haystack.utils.type_serialization import deserialize_type + +with LazyImport("Run 'pip install pypdf'") as pypdf_import: + from pypdf import PdfReader + + +logger = logging.getLogger(__name__) + + +class PyPDFConverter(Protocol): + """ + A protocol that defines a converter which takes a PdfReader object and converts it into a Document object. + """ + + def convert(self, reader: "PdfReader") -> Document: # noqa: D102 + ... + + def to_dict(self): # noqa: D102 + ... + + @classmethod + def from_dict(cls, data): # noqa: D102 + ... + + +class DefaultConverter: + """ + The default converter class that extracts text from a PdfReader object's pages and returns a Document. + """ + + def __init__(self): + warnings.warn( + "This class is deprecated and will be merged into `PyPDFToDocument` in 2.7.0.", DeprecationWarning + ) + + def convert(self, reader: "PdfReader") -> Document: + """Extract text from the PDF and return a Document object with the text content.""" + text = "\f".join(page.extract_text() for page in reader.pages) + return Document(content=text) + + def to_dict(self): + """Serialize the converter to a dictionary.""" + return default_to_dict(self) + + @classmethod + def from_dict(cls, data): + """Deserialize the converter from a dictionary.""" + return default_from_dict(cls, data) + + +@component +class PyPDFToDocument: + """ + Converts PDF files to documents your pipeline can query. + + This component uses converters compatible with the PyPDF library. + If no converter is provided, uses a default text extraction converter. + You can attach metadata to the resulting documents. + + ### Usage example + + ```python + from haystack.components.converters.pypdf import PyPDFToDocument + + converter = PyPDFToDocument() + results = converter.run(sources=["sample.pdf"], meta={"date_added": datetime.now().isoformat()}) + documents = results["documents"] + print(documents[0].content) + # 'This is a text from the PDF file.' + ``` + """ + + def __init__(self, converter: Optional[PyPDFConverter] = None): + """ + Create an PyPDFToDocument component. + + :param converter: + An instance of a PyPDFConverter compatible class. + """ + pypdf_import.check() + + self.converter = converter + + def to_dict(self): + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, converter=(serialize_class_instance(self.converter) if self.converter is not None else None) + ) + + @classmethod + def from_dict(cls, data): + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary with serialized data. + + :returns: + Deserialized component. + """ + custom_converter_data = data["init_parameters"]["converter"] + if custom_converter_data is not None: + if "data" in custom_converter_data: + data["init_parameters"]["converter"] = deserialize_class_instance(custom_converter_data) + else: + # TODO: Remove in 2.7.0 + converter_class = deserialize_type(custom_converter_data["type"]) + data["init_parameters"]["converter"] = converter_class.from_dict(custom_converter_data) + return default_from_dict(cls, data) + + def _default_convert(self, reader: "PdfReader") -> Document: + text = "\f".join(page.extract_text() for page in reader.pages) + return Document(content=text) + + @component.output_types(documents=List[Document]) + def run( + self, + sources: List[Union[str, Path, ByteStream]], + meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, + ): + """ + Converts PDF files to documents. + + :param sources: + List of file paths or ByteStream objects to convert. + :param meta: + Optional metadata to attach to the documents. + This value can be a list of dictionaries or a single dictionary. + If it's a single dictionary, its content is added to the metadata of all produced documents. + If it's a list, its length must match the number of sources, as they are zipped together. + For ByteStream objects, their `meta` is added to the output documents. + + :returns: + A dictionary with the following keys: + - `documents`: A list of converted documents. + """ + documents = [] + meta_list = normalize_metadata(meta, sources_count=len(sources)) + + for source, metadata in zip(sources, meta_list): + try: + bytestream = get_bytestream_from_source(source) + except Exception as e: + logger.warning("Could not read {source}. Skipping it. Error: {error}", source=source, error=e) + continue + try: + pdf_reader = PdfReader(io.BytesIO(bytestream.data)) + document = ( + self._default_convert(pdf_reader) if self.converter is None else self.converter.convert(pdf_reader) + ) + except Exception as e: + logger.warning( + "Could not read {source} and convert it to Document, skipping. {error}", source=source, error=e + ) + continue + + merged_metadata = {**bytestream.meta, **metadata} + document.meta = merged_metadata + documents.append(document) + + return {"documents": documents} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/tika.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/tika.py new file mode 100644 index 0000000000000000000000000000000000000000..926968a176a99a690905c0e6b3f751308bd0d438 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/tika.py @@ -0,0 +1,138 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import io +from html.parser import HTMLParser +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from haystack import Document, component, logging +from haystack.components.converters.utils import get_bytestream_from_source, normalize_metadata +from haystack.dataclasses import ByteStream +from haystack.lazy_imports import LazyImport + +with LazyImport("Run 'pip install tika'") as tika_import: + from tika import parser as tika_parser + +logger = logging.getLogger(__name__) + + +class XHTMLParser(HTMLParser): + """ + Custom parser to extract pages from Tika XHTML content. + """ + + def __init__(self): + super().__init__() + self.ingest = True + self.page = "" + self.pages: List[str] = [] + + def handle_starttag(self, tag: str, attrs: List[tuple]): + """Identify the start of a page div.""" + if tag == "div" and any(attr == "class" and value == "page" for attr, value in attrs): + self.ingest = True + + def handle_endtag(self, tag: str): + """Identify the end of a page div.""" + if self.ingest and tag in ("div", "body"): + self.ingest = False + # restore words hyphened to the next line + self.pages.append(self.page.replace("-\n", "")) + self.page = "" + + def handle_data(self, data: str): + """Populate the page content.""" + if self.ingest: + self.page += data + + +@component +class TikaDocumentConverter: + """ + Converts files of different types to Documents. + + This component uses [Apache Tika](https://tika.apache.org/) for parsing the files and, therefore, + requires a running Tika server. + For more options on running Tika, + see the [official documentation](https://github.com/apache/tika-docker/blob/main/README.md#usage). + + Usage example: + ```python + from haystack.components.converters.tika import TikaDocumentConverter + + converter = TikaDocumentConverter() + results = converter.run( + sources=["sample.docx", "my_document.rtf", "archive.zip"], + meta={"date_added": datetime.now().isoformat()} + ) + documents = results["documents"] + print(documents[0].content) + # 'This is a text from the docx file.' + ``` + """ + + def __init__(self, tika_url: str = "http://localhost:9998/tika"): + """ + Create a TikaDocumentConverter component. + + :param tika_url: + Tika server URL. + """ + tika_import.check() + self.tika_url = tika_url + + @component.output_types(documents=List[Document]) + def run( + self, + sources: List[Union[str, Path, ByteStream]], + meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, + ): + """ + Converts files to Documents. + + :param sources: + List of HTML file paths or ByteStream objects. + :param meta: + Optional metadata to attach to the Documents. + This value can be either a list of dictionaries or a single dictionary. + If it's a single dictionary, its content is added to the metadata of all produced Documents. + If it's a list, the length of the list must match the number of sources, because the two lists will + be zipped. + If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. + + :returns: + A dictionary with the following keys: + - `documents`: Created Documents + """ + documents = [] + meta_list = normalize_metadata(meta=meta, sources_count=len(sources)) + + for source, metadata in zip(sources, meta_list): + try: + bytestream = get_bytestream_from_source(source) + except Exception as e: + logger.warning("Could not read {source}. Skipping it. Error: {error}", source=source, error=e) + continue + try: + # we extract the content as XHTML to preserve the structure of the document as much as possible + # this works for PDFs, but does not work for other file types (DOCX) + xhtml_content = tika_parser.from_buffer( + io.BytesIO(bytestream.data), serverEndpoint=self.tika_url, xmlContent=True + )["content"] + xhtml_parser = XHTMLParser() + xhtml_parser.feed(xhtml_content) + text = "\f".join(xhtml_parser.pages) + except Exception as conversion_e: + logger.warning( + "Failed to extract text from {source}. Skipping it. Error: {error}", + source=source, + error=conversion_e, + ) + continue + + merged_metadata = {**bytestream.meta, **metadata} + document = Document(content=text, meta=merged_metadata) + documents.append(document) + return {"documents": documents} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/txt.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/txt.py new file mode 100644 index 0000000000000000000000000000000000000000..da5ca9a259618a0afdbebcb0a4bfab4e5c092edd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/txt.py @@ -0,0 +1,93 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from haystack import Document, component, logging +from haystack.components.converters.utils import get_bytestream_from_source, normalize_metadata +from haystack.dataclasses import ByteStream + +logger = logging.getLogger(__name__) + + +@component +class TextFileToDocument: + """ + Converts text files to documents your pipeline can query. + + By default, it uses UTF-8 encoding when converting files but + you can also set custom encoding. + It can attach metadata to the resulting documents. + + ### Usage example + + ```python + from haystack.components.converters.txt import TextFileToDocument + + converter = TextFileToDocument() + results = converter.run(sources=["sample.txt"]) + documents = results["documents"] + print(documents[0].content) + # 'This is the content from the txt file.' + ``` + """ + + def __init__(self, encoding: str = "utf-8"): + """ + Creates a TextFileToDocument component. + + :param encoding: + The encoding of the text files to convert. + If the encoding is specified in the metadata of a source ByteStream, + it overrides this value. + """ + self.encoding = encoding + + @component.output_types(documents=List[Document]) + def run( + self, + sources: List[Union[str, Path, ByteStream]], + meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, + ): + """ + Converts text files to documents. + + :param sources: + List of HTML file paths or ByteStream objects to convert. + :param meta: + Optional metadata to attach to the documents. + This value can be a list of dictionaries or a single dictionary. + If it's a single dictionary, its content is added to the metadata of all produced documents. + If it's a list, its length must match the number of sources as they're zipped together. + For ByteStream objects, their `meta` is added to the output documents. + + :returns: + A dictionary with the following keys: + - `documents`: A list of converted documents. + """ + documents = [] + + meta_list = normalize_metadata(meta, sources_count=len(sources)) + + for source, metadata in zip(sources, meta_list): + try: + bytestream = get_bytestream_from_source(source) + except Exception as e: + logger.warning("Could not read {source}. Skipping it. Error: {error}", source=source, error=e) + continue + try: + encoding = bytestream.meta.get("encoding", self.encoding) + text = bytestream.data.decode(encoding) + except Exception as e: + logger.warning( + "Could not convert file {source}. Skipping it. Error message: {error}", source=source, error=e + ) + continue + + merged_metadata = {**bytestream.meta, **metadata} + document = Document(content=text, meta=merged_metadata) + documents.append(document) + + return {"documents": documents} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/utils.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..87cd143239688424bcb20ee456a933688dd0dbf4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/converters/utils.py @@ -0,0 +1,51 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from haystack.dataclasses import ByteStream + + +def get_bytestream_from_source(source: Union[str, Path, ByteStream]) -> ByteStream: + """ + Creates a ByteStream object from a source. + + :param source: + A source to convert to a ByteStream. Can be a string (path to a file), a Path object, or a ByteStream. + :return: + A ByteStream object. + """ + + if isinstance(source, ByteStream): + return source + if isinstance(source, (str, Path)): + bs = ByteStream.from_file_path(Path(source)) + bs.meta["file_path"] = str(source) + return bs + raise ValueError(f"Unsupported source type {type(source)}") + + +def normalize_metadata( + meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]], sources_count: int +) -> List[Dict[str, Any]]: + """ + Normalize the metadata input for a converter. + + Given all the possible value of the meta input for a converter (None, dictionary or list of dicts), + makes sure to return a list of dictionaries of the correct length for the converter to use. + + :param meta: the meta input of the converter, as-is + :param sources_count: the number of sources the converter received + :returns: a list of dictionaries of the make length as the sources list + """ + if meta is None: + return [{}] * sources_count + if isinstance(meta, dict): + return [meta] * sources_count + if isinstance(meta, list): + if sources_count != len(meta): + raise ValueError("The length of the metadata list must match the number of sources.") + return meta + raise ValueError("meta must be either None, a dictionary or a list of dictionaries.") diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2b6cf4301e97bee041e6fcb61df0bda3e934caec --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/__init__.py @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.embedders.azure_document_embedder import AzureOpenAIDocumentEmbedder +from haystack.components.embedders.azure_text_embedder import AzureOpenAITextEmbedder +from haystack.components.embedders.hugging_face_api_document_embedder import HuggingFaceAPIDocumentEmbedder +from haystack.components.embedders.hugging_face_api_text_embedder import HuggingFaceAPITextEmbedder +from haystack.components.embedders.openai_document_embedder import OpenAIDocumentEmbedder +from haystack.components.embedders.openai_text_embedder import OpenAITextEmbedder +from haystack.components.embedders.sentence_transformers_document_embedder import SentenceTransformersDocumentEmbedder +from haystack.components.embedders.sentence_transformers_text_embedder import SentenceTransformersTextEmbedder + +__all__ = [ + "HuggingFaceAPITextEmbedder", + "HuggingFaceAPIDocumentEmbedder", + "SentenceTransformersTextEmbedder", + "SentenceTransformersDocumentEmbedder", + "OpenAITextEmbedder", + "OpenAIDocumentEmbedder", + "AzureOpenAITextEmbedder", + "AzureOpenAIDocumentEmbedder", +] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/azure_document_embedder.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/azure_document_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..e60c8781b6f5af28535148c98c8a57d37c6a4cc0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/azure_document_embedder.py @@ -0,0 +1,249 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +from typing import Any, Dict, List, Optional, Tuple + +from openai.lib.azure import AzureOpenAI +from tqdm import tqdm + +from haystack import Document, component, default_from_dict, default_to_dict +from haystack.utils import Secret, deserialize_secrets_inplace + + +@component +class AzureOpenAIDocumentEmbedder: + """ + Calculates document embeddings using OpenAI models deployed on Azure. + + ### Usage example + + ```python + from haystack import Document + from haystack.components.embedders import AzureOpenAIDocumentEmbedder + + doc = Document(content="I love pizza!") + + document_embedder = AzureOpenAIDocumentEmbedder() + + result = document_embedder.run([doc]) + print(result['documents'][0].embedding) + + # [0.017020374536514282, -0.023255806416273117, ...] + ``` + """ + + def __init__( # noqa: PLR0913 (too-many-arguments) + self, + azure_endpoint: Optional[str] = None, + api_version: Optional[str] = "2023-05-15", + azure_deployment: str = "text-embedding-ada-002", + dimensions: Optional[int] = None, + api_key: Optional[Secret] = Secret.from_env_var("AZURE_OPENAI_API_KEY", strict=False), + azure_ad_token: Optional[Secret] = Secret.from_env_var("AZURE_OPENAI_AD_TOKEN", strict=False), + organization: Optional[str] = None, + prefix: str = "", + suffix: str = "", + batch_size: int = 32, + progress_bar: bool = True, + meta_fields_to_embed: Optional[List[str]] = None, + embedding_separator: str = "\n", + timeout: Optional[float] = None, + max_retries: Optional[int] = None, + ): + """ + Creates an AzureOpenAIDocumentEmbedder component. + + :param azure_endpoint: + The endpoint of the model deployed on Azure. + :param api_version: + The version of the API to use. + :param azure_deployment: + The name of the model deployed on Azure. The default model is text-embedding-ada-002. + :param dimensions: + The number of dimensions of the resulting embeddings. Only supported in text-embedding-3 + and later models. + :param api_key: + The Azure OpenAI API key. + You can set it with an environment variable `AZURE_OPENAI_API_KEY`, or pass with this + parameter during initialization. + :param azure_ad_token: + Microsoft Entra ID token, see Microsoft's + [Entra ID](https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id) + documentation for more information. You can set it with an environment variable + `AZURE_OPENAI_AD_TOKEN`, or pass with this parameter during initialization. + Previously called Azure Active Directory. + :param organization: + Your organization ID. See OpenAI's + [Setting Up Your Organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization) + for more information. + :param prefix: + A string to add at the beginning of each text. + :param suffix: + A string to add at the end of each text. + :param batch_size: + Number of documents to embed at once. + :param progress_bar: + If `True`, shows a progress bar when running. + :param meta_fields_to_embed: + List of metadata fields to embed along with the document text. + :param embedding_separator: + Separator used to concatenate the metadata fields to the document text. + :param timeout: The timeout for `AzureOpenAI` client calls, in seconds. + If not set, defaults to either the + `OPENAI_TIMEOUT` environment variable, or 30 seconds. + :param max_retries: Maximum number of retries to contact AzureOpenAI after an internal error. + If not set, defaults to either the `OPENAI_MAX_RETRIES` environment variable or to 5 retries. + """ + # if not provided as a parameter, azure_endpoint is read from the env var AZURE_OPENAI_ENDPOINT + azure_endpoint = azure_endpoint or os.environ.get("AZURE_OPENAI_ENDPOINT") + if not azure_endpoint: + raise ValueError("Please provide an Azure endpoint or set the environment variable AZURE_OPENAI_ENDPOINT.") + + if api_key is None and azure_ad_token is None: + raise ValueError("Please provide an API key or an Azure Active Directory token.") + + self.api_key = api_key + self.azure_ad_token = azure_ad_token + self.api_version = api_version + self.azure_endpoint = azure_endpoint + self.azure_deployment = azure_deployment + self.dimensions = dimensions + self.organization = organization + self.prefix = prefix + self.suffix = suffix + self.batch_size = batch_size + self.progress_bar = progress_bar + self.meta_fields_to_embed = meta_fields_to_embed or [] + self.embedding_separator = embedding_separator + self.timeout = timeout or float(os.environ.get("OPENAI_TIMEOUT", 30.0)) + self.max_retries = max_retries or int(os.environ.get("OPENAI_MAX_RETRIES", 5)) + + self._client = AzureOpenAI( + api_version=api_version, + azure_endpoint=azure_endpoint, + azure_deployment=azure_deployment, + api_key=api_key.resolve_value() if api_key is not None else None, + azure_ad_token=azure_ad_token.resolve_value() if azure_ad_token is not None else None, + organization=organization, + timeout=self.timeout, + max_retries=self.max_retries, + ) + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"model": self.azure_deployment} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + azure_endpoint=self.azure_endpoint, + azure_deployment=self.azure_deployment, + dimensions=self.dimensions, + organization=self.organization, + api_version=self.api_version, + prefix=self.prefix, + suffix=self.suffix, + batch_size=self.batch_size, + progress_bar=self.progress_bar, + meta_fields_to_embed=self.meta_fields_to_embed, + embedding_separator=self.embedding_separator, + api_key=self.api_key.to_dict() if self.api_key is not None else None, + azure_ad_token=self.azure_ad_token.to_dict() if self.azure_ad_token is not None else None, + timeout=self.timeout, + max_retries=self.max_retries, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "AzureOpenAIDocumentEmbedder": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key", "azure_ad_token"]) + return default_from_dict(cls, data) + + def _prepare_texts_to_embed(self, documents: List[Document]) -> List[str]: + """ + Prepare the texts to embed by concatenating the Document text with the metadata fields to embed. + """ + texts_to_embed = [] + for doc in documents: + meta_values_to_embed = [ + str(doc.meta[key]) for key in self.meta_fields_to_embed if key in doc.meta and doc.meta[key] is not None + ] + + text_to_embed = ( + self.prefix + self.embedding_separator.join(meta_values_to_embed + [doc.content or ""]) + self.suffix + ).replace("\n", " ") + + texts_to_embed.append(text_to_embed) + return texts_to_embed + + def _embed_batch(self, texts_to_embed: List[str], batch_size: int) -> Tuple[List[List[float]], Dict[str, Any]]: + """ + Embed a list of texts in batches. + """ + + all_embeddings: List[List[float]] = [] + meta: Dict[str, Any] = {"model": "", "usage": {"prompt_tokens": 0, "total_tokens": 0}} + for i in tqdm(range(0, len(texts_to_embed), batch_size), desc="Embedding Texts"): + batch = texts_to_embed[i : i + batch_size] + if self.dimensions is not None: + response = self._client.embeddings.create( + model=self.azure_deployment, dimensions=self.dimensions, input=batch + ) + else: + response = self._client.embeddings.create(model=self.azure_deployment, input=batch) + + # Append embeddings to the list + all_embeddings.extend(el.embedding for el in response.data) + + # Update the meta information only once if it's empty + if not meta["model"]: + meta["model"] = response.model + meta["usage"] = dict(response.usage) + else: + # Update the usage tokens + meta["usage"]["prompt_tokens"] += response.usage.prompt_tokens + meta["usage"]["total_tokens"] += response.usage.total_tokens + + return all_embeddings, meta + + @component.output_types(documents=List[Document], meta=Dict[str, Any]) + def run(self, documents: List[Document]) -> Dict[str, Any]: + """ + Embeds a list of documents. + + :param documents: + Documents to embed. + + :returns: + A dictionary with the following keys: + - `documents`: A list of documents with embeddings. + - `meta`: Information about the usage of the model. + """ + if not (isinstance(documents, list) and all(isinstance(doc, Document) for doc in documents)): + raise TypeError("Input must be a list of Document instances. For strings, use AzureOpenAITextEmbedder.") + + texts_to_embed = self._prepare_texts_to_embed(documents=documents) + embeddings, meta = self._embed_batch(texts_to_embed=texts_to_embed, batch_size=self.batch_size) + + # Assign the corresponding embeddings to each document + for doc, emb in zip(documents, embeddings): + doc.embedding = emb + + return {"documents": documents, "meta": meta} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/azure_text_embedder.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/azure_text_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..961cd910ada302fa4eb530e87769a9a56315f970 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/azure_text_embedder.py @@ -0,0 +1,196 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +from typing import Any, Dict, List, Optional + +from openai.lib.azure import AzureOpenAI + +from haystack import Document, component, default_from_dict, default_to_dict +from haystack.utils import Secret, deserialize_secrets_inplace + + +@component +class AzureOpenAITextEmbedder: + """ + Embeds strings using OpenAI models deployed on Azure. + + ### Usage example + + ```python + from haystack.components.embedders import AzureOpenAITextEmbedder + + text_to_embed = "I love pizza!" + + text_embedder = AzureOpenAITextEmbedder() + + print(text_embedder.run(text_to_embed)) + + # {'embedding': [0.017020374536514282, -0.023255806416273117, ...], + # 'meta': {'model': 'text-embedding-ada-002-v2', + # 'usage': {'prompt_tokens': 4, 'total_tokens': 4}}} + ``` + """ + + def __init__( + self, + azure_endpoint: Optional[str] = None, + api_version: Optional[str] = "2023-05-15", + azure_deployment: str = "text-embedding-ada-002", + dimensions: Optional[int] = None, + api_key: Optional[Secret] = Secret.from_env_var("AZURE_OPENAI_API_KEY", strict=False), + azure_ad_token: Optional[Secret] = Secret.from_env_var("AZURE_OPENAI_AD_TOKEN", strict=False), + organization: Optional[str] = None, + timeout: Optional[float] = None, + max_retries: Optional[int] = None, + prefix: str = "", + suffix: str = "", + ): + """ + Creates an AzureOpenAITextEmbedder component. + + :param azure_endpoint: + The endpoint of the model deployed on Azure. + :param api_version: + The version of the API to use. + :param azure_deployment: + The name of the model deployed on Azure. The default model is text-embedding-ada-002. + :param dimensions: + The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 + and later models. + :param api_key: + The Azure OpenAI API key. + You can set it with an environment variable `AZURE_OPENAI_API_KEY`, or pass with this + parameter during initialization. + :param azure_ad_token: + Microsoft Entra ID token, see Microsoft's + [Entra ID](https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id) + documentation for more information. You can set it with an environment variable + `AZURE_OPENAI_AD_TOKEN`, or pass with this parameter during initialization. + Previously called Azure Active Directory. + :param organization: + Your organization ID. See OpenAI's + [Setting Up Your Organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization) + for more information. + :param timeout: The timeout for `AzureOpenAI` client calls, in seconds. + If not set, defaults to either the + `OPENAI_TIMEOUT` environment variable, or 30 seconds. + :param max_retries: Maximum number of retries to contact AzureOpenAI after an internal error. + If not set, defaults to either the `OPENAI_MAX_RETRIES` environment variable, or to 5 retries. + :param prefix: + A string to add at the beginning of each text. + :param suffix: + A string to add at the end of each text. + """ + # Why is this here? + # AzureOpenAI init is forcing us to use an init method that takes either base_url or azure_endpoint as not + # None init parameters. This way we accommodate the use case where env var AZURE_OPENAI_ENDPOINT is set instead + # of passing it as a parameter. + azure_endpoint = azure_endpoint or os.environ.get("AZURE_OPENAI_ENDPOINT") + if not azure_endpoint: + raise ValueError("Please provide an Azure endpoint or set the environment variable AZURE_OPENAI_ENDPOINT.") + + if api_key is None and azure_ad_token is None: + raise ValueError("Please provide an API key or an Azure Active Directory token.") + + self.api_key = api_key + self.azure_ad_token = azure_ad_token + self.api_version = api_version + self.azure_endpoint = azure_endpoint + self.azure_deployment = azure_deployment + self.dimensions = dimensions + self.organization = organization + self.timeout = timeout or float(os.environ.get("OPENAI_TIMEOUT", 30.0)) + self.max_retries = max_retries or int(os.environ.get("OPENAI_MAX_RETRIES", 5)) + self.prefix = prefix + self.suffix = suffix + + self._client = AzureOpenAI( + api_version=api_version, + azure_endpoint=azure_endpoint, + azure_deployment=azure_deployment, + api_key=api_key.resolve_value() if api_key is not None else None, + azure_ad_token=azure_ad_token.resolve_value() if azure_ad_token is not None else None, + organization=organization, + timeout=self.timeout, + max_retries=self.max_retries, + ) + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"model": self.azure_deployment} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + azure_endpoint=self.azure_endpoint, + azure_deployment=self.azure_deployment, + dimensions=self.dimensions, + organization=self.organization, + api_version=self.api_version, + prefix=self.prefix, + suffix=self.suffix, + api_key=self.api_key.to_dict() if self.api_key is not None else None, + azure_ad_token=self.azure_ad_token.to_dict() if self.azure_ad_token is not None else None, + timeout=self.timeout, + max_retries=self.max_retries, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "AzureOpenAITextEmbedder": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key", "azure_ad_token"]) + return default_from_dict(cls, data) + + @component.output_types(embedding=List[float], meta=Dict[str, Any]) + def run(self, text: str): + """ + Embeds a single string. + + :param text: + Text to embed. + + :returns: + A dictionary with the following keys: + - `embedding`: The embedding of the input text. + - `meta`: Information about the usage of the model. + """ + if not isinstance(text, str): + # Check if input is a list and all elements are instances of Document + if isinstance(text, list) and all(isinstance(elem, Document) for elem in text): + error_message = "Input must be a string. Use AzureOpenAIDocumentEmbedder for a list of Documents." + else: + error_message = "Input must be a string." + raise TypeError(error_message) + + # Preprocess the text by adding prefixes/suffixes + # finally, replace newlines as recommended by OpenAI docs + processed_text = f"{self.prefix}{text}{self.suffix}".replace("\n", " ") + + if self.dimensions is not None: + response = self._client.embeddings.create( + model=self.azure_deployment, dimensions=self.dimensions, input=processed_text + ) + else: + response = self._client.embeddings.create(model=self.azure_deployment, input=processed_text) + + return { + "embedding": response.data[0].embedding, + "meta": {"model": response.model, "usage": dict(response.usage)}, + } diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/backends/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/backends/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/backends/sentence_transformers_backend.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/backends/sentence_transformers_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..e3550183e9f25c9b5c4bb109fe4c52902af59dee --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/backends/sentence_transformers_backend.py @@ -0,0 +1,80 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional + +from haystack.lazy_imports import LazyImport +from haystack.utils.auth import Secret + +with LazyImport(message="Run 'pip install \"sentence-transformers>=3.0.0\"'") as sentence_transformers_import: + from sentence_transformers import SentenceTransformer + + +class _SentenceTransformersEmbeddingBackendFactory: + """ + Factory class to create instances of Sentence Transformers embedding backends. + """ + + _instances: Dict[str, "_SentenceTransformersEmbeddingBackend"] = {} + + @staticmethod + def get_embedding_backend( + model: str, + device: Optional[str] = None, + auth_token: Optional[Secret] = None, + trust_remote_code: bool = False, + truncate_dim: Optional[int] = None, + model_kwargs: Optional[Dict[str, Any]] = None, + tokenizer_kwargs: Optional[Dict[str, Any]] = None, + config_kwargs: Optional[Dict[str, Any]] = None, + ): + embedding_backend_id = f"{model}{device}{auth_token}{truncate_dim}" + + if embedding_backend_id in _SentenceTransformersEmbeddingBackendFactory._instances: + return _SentenceTransformersEmbeddingBackendFactory._instances[embedding_backend_id] + embedding_backend = _SentenceTransformersEmbeddingBackend( + model=model, + device=device, + auth_token=auth_token, + trust_remote_code=trust_remote_code, + truncate_dim=truncate_dim, + model_kwargs=model_kwargs, + tokenizer_kwargs=tokenizer_kwargs, + config_kwargs=config_kwargs, + ) + _SentenceTransformersEmbeddingBackendFactory._instances[embedding_backend_id] = embedding_backend + return embedding_backend + + +class _SentenceTransformersEmbeddingBackend: + """ + Class to manage Sentence Transformers embeddings. + """ + + def __init__( + self, + model: str, + device: Optional[str] = None, + auth_token: Optional[Secret] = None, + trust_remote_code: bool = False, + truncate_dim: Optional[int] = None, + model_kwargs: Optional[Dict[str, Any]] = None, + tokenizer_kwargs: Optional[Dict[str, Any]] = None, + config_kwargs: Optional[Dict[str, Any]] = None, + ): + sentence_transformers_import.check() + self.model = SentenceTransformer( + model_name_or_path=model, + device=device, + use_auth_token=auth_token.resolve_value() if auth_token else None, + trust_remote_code=trust_remote_code, + truncate_dim=truncate_dim, + model_kwargs=model_kwargs, + tokenizer_kwargs=tokenizer_kwargs, + config_kwargs=config_kwargs, + ) + + def embed(self, data: List[str], **kwargs) -> List[List[float]]: + embeddings = self.model.encode(data, **kwargs).tolist() + return embeddings diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/hugging_face_api_document_embedder.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/hugging_face_api_document_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..deeaf515ef3e9d3fc0044cc559365d1d8171f968 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/hugging_face_api_document_embedder.py @@ -0,0 +1,282 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +from typing import Any, Dict, List, Optional, Union + +from tqdm import tqdm + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.dataclasses import Document +from haystack.lazy_imports import LazyImport +from haystack.utils import Secret, deserialize_secrets_inplace +from haystack.utils.hf import HFEmbeddingAPIType, HFModelType, check_valid_model +from haystack.utils.url_validation import is_valid_http_url + +with LazyImport(message="Run 'pip install \"huggingface_hub>=0.23.0\"'") as huggingface_hub_import: + from huggingface_hub import InferenceClient + +logger = logging.getLogger(__name__) + + +@component +class HuggingFaceAPIDocumentEmbedder: + """ + Embeds documents using Hugging Face APIs. + + Use it with the following Hugging Face APIs: + - [Free Serverless Inference API](https://huggingface.co/inference-api) + - [Paid Inference Endpoints](https://huggingface.co/inference-endpoints) + - [Self-hosted Text Embeddings Inference](https://github.com/huggingface/text-embeddings-inference) + + + ### Usage examples + + #### With free serverless inference API + + ```python + from haystack.components.embedders import HuggingFaceAPIDocumentEmbedder + from haystack.utils import Secret + from haystack.dataclasses import Document + + doc = Document(content="I love pizza!") + + doc_embedder = HuggingFaceAPIDocumentEmbedder(api_type="serverless_inference_api", + api_params={"model": "BAAI/bge-small-en-v1.5"}, + token=Secret.from_token("")) + + result = document_embedder.run([doc]) + print(result["documents"][0].embedding) + + # [0.017020374536514282, -0.023255806416273117, ...] + ``` + + #### With paid inference endpoints + + ```python + from haystack.components.embedders import HuggingFaceAPIDocumentEmbedder + from haystack.utils import Secret + from haystack.dataclasses import Document + + doc = Document(content="I love pizza!") + + doc_embedder = HuggingFaceAPIDocumentEmbedder(api_type="inference_endpoints", + api_params={"url": ""}, + token=Secret.from_token("")) + + result = document_embedder.run([doc]) + print(result["documents"][0].embedding) + + # [0.017020374536514282, -0.023255806416273117, ...] + ``` + + #### With self-hosted text embeddings inference + + ```python + from haystack.components.embedders import HuggingFaceAPIDocumentEmbedder + from haystack.dataclasses import Document + + doc = Document(content="I love pizza!") + + doc_embedder = HuggingFaceAPIDocumentEmbedder(api_type="text_embeddings_inference", + api_params={"url": "http://localhost:8080"}) + + result = document_embedder.run([doc]) + print(result["documents"][0].embedding) + + # [0.017020374536514282, -0.023255806416273117, ...] + ``` + """ + + def __init__( + self, + api_type: Union[HFEmbeddingAPIType, str], + api_params: Dict[str, str], + token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + prefix: str = "", + suffix: str = "", + truncate: bool = True, + normalize: bool = False, + batch_size: int = 32, + progress_bar: bool = True, + meta_fields_to_embed: Optional[List[str]] = None, + embedding_separator: str = "\n", + ): + """ + Creates a HuggingFaceAPIDocumentEmbedder component. + + :param api_type: + The type of Hugging Face API to use. + :param api_params: + A dictionary with the following keys: + - `model`: Hugging Face model ID. Required when `api_type` is `SERVERLESS_INFERENCE_API`. + - `url`: URL of the inference endpoint. Required when `api_type` is `INFERENCE_ENDPOINTS` or + `TEXT_EMBEDDINGS_INFERENCE`. + :param token: The Hugging Face token to use as HTTP bearer authorization. + Check your HF token in your [account settings](https://huggingface.co/settings/tokens). + :param prefix: + A string to add at the beginning of each text. + :param suffix: + A string to add at the end of each text. + :param truncate: + Truncates the input text to the maximum length supported by the model. + Applicable when `api_type` is `TEXT_EMBEDDINGS_INFERENCE`, or `INFERENCE_ENDPOINTS` + if the backend uses Text Embeddings Inference. + If `api_type` is `SERVERLESS_INFERENCE_API`, this parameter is ignored. + It is always set to `True` and cannot be changed. + :param normalize: + Normalizes the embeddings to unit length. + Applicable when `api_type` is `TEXT_EMBEDDINGS_INFERENCE`, or `INFERENCE_ENDPOINTS` + if the backend uses Text Embeddings Inference. + If `api_type` is `SERVERLESS_INFERENCE_API`, this parameter is ignored. + It is always set to `False` and cannot be changed. + :param batch_size: + Number of documents to process at once. + :param progress_bar: + If `True`, shows a progress bar when running. + :param meta_fields_to_embed: + List of metadata fields to embed along with the document text. + :param embedding_separator: + Separator used to concatenate the metadata fields to the document text. + """ + huggingface_hub_import.check() + + if isinstance(api_type, str): + api_type = HFEmbeddingAPIType.from_str(api_type) + + api_params = api_params or {} + + if api_type == HFEmbeddingAPIType.SERVERLESS_INFERENCE_API: + model = api_params.get("model") + if model is None: + raise ValueError( + "To use the Serverless Inference API, you need to specify the `model` parameter in `api_params`." + ) + check_valid_model(model, HFModelType.EMBEDDING, token) + model_or_url = model + elif api_type in [HFEmbeddingAPIType.INFERENCE_ENDPOINTS, HFEmbeddingAPIType.TEXT_EMBEDDINGS_INFERENCE]: + url = api_params.get("url") + if url is None: + msg = ( + "To use Text Embeddings Inference or Inference Endpoints, you need to specify the `url` " + "parameter in `api_params`." + ) + raise ValueError(msg) + if not is_valid_http_url(url): + raise ValueError(f"Invalid URL: {url}") + model_or_url = url + else: + msg = f"Unknown api_type {api_type}" + raise ValueError(api_type) + + self.api_type = api_type + self.api_params = api_params + self.token = token + self.prefix = prefix + self.suffix = suffix + self.truncate = truncate + self.normalize = normalize + self.batch_size = batch_size + self.progress_bar = progress_bar + self.meta_fields_to_embed = meta_fields_to_embed or [] + self.embedding_separator = embedding_separator + self._client = InferenceClient(model_or_url, token=token.resolve_value() if token else None) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + api_type=str(self.api_type), + api_params=self.api_params, + prefix=self.prefix, + suffix=self.suffix, + token=self.token.to_dict() if self.token else None, + truncate=self.truncate, + normalize=self.normalize, + batch_size=self.batch_size, + progress_bar=self.progress_bar, + meta_fields_to_embed=self.meta_fields_to_embed, + embedding_separator=self.embedding_separator, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "HuggingFaceAPIDocumentEmbedder": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["token"]) + return default_from_dict(cls, data) + + def _prepare_texts_to_embed(self, documents: List[Document]) -> List[str]: + """ + Prepare the texts to embed by concatenating the Document text with the metadata fields to embed. + """ + texts_to_embed = [] + for doc in documents: + meta_values_to_embed = [ + str(doc.meta[key]) for key in self.meta_fields_to_embed if key in doc.meta and doc.meta[key] is not None + ] + + text_to_embed = ( + self.prefix + self.embedding_separator.join(meta_values_to_embed + [doc.content or ""]) + self.suffix + ) + + texts_to_embed.append(text_to_embed) + return texts_to_embed + + def _embed_batch(self, texts_to_embed: List[str], batch_size: int) -> List[List[float]]: + """ + Embed a list of texts in batches. + """ + + all_embeddings = [] + for i in tqdm( + range(0, len(texts_to_embed), batch_size), disable=not self.progress_bar, desc="Calculating embeddings" + ): + batch = texts_to_embed[i : i + batch_size] + response = self._client.post( + json={"inputs": batch, "truncate": self.truncate, "normalize": self.normalize}, + task="feature-extraction", + ) + embeddings = json.loads(response.decode()) + all_embeddings.extend(embeddings) + + return all_embeddings + + @component.output_types(documents=List[Document]) + def run(self, documents: List[Document]): + """ + Embeds a list of documents. + + :param documents: + Documents to embed. + + :returns: + A dictionary with the following keys: + - `documents`: A list of documents with embeddings. + """ + if not isinstance(documents, list) or documents and not isinstance(documents[0], Document): + raise TypeError( + "HuggingFaceAPIDocumentEmbedder expects a list of Documents as input." + " In case you want to embed a string, please use the HuggingFaceAPITextEmbedder." + ) + + texts_to_embed = self._prepare_texts_to_embed(documents=documents) + + embeddings = self._embed_batch(texts_to_embed=texts_to_embed, batch_size=self.batch_size) + + for doc, emb in zip(documents, embeddings): + doc.embedding = emb + + return {"documents": documents} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/hugging_face_api_text_embedder.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/hugging_face_api_text_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..7471839721e179b2cf2eb2e674db5a0e57c549dd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/hugging_face_api_text_embedder.py @@ -0,0 +1,209 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +from typing import Any, Dict, List, Optional, Union + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.lazy_imports import LazyImport +from haystack.utils import Secret, deserialize_secrets_inplace +from haystack.utils.hf import HFEmbeddingAPIType, HFModelType, check_valid_model +from haystack.utils.url_validation import is_valid_http_url + +with LazyImport(message="Run 'pip install \"huggingface_hub>=0.23.0\"'") as huggingface_hub_import: + from huggingface_hub import InferenceClient + +logger = logging.getLogger(__name__) + + +@component +class HuggingFaceAPITextEmbedder: + """ + Embeds strings using Hugging Face APIs. + + Use it with the following Hugging Face APIs: + - [Free Serverless Inference API](https://huggingface.co/inference-api) + - [Paid Inference Endpoints](https://huggingface.co/inference-endpoints) + - [Self-hosted Text Embeddings Inference](https://github.com/huggingface/text-embeddings-inference) + + ### Usage examples + + #### With free serverless inference API + + ```python + from haystack.components.embedders import HuggingFaceAPITextEmbedder + from haystack.utils import Secret + + text_embedder = HuggingFaceAPITextEmbedder(api_type="serverless_inference_api", + api_params={"model": "BAAI/bge-small-en-v1.5"}, + token=Secret.from_token("")) + + print(text_embedder.run("I love pizza!")) + + # {'embedding': [0.017020374536514282, -0.023255806416273117, ...], + ``` + + #### With paid inference endpoints + + ```python + from haystack.components.embedders import HuggingFaceAPITextEmbedder + from haystack.utils import Secret + text_embedder = HuggingFaceAPITextEmbedder(api_type="inference_endpoints", + api_params={"model": "BAAI/bge-small-en-v1.5"}, + token=Secret.from_token("")) + + print(text_embedder.run("I love pizza!")) + + # {'embedding': [0.017020374536514282, -0.023255806416273117, ...], + ``` + + #### With self-hosted text embeddings inference + + ```python + from haystack.components.embedders import HuggingFaceAPITextEmbedder + from haystack.utils import Secret + + text_embedder = HuggingFaceAPITextEmbedder(api_type="text_embeddings_inference", + api_params={"url": "http://localhost:8080"}) + + print(text_embedder.run("I love pizza!")) + + # {'embedding': [0.017020374536514282, -0.023255806416273117, ...], + ``` + """ + + def __init__( + self, + api_type: Union[HFEmbeddingAPIType, str], + api_params: Dict[str, str], + token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + prefix: str = "", + suffix: str = "", + truncate: bool = True, + normalize: bool = False, + ): + """ + Creates a HuggingFaceAPITextEmbedder component. + + :param api_type: + The type of Hugging Face API to use. + :param api_params: + A dictionary with the following keys: + - `model`: Hugging Face model ID. Required when `api_type` is `SERVERLESS_INFERENCE_API`. + - `url`: URL of the inference endpoint. Required when `api_type` is `INFERENCE_ENDPOINTS` or + `TEXT_EMBEDDINGS_INFERENCE`. + :param token: The Hugging Face token to use as HTTP bearer authorization. + Check your HF token in your [account settings](https://huggingface.co/settings/tokens). + :param prefix: + A string to add at the beginning of each text. + :param suffix: + A string to add at the end of each text. + :param truncate: + Truncates the input text to the maximum length supported by the model. + Applicable when `api_type` is `TEXT_EMBEDDINGS_INFERENCE`, or `INFERENCE_ENDPOINTS` + if the backend uses Text Embeddings Inference. + If `api_type` is `SERVERLESS_INFERENCE_API`, this parameter is ignored. + It is always set to `True` and cannot be changed. + :param normalize: + Normalizes the embeddings to unit length. + Applicable when `api_type` is `TEXT_EMBEDDINGS_INFERENCE`, or `INFERENCE_ENDPOINTS` + if the backend uses Text Embeddings Inference. + If `api_type` is `SERVERLESS_INFERENCE_API`, this parameter is ignored. + It is always set to `False` and cannot be changed. + """ + huggingface_hub_import.check() + + if isinstance(api_type, str): + api_type = HFEmbeddingAPIType.from_str(api_type) + + if api_type == HFEmbeddingAPIType.SERVERLESS_INFERENCE_API: + model = api_params.get("model") + if model is None: + raise ValueError( + "To use the Serverless Inference API, you need to specify the `model` parameter in `api_params`." + ) + check_valid_model(model, HFModelType.EMBEDDING, token) + model_or_url = model + elif api_type in [HFEmbeddingAPIType.INFERENCE_ENDPOINTS, HFEmbeddingAPIType.TEXT_EMBEDDINGS_INFERENCE]: + url = api_params.get("url") + if url is None: + msg = ( + "To use Text Embeddings Inference or Inference Endpoints, you need to specify the `url` " + "parameter in `api_params`." + ) + raise ValueError(msg) + if not is_valid_http_url(url): + raise ValueError(f"Invalid URL: {url}") + model_or_url = url + else: + msg = f"Unknown api_type {api_type}" + raise ValueError() + + self.api_type = api_type + self.api_params = api_params + self.token = token + self.prefix = prefix + self.suffix = suffix + self.truncate = truncate + self.normalize = normalize + self._client = InferenceClient(model_or_url, token=token.resolve_value() if token else None) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + api_type=str(self.api_type), + api_params=self.api_params, + prefix=self.prefix, + suffix=self.suffix, + token=self.token.to_dict() if self.token else None, + truncate=self.truncate, + normalize=self.normalize, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "HuggingFaceAPITextEmbedder": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["token"]) + return default_from_dict(cls, data) + + @component.output_types(embedding=List[float]) + def run(self, text: str): + """ + Embeds a single string. + + :param text: + Text to embed. + + :returns: + A dictionary with the following keys: + - `embedding`: The embedding of the input text. + """ + if not isinstance(text, str): + raise TypeError( + "HuggingFaceAPITextEmbedder expects a string as an input." + "In case you want to embed a list of Documents, please use the HuggingFaceAPIDocumentEmbedder." + ) + + text_to_embed = self.prefix + text + self.suffix + + response = self._client.post( + json={"inputs": [text_to_embed], "truncate": self.truncate, "normalize": self.normalize}, + task="feature-extraction", + ) + embedding = json.loads(response.decode())[0] + + return {"embedding": embedding} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/openai_document_embedder.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/openai_document_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..61b0cb4df945ae0a8d842eacb4cb72dd351beb66 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/openai_document_embedder.py @@ -0,0 +1,235 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +from typing import Any, Dict, List, Optional, Tuple + +from openai import OpenAI +from tqdm import tqdm + +from haystack import Document, component, default_from_dict, default_to_dict +from haystack.utils import Secret, deserialize_secrets_inplace + + +@component +class OpenAIDocumentEmbedder: + """ + Computes document embeddings using OpenAI models. + + ### Usage example + + ```python + from haystack import Document + from haystack.components.embedders import OpenAIDocumentEmbedder + + doc = Document(content="I love pizza!") + + document_embedder = OpenAIDocumentEmbedder() + + result = document_embedder.run([doc]) + print(result['documents'][0].embedding) + + # [0.017020374536514282, -0.023255806416273117, ...] + ``` + """ + + def __init__( + self, + api_key: Secret = Secret.from_env_var("OPENAI_API_KEY"), + model: str = "text-embedding-ada-002", + dimensions: Optional[int] = None, + api_base_url: Optional[str] = None, + organization: Optional[str] = None, + prefix: str = "", + suffix: str = "", + batch_size: int = 32, + progress_bar: bool = True, + meta_fields_to_embed: Optional[List[str]] = None, + embedding_separator: str = "\n", + timeout: Optional[float] = None, + max_retries: Optional[int] = None, + ): + """ + Creates an OpenAIDocumentEmbedder component. + + Before initializing the component, you can set the 'OPENAI_TIMEOUT' and 'OPENAI_MAX_RETRIES' + environment variables to override the `timeout` and `max_retries` parameters respectively + in the OpenAI client. + + :param api_key: + The OpenAI API key. + You can set it with an environment variable `OPENAI_API_KEY`, or pass with this parameter + during initialization. + :param model: + The name of the model to use for calculating embeddings. + The default model is `text-embedding-ada-002`. + :param dimensions: + The number of dimensions of the resulting embeddings. Only `text-embedding-3` and + later models support this parameter. + :param api_base_url: + Overrides the default base URL for all HTTP requests. + :param organization: + Your OpenAI organization ID. See OpenAI's + [Setting Up Your Organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization) + for more information. + :param prefix: + A string to add at the beginning of each text. + :param suffix: + A string to add at the end of each text. + :param batch_size: + Number of documents to embed at once. + :param progress_bar: + If `True`, shows a progress bar when running. + :param meta_fields_to_embed: + List of metadata fields to embed along with the document text. + :param embedding_separator: + Separator used to concatenate the metadata fields to the document text. + :param timeout: + Timeout for OpenAI client calls. If not set, it defaults to either the + `OPENAI_TIMEOUT` environment variable, or 30 seconds. + :param max_retries: + Maximum number of retries to contact OpenAI after an internal error. + If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or 5 retries. + """ + self.api_key = api_key + self.model = model + self.dimensions = dimensions + self.api_base_url = api_base_url + self.organization = organization + self.prefix = prefix + self.suffix = suffix + self.batch_size = batch_size + self.progress_bar = progress_bar + self.meta_fields_to_embed = meta_fields_to_embed or [] + self.embedding_separator = embedding_separator + + if timeout is None: + timeout = float(os.environ.get("OPENAI_TIMEOUT", 30.0)) + if max_retries is None: + max_retries = int(os.environ.get("OPENAI_MAX_RETRIES", 5)) + + self.client = OpenAI( + api_key=api_key.resolve_value(), + organization=organization, + base_url=api_base_url, + timeout=timeout, + max_retries=max_retries, + ) + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"model": self.model} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + model=self.model, + dimensions=self.dimensions, + organization=self.organization, + api_base_url=self.api_base_url, + prefix=self.prefix, + suffix=self.suffix, + batch_size=self.batch_size, + progress_bar=self.progress_bar, + meta_fields_to_embed=self.meta_fields_to_embed, + embedding_separator=self.embedding_separator, + api_key=self.api_key.to_dict(), + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "OpenAIDocumentEmbedder": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + return default_from_dict(cls, data) + + def _prepare_texts_to_embed(self, documents: List[Document]) -> List[str]: + """ + Prepare the texts to embed by concatenating the Document text with the metadata fields to embed. + """ + texts_to_embed = [] + for doc in documents: + meta_values_to_embed = [ + str(doc.meta[key]) for key in self.meta_fields_to_embed if key in doc.meta and doc.meta[key] is not None + ] + + text_to_embed = ( + self.prefix + self.embedding_separator.join(meta_values_to_embed + [doc.content or ""]) + self.suffix + ) + + # copied from OpenAI embedding_utils (https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py) + # replace newlines, which can negatively affect performance. + text_to_embed = text_to_embed.replace("\n", " ") + texts_to_embed.append(text_to_embed) + return texts_to_embed + + def _embed_batch(self, texts_to_embed: List[str], batch_size: int) -> Tuple[List[List[float]], Dict[str, Any]]: + """ + Embed a list of texts in batches. + """ + + all_embeddings = [] + meta: Dict[str, Any] = {} + for i in tqdm( + range(0, len(texts_to_embed), batch_size), disable=not self.progress_bar, desc="Calculating embeddings" + ): + batch = texts_to_embed[i : i + batch_size] + if self.dimensions is not None: + response = self.client.embeddings.create(model=self.model, dimensions=self.dimensions, input=batch) + else: + response = self.client.embeddings.create(model=self.model, input=batch) + embeddings = [el.embedding for el in response.data] + all_embeddings.extend(embeddings) + + if "model" not in meta: + meta["model"] = response.model + if "usage" not in meta: + meta["usage"] = dict(response.usage) + else: + meta["usage"]["prompt_tokens"] += response.usage.prompt_tokens + meta["usage"]["total_tokens"] += response.usage.total_tokens + + return all_embeddings, meta + + @component.output_types(documents=List[Document], meta=Dict[str, Any]) + def run(self, documents: List[Document]): + """ + Embeds a list of documents. + + :param documents: + A list of documents to embed. + + :returns: + A dictionary with the following keys: + - `documents`: A list of documents with embeddings. + - `meta`: Information about the usage of the model. + """ + if not isinstance(documents, list) or documents and not isinstance(documents[0], Document): + raise TypeError( + "OpenAIDocumentEmbedder expects a list of Documents as input." + "In case you want to embed a string, please use the OpenAITextEmbedder." + ) + + texts_to_embed = self._prepare_texts_to_embed(documents=documents) + + embeddings, meta = self._embed_batch(texts_to_embed=texts_to_embed, batch_size=self.batch_size) + + for doc, emb in zip(documents, embeddings): + doc.embedding = emb + + return {"documents": documents, "meta": meta} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/openai_text_embedder.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/openai_text_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..4a2d9d3bee91c9be9dd283cdb5cdb2398fddb2f8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/openai_text_embedder.py @@ -0,0 +1,177 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +from typing import Any, Dict, List, Optional + +from openai import OpenAI + +from haystack import component, default_from_dict, default_to_dict +from haystack.utils import Secret, deserialize_secrets_inplace + +OPENAI_TIMEOUT = float(os.environ.get("OPENAI_TIMEOUT", 30)) +OPENAI_MAX_RETRIES = int(os.environ.get("OPENAI_MAX_RETRIES", 5)) + + +@component +class OpenAITextEmbedder: + """ + Embeds strings using OpenAI models. + + You can use it to embed user query and send it to an embedding Retriever. + + ### Usage example + + ```python + from haystack.components.embedders import OpenAITextEmbedder + + text_to_embed = "I love pizza!" + + text_embedder = OpenAITextEmbedder() + + print(text_embedder.run(text_to_embed)) + + # {'embedding': [0.017020374536514282, -0.023255806416273117, ...], + # 'meta': {'model': 'text-embedding-ada-002-v2', + # 'usage': {'prompt_tokens': 4, 'total_tokens': 4}}} + ``` + """ + + def __init__( + self, + api_key: Secret = Secret.from_env_var("OPENAI_API_KEY"), + model: str = "text-embedding-ada-002", + dimensions: Optional[int] = None, + api_base_url: Optional[str] = None, + organization: Optional[str] = None, + prefix: str = "", + suffix: str = "", + timeout: Optional[float] = None, + max_retries: Optional[int] = None, + ): + """ + Creates an OpenAITextEmbedder component. + + Before initializing the component, you can set the 'OPENAI_TIMEOUT' and 'OPENAI_MAX_RETRIES' + environment variables to override the `timeout` and `max_retries` parameters respectively + in the OpenAI client. + + :param api_key: + The OpenAI API key. + You can set it with an environment variable `OPENAI_API_KEY`, or pass with this parameter + during initialization. + :param model: + The name of the model to use for calculating embeddings. + The default model is `text-embedding-ada-002`. + :param dimensions: + The number of dimensions of the resulting embeddings. Only `text-embedding-3` and + later models support this parameter. + :param api_base_url: + Overrides default base URL for all HTTP requests. + :param organization: + Your organization ID. See OpenAI's + [production best practices](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization) + for more information. + :param prefix: + A string to add at the beginning of each text to embed. + :param suffix: + A string to add at the end of each text to embed. + :param timeout: + Timeout for OpenAI client calls. If not set, it defaults to either the + `OPENAI_TIMEOUT` environment variable, or 30 seconds. + :param max_retries: + Maximum number of retries to contact OpenAI after an internal error. + If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5. + """ + self.model = model + self.dimensions = dimensions + self.api_base_url = api_base_url + self.organization = organization + self.prefix = prefix + self.suffix = suffix + self.api_key = api_key + + if timeout is None: + timeout = float(os.environ.get("OPENAI_TIMEOUT", 30.0)) + if max_retries is None: + max_retries = int(os.environ.get("OPENAI_MAX_RETRIES", 5)) + + self.client = OpenAI( + api_key=api_key.resolve_value(), + organization=organization, + base_url=api_base_url, + timeout=timeout, + max_retries=max_retries, + ) + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"model": self.model} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + model=self.model, + api_base_url=self.api_base_url, + organization=self.organization, + prefix=self.prefix, + suffix=self.suffix, + dimensions=self.dimensions, + api_key=self.api_key.to_dict(), + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "OpenAITextEmbedder": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + return default_from_dict(cls, data) + + @component.output_types(embedding=List[float], meta=Dict[str, Any]) + def run(self, text: str): + """ + Embeds a single string. + + :param text: + Text to embed. + + :returns: + A dictionary with the following keys: + - `embedding`: The embedding of the input text. + - `meta`: Information about the usage of the model. + """ + if not isinstance(text, str): + raise TypeError( + "OpenAITextEmbedder expects a string as an input." + "In case you want to embed a list of Documents, please use the OpenAIDocumentEmbedder." + ) + + text_to_embed = self.prefix + text + self.suffix + + # copied from OpenAI embedding_utils (https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py) + # replace newlines, which can negatively affect performance. + text_to_embed = text_to_embed.replace("\n", " ") + + if self.dimensions is not None: + response = self.client.embeddings.create(model=self.model, dimensions=self.dimensions, input=text_to_embed) + else: + response = self.client.embeddings.create(model=self.model, input=text_to_embed) + + meta = {"model": response.model, "usage": dict(response.usage)} + + return {"embedding": response.data[0].embedding, "meta": meta} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/sentence_transformers_document_embedder.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/sentence_transformers_document_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..195c5d10c850857cb76a7fd3db8d7544f3b31958 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/sentence_transformers_document_embedder.py @@ -0,0 +1,240 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Literal, Optional + +from haystack import Document, component, default_from_dict, default_to_dict +from haystack.components.embedders.backends.sentence_transformers_backend import ( + _SentenceTransformersEmbeddingBackendFactory, +) +from haystack.utils import ComponentDevice, Secret, deserialize_secrets_inplace +from haystack.utils.hf import deserialize_hf_model_kwargs, serialize_hf_model_kwargs + + +@component +class SentenceTransformersDocumentEmbedder: + """ + Calculates document embeddings using Sentence Transformers models. + + It stores the embeddings in the `embedding` metadata field of each document. + You can also embed documents' metadata. + Use this component in indexing pipelines to embed input documents + and send them to DocumentWriter to write a into a Document Store. + + ### Usage example: + + ```python + from haystack import Document + from haystack.components.embedders import SentenceTransformersDocumentEmbedder + doc = Document(content="I love pizza!") + doc_embedder = SentenceTransformersDocumentEmbedder() + doc_embedder.warm_up() + + result = doc_embedder.run([doc]) + print(result['documents'][0].embedding) + + # [-0.07804739475250244, 0.1498992145061493, ...] + ``` + """ + + def __init__( # noqa: PLR0913 + self, + model: str = "sentence-transformers/all-mpnet-base-v2", + device: Optional[ComponentDevice] = None, + token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + prefix: str = "", + suffix: str = "", + batch_size: int = 32, + progress_bar: bool = True, + normalize_embeddings: bool = False, + meta_fields_to_embed: Optional[List[str]] = None, + embedding_separator: str = "\n", + trust_remote_code: bool = False, + truncate_dim: Optional[int] = None, + model_kwargs: Optional[Dict[str, Any]] = None, + tokenizer_kwargs: Optional[Dict[str, Any]] = None, + config_kwargs: Optional[Dict[str, Any]] = None, + precision: Literal["float32", "int8", "uint8", "binary", "ubinary"] = "float32", + ): + """ + Creates a SentenceTransformersDocumentEmbedder component. + + :param model: + The model to use for calculating embeddings. + Pass a local path or ID of the model on Hugging Face. + :param device: + The device to use for loading the model. + Overrides the default device. + :param token: + The API token to download private models from Hugging Face. + :param prefix: + A string to add at the beginning of each document text. + Can be used to prepend the text with an instruction, as required by some embedding models, + such as E5 and bge. + :param suffix: + A string to add at the end of each document text. + :param batch_size: + Number of documents to embed at once. + :param progress_bar: + If `True`, shows a progress bar when embedding documents. + :param normalize_embeddings: + If `True`, returns vectors with length 1. + :param meta_fields_to_embed: + List of metadata fields to embed along with the document text. + :param embedding_separator: + Separator used to concatenate the metadata fields to the document text. + :param trust_remote_code: + If `False`, allows only Hugging Face verified model architectures. + If `True`, allows custom models and scripts. + :param truncate_dim: + The dimension to truncate sentence embeddings to. `None` does no truncation. + If the model wasn't trained with Matryoshka Representation Learning, + truncating embeddings can significantly affect performance. + :param model_kwargs: + Additional keyword arguments for `AutoModelForSequenceClassification.from_pretrained` + when loading the model. Refer to specific model documentation for available kwargs. + :param tokenizer_kwargs: + Additional keyword arguments for `AutoTokenizer.from_pretrained` when loading the tokenizer. + Refer to specific model documentation for available kwargs. + :param config_kwargs: + Additional keyword arguments for `AutoConfig.from_pretrained` when loading the model configuration. + :param precision: + The precision to use for the embeddings. + All non-float32 precisions are quantized embeddings. + Quantized embeddings are smaller and faster to compute, but may have a lower accuracy. + They are useful for reducing the size of the embeddings of a corpus for semantic search, among other tasks. + """ + + self.model = model + self.device = ComponentDevice.resolve_device(device) + self.token = token + self.prefix = prefix + self.suffix = suffix + self.batch_size = batch_size + self.progress_bar = progress_bar + self.normalize_embeddings = normalize_embeddings + self.meta_fields_to_embed = meta_fields_to_embed or [] + self.embedding_separator = embedding_separator + self.trust_remote_code = trust_remote_code + self.truncate_dim = truncate_dim + self.model_kwargs = model_kwargs + self.tokenizer_kwargs = tokenizer_kwargs + self.config_kwargs = config_kwargs + self.embedding_backend = None + self.precision = precision + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"model": self.model} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + serialization_dict = default_to_dict( + self, + model=self.model, + device=self.device.to_dict(), + token=self.token.to_dict() if self.token else None, + prefix=self.prefix, + suffix=self.suffix, + batch_size=self.batch_size, + progress_bar=self.progress_bar, + normalize_embeddings=self.normalize_embeddings, + meta_fields_to_embed=self.meta_fields_to_embed, + embedding_separator=self.embedding_separator, + trust_remote_code=self.trust_remote_code, + truncate_dim=self.truncate_dim, + model_kwargs=self.model_kwargs, + tokenizer_kwargs=self.tokenizer_kwargs, + config_kwargs=self.config_kwargs, + precision=self.precision, + ) + if serialization_dict["init_parameters"].get("model_kwargs") is not None: + serialize_hf_model_kwargs(serialization_dict["init_parameters"]["model_kwargs"]) + return serialization_dict + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "SentenceTransformersDocumentEmbedder": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + init_params = data["init_parameters"] + if init_params.get("device") is not None: + init_params["device"] = ComponentDevice.from_dict(init_params["device"]) + deserialize_secrets_inplace(init_params, keys=["token"]) + if init_params.get("model_kwargs") is not None: + deserialize_hf_model_kwargs(init_params["model_kwargs"]) + return default_from_dict(cls, data) + + def warm_up(self): + """ + Initializes the component. + """ + if self.embedding_backend is None: + self.embedding_backend = _SentenceTransformersEmbeddingBackendFactory.get_embedding_backend( + model=self.model, + device=self.device.to_torch_str(), + auth_token=self.token, + trust_remote_code=self.trust_remote_code, + truncate_dim=self.truncate_dim, + model_kwargs=self.model_kwargs, + tokenizer_kwargs=self.tokenizer_kwargs, + config_kwargs=self.config_kwargs, + ) + if self.tokenizer_kwargs and self.tokenizer_kwargs.get("model_max_length"): + self.embedding_backend.model.max_seq_length = self.tokenizer_kwargs["model_max_length"] + + @component.output_types(documents=List[Document]) + def run(self, documents: List[Document]): + """ + Embed a list of documents. + + :param documents: + Documents to embed. + + :returns: + A dictionary with the following keys: + - `documents`: Documents with embeddings. + """ + if not isinstance(documents, list) or documents and not isinstance(documents[0], Document): + raise TypeError( + "SentenceTransformersDocumentEmbedder expects a list of Documents as input." + "In case you want to embed a list of strings, please use the SentenceTransformersTextEmbedder." + ) + if self.embedding_backend is None: + raise RuntimeError("The embedding model has not been loaded. Please call warm_up() before running.") + + texts_to_embed = [] + for doc in documents: + meta_values_to_embed = [ + str(doc.meta[key]) for key in self.meta_fields_to_embed if key in doc.meta and doc.meta[key] + ] + text_to_embed = ( + self.prefix + self.embedding_separator.join(meta_values_to_embed + [doc.content or ""]) + self.suffix + ) + texts_to_embed.append(text_to_embed) + + embeddings = self.embedding_backend.embed( + texts_to_embed, + batch_size=self.batch_size, + show_progress_bar=self.progress_bar, + normalize_embeddings=self.normalize_embeddings, + precision=self.precision, + ) + + for doc, emb in zip(documents, embeddings): + doc.embedding = emb + + return {"documents": documents} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/sentence_transformers_text_embedder.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/sentence_transformers_text_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..f8b959495fa550b8ea65893183452e1b42a1306a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/embedders/sentence_transformers_text_embedder.py @@ -0,0 +1,213 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Literal, Optional + +from haystack import component, default_from_dict, default_to_dict +from haystack.components.embedders.backends.sentence_transformers_backend import ( + _SentenceTransformersEmbeddingBackendFactory, +) +from haystack.utils import ComponentDevice, Secret, deserialize_secrets_inplace +from haystack.utils.hf import deserialize_hf_model_kwargs, serialize_hf_model_kwargs + + +@component +class SentenceTransformersTextEmbedder: + """ + Embeds strings using Sentence Transformers models. + + You can use it to embed user query and send it to an embedding retriever. + + Usage example: + ```python + from haystack.components.embedders import SentenceTransformersTextEmbedder + + text_to_embed = "I love pizza!" + + text_embedder = SentenceTransformersTextEmbedder() + text_embedder.warm_up() + + print(text_embedder.run(text_to_embed)) + + # {'embedding': [-0.07804739475250244, 0.1498992145061493,, ...]} + ``` + """ + + def __init__( # noqa: PLR0913 + self, + model: str = "sentence-transformers/all-mpnet-base-v2", + device: Optional[ComponentDevice] = None, + token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + prefix: str = "", + suffix: str = "", + batch_size: int = 32, + progress_bar: bool = True, + normalize_embeddings: bool = False, + trust_remote_code: bool = False, + truncate_dim: Optional[int] = None, + model_kwargs: Optional[Dict[str, Any]] = None, + tokenizer_kwargs: Optional[Dict[str, Any]] = None, + config_kwargs: Optional[Dict[str, Any]] = None, + precision: Literal["float32", "int8", "uint8", "binary", "ubinary"] = "float32", + ): + """ + Create a SentenceTransformersTextEmbedder component. + + :param model: + The model to use for calculating embeddings. + Specify the path to a local model or the ID of the model on Hugging Face. + :param device: + Overrides the default device used to load the model. + :param token: + An API token to use private models from Hugging Face. + :param prefix: + A string to add at the beginning of each text to be embedded. + You can use it to prepend the text with an instruction, as required by some embedding models, + such as E5 and bge. + :param suffix: + A string to add at the end of each text to embed. + :param batch_size: + Number of texts to embed at once. + :param progress_bar: + If `True`, shows a progress bar for calculating embeddings. + If `False`, disables the progress bar. + :param normalize_embeddings: + If `True`, returned vectors have a length of 1. + :param trust_remote_code: + If `False`, permits only Hugging Face verified model architectures. + If `True`, permits custom models and scripts. + :param truncate_dim: + The dimension to truncate sentence embeddings to. `None` does no truncation. + If the model has not been trained with Matryoshka Representation Learning, + truncation of embeddings can significantly affect performance. + :param model_kwargs: + Additional keyword arguments for `AutoModelForSequenceClassification.from_pretrained` + when loading the model. Refer to specific model documentation for available kwargs. + :param tokenizer_kwargs: + Additional keyword arguments for `AutoTokenizer.from_pretrained` when loading the tokenizer. + Refer to specific model documentation for available kwargs. + :param config_kwargs: + Additional keyword arguments for `AutoConfig.from_pretrained` when loading the model configuration. + :param precision: + The precision to use for the embeddings. + All non-float32 precisions are quantized embeddings. + Quantized embeddings are smaller in size and faster to compute, but may have a lower accuracy. + They are useful for reducing the size of the embeddings of a corpus for semantic search, among other tasks. + """ + + self.model = model + self.device = ComponentDevice.resolve_device(device) + self.token = token + self.prefix = prefix + self.suffix = suffix + self.batch_size = batch_size + self.progress_bar = progress_bar + self.normalize_embeddings = normalize_embeddings + self.trust_remote_code = trust_remote_code + self.truncate_dim = truncate_dim + self.model_kwargs = model_kwargs + self.tokenizer_kwargs = tokenizer_kwargs + self.config_kwargs = config_kwargs + self.embedding_backend = None + self.precision = precision + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"model": self.model} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + serialization_dict = default_to_dict( + self, + model=self.model, + device=self.device.to_dict(), + token=self.token.to_dict() if self.token else None, + prefix=self.prefix, + suffix=self.suffix, + batch_size=self.batch_size, + progress_bar=self.progress_bar, + normalize_embeddings=self.normalize_embeddings, + trust_remote_code=self.trust_remote_code, + truncate_dim=self.truncate_dim, + model_kwargs=self.model_kwargs, + tokenizer_kwargs=self.tokenizer_kwargs, + config_kwargs=self.config_kwargs, + precision=self.precision, + ) + if serialization_dict["init_parameters"].get("model_kwargs") is not None: + serialize_hf_model_kwargs(serialization_dict["init_parameters"]["model_kwargs"]) + return serialization_dict + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "SentenceTransformersTextEmbedder": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + init_params = data["init_parameters"] + if init_params.get("device") is not None: + init_params["device"] = ComponentDevice.from_dict(init_params["device"]) + deserialize_secrets_inplace(init_params, keys=["token"]) + if init_params.get("model_kwargs") is not None: + deserialize_hf_model_kwargs(init_params["model_kwargs"]) + return default_from_dict(cls, data) + + def warm_up(self): + """ + Initializes the component. + """ + if self.embedding_backend is None: + self.embedding_backend = _SentenceTransformersEmbeddingBackendFactory.get_embedding_backend( + model=self.model, + device=self.device.to_torch_str(), + auth_token=self.token, + trust_remote_code=self.trust_remote_code, + truncate_dim=self.truncate_dim, + model_kwargs=self.model_kwargs, + tokenizer_kwargs=self.tokenizer_kwargs, + config_kwargs=self.config_kwargs, + ) + if self.tokenizer_kwargs and self.tokenizer_kwargs.get("model_max_length"): + self.embedding_backend.model.max_seq_length = self.tokenizer_kwargs["model_max_length"] + + @component.output_types(embedding=List[float]) + def run(self, text: str): + """ + Embed a single string. + + :param text: + Text to embed. + + :returns: + A dictionary with the following keys: + - `embedding`: The embedding of the input text. + """ + if not isinstance(text, str): + raise TypeError( + "SentenceTransformersTextEmbedder expects a string as input." + "In case you want to embed a list of Documents, please use the SentenceTransformersDocumentEmbedder." + ) + if self.embedding_backend is None: + raise RuntimeError("The embedding model has not been loaded. Please call warm_up() before running.") + + text_to_embed = self.prefix + text + self.suffix + embedding = self.embedding_backend.embed( + [text_to_embed], + batch_size=self.batch_size, + show_progress_bar=self.progress_bar, + normalize_embeddings=self.normalize_embeddings, + precision=self.precision, + )[0] + return {"embedding": embedding} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d57da5c1f2bf129478ab8fd7e864de569de1943a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/__init__.py @@ -0,0 +1,25 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from .answer_exact_match import AnswerExactMatchEvaluator +from .context_relevance import ContextRelevanceEvaluator +from .document_map import DocumentMAPEvaluator +from .document_mrr import DocumentMRREvaluator +from .document_ndcg import DocumentNDCGEvaluator +from .document_recall import DocumentRecallEvaluator +from .faithfulness import FaithfulnessEvaluator +from .llm_evaluator import LLMEvaluator +from .sas_evaluator import SASEvaluator + +__all__ = [ + "AnswerExactMatchEvaluator", + "ContextRelevanceEvaluator", + "DocumentMAPEvaluator", + "DocumentMRREvaluator", + "DocumentNDCGEvaluator", + "DocumentRecallEvaluator", + "FaithfulnessEvaluator", + "LLMEvaluator", + "SASEvaluator", +] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/answer_exact_match.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/answer_exact_match.py new file mode 100644 index 0000000000000000000000000000000000000000..dd9026b2bdf85e3f357564bc050482a852830b9b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/answer_exact_match.py @@ -0,0 +1,69 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List + +from haystack.core.component import component + + +@component +class AnswerExactMatchEvaluator: + """ + An answer exact match evaluator class. + + The evaluator that checks if the predicted answers matches any of the ground truth answers exactly. + The result is a number from 0.0 to 1.0, it represents the proportion of predicted answers + that matched one of the ground truth answers. + There can be multiple ground truth answers and multiple predicted answers as input. + + + Usage example: + ```python + from haystack.components.evaluators import AnswerExactMatchEvaluator + + evaluator = AnswerExactMatchEvaluator() + result = evaluator.run( + ground_truth_answers=["Berlin", "Paris"], + predicted_answers=["Berlin", "Lyon"], + ) + + print(result["individual_scores"]) + # [1, 0] + print(result["score"]) + # 0.5 + ``` + """ + + @component.output_types(individual_scores=List[int], score=float) + def run(self, ground_truth_answers: List[str], predicted_answers: List[str]) -> Dict[str, Any]: + """ + Run the AnswerExactMatchEvaluator on the given inputs. + + The `ground_truth_answers` and `retrieved_answers` must have the same length. + + :param ground_truth_answers: + A list of expected answers. + :param predicted_answers: + A list of predicted answers. + :returns: + A dictionary with the following outputs: + - `individual_scores` - A list of 0s and 1s, where 1 means that the predicted answer matched one of the + ground truth. + - `score` - A number from 0.0 to 1.0 that represents the proportion of questions where any predicted + answer matched one of the ground truth answers. + """ + if not len(ground_truth_answers) == len(predicted_answers): + raise ValueError("The length of ground_truth_answers and predicted_answers must be the same.") + + matches = [] + for truth, extracted in zip(ground_truth_answers, predicted_answers): + if truth == extracted: + matches.append(1) + else: + matches.append(0) + + # The proportion of questions where any predicted answer matched one of the ground truth answers + average = sum(matches) / len(predicted_answers) + + return {"individual_scores": matches, "score": average} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/context_relevance.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/context_relevance.py new file mode 100644 index 0000000000000000000000000000000000000000..c60bd0bd53304052bf17d26efe93e0f33f4ecd84 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/context_relevance.py @@ -0,0 +1,222 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from statistics import mean +from typing import Any, Dict, List, Optional + +from haystack import component, default_from_dict, default_to_dict +from haystack.components.evaluators.llm_evaluator import LLMEvaluator +from haystack.utils import Secret, deserialize_secrets_inplace + +# Private global variable for default examples to include in the prompt if the user does not provide any examples +_DEFAULT_EXAMPLES = [ + { + "inputs": { + "questions": "What is the capital of Germany?", + "contexts": ["Berlin is the capital of Germany. Berlin and was founded in 1244."], + }, + "outputs": {"relevant_statements": ["Berlin is the capital of Germany."]}, + }, + { + "inputs": { + "questions": "What is the capital of France?", + "contexts": [ + "Berlin is the capital of Germany and was founded in 1244.", + "Europe is a continent with 44 countries.", + "Madrid is the capital of Spain.", + ], + }, + "outputs": {"relevant_statements": []}, + }, + { + "inputs": {"questions": "What is the capital of Italy?", "contexts": ["Rome is the capital of Italy."]}, + "outputs": {"relevant_statements": ["Rome is the capital of Italy."]}, + }, +] + + +@component +class ContextRelevanceEvaluator(LLMEvaluator): + """ + Evaluator that checks if a provided context is relevant to the question. + + An LLM breaks up a context into multiple statements and checks whether each statement + is relevant for answering a question. + The score for each context is either binary score of 1 or 0, where 1 indicates that the context is relevant + to the question and 0 indicates that the context is not relevant. + The evaluator also provides the relevant statements from the context and an average score over all the provided + input questions contexts pairs. + + Usage example: + ```python + from haystack.components.evaluators import ContextRelevanceEvaluator + + questions = ["Who created the Python language?", "Why does Java needs a JVM?", "Is C++ better than Python?"] + contexts = [ + [( + "Python, created by Guido van Rossum in the late 1980s, is a high-level general-purpose programming " + "language. Its design philosophy emphasizes code readability, and its language constructs aim to help " + "programmers write clear, logical code for both small and large-scale software projects." + )], + [( + "Java is a high-level, class-based, object-oriented programming language that is designed to have as few " + "implementation dependencies as possible. The JVM has two primary functions: to allow Java programs to run" + "on any device or operating system (known as the 'write once, run anywhere' principle), and to manage and" + "optimize program memory." + )], + [( + "C++ is a general-purpose programming language created by Bjarne Stroustrup as an extension of the C " + "programming language." + )], + ] + + evaluator = ContextRelevanceEvaluator() + result = evaluator.run(questions=questions, contexts=contexts) + print(result["score"]) + # 0.67 + print(result["individual_scores"]) + # [1,1,0] + print(result["results"]) + # [{ + # 'relevant_statements': ['Python, created by Guido van Rossum in the late 1980s.'], + # 'score': 1.0 + # }, + # { + # 'relevant_statements': ['The JVM has two primary functions: to allow Java programs to run on any device or + # operating system (known as the "write once, run anywhere" principle), and to manage and + # optimize program memory'], + # 'score': 1.0 + # }, + # { + # 'relevant_statements': [], + # 'score': 0.0 + # }] + ``` + """ + + def __init__( + self, + examples: Optional[List[Dict[str, Any]]] = None, + progress_bar: bool = True, + api: str = "openai", + api_key: Secret = Secret.from_env_var("OPENAI_API_KEY"), + api_params: Optional[Dict[str, Any]] = None, + raise_on_failure: bool = True, + ): + """ + Creates an instance of ContextRelevanceEvaluator. + + :param examples: + Optional few-shot examples conforming to the expected input and output format of ContextRelevanceEvaluator. + Default examples will be used if none are provided. + Each example must be a dictionary with keys "inputs" and "outputs". + "inputs" must be a dictionary with keys "questions" and "contexts". + "outputs" must be a dictionary with "relevant_statements". + Expected format: + [{ + "inputs": { + "questions": "What is the capital of Italy?", "contexts": ["Rome is the capital of Italy."], + }, + "outputs": { + "relevant_statements": ["Rome is the capital of Italy."], + }, + }] + :param progress_bar: + Whether to show a progress bar during the evaluation. + :param api: + The API to use for calling an LLM through a Generator. + Supported APIs: "openai". + :param api_key: + The API key. + :param api_params: + Parameters for an OpenAI API compatible completions call. + :param raise_on_failure: + Whether to raise an exception if the API call fails. + + """ + + self.instructions = ( + "Please extract only sentences from the provided context which are absolutely relevant and " + "required to answer the following question. If no relevant sentences are found, or if you " + "believe the question cannot be answered from the given context, return an empty list, example: []" + ) + self.inputs = [("questions", List[str]), ("contexts", List[List[str]])] + self.outputs = ["relevant_statements"] + self.examples = examples or _DEFAULT_EXAMPLES + self.api = api + self.api_key = api_key + self.api_params = api_params or {} + + super(ContextRelevanceEvaluator, self).__init__( + instructions=self.instructions, + inputs=self.inputs, + outputs=self.outputs, + examples=self.examples, + api=self.api, + api_key=self.api_key, + api_params=self.api_params, + raise_on_failure=raise_on_failure, + progress_bar=progress_bar, + ) + + @component.output_types(score=float, results=List[Dict[str, Any]]) + def run(self, **inputs) -> Dict[str, Any]: + """ + Run the LLM evaluator. + + :param questions: + A list of questions. + :param contexts: + A list of lists of contexts. Each list of contexts corresponds to one question. + :returns: + A dictionary with the following outputs: + - `score`: Mean context relevance score over all the provided input questions. + - `results`: A list of dictionaries with `relevant_statements` and `score` for each input context. + """ + result = super(ContextRelevanceEvaluator, self).run(**inputs) + + for idx, res in enumerate(result["results"]): + if res is None: + result["results"][idx] = {"relevant_statements": [], "score": float("nan")} + continue + if len(res["relevant_statements"]) > 0: + res["score"] = 1 + else: + res["score"] = 0 + + # calculate average context relevance score over all queries + result["score"] = mean([res["score"] for res in result["results"]]) + result["individual_scores"] = [res["score"] for res in result["results"]] # useful for the EvaluationRunResult + + return result + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + + :returns: + A dictionary with serialized data. + """ + return default_to_dict( + self, + api=self.api, + api_key=self.api_key.to_dict() if self.api_key else None, + examples=self.examples, + progress_bar=self.progress_bar, + api_params=self.api_params, + raise_on_failure=self.raise_on_failure, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "ContextRelevanceEvaluator": + """ + Deserialize this component from a dictionary. + + :param data: + The dictionary representation of this component. + :returns: + The deserialized component instance. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + return default_from_dict(cls, data) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/document_map.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/document_map.py new file mode 100644 index 0000000000000000000000000000000000000000..f4543671c0088be00e066314027175a0d557ea96 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/document_map.py @@ -0,0 +1,90 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List + +from haystack import Document, component + + +@component +class DocumentMAPEvaluator: + """ + A Mean Average Precision (MAP) evaluator for documents. + + Evaluator that calculates the mean average precision of the retrieved documents, a metric + that measures how high retrieved documents are ranked. + Each question can have multiple ground truth documents and multiple retrieved documents. + + `DocumentMAPEvaluator` doesn't normalize its inputs, the `DocumentCleaner` component + should be used to clean and normalize the documents before passing them to this evaluator. + + Usage example: + ```python + from haystack import Document + from haystack.components.evaluators import DocumentMAPEvaluator + + evaluator = DocumentMAPEvaluator() + result = evaluator.run( + ground_truth_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="9th")], + ], + retrieved_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="10th century"), Document(content="9th")], + ], + ) + + print(result["individual_scores"]) + # [1.0, 0.8333333333333333] + print(result["score"]) + # 0.9166666666666666 + ``` + """ + + # Refer to https://www.pinecone.io/learn/offline-evaluation/ for the algorithm. + @component.output_types(score=float, individual_scores=List[float]) + def run( + self, ground_truth_documents: List[List[Document]], retrieved_documents: List[List[Document]] + ) -> Dict[str, Any]: + """ + Run the DocumentMAPEvaluator on the given inputs. + + All lists must have the same length. + + :param ground_truth_documents: + A list of expected documents for each question. + :param retrieved_documents: + A list of retrieved documents for each question. + :returns: + A dictionary with the following outputs: + - `score` - The average of calculated scores. + - `individual_scores` - A list of numbers from 0.0 to 1.0 that represents how high retrieved documents + are ranked. + """ + if len(ground_truth_documents) != len(retrieved_documents): + msg = "The length of ground_truth_documents and retrieved_documents must be the same." + raise ValueError(msg) + + individual_scores = [] + + for ground_truth, retrieved in zip(ground_truth_documents, retrieved_documents): + average_precision = 0.0 + average_precision_numerator = 0.0 + relevant_documents = 0 + + ground_truth_contents = [doc.content for doc in ground_truth if doc.content is not None] + for rank, retrieved_document in enumerate(retrieved): + if retrieved_document.content is None: + continue + + if retrieved_document.content in ground_truth_contents: + relevant_documents += 1 + average_precision_numerator += relevant_documents / (rank + 1) + if relevant_documents > 0: + average_precision = average_precision_numerator / relevant_documents + individual_scores.append(average_precision) + + score = sum(individual_scores) / len(ground_truth_documents) + return {"score": score, "individual_scores": individual_scores} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/document_mrr.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/document_mrr.py new file mode 100644 index 0000000000000000000000000000000000000000..fbbaa1265680f6d9d34b0ea966f92e0581d117ea --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/document_mrr.py @@ -0,0 +1,84 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List + +from haystack import Document, component + + +@component +class DocumentMRREvaluator: + """ + Evaluator that calculates the mean reciprocal rank of the retrieved documents. + + MRR measures how high the first retrieved document is ranked. + Each question can have multiple ground truth documents and multiple retrieved documents. + + `DocumentMRREvaluator` doesn't normalize its inputs, the `DocumentCleaner` component + should be used to clean and normalize the documents before passing them to this evaluator. + + Usage example: + ```python + from haystack import Document + from haystack.components.evaluators import DocumentMRREvaluator + + evaluator = DocumentMRREvaluator() + result = evaluator.run( + ground_truth_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="9th")], + ], + retrieved_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="10th century"), Document(content="9th")], + ], + ) + print(result["individual_scores"]) + # [1.0, 1.0] + print(result["score"]) + # 1.0 + ``` + """ + + # Refer to https://www.pinecone.io/learn/offline-evaluation/ for the algorithm. + @component.output_types(score=float, individual_scores=List[float]) + def run( + self, ground_truth_documents: List[List[Document]], retrieved_documents: List[List[Document]] + ) -> Dict[str, Any]: + """ + Run the DocumentMRREvaluator on the given inputs. + + `ground_truth_documents` and `retrieved_documents` must have the same length. + + :param ground_truth_documents: + A list of expected documents for each question. + :param retrieved_documents: + A list of retrieved documents for each question. + :returns: + A dictionary with the following outputs: + - `score` - The average of calculated scores. + - `individual_scores` - A list of numbers from 0.0 to 1.0 that represents how high the first retrieved + document is ranked. + """ + if len(ground_truth_documents) != len(retrieved_documents): + msg = "The length of ground_truth_documents and retrieved_documents must be the same." + raise ValueError(msg) + + individual_scores = [] + + for ground_truth, retrieved in zip(ground_truth_documents, retrieved_documents): + reciprocal_rank = 0.0 + + ground_truth_contents = [doc.content for doc in ground_truth if doc.content is not None] + for rank, retrieved_document in enumerate(retrieved): + if retrieved_document.content is None: + continue + if retrieved_document.content in ground_truth_contents: + reciprocal_rank = 1 / (rank + 1) + break + individual_scores.append(reciprocal_rank) + + score = sum(individual_scores) / len(ground_truth_documents) + + return {"score": score, "individual_scores": individual_scores} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/document_ndcg.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/document_ndcg.py new file mode 100644 index 0000000000000000000000000000000000000000..e3430f1db7cc35f3600228ac9a8d9e06f92ce7df --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/document_ndcg.py @@ -0,0 +1,133 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from math import log2 +from typing import Any, Dict, List + +from haystack import Document, component + + +@component +class DocumentNDCGEvaluator: + """ + Evaluator that calculates the normalized discounted cumulative gain (NDCG) of retrieved documents. + + Each question can have multiple ground truth documents and multiple retrieved documents. + If the ground truth documents have relevance scores, the NDCG calculation uses these scores. + Otherwise, it assumes binary relevance of all ground truth documents. + + Usage example: + ```python + from haystack import Document + from haystack.components.evaluators import DocumentNDCGEvaluator + + evaluator = DocumentNDCGEvaluator() + result = evaluator.run( + ground_truth_documents=[[Document(content="France", score=1.0), Document(content="Paris", score=0.5)]], + retrieved_documents=[[Document(content="France"), Document(content="Germany"), Document(content="Paris")]], + ) + print(result["individual_scores"]) + # [0.8869] + print(result["score"]) + # 0.8869 + ``` + """ + + @component.output_types(score=float, individual_scores=List[float]) + def run( + self, ground_truth_documents: List[List[Document]], retrieved_documents: List[List[Document]] + ) -> Dict[str, Any]: + """ + Run the DocumentNDCGEvaluator on the given inputs. + + `ground_truth_documents` and `retrieved_documents` must have the same length. + The list items within `ground_truth_documents` and `retrieved_documents` can differ in length. + + :param ground_truth_documents: + Lists of expected documents, one list per question. Binary relevance is used if documents have no scores. + :param retrieved_documents: + Lists of retrieved documents, one list per question. + :returns: + A dictionary with the following outputs: + - `score` - The average of calculated scores. + - `individual_scores` - A list of numbers from 0.0 to 1.0 that represents the NDCG for each question. + """ + self.validate_inputs(ground_truth_documents, retrieved_documents) + + individual_scores = [] + + for gt_docs, ret_docs in zip(ground_truth_documents, retrieved_documents): + dcg = self.calculate_dcg(gt_docs, ret_docs) + idcg = self.calculate_idcg(gt_docs) + ndcg = dcg / idcg if idcg > 0 else 0 + individual_scores.append(ndcg) + + score = sum(individual_scores) / len(ground_truth_documents) + + return {"score": score, "individual_scores": individual_scores} + + @staticmethod + def validate_inputs(gt_docs: List[List[Document]], ret_docs: List[List[Document]]): + """ + Validate the input parameters. + + :param gt_docs: + The ground_truth_documents to validate. + :param ret_docs: + The retrieved_documents to validate. + + :raises ValueError: + If the ground_truth_documents or the retrieved_documents are an empty a list. + If the length of ground_truth_documents and retrieved_documents differs. + If any list of documents in ground_truth_documents contains a mix of documents with and without a score. + """ + if len(gt_docs) == 0 or len(ret_docs) == 0: + msg = "ground_truth_documents and retrieved_documents must be provided." + raise ValueError(msg) + + if len(gt_docs) != len(ret_docs): + msg = "The length of ground_truth_documents and retrieved_documents must be the same." + raise ValueError(msg) + + for docs in gt_docs: + if any(doc.score is not None for doc in docs) and any(doc.score is None for doc in docs): + msg = "Either none or all documents in each list of ground_truth_documents must have a score." + raise ValueError(msg) + + @staticmethod + def calculate_dcg(gt_docs: List[Document], ret_docs: List[Document]) -> float: + """ + Calculate the discounted cumulative gain (DCG) of the retrieved documents. + + :param gt_docs: + The ground truth documents. + :param ret_docs: + The retrieved documents. + :returns: + The discounted cumulative gain (DCG) of the retrieved + documents based on the ground truth documents. + """ + dcg = 0.0 + relevant_id_to_score = {doc.id: doc.score if doc.score is not None else 1 for doc in gt_docs} + for i, doc in enumerate(ret_docs): + if doc.id in relevant_id_to_score: # TODO Related to https://github.com/deepset-ai/haystack/issues/8412 + dcg += relevant_id_to_score[doc.id] / log2(i + 2) # i + 2 because i is 0-indexed + return dcg + + @staticmethod + def calculate_idcg(gt_docs: List[Document]) -> float: + """ + Calculate the ideal discounted cumulative gain (IDCG) of the ground truth documents. + + :param gt_docs: + The ground truth documents. + :returns: + The ideal discounted cumulative gain (IDCG) of the ground truth documents. + """ + idcg = 0.0 + for i, doc in enumerate(sorted(gt_docs, key=lambda x: x.score if x.score is not None else 1, reverse=True)): + # If the document has a score, use it; otherwise, use 1 for binary relevance. + relevance = doc.score if doc.score is not None else 1 + idcg += relevance / log2(i + 2) # i + 2 because i is 0-indexed + return idcg diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/document_recall.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/document_recall.py new file mode 100644 index 0000000000000000000000000000000000000000..bf0f1be3c90b079a4d9bf781788f78533cbefa96 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/document_recall.py @@ -0,0 +1,133 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from enum import Enum +from typing import Any, Dict, List, Union + +from haystack import component, default_to_dict +from haystack.dataclasses import Document + + +class RecallMode(Enum): + """ + Enum for the mode to use for calculating the recall score. + """ + + # Score is based on whether any document is retrieved. + SINGLE_HIT = "single_hit" + # Score is based on how many documents were retrieved. + MULTI_HIT = "multi_hit" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "RecallMode": + """ + Convert a string to a RecallMode enum. + """ + enum_map = {e.value: e for e in RecallMode} + mode = enum_map.get(string) + if mode is None: + msg = f"Unknown recall mode '{string}'. Supported modes are: {list(enum_map.keys())}" + raise ValueError(msg) + return mode + + +@component +class DocumentRecallEvaluator: + """ + Evaluator that calculates the Recall score for a list of documents. + + Returns both a list of scores for each question and the average. + There can be multiple ground truth documents and multiple predicted documents as input. + + Usage example: + ```python + from haystack import Document + from haystack.components.evaluators import DocumentRecallEvaluator + + evaluator = DocumentRecallEvaluator() + result = evaluator.run( + ground_truth_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="9th")], + ], + retrieved_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="10th century"), Document(content="9th")], + ], + ) + print(result["individual_scores"]) + # [1.0, 1.0] + print(result["score"]) + # 1.0 + ``` + """ + + def __init__(self, mode: Union[str, RecallMode] = RecallMode.SINGLE_HIT): + """ + Create a DocumentRecallEvaluator component. + + :param mode: + Mode to use for calculating the recall score. + """ + if isinstance(mode, str): + mode = RecallMode.from_str(mode) + + mode_functions = {RecallMode.SINGLE_HIT: self._recall_single_hit, RecallMode.MULTI_HIT: self._recall_multi_hit} + self.mode_function = mode_functions[mode] + self.mode = mode + + def _recall_single_hit(self, ground_truth_documents: List[Document], retrieved_documents: List[Document]) -> float: + unique_truths = {g.content for g in ground_truth_documents} + unique_retrievals = {p.content for p in retrieved_documents} + retrieved_ground_truths = unique_truths.intersection(unique_retrievals) + + return float(len(retrieved_ground_truths) > 0) + + def _recall_multi_hit(self, ground_truth_documents: List[Document], retrieved_documents: List[Document]) -> float: + unique_truths = {g.content for g in ground_truth_documents} + unique_retrievals = {p.content for p in retrieved_documents} + retrieved_ground_truths = unique_truths.intersection(unique_retrievals) + + return len(retrieved_ground_truths) / len(ground_truth_documents) + + @component.output_types(score=float, individual_scores=List[float]) + def run( + self, ground_truth_documents: List[List[Document]], retrieved_documents: List[List[Document]] + ) -> Dict[str, Any]: + """ + Run the DocumentRecallEvaluator on the given inputs. + + `ground_truth_documents` and `retrieved_documents` must have the same length. + + :param ground_truth_documents: + A list of expected documents for each question. + :param retrieved_documents: + A list of retrieved documents for each question. + A dictionary with the following outputs: + - `score` - The average of calculated scores. + - `invididual_scores` - A list of numbers from 0.0 to 1.0 that represents the proportion of matching + documents retrieved. If the mode is `single_hit`, the individual scores are 0 or 1. + """ + if len(ground_truth_documents) != len(retrieved_documents): + msg = "The length of ground_truth_documents and retrieved_documents must be the same." + raise ValueError(msg) + + scores = [] + for ground_truth, retrieved in zip(ground_truth_documents, retrieved_documents): + score = self.mode_function(ground_truth, retrieved) + scores.append(score) + + return {"score": sum(scores) / len(retrieved_documents), "individual_scores": scores} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict(self, mode=str(self.mode)) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/faithfulness.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/faithfulness.py new file mode 100644 index 0000000000000000000000000000000000000000..8daf9dc0e0dc71031ada2ef1d113d6919137c3aa --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/faithfulness.py @@ -0,0 +1,216 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional + +from numpy import mean as np_mean + +from haystack import component, default_from_dict, default_to_dict +from haystack.components.evaluators.llm_evaluator import LLMEvaluator +from haystack.utils import Secret, deserialize_secrets_inplace + +# Default examples to include in the prompt if the user does not provide any examples +_DEFAULT_EXAMPLES = [ + { + "inputs": { + "questions": "What is the capital of Germany and when was it founded?", + "contexts": ["Berlin is the capital of Germany and was founded in 1244."], + "predicted_answers": "The capital of Germany, Berlin, was founded in the 13th century.", + }, + "outputs": { + "statements": ["Berlin is the capital of Germany.", "Berlin was founded in 1244."], + "statement_scores": [1, 1], + }, + }, + { + "inputs": { + "questions": "What is the capital of France?", + "contexts": ["Berlin is the capital of Germany."], + "predicted_answers": "Paris", + }, + "outputs": {"statements": ["Paris is the capital of France."], "statement_scores": [0]}, + }, + { + "inputs": { + "questions": "What is the capital of Italy?", + "contexts": ["Rome is the capital of Italy."], + "predicted_answers": "Rome is the capital of Italy with more than 4 million inhabitants.", + }, + "outputs": { + "statements": ["Rome is the capital of Italy.", "Rome has more than 4 million inhabitants."], + "statement_scores": [1, 0], + }, + }, +] + + +@component +class FaithfulnessEvaluator(LLMEvaluator): + """ + Evaluator that checks if a generated answer can be inferred from the provided contexts. + + An LLM separates the answer into multiple statements and checks whether the statement can be inferred from the + context or not. The final score for the full answer is a number from 0.0 to 1.0. It represents the proportion of + statements that can be inferred from the provided contexts. + + Usage example: + ```python + from haystack.components.evaluators import FaithfulnessEvaluator + + questions = ["Who created the Python language?"] + contexts = [ + [( + "Python, created by Guido van Rossum in the late 1980s, is a high-level general-purpose programming " + "language. Its design philosophy emphasizes code readability, and its language constructs aim to help " + "programmers write clear, logical code for both small and large-scale software projects." + )], + ] + predicted_answers = [ + "Python is a high-level general-purpose programming language that was created by George Lucas." + ] + evaluator = FaithfulnessEvaluator() + result = evaluator.run(questions=questions, contexts=contexts, predicted_answers=predicted_answers) + + print(result["individual_scores"]) + # [0.5] + print(result["score"]) + # 0.5 + print(result["results"]) + # [{'statements': ['Python is a high-level general-purpose programming language.', + 'Python was created by George Lucas.'], 'statement_scores': [1, 0], 'score': 0.5}] + ``` + """ + + def __init__( + self, + examples: Optional[List[Dict[str, Any]]] = None, + progress_bar: bool = True, + api: str = "openai", + api_key: Secret = Secret.from_env_var("OPENAI_API_KEY"), + api_params: Optional[Dict[str, Any]] = None, + raise_on_failure: bool = True, + ): + """ + Creates an instance of FaithfulnessEvaluator. + + :param examples: + Optional few-shot examples conforming to the expected input and output format of FaithfulnessEvaluator. + Default examples will be used if none are provided. + Each example must be a dictionary with keys "inputs" and "outputs". + "inputs" must be a dictionary with keys "questions", "contexts", and "predicted_answers". + "outputs" must be a dictionary with "statements" and "statement_scores". + Expected format: + [{ + "inputs": { + "questions": "What is the capital of Italy?", "contexts": ["Rome is the capital of Italy."], + "predicted_answers": "Rome is the capital of Italy with more than 4 million inhabitants.", + }, + "outputs": { + "statements": ["Rome is the capital of Italy.", "Rome has more than 4 million inhabitants."], + "statement_scores": [1, 0], + }, + }] + :param progress_bar: + Whether to show a progress bar during the evaluation. + :param api: + The API to use for calling an LLM through a Generator. + Supported APIs: "openai". + :param api_key: + The API key. + :param api_params: + Parameters for an OpenAI API compatible completions call. + :param raise_on_failure: + Whether to raise an exception if the API call fails. + + """ + self.instructions = ( + "Your task is to judge the faithfulness or groundedness of statements based " + "on context information. First, please extract statements from a provided " + "predicted answer to a question. Second, calculate a faithfulness score for each " + "statement made in the predicted answer. The score is 1 if the statement can be " + "inferred from the provided context or 0 if it cannot be inferred." + ) + self.inputs = [("questions", List[str]), ("contexts", List[List[str]]), ("predicted_answers", List[str])] + self.outputs = ["statements", "statement_scores"] + self.examples = examples or _DEFAULT_EXAMPLES + self.api = api + self.api_key = api_key + self.api_params = api_params or {} + + super(FaithfulnessEvaluator, self).__init__( + instructions=self.instructions, + inputs=self.inputs, + outputs=self.outputs, + examples=self.examples, + api=self.api, + api_key=self.api_key, + api_params=self.api_params, + raise_on_failure=raise_on_failure, + progress_bar=progress_bar, + ) + + @component.output_types(individual_scores=List[int], score=float, results=List[Dict[str, Any]]) + def run(self, **inputs) -> Dict[str, Any]: + """ + Run the LLM evaluator. + + :param questions: + A list of questions. + :param contexts: + A nested list of contexts that correspond to the questions. + :param predicted_answers: + A list of predicted answers. + :returns: + A dictionary with the following outputs: + - `score`: Mean faithfulness score over all the provided input answers. + - `individual_scores`: A list of faithfulness scores for each input answer. + - `results`: A list of dictionaries with `statements` and `statement_scores` for each input answer. + """ + result = super(FaithfulnessEvaluator, self).run(**inputs) + + # calculate average statement faithfulness score per query + for idx, res in enumerate(result["results"]): + if res is None: + result["results"][idx] = {"statements": [], "statement_scores": [], "score": float("nan")} + continue + if not res["statements"]: + res["score"] = 0 + else: + res["score"] = np_mean(res["statement_scores"]) + + # calculate average answer faithfulness score over all queries + result["score"] = np_mean([res["score"] for res in result["results"]]) + result["individual_scores"] = [res["score"] for res in result["results"]] + + return result + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + + :returns: + A dictionary with serialized data. + """ + return default_to_dict( + self, + api=self.api, + api_key=self.api_key.to_dict() if self.api_key else None, + api_params=self.api_params, + examples=self.examples, + progress_bar=self.progress_bar, + raise_on_failure=self.raise_on_failure, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "FaithfulnessEvaluator": + """ + Deserialize this component from a dictionary. + + :param data: + The dictionary representation of this component. + :returns: + The deserialized component instance. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + return default_from_dict(cls, data) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/llm_evaluator.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/llm_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..39a80b93a5c21617774bdc49fee2fac9c8227fb2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/llm_evaluator.py @@ -0,0 +1,387 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +from typing import Any, Dict, List, Optional, Tuple, Type +from warnings import warn + +from tqdm import tqdm + +from haystack import component, default_from_dict, default_to_dict +from haystack.components.builders import PromptBuilder +from haystack.components.generators import OpenAIGenerator +from haystack.utils import Secret, deserialize_secrets_inplace, deserialize_type, serialize_type + + +@component +class LLMEvaluator: + """ + Uses an LLM to evaluate inputs based on a prompt containing instructions and examples. + + The default API requires an OpenAI API key to be provided as an environment variable "OPENAI_API_KEY". + The inputs are lists that are user-defined depending on the desired metric. + The output is a dictionary with a key `results` containing a list of evaluation results. + Each result is a dictionary with user-defined keys and values of either 0 for FALSE or 1 for TRUE respectively. + + Usage example: + ```python + from typing import List + from haystack.components.evaluators import LLMEvaluator + evaluator = LLMEvaluator( + instructions="Is this answer problematic for children?", + inputs=[("predicted_answers", List[str])], + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Damn, this is straight outta hell!!!"}, "outputs": {"score": 1}}, + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}}, + ], + ) + predicted_answers = [ + "Football is the most popular sport with around 4 billion followers worldwide", + "Python language was created by Guido van Rossum.", + ] + results = evaluator.run(predicted_answers=predicted_answers) + print(results) + # {'results': [{'score': 0}, {'score': 0}]} + ``` + """ + + def __init__( + self, + instructions: str, + inputs: List[Tuple[str, Type[List]]], + outputs: List[str], + examples: List[Dict[str, Any]], + progress_bar: bool = True, + *, + raise_on_failure: bool = True, + api: str = "openai", + api_key: Optional[Secret] = None, + api_params: Optional[Dict[str, Any]] = None, + ): + """ + Creates an instance of LLMEvaluator. + + :param instructions: + The prompt instructions to use for evaluation. + Should be a question about the inputs that can be answered with yes or no. + :param inputs: + The inputs that the component expects as incoming connections and that it evaluates. + Each input is a tuple of an input name and input type. Input types must be lists. + :param outputs: + Output names of the evaluation results. They correspond to keys in the output dictionary. + :param examples: + Few-shot examples conforming to the expected input and output format as defined in the `inputs` and + `outputs` parameters. + Each example is a dictionary with keys "inputs" and "outputs" + They contain the input and output as dictionaries respectively. + :param raise_on_failure: + If True, the component will raise an exception on an unsuccessful API call. + :param progress_bar: + Whether to show a progress bar during the evaluation. + :param api: + The API to use for calling an LLM through a Generator. + Supported APIs: "openai". + :param api_key: + The API key to be passed to a LLM provider. It may not be necessary when using a locally hosted model. + :param api_params: + Parameters for an OpenAI API compatible completions call. + + """ + self.validate_init_parameters(inputs, outputs, examples) + self.raise_on_failure = raise_on_failure + self.instructions = instructions + self.inputs = inputs + self.outputs = outputs + self.examples = examples + self.api = api + self.api_key = api_key + self.api_params = api_params or {} + self.progress_bar = progress_bar + + default_generation_kwargs = {"response_format": {"type": "json_object"}, "seed": 42} + user_generation_kwargs = self.api_params.get("generation_kwargs", {}) + merged_generation_kwargs = {**default_generation_kwargs, **user_generation_kwargs} + self.api_params["generation_kwargs"] = merged_generation_kwargs + + if api == "openai": + generator_kwargs = {**self.api_params} + if api_key: + generator_kwargs["api_key"] = api_key + self.generator = OpenAIGenerator(**generator_kwargs) + else: + raise ValueError(f"Unsupported API: {api}") + + template = self.prepare_template() + self.builder = PromptBuilder(template=template) + + component.set_input_types(self, **dict(inputs)) + + @staticmethod + def validate_init_parameters( + inputs: List[Tuple[str, Type[List]]], outputs: List[str], examples: List[Dict[str, Any]] + ): + """ + Validate the init parameters. + + :param inputs: + The inputs to validate. + :param outputs: + The outputs to validate. + :param examples: + The examples to validate. + + :raises ValueError: + If the inputs are not a list of tuples with a string and a type of list. + If the outputs are not a list of strings. + If the examples are not a list of dictionaries. + If any example does not have keys "inputs" and "outputs" with values that are dictionaries with string keys. + """ + # Validate inputs + if ( + not isinstance(inputs, list) + or not all(isinstance(_input, tuple) for _input in inputs) + or not all(isinstance(_input[0], str) and _input[1] is not list and len(_input) == 2 for _input in inputs) + ): + msg = ( + f"LLM evaluator expects inputs to be a list of tuples. Each tuple must contain an input name and " + f"type of list but received {inputs}." + ) + raise ValueError(msg) + + # Validate outputs + if not isinstance(outputs, list) or not all(isinstance(output, str) for output in outputs): + msg = f"LLM evaluator expects outputs to be a list of str but received {outputs}." + raise ValueError(msg) + + # Validate examples are lists of dicts + if not isinstance(examples, list) or not all(isinstance(example, dict) for example in examples): + msg = f"LLM evaluator expects examples to be a list of dictionaries but received {examples}." + raise ValueError(msg) + + # Validate each example + for example in examples: + if ( + {"inputs", "outputs"} != example.keys() + or not all(isinstance(example[param], dict) for param in ["inputs", "outputs"]) + or not all(isinstance(key, str) for param in ["inputs", "outputs"] for key in example[param]) + ): + msg = ( + f"LLM evaluator expects each example to have keys `inputs` and `outputs` with values that are " + f"dictionaries with str keys but received {example}." + ) + raise ValueError(msg) + + @component.output_types(results=List[Dict[str, Any]]) + def run(self, **inputs) -> Dict[str, Any]: + """ + Run the LLM evaluator. + + :param inputs: + The input values to evaluate. The keys are the input names and the values are lists of input values. + :returns: + A dictionary with a `results` entry that contains a list of results. + Each result is a dictionary containing the keys as defined in the `outputs` parameter of the LLMEvaluator + and the evaluation results as the values. If an exception occurs for a particular input value, the result + will be `None` for that entry. + If the API is "openai" and the response contains a "meta" key, the metadata from OpenAI will be included + in the output dictionary, under the key "meta". + :raises ValueError: + Only in the case that `raise_on_failure` is set to True and the received inputs are not lists or have + different lengths, or if the output is not a valid JSON or doesn't contain the expected keys. + """ + self.validate_input_parameters(dict(self.inputs), inputs) + + # inputs is a dictionary with keys being input names and values being a list of input values + # We need to iterate through the lists in parallel for all keys of the dictionary + input_names, values = inputs.keys(), list(zip(*inputs.values())) + list_of_input_names_to_values = [dict(zip(input_names, v)) for v in values] + + results: List[Optional[Dict[str, Any]]] = [] + metadata = None + errors = 0 + for input_names_to_values in tqdm(list_of_input_names_to_values, disable=not self.progress_bar): + prompt = self.builder.run(**input_names_to_values) + try: + result = self.generator.run(prompt=prompt["prompt"]) + except Exception as e: + msg = f"Error while generating response for prompt: {prompt}. Error: {e}" + if self.raise_on_failure: + raise ValueError(msg) + warn(msg) + results.append(None) + errors += 1 + continue + + if self.is_valid_json_and_has_expected_keys(expected=self.outputs, received=result["replies"][0]): + parsed_result = json.loads(result["replies"][0]) + results.append(parsed_result) + else: + results.append(None) + errors += 1 + + if self.api == "openai" and "meta" in result: + metadata = result["meta"] + + if errors > 0: + msg = f"LLM evaluator failed for {errors} out of {len(list_of_input_names_to_values)} inputs." + warn(msg) + + return {"results": results, "meta": metadata} + + def prepare_template(self) -> str: + """ + Prepare the prompt template. + + Combine instructions, inputs, outputs, and examples into one prompt template with the following format: + Instructions: + + + Generate the response in JSON format with the following keys: + + Consider the instructions and the examples below to determine those values. + + Examples: + + + Inputs: + + Outputs: + + :returns: + The prompt template. + """ + inputs_section = ( + "{" + ", ".join([f'"{input_socket[0]}": {{{{ {input_socket[0]} }}}}' for input_socket in self.inputs]) + "}" + ) + + examples_section = "\n".join( + [ + "Inputs:\n" + json.dumps(example["inputs"]) + "\nOutputs:\n" + json.dumps(example["outputs"]) + for example in self.examples + ] + ) + return ( + f"Instructions:\n" + f"{self.instructions}\n\n" + f"Generate the response in JSON format with the following keys:\n" + f"{json.dumps(self.outputs)}\n" + f"Consider the instructions and the examples below to determine those values.\n\n" + f"Examples:\n" + f"{examples_section}\n\n" + f"Inputs:\n" + f"{inputs_section}\n" + f"Outputs:\n" + ) + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + + :returns: + The serialized component as a dictionary. + """ + # Since we cannot currently serialize tuples, convert the inputs to a list. + inputs = [[name, serialize_type(type_)] for name, type_ in self.inputs] + return default_to_dict( + self, + instructions=self.instructions, + inputs=inputs, + outputs=self.outputs, + examples=self.examples, + api=self.api, + api_key=self.api_key and self.api_key.to_dict(), + api_params=self.api_params, + progress_bar=self.progress_bar, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "LLMEvaluator": + """ + Deserialize this component from a dictionary. + + :param data: + The dictionary representation of this component. + :returns: + The deserialized component instance. + """ + data["init_parameters"]["inputs"] = [ + (name, deserialize_type(type_)) for name, type_ in data["init_parameters"]["inputs"] + ] + + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + return default_from_dict(cls, data) + + @staticmethod + def validate_input_parameters(expected: Dict[str, Any], received: Dict[str, Any]) -> None: + """ + Validate the input parameters. + + :param expected: + The expected input parameters. + :param received: + The received input parameters. + + :raises ValueError: + If not all expected inputs are present in the received inputs + If the received inputs are not lists or have different lengths + """ + # Validate that all expected inputs are present in the received inputs + for param in expected.keys(): + if param not in received: + msg = f"LLM evaluator expected input parameter '{param}' but received only {received.keys()}." + raise ValueError(msg) + + # Validate that all received inputs are lists + if not all(isinstance(_input, list) for _input in received.values()): + msg = ( + "LLM evaluator expects all input values to be lists but received " + f"{[type(_input) for _input in received.values()]}." + ) + raise ValueError(msg) + + # Validate that all received inputs are of the same length + inputs = received.values() + length = len(next(iter(inputs))) + if not all(len(_input) == length for _input in inputs): + msg = ( + f"LLM evaluator expects all input lists to have the same length but received {inputs} with lengths " + f"{[len(_input) for _input in inputs]}." + ) + raise ValueError(msg) + + def is_valid_json_and_has_expected_keys(self, expected: List[str], received: str) -> bool: + """ + Output must be a valid JSON with the expected keys. + + :param expected: + Names of expected outputs + :param received: + Names of received outputs + + :raises ValueError: + If the output is not a valid JSON with the expected keys: + - with `raise_on_failure` set to True a ValueError is raised. + - with `raise_on_failure` set to False a warning is issued and False is returned. + + :returns: + True if the received output is a valid JSON with the expected keys, False otherwise. + """ + try: + parsed_output = json.loads(received) + except json.JSONDecodeError: + msg = "Response from LLM evaluator is not a valid JSON." + if self.raise_on_failure: + raise ValueError(msg) + warn(msg) + return False + + if not all(output in parsed_output for output in expected): + msg = f"Expected response from LLM evaluator to be JSON with keys {expected}, got {received}." + if self.raise_on_failure: + raise ValueError(msg) + warn(msg) + return False + + return True diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/sas_evaluator.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/sas_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..b9645a1ab9a95c15cea2df19ee855adf8a95b55c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/evaluators/sas_evaluator.py @@ -0,0 +1,201 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional + +from numpy import mean as np_mean + +from haystack import component, default_from_dict, default_to_dict +from haystack.lazy_imports import LazyImport +from haystack.utils import ComponentDevice, expit +from haystack.utils.auth import Secret, deserialize_secrets_inplace + +with LazyImport(message="Run 'pip install \"sentence-transformers>=3.0.0\"'") as sas_import: + from sentence_transformers import CrossEncoder, SentenceTransformer, util + from transformers import AutoConfig + + +@component +class SASEvaluator: + """ + SASEvaluator computes the Semantic Answer Similarity (SAS) between a list of predictions and a one of ground truths. + + It's usually used in Retrieval Augmented Generation (RAG) pipelines to evaluate the quality of the generated + answers. The SAS is computed using a pre-trained model from the Hugging Face model hub. The model can be either a + Bi-Encoder or a Cross-Encoder. The choice of the model is based on the `model` parameter. + + Usage example: + ```python + from haystack.components.evaluators.sas_evaluator import SASEvaluator + + evaluator = SASEvaluator(model="cross-encoder/ms-marco-MiniLM-L-6-v2") + evaluator.warm_up() + ground_truths = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + predictions = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + result = evaluator.run( + ground_truths_answers=ground_truths, predicted_answers=predictions + ) + + print(result["score"]) + # 0.9999673763910929 + + print(result["individual_scores"]) + # [0.9999765157699585, 0.999968409538269, 0.9999572038650513] + ``` + """ + + def __init__( + self, + model: str = "sentence-transformers/paraphrase-multilingual-mpnet-base-v2", + batch_size: int = 32, + device: Optional[ComponentDevice] = None, + token: Secret = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + ): + """ + Creates a new instance of SASEvaluator. + + :param model: + SentenceTransformers semantic textual similarity model, should be path or string pointing to a downloadable + model. + :param batch_size: + Number of prediction-label pairs to encode at once. + :param device: + The device on which the model is loaded. If `None`, the default device is automatically selected. + :param token: + The Hugging Face token for HTTP bearer authorization. + You can find your HF token in your [account settings](https://huggingface.co/settings/tokens) + """ + sas_import.check() + + self._model = model + self._batch_size = batch_size + self._device = device + self._token = token + self._similarity_model = None + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + + :returns: + The serialized component as a dictionary. + """ + return default_to_dict( + self, + model=self._model, + batch_size=self._batch_size, + device=self._device.to_dict() if self._device else None, + token=self._token.to_dict() if self._token else None, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "SASEvaluator": + """ + Deserialize this component from a dictionary. + + :param data: + The dictionary representation of this component. + :returns: + The deserialized component instance. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["token"]) + if device := data.get("init_parameters", {}).get("device"): + data["init_parameters"]["device"] = ComponentDevice.from_dict(device) + return default_from_dict(cls, data) + + def warm_up(self): + """ + Initializes the component. + """ + if self._similarity_model: + return + + token = self._token.resolve_value() if self._token else None + config = AutoConfig.from_pretrained(self._model, use_auth_token=token) + cross_encoder_used = False + if config.architectures: + cross_encoder_used = any(arch.endswith("ForSequenceClassification") for arch in config.architectures) + device = ComponentDevice.resolve_device(self._device).to_torch_str() + # Based on the Model string we can load either Bi-Encoders or Cross Encoders. + # Similarity computation changes for both approaches + if cross_encoder_used: + self._similarity_model = CrossEncoder( + self._model, + device=device, + tokenizer_args={"use_auth_token": token}, + automodel_args={"use_auth_token": token}, + ) + else: + self._similarity_model = SentenceTransformer(self._model, device=device, use_auth_token=token) + + @component.output_types(score=float, individual_scores=List[float]) + def run(self, ground_truth_answers: List[str], predicted_answers: List[str]) -> Dict[str, Any]: + """ + SASEvaluator component run method. + + Run the SASEvaluator to compute the Semantic Answer Similarity (SAS) between a list of predicted answers + and a list of ground truth answers. Both must be list of strings of same length. + + :param ground_truth_answers: + A list of expected answers for each question. + :param predicted_answers: + A list of generated answers for each question. + :returns: + A dictionary with the following outputs: + - `score`: Mean SAS score over all the predictions/ground-truth pairs. + - `individual_scores`: A list of similarity scores for each prediction/ground-truth pair. + """ + if len(ground_truth_answers) != len(predicted_answers): + raise ValueError("The number of predictions and labels must be the same.") + + if any(answer is None for answer in predicted_answers): + raise ValueError("Predicted answers must not contain None values.") + + if len(predicted_answers) == 0: + return {"score": 0.0, "individual_scores": [0.0]} + + if not self._similarity_model: + msg = "The model has not been initialized. Call warm_up() before running the evaluator." + raise RuntimeError(msg) + + if isinstance(self._similarity_model, CrossEncoder): + # For Cross Encoders we create a list of pairs of predictions and labels + sentence_pairs = list(zip(predicted_answers, ground_truth_answers)) + similarity_scores = self._similarity_model.predict( + sentence_pairs, batch_size=self._batch_size, convert_to_numpy=True + ) + + # All Cross Encoders do not return a set of logits scores that are normalized + # We normalize scores if they are larger than 1 + if (similarity_scores > 1).any(): + similarity_scores = expit(similarity_scores) + + # Convert scores to list of floats from numpy array + similarity_scores = similarity_scores.tolist() + + else: + # For Bi-encoders we create embeddings separately for predictions and labels + predictions_embeddings = self._similarity_model.encode( + predicted_answers, batch_size=self._batch_size, convert_to_tensor=True + ) + label_embeddings = self._similarity_model.encode( + ground_truth_answers, batch_size=self._batch_size, convert_to_tensor=True + ) + + # Compute cosine-similarities + similarity_scores = [ + float(util.cos_sim(p, l).cpu().numpy()) for p, l in zip(predictions_embeddings, label_embeddings) + ] + + sas_score = np_mean(similarity_scores) + + return {"score": sas_score, "individual_scores": similarity_scores} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/extractors/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/extractors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..510cf691f96556ce2b5f3b0846e379b2d8184f40 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/extractors/__init__.py @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.extractors.named_entity_extractor import ( + NamedEntityAnnotation, + NamedEntityExtractor, + NamedEntityExtractorBackend, +) + +__all__ = ["NamedEntityExtractor", "NamedEntityExtractorBackend", "NamedEntityAnnotation"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/extractors/named_entity_extractor.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/extractors/named_entity_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..00350e6aedacaab3aeb93f273ce170f2a0d42dc4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/extractors/named_entity_extractor.py @@ -0,0 +1,485 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from abc import ABC, abstractmethod +from contextlib import contextmanager +from dataclasses import dataclass +from enum import Enum +from typing import Any, Dict, List, Optional, Union + +from haystack import ComponentError, DeserializationError, Document, component, default_from_dict, default_to_dict +from haystack.lazy_imports import LazyImport +from haystack.utils.device import ComponentDevice + +with LazyImport(message="Run 'pip install \"transformers[torch]\"'") as transformers_import: + from transformers import AutoModelForTokenClassification, AutoTokenizer, pipeline + from transformers import Pipeline as HfPipeline + +with LazyImport(message="Run 'pip install spacy'") as spacy_import: + import spacy + from spacy import Language as SpacyPipeline + + +class NamedEntityExtractorBackend(Enum): + """ + NLP backend to use for Named Entity Recognition. + """ + + #: Uses an Hugging Face model and pipeline. + HUGGING_FACE = "hugging_face" + + #: Uses a spaCy model and pipeline. + SPACY = "spacy" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "NamedEntityExtractorBackend": + """ + Convert a string to a NamedEntityExtractorBackend enum. + """ + enum_map = {e.value: e for e in NamedEntityExtractorBackend} + mode = enum_map.get(string) + if mode is None: + msg = ( + f"Invalid backend '{string}' for named entity extractor. " + f"Supported backends are: {list(enum_map.keys())}" + ) + raise ComponentError(msg) + return mode + + +@dataclass +class NamedEntityAnnotation: + """ + Describes a single NER annotation. + + :param entity: + Entity label. + :param start: + Start index of the entity in the document. + :param end: + End index of the entity in the document. + :param score: + Score calculated by the model. + """ + + entity: str + start: int + end: int + score: Optional[float] = None + + +@component +class NamedEntityExtractor: + """ + Annotates named entities in a collection of documents. + + The component supports two backends: Hugging Face and spaCy. The + former can be used with any sequence classification model from the + [Hugging Face model hub](https://huggingface.co/models), while the + latter can be used with any [spaCy model](https://spacy.io/models) + that contains an NER component. Annotations are stored as metadata + in the documents. + + Usage example: + ```python + from haystack import Document + from haystack.components.extractors.named_entity_extractor import NamedEntityExtractor + + documents = [ + Document(content="I'm Merlin, the happy pig!"), + Document(content="My name is Clara and I live in Berkeley, California."), + ] + extractor = NamedEntityExtractor(backend="hugging_face", model="dslim/bert-base-NER") + extractor.warm_up() + results = extractor.run(documents=documents)["documents"] + annotations = [NamedEntityExtractor.get_stored_annotations(doc) for doc in results] + print(annotations) + ``` + """ + + _METADATA_KEY = "named_entities" + + def __init__( + self, + *, + backend: Union[str, NamedEntityExtractorBackend], + model: str, + pipeline_kwargs: Optional[Dict[str, Any]] = None, + device: Optional[ComponentDevice] = None, + ) -> None: + """ + Create a Named Entity extractor component. + + :param backend: + Backend to use for NER. + :param model: + Name of the model or a path to the model on + the local disk. Dependent on the backend. + :param pipeline_kwargs: + Keyword arguments passed to the pipeline. The + pipeline can override these arguments. Dependent on the backend. + :param device: + The device on which the model is loaded. If `None`, + the default device is automatically selected. If a + device/device map is specified in `pipeline_kwargs`, + it overrides this parameter (only applicable to the + HuggingFace backend). + """ + + if isinstance(backend, str): + backend = NamedEntityExtractorBackend.from_str(backend) + + self._backend: _NerBackend + self._warmed_up: bool = False + device = ComponentDevice.resolve_device(device) + + if backend == NamedEntityExtractorBackend.HUGGING_FACE: + self._backend = _HfBackend(model_name_or_path=model, device=device, pipeline_kwargs=pipeline_kwargs) + elif backend == NamedEntityExtractorBackend.SPACY: + self._backend = _SpacyBackend(model_name_or_path=model, device=device, pipeline_kwargs=pipeline_kwargs) + else: + raise ComponentError(f"Unknown NER backend '{type(backend).__name__}' for extractor") + + def warm_up(self): + """ + Initialize the component. + + :raises ComponentError: + If the backend fails to initialize successfully. + """ + if self._warmed_up: + return + + try: + self._backend.initialize() + self._warmed_up = True + except Exception as e: + raise ComponentError( + f"Named entity extractor with backend '{self._backend.type} failed to initialize." + ) from e + + @component.output_types(documents=List[Document]) + def run(self, documents: List[Document], batch_size: int = 1) -> Dict[str, Any]: + """ + Annotate named entities in each document and store the annotations in the document's metadata. + + :param documents: + Documents to process. + :param batch_size: + Batch size used for processing the documents. + :returns: + Processed documents. + :raises ComponentError: + If the backend fails to process a document. + """ + if not self._warmed_up: + msg = "The component NamedEntityExtractor was not warmed up. Call warm_up() before running the component." + raise RuntimeError(msg) + + texts = [doc.content if doc.content is not None else "" for doc in documents] + annotations = self._backend.annotate(texts, batch_size=batch_size) + + if len(annotations) != len(documents): + raise ComponentError( + "NER backend did not return the correct number of annotations; " + f"got {len(annotations)} but expected {len(documents)}" + ) + + for doc, doc_annotations in zip(documents, annotations): + doc.meta[self._METADATA_KEY] = doc_annotations + + return {"documents": documents} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + backend=self._backend.type.name, + model=self._backend.model_name, + device=self._backend.device.to_dict(), + pipeline_kwargs=self._backend._pipeline_kwargs, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "NamedEntityExtractor": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + try: + init_params = data["init_parameters"] + if init_params.get("device") is not None: + init_params["device"] = ComponentDevice.from_dict(init_params["device"]) + init_params["backend"] = NamedEntityExtractorBackend[init_params["backend"]] + return default_from_dict(cls, data) + except Exception as e: + raise DeserializationError(f"Couldn't deserialize {cls.__name__} instance") from e + + @property + def initialized(self) -> bool: + """ + Returns if the extractor is ready to annotate text. + """ + return self._backend.initialized + + @classmethod + def get_stored_annotations(cls, document: Document) -> Optional[List[NamedEntityAnnotation]]: + """ + Returns the document's named entity annotations stored in its metadata, if any. + + :param document: + Document whose annotations are to be fetched. + :returns: + The stored annotations. + """ + + return document.meta.get(cls._METADATA_KEY) + + +class _NerBackend(ABC): + """ + Base class for NER backends. + """ + + def __init__( + self, + _type: NamedEntityExtractorBackend, + device: ComponentDevice, + pipeline_kwargs: Optional[Dict[str, Any]] = None, + ) -> None: + super().__init__() + + self._type = _type + self._device = device + self._pipeline_kwargs = pipeline_kwargs if pipeline_kwargs is not None else {} + + @abstractmethod + def initialize(self): + """ + Initializes the backend. This would usually entail loading models, pipelines, and so on. + """ + + @property + @abstractmethod + def initialized(self) -> bool: + """ + Returns if the backend has been initialized, for example, ready to annotate text. + """ + + @abstractmethod + def annotate(self, texts: List[str], *, batch_size: int = 1) -> List[List[NamedEntityAnnotation]]: + """ + Predict annotations for a collection of documents. + + :param texts: + Raw texts to be annotated. + :param batch_size: + Size of text batches that are + passed to the model. + :returns: + NER annotations. + """ + + @property + @abstractmethod + def model_name(self) -> str: + """ + Returns the model name or path on the local disk. + """ + + @property + def device(self) -> ComponentDevice: + """ + The device on which the backend's model is loaded. + + :returns: + The device on which the backend's model is loaded. + """ + return self._device + + @property + def type(self) -> NamedEntityExtractorBackend: + """ + Returns the type of the backend. + """ + return self._type + + +class _HfBackend(_NerBackend): + """ + Hugging Face backend for NER. + """ + + def __init__( + self, *, model_name_or_path: str, device: ComponentDevice, pipeline_kwargs: Optional[Dict[str, Any]] = None + ) -> None: + """ + Construct a Hugging Face NER backend. + + :param model_name_or_path: + Name of the model or a path to the Hugging Face + model on the local disk. + :param device: + The device on which the model is loaded. If `None`, + the default device is automatically selected. + + If a device/device map is specified in `pipeline_kwargs`, + it overrides this parameter. + :param pipeline_kwargs: + Keyword arguments passed to the pipeline. The + pipeline can override these arguments. + """ + super().__init__(NamedEntityExtractorBackend.HUGGING_FACE, device, pipeline_kwargs) + + transformers_import.check() + + self._model_name_or_path = model_name_or_path + self.tokenizer: Optional[AutoTokenizer] = None + self.model: Optional[AutoModelForTokenClassification] = None + self.pipeline: Optional[HfPipeline] = None + + def initialize(self): + self.tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path) + self.model = AutoModelForTokenClassification.from_pretrained(self._model_name_or_path) + + pipeline_params = { + "task": "ner", + "model": self.model, + "tokenizer": self.tokenizer, + "aggregation_strategy": "simple", + } + pipeline_params.update({k: v for k, v in self._pipeline_kwargs.items() if k not in pipeline_params}) + self.device.update_hf_kwargs(pipeline_params, overwrite=False) + self.pipeline = pipeline(**pipeline_params) + + def annotate(self, texts: List[str], *, batch_size: int = 1) -> List[List[NamedEntityAnnotation]]: + if not self.initialized: + raise ComponentError("Hugging Face NER backend was not initialized - Did you call `warm_up()`?") + + assert self.pipeline is not None + outputs = self.pipeline(texts, batch_size=batch_size) + return [ + [ + NamedEntityAnnotation( + entity=annotation["entity"] if "entity" in annotation else annotation["entity_group"], + start=annotation["start"], + end=annotation["end"], + score=annotation["score"], + ) + for annotation in annotations + ] + for annotations in outputs + ] + + @property + def initialized(self) -> bool: + return self.tokenizer is not None and self.model is not None or self.pipeline is not None + + @property + def model_name(self) -> str: + return self._model_name_or_path + + +class _SpacyBackend(_NerBackend): + """ + spaCy backend for NER. + """ + + def __init__( + self, *, model_name_or_path: str, device: ComponentDevice, pipeline_kwargs: Optional[Dict[str, Any]] = None + ) -> None: + """ + Construct a spaCy NER backend. + + :param model_name_or_path: + Name of the model or a path to the spaCy + model on the local disk. + :param device: + The device on which the model is loaded. If `None`, + the default device is automatically selected. + :param pipeline_kwargs: + Keyword arguments passed to the pipeline. The + pipeline can override these arguments. + """ + super().__init__(NamedEntityExtractorBackend.SPACY, device, pipeline_kwargs) + + spacy_import.check() + + self._model_name_or_path = model_name_or_path + self.pipeline: Optional[SpacyPipeline] = None + + if self.device.has_multiple_devices: + raise ValueError("spaCy backend for named entity extractor only supports inference on single devices") + + def initialize(self): + # We need to initialize the model on the GPU if needed. + with self._select_device(): + self.pipeline = spacy.load(self._model_name_or_path) + + if not self.pipeline.has_pipe("ner"): + raise ComponentError(f"spaCy pipeline '{self._model_name_or_path}' does not contain an NER component") + + # Disable unnecessary pipes. + pipes_to_keep = ("ner", "tok2vec", "transformer", "curated_transformer") + for name in self.pipeline.pipe_names: + if name not in pipes_to_keep: + self.pipeline.disable_pipe(name) + + self._pipeline_kwargs = {k: v for k, v in self._pipeline_kwargs.items() if k not in ("texts", "batch_size")} + + def annotate(self, texts: List[str], *, batch_size: int = 1) -> List[List[NamedEntityAnnotation]]: + if not self.initialized: + raise ComponentError("spaCy NER backend was not initialized - Did you call `warm_up()`?") + + assert self.pipeline is not None + with self._select_device(): + outputs = list(self.pipeline.pipe(texts=texts, batch_size=batch_size, **self._pipeline_kwargs)) + + return [ + [ + NamedEntityAnnotation(entity=entity.label_, start=entity.start_char, end=entity.end_char) + for entity in doc.ents + ] + for doc in outputs + ] + + @property + def initialized(self) -> bool: + return self.pipeline is not None + + @property + def model_name(self) -> str: + return self._model_name_or_path + + @contextmanager + def _select_device(self): + """ + Context manager used to run spaCy models on a specific GPU in a scoped manner. + """ + + # TODO: This won't restore the active device. + # Since there are no opaque API functions to determine + # the active device in spaCy/Thinc, we can't do much + # about it as a consumer unless we start poking into their + # internals. + device_id = self._device.to_spacy() + try: + if device_id >= 0: + spacy.require_gpu(device_id) + yield + finally: + if device_id >= 0: + spacy.require_cpu() diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/fetchers/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/fetchers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..010695cdae66600d4889525d94558a33d43a01a0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/fetchers/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.fetchers.link_content import LinkContentFetcher + +__all__ = ["LinkContentFetcher"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/fetchers/link_content.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/fetchers/link_content.py new file mode 100644 index 0000000000000000000000000000000000000000..38712d683f7f33bc6549465f6f2f110228de6841 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/fetchers/link_content.py @@ -0,0 +1,260 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from collections import defaultdict +from concurrent.futures import ThreadPoolExecutor +from fnmatch import fnmatch +from typing import Callable, Dict, List, Optional, Tuple + +import requests +from requests import Response +from requests.exceptions import HTTPError +from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential + +from haystack import component, logging +from haystack.dataclasses import ByteStream +from haystack.version import __version__ + +logger = logging.getLogger(__name__) + + +DEFAULT_USER_AGENT = f"haystack/LinkContentFetcher/{__version__}" + +REQUEST_HEADERS = { + "accept": "*/*", + "User-Agent": DEFAULT_USER_AGENT, + "Accept-Language": "en-US,en;q=0.9,it;q=0.8,es;q=0.7", + "referer": "https://www.google.com/", +} + + +def _text_content_handler(response: Response) -> ByteStream: + """ + Handles text content. + + :param response: Response object from the request. + :return: The extracted text. + """ + return ByteStream.from_string(response.text) + + +def _binary_content_handler(response: Response) -> ByteStream: + """ + Handles binary content. + + :param response: Response object from the request. + :return: The extracted binary file-like object. + """ + return ByteStream(data=response.content) + + +@component +class LinkContentFetcher: + """ + Fetches and extracts content from URLs. + + It supports various content types, retries on failures, and automatic user-agent rotation for failed web + requests. Use it as the data-fetching step in your pipelines. + + You may need to convert LinkContentFetcher's output into a list of documents. Use HTMLToDocument + converter to do this. + + ### Usage example + + ```python + from haystack.components.fetchers.link_content import LinkContentFetcher + + fetcher = LinkContentFetcher() + streams = fetcher.run(urls=["https://www.google.com"])["streams"] + + assert len(streams) == 1 + assert streams[0].meta == {'content_type': 'text/html', 'url': 'https://www.google.com'} + assert streams[0].data + ``` + """ + + def __init__( + self, + raise_on_failure: bool = True, + user_agents: Optional[List[str]] = None, + retry_attempts: int = 2, + timeout: int = 3, + ): + """ + Initializes the component. + + :param raise_on_failure: If `True`, raises an exception if it fails to fetch a single URL. + For multiple URLs, it logs errors and returns the content it successfully fetched. + :param user_agents: [User agents](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent) + for fetching content. If `None`, a default user agent is used. + :param retry_attempts: The number of times to retry to fetch the URL's content. + :param timeout: Timeout in seconds for the request. + """ + self.raise_on_failure = raise_on_failure + self.user_agents = user_agents or [DEFAULT_USER_AGENT] + self.current_user_agent_idx: int = 0 + self.retry_attempts = retry_attempts + self.timeout = timeout + + # register default content handlers that extract data from the response + self.handlers: Dict[str, Callable[[Response], ByteStream]] = defaultdict(lambda: _text_content_handler) + self.handlers["text/*"] = _text_content_handler + self.handlers["text/html"] = _binary_content_handler + self.handlers["application/json"] = _text_content_handler + self.handlers["application/*"] = _binary_content_handler + self.handlers["image/*"] = _binary_content_handler + self.handlers["audio/*"] = _binary_content_handler + self.handlers["video/*"] = _binary_content_handler + + @retry( + reraise=True, + stop=stop_after_attempt(self.retry_attempts), + wait=wait_exponential(multiplier=1, min=2, max=10), + retry=(retry_if_exception_type((HTTPError, requests.RequestException))), + # This method is invoked only after failed requests (exception raised) + after=self._switch_user_agent, + ) + def get_response(url): + # we need to copy because we modify the headers + headers = REQUEST_HEADERS.copy() + headers["User-Agent"] = self.user_agents[self.current_user_agent_idx] + response = requests.get(url, headers=headers, timeout=timeout or 3) + response.raise_for_status() + return response + + self._get_response: Callable = get_response + + @component.output_types(streams=List[ByteStream]) + def run(self, urls: List[str]): + """ + Fetches content from a list of URLs and returns a list of extracted content streams. + + Each content stream is a `ByteStream` object containing the extracted content as binary data. + Each ByteStream object in the returned list corresponds to the contents of a single URL. + The content type of each stream is stored in the metadata of the ByteStream object under + the key "content_type". The URL of the fetched content is stored under the key "url". + + :param urls: A list of URLs to fetch content from. + :return: `ByteStream` objects representing the extracted content. + + :raises Exception: If the provided list of URLs contains only a single URL, and `raise_on_failure` is set to + `True`, an exception will be raised in case of an error during content retrieval. + In all other scenarios, any retrieval errors are logged, and a list of successfully retrieved `ByteStream` + objects is returned. + """ + streams: List[ByteStream] = [] + if not urls: + return {"streams": streams} + + # don't use multithreading if there's only one URL + if len(urls) == 1: + stream_metadata, stream = self._fetch(urls[0]) + stream.meta.update(stream_metadata) + streams.append(stream) + else: + with ThreadPoolExecutor() as executor: + results = executor.map(self._fetch_with_exception_suppression, urls) + + for stream_metadata, stream in results: # type: ignore + if stream_metadata is not None and stream is not None: + stream.meta.update(stream_metadata) + stream.mime_type = stream.meta.get("content_type", None) + streams.append(stream) + + return {"streams": streams} + + def _fetch(self, url: str) -> Tuple[Dict[str, str], ByteStream]: + """ + Fetches content from a URL and returns it as a ByteStream. + + :param url: The URL to fetch content from. + :return: A tuple containing the ByteStream metadata dict and the corresponding ByteStream. + ByteStream metadata contains the URL and the content type of the fetched content. + The content type is a string indicating the type of content fetched (for example, "text/html", + "application/pdf"). The ByteStream object contains the fetched content as binary data. + + :raises: If an error occurs during content retrieval and `raise_on_failure` is set to True, this method will + raise an exception. Otherwise, all fetching errors are logged, and an empty ByteStream is returned. + + """ + content_type: str = "text/html" + stream: ByteStream = ByteStream(data=b"") + try: + response = self._get_response(url) + content_type = self._get_content_type(response) + handler: Callable = self._resolve_handler(content_type) + stream = handler(response) + except Exception as e: + if self.raise_on_failure: + raise e + # less verbose log as this is expected to happen often (requests failing, blocked, etc.) + logger.debug("Couldn't retrieve content from {url} because {error}", url=url, error=str(e)) + + finally: + self.current_user_agent_idx = 0 + + return {"content_type": content_type, "url": url}, stream + + def _fetch_with_exception_suppression(self, url: str) -> Tuple[Optional[Dict[str, str]], Optional[ByteStream]]: + """ + Fetches content from a URL and returns it as a ByteStream. + + If `raise_on_failure` is set to True, this method will wrap the fetch() method and catch any exceptions. + Otherwise, it will simply call the fetch() method. + :param url: The URL to fetch content from. + :return: A tuple containing the ByteStream metadata dict and the corresponding ByteStream. + + """ + if self.raise_on_failure: + try: + return self._fetch(url) + except Exception as e: + logger.warning("Error fetching {url}: {error}", url=url, error=str(e)) + return {"content_type": "Unknown", "url": url}, None + else: + return self._fetch(url) + + def _get_content_type(self, response: Response): + """ + Get the content type of the response. + + :param response: The response object. + :return: The content type of the response. + """ + content_type = response.headers.get("Content-Type", "") + return content_type.split(";")[0] + + def _resolve_handler(self, content_type: str) -> Callable[[Response], ByteStream]: + """ + Resolves the handler for the given content type. + + First, it tries to find a direct match for the content type in the handlers dictionary. + If no direct match is found, it tries to find a pattern match using the fnmatch function. + If no pattern match is found, it returns the default handler for text/plain. + + :param content_type: The content type to resolve the handler for. + :returns: The handler for the given content type, if found. Otherwise, the default handler for text/plain. + """ + # direct match + if content_type in self.handlers: + return self.handlers[content_type] + + # pattern matches + for pattern, handler in self.handlers.items(): + if fnmatch(content_type, pattern): + return handler + + # default handler + return self.handlers["text/plain"] + + def _switch_user_agent(self, retry_state: RetryCallState) -> None: + """ + Switches the User-Agent for this LinkContentRetriever to the next one in the list of user agents. + + Used by tenacity to retry the requests with a different user agent. + + :param retry_state: The retry state (unused, required by tenacity). + """ + self.current_user_agent_idx = (self.current_user_agent_idx + 1) % len(self.user_agents) + logger.debug("Switched user agent to {user_agent}", user_agent=self.user_agents[self.current_user_agent_idx]) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b93270d82f95d6117ad26e667b22a7f8d63edce2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/__init__.py @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.generators.openai import ( # noqa: I001 (otherwise we end up with partial imports) + OpenAIGenerator, +) +from haystack.components.generators.azure import AzureOpenAIGenerator +from haystack.components.generators.hugging_face_local import HuggingFaceLocalGenerator +from haystack.components.generators.hugging_face_api import HuggingFaceAPIGenerator + +__all__ = ["HuggingFaceLocalGenerator", "HuggingFaceAPIGenerator", "OpenAIGenerator", "AzureOpenAIGenerator"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/azure.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/azure.py new file mode 100644 index 0000000000000000000000000000000000000000..20bb2cda8ee637d5dccf03a18f82279bc9ec1428 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/azure.py @@ -0,0 +1,194 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +from typing import Any, Callable, Dict, Optional + +# pylint: disable=import-error +from openai.lib.azure import AzureOpenAI + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.components.generators import OpenAIGenerator +from haystack.dataclasses import StreamingChunk +from haystack.utils import Secret, deserialize_callable, deserialize_secrets_inplace, serialize_callable + +logger = logging.getLogger(__name__) + + +@component +class AzureOpenAIGenerator(OpenAIGenerator): + """ + Generates text using OpenAI's large language models (LLMs). + + It works with the gpt-4 and gpt-3.5-turbo family of models. + You can customize how the text is generated by passing parameters to the + OpenAI API. Use the `**generation_kwargs` argument when you initialize + the component or when you run it. Any parameter that works with + `openai.ChatCompletion.create` will work here too. + + + For details on OpenAI API parameters, see + [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat). + + + ### Usage example + + ```python + from haystack.components.generators import AzureOpenAIGenerator + from haystack.utils import Secret + client = AzureOpenAIGenerator( + azure_endpoint="", + api_key=Secret.from_token(""), + azure_deployment="") + response = client.run("What's Natural Language Processing? Be brief.") + print(response) + ``` + + ``` + >> {'replies': ['Natural Language Processing (NLP) is a branch of artificial intelligence that focuses on + >> the interaction between computers and human language. It involves enabling computers to understand, interpret, + >> and respond to natural human language in a way that is both meaningful and useful.'], 'meta': [{'model': + >> 'gpt-4o-mini', 'index': 0, 'finish_reason': 'stop', 'usage': {'prompt_tokens': 16, + >> 'completion_tokens': 49, 'total_tokens': 65}}]} + ``` + """ + + # pylint: disable=super-init-not-called + def __init__( + self, + azure_endpoint: Optional[str] = None, + api_version: Optional[str] = "2023-05-15", + azure_deployment: Optional[str] = "gpt-4o-mini", + api_key: Optional[Secret] = Secret.from_env_var("AZURE_OPENAI_API_KEY", strict=False), + azure_ad_token: Optional[Secret] = Secret.from_env_var("AZURE_OPENAI_AD_TOKEN", strict=False), + organization: Optional[str] = None, + streaming_callback: Optional[Callable[[StreamingChunk], None]] = None, + system_prompt: Optional[str] = None, + timeout: Optional[float] = None, + max_retries: Optional[int] = None, + generation_kwargs: Optional[Dict[str, Any]] = None, + default_headers: Optional[Dict[str, str]] = None, + ): + """ + Initialize the Azure OpenAI Generator. + + :param azure_endpoint: The endpoint of the deployed model, for example `https://example-resource.azure.openai.com/`. + :param api_version: The version of the API to use. Defaults to 2023-05-15. + :param azure_deployment: The deployment of the model, usually the model name. + :param api_key: The API key to use for authentication. + :param azure_ad_token: [Azure Active Directory token](https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id). + :param organization: Your organization ID, defaults to `None`. For help, see + [Setting up your organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization). + :param streaming_callback: A callback function called when a new token is received from the stream. + It accepts [StreamingChunk](https://docs.haystack.deepset.ai/docs/data-classes#streamingchunk) + as an argument. + :param system_prompt: The system prompt to use for text generation. If not provided, the Generator + omits the system prompt and uses the default system prompt. + :param timeout: Timeout for AzureOpenAI client. If not set, it is inferred from the + `OPENAI_TIMEOUT` environment variable or set to 30. + :param max_retries: Maximum retries to establish contact with AzureOpenAI if it returns an internal error. + If not set, it is inferred from the `OPENAI_MAX_RETRIES` environment variable or set to 5. + :param generation_kwargs: Other parameters to use for the model, sent directly to + the OpenAI endpoint. See [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat) for + more details. + Some of the supported parameters: + - `max_tokens`: The maximum number of tokens the output text can have. + - `temperature`: The sampling temperature to use. Higher values mean the model takes more risks. + Try 0.9 for more creative applications and 0 (argmax sampling) for ones with a well-defined answer. + - `top_p`: An alternative to sampling with temperature, called nucleus sampling, where the model + considers the results of the tokens with top_p probability mass. For example, 0.1 means only the tokens + comprising the top 10% probability mass are considered. + - `n`: The number of completions to generate for each prompt. For example, with 3 prompts and n=2, + the LLM will generate two completions per prompt, resulting in 6 completions total. + - `stop`: One or more sequences after which the LLM should stop generating tokens. + - `presence_penalty`: The penalty applied if a token is already present. + Higher values make the model less likely to repeat the token. + - `frequency_penalty`: Penalty applied if a token has already been generated. + Higher values make the model less likely to repeat the token. + - `logit_bias`: Adds a logit bias to specific tokens. The keys of the dictionary are tokens, and the + values are the bias to add to that token. + :param default_headers: Default headers to use for the AzureOpenAI client. + """ + # We intentionally do not call super().__init__ here because we only need to instantiate the client to interact + # with the API. + + # Why is this here? + # AzureOpenAI init is forcing us to use an init method that takes either base_url or azure_endpoint as not + # None init parameters. This way we accommodate the use case where env var AZURE_OPENAI_ENDPOINT is set instead + # of passing it as a parameter. + azure_endpoint = azure_endpoint or os.environ.get("AZURE_OPENAI_ENDPOINT") + if not azure_endpoint: + raise ValueError("Please provide an Azure endpoint or set the environment variable AZURE_OPENAI_ENDPOINT.") + + if api_key is None and azure_ad_token is None: + raise ValueError("Please provide an API key or an Azure Active Directory token.") + + # The check above makes mypy incorrectly infer that api_key is never None, + # which propagates the incorrect type. + self.api_key = api_key # type: ignore + self.azure_ad_token = azure_ad_token + self.generation_kwargs = generation_kwargs or {} + self.system_prompt = system_prompt + self.streaming_callback = streaming_callback + self.api_version = api_version + self.azure_endpoint = azure_endpoint + self.azure_deployment = azure_deployment + self.organization = organization + self.model: str = azure_deployment or "gpt-4o-mini" + self.timeout = timeout or float(os.environ.get("OPENAI_TIMEOUT", 30.0)) + self.max_retries = max_retries or int(os.environ.get("OPENAI_MAX_RETRIES", 5)) + self.default_headers = default_headers or {} + + self.client = AzureOpenAI( + api_version=api_version, + azure_endpoint=azure_endpoint, + azure_deployment=azure_deployment, + api_key=api_key.resolve_value() if api_key is not None else None, + azure_ad_token=azure_ad_token.resolve_value() if azure_ad_token is not None else None, + organization=organization, + timeout=self.timeout, + max_retries=self.max_retries, + default_headers=self.default_headers, + ) + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + + :returns: + The serialized component as a dictionary. + """ + callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None + return default_to_dict( + self, + azure_endpoint=self.azure_endpoint, + azure_deployment=self.azure_deployment, + organization=self.organization, + api_version=self.api_version, + streaming_callback=callback_name, + generation_kwargs=self.generation_kwargs, + system_prompt=self.system_prompt, + api_key=self.api_key.to_dict() if self.api_key is not None else None, + azure_ad_token=self.azure_ad_token.to_dict() if self.azure_ad_token is not None else None, + timeout=self.timeout, + max_retries=self.max_retries, + default_headers=self.default_headers, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "AzureOpenAIGenerator": + """ + Deserialize this component from a dictionary. + + :param data: + The dictionary representation of this component. + :returns: + The deserialized component instance. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key", "azure_ad_token"]) + init_params = data.get("init_parameters", {}) + serialized_callback_handler = init_params.get("streaming_callback") + if serialized_callback_handler: + data["init_parameters"]["streaming_callback"] = deserialize_callable(serialized_callback_handler) + return default_from_dict(cls, data) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/chat/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/chat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1c7ecbad8d6810da0ec6def3dccceba52c410af8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/chat/__init__.py @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.generators.chat.openai import ( # noqa: I001 (otherwise we end up with partial imports) + OpenAIChatGenerator, +) +from haystack.components.generators.chat.azure import AzureOpenAIChatGenerator +from haystack.components.generators.chat.hugging_face_local import HuggingFaceLocalChatGenerator +from haystack.components.generators.chat.hugging_face_api import HuggingFaceAPIChatGenerator + +__all__ = [ + "HuggingFaceLocalChatGenerator", + "HuggingFaceAPIChatGenerator", + "OpenAIChatGenerator", + "AzureOpenAIChatGenerator", +] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/chat/azure.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/chat/azure.py new file mode 100644 index 0000000000000000000000000000000000000000..445e58040211cb40bc402a184101e1865d544de8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/chat/azure.py @@ -0,0 +1,194 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +from typing import Any, Callable, Dict, Optional + +# pylint: disable=import-error +from openai.lib.azure import AzureOpenAI + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.components.generators.chat import OpenAIChatGenerator +from haystack.dataclasses import StreamingChunk +from haystack.utils import Secret, deserialize_callable, deserialize_secrets_inplace, serialize_callable + +logger = logging.getLogger(__name__) + + +@component +class AzureOpenAIChatGenerator(OpenAIChatGenerator): + """ + Generates text using OpenAI's models on Azure. + + It works with the gpt-4 and gpt-3.5-turbo - type models and supports streaming responses + from OpenAI API. It uses [ChatMessage](https://docs.haystack.deepset.ai/docs/data-classes#chatmessage) + format in input and output. + + You can customize how the text is generated by passing parameters to the + OpenAI API. Use the `**generation_kwargs` argument when you initialize + the component or when you run it. Any parameter that works with + `openai.ChatCompletion.create` will work here too. + + For details on OpenAI API parameters, see + [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat). + + ### Usage example + + ```python + from haystack.components.generators.chat import AzureOpenAIGenerator + from haystack.dataclasses import ChatMessage + from haystack.utils import Secret + + messages = [ChatMessage.from_user("What's Natural Language Processing?")] + + client = AzureOpenAIGenerator( + azure_endpoint="", + api_key=Secret.from_token(""), + azure_deployment="") + response = client.run(messages) + print(response) + ``` + + ``` + {'replies': + [ChatMessage(content='Natural Language Processing (NLP) is a branch of artificial intelligence that focuses on + enabling computers to understand, interpret, and generate human language in a way that is useful.', + role=, name=None, + meta={'model': 'gpt-4o-mini', 'index': 0, 'finish_reason': 'stop', + 'usage': {'prompt_tokens': 15, 'completion_tokens': 36, 'total_tokens': 51}})] + } + ``` + """ + + # pylint: disable=super-init-not-called + def __init__( + self, + azure_endpoint: Optional[str] = None, + api_version: Optional[str] = "2023-05-15", + azure_deployment: Optional[str] = "gpt-4o-mini", + api_key: Optional[Secret] = Secret.from_env_var("AZURE_OPENAI_API_KEY", strict=False), + azure_ad_token: Optional[Secret] = Secret.from_env_var("AZURE_OPENAI_AD_TOKEN", strict=False), + organization: Optional[str] = None, + streaming_callback: Optional[Callable[[StreamingChunk], None]] = None, + timeout: Optional[float] = None, + max_retries: Optional[int] = None, + generation_kwargs: Optional[Dict[str, Any]] = None, + default_headers: Optional[Dict[str, str]] = None, + ): + """ + Initialize the Azure OpenAI Chat Generator component. + + :param azure_endpoint: The endpoint of the deployed model, for example `"https://example-resource.azure.openai.com/"`. + :param api_version: The version of the API to use. Defaults to 2023-05-15. + :param azure_deployment: The deployment of the model, usually the model name. + :param api_key: The API key to use for authentication. + :param azure_ad_token: [Azure Active Directory token](https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id). + :param organization: Your organization ID, defaults to `None`. For help, see + [Setting up your organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization). + :param streaming_callback: A callback function called when a new token is received from the stream. + It accepts [StreamingChunk](https://docs.haystack.deepset.ai/docs/data-classes#streamingchunk) + as an argument. + :param timeout: Timeout for OpenAI client calls. If not set, it defaults to either the + `OPENAI_TIMEOUT` environment variable, or 30 seconds. + :param max_retries: Maximum number of retries to contact OpenAI after an internal error. + If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5. + :param generation_kwargs: Other parameters to use for the model. These parameters are sent directly to + the OpenAI endpoint. For details, see [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat). + Some of the supported parameters: + - `max_tokens`: The maximum number of tokens the output text can have. + - `temperature`: The sampling temperature to use. Higher values mean the model takes more risks. + Try 0.9 for more creative applications and 0 (argmax sampling) for ones with a well-defined answer. + - `top_p`: Nucleus sampling is an alternative to sampling with temperature, where the model considers + tokens with a top_p probability mass. For example, 0.1 means only the tokens comprising + the top 10% probability mass are considered. + - `n`: The number of completions to generate for each prompt. For example, with 3 prompts and n=2, + the LLM will generate two completions per prompt, resulting in 6 completions total. + - `stop`: One or more sequences after which the LLM should stop generating tokens. + - `presence_penalty`: The penalty applied if a token is already present. + Higher values make the model less likely to repeat the token. + - `frequency_penalty`: Penalty applied if a token has already been generated. + Higher values make the model less likely to repeat the token. + - `logit_bias`: Adds a logit bias to specific tokens. The keys of the dictionary are tokens, and the + values are the bias to add to that token. + :param default_headers: Default headers to use for the AzureOpenAI client. + """ + # We intentionally do not call super().__init__ here because we only need to instantiate the client to interact + # with the API. + + # Why is this here? + # AzureOpenAI init is forcing us to use an init method that takes either base_url or azure_endpoint as not + # None init parameters. This way we accommodate the use case where env var AZURE_OPENAI_ENDPOINT is set instead + # of passing it as a parameter. + azure_endpoint = azure_endpoint or os.environ.get("AZURE_OPENAI_ENDPOINT") + if not azure_endpoint: + raise ValueError("Please provide an Azure endpoint or set the environment variable AZURE_OPENAI_ENDPOINT.") + + if api_key is None and azure_ad_token is None: + raise ValueError("Please provide an API key or an Azure Active Directory token.") + + # The check above makes mypy incorrectly infer that api_key is never None, + # which propagates the incorrect type. + self.api_key = api_key # type: ignore + self.azure_ad_token = azure_ad_token + self.generation_kwargs = generation_kwargs or {} + self.streaming_callback = streaming_callback + self.api_version = api_version + self.azure_endpoint = azure_endpoint + self.azure_deployment = azure_deployment + self.organization = organization + self.model = azure_deployment or "gpt-4o-mini" + self.timeout = timeout or float(os.environ.get("OPENAI_TIMEOUT", 30.0)) + self.max_retries = max_retries or int(os.environ.get("OPENAI_MAX_RETRIES", 5)) + self.default_headers = default_headers or {} + + self.client = AzureOpenAI( + api_version=api_version, + azure_endpoint=azure_endpoint, + azure_deployment=azure_deployment, + api_key=api_key.resolve_value() if api_key is not None else None, + azure_ad_token=azure_ad_token.resolve_value() if azure_ad_token is not None else None, + organization=organization, + timeout=self.timeout, + max_retries=self.max_retries, + default_headers=self.default_headers, + ) + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + + :returns: + The serialized component as a dictionary. + """ + callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None + return default_to_dict( + self, + azure_endpoint=self.azure_endpoint, + azure_deployment=self.azure_deployment, + organization=self.organization, + api_version=self.api_version, + streaming_callback=callback_name, + generation_kwargs=self.generation_kwargs, + timeout=self.timeout, + max_retries=self.max_retries, + api_key=self.api_key.to_dict() if self.api_key is not None else None, + azure_ad_token=self.azure_ad_token.to_dict() if self.azure_ad_token is not None else None, + default_headers=self.default_headers, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "AzureOpenAIChatGenerator": + """ + Deserialize this component from a dictionary. + + :param data: The dictionary representation of this component. + :returns: + The deserialized component instance. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key", "azure_ad_token"]) + init_params = data.get("init_parameters", {}) + serialized_callback_handler = init_params.get("streaming_callback") + if serialized_callback_handler: + data["init_parameters"]["streaming_callback"] = deserialize_callable(serialized_callback_handler) + return default_from_dict(cls, data) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/chat/hugging_face_api.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/chat/hugging_face_api.py new file mode 100644 index 0000000000000000000000000000000000000000..8b37e82404f71fa00113b6816249d4f5e16ff2f0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/chat/hugging_face_api.py @@ -0,0 +1,279 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Callable, Dict, Iterable, List, Optional, Union + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.dataclasses import ChatMessage, StreamingChunk +from haystack.lazy_imports import LazyImport +from haystack.utils import Secret, deserialize_callable, deserialize_secrets_inplace, serialize_callable +from haystack.utils.hf import HFGenerationAPIType, HFModelType, check_valid_model +from haystack.utils.url_validation import is_valid_http_url + +with LazyImport(message="Run 'pip install \"huggingface_hub[inference]>=0.23.0\"'") as huggingface_hub_import: + from huggingface_hub import ChatCompletionOutput, ChatCompletionStreamOutput, InferenceClient + + +logger = logging.getLogger(__name__) + + +def _convert_message_to_hfapi_format(message: ChatMessage) -> Dict[str, str]: + """ + Convert a message to the format expected by Hugging Face APIs. + + :returns: A dictionary with the following keys: + - `role` + - `content` + - `name` (optional) + """ + formatted_msg = {"role": message.role.value, "content": message.content} + if message.name: + formatted_msg["name"] = message.name + + return formatted_msg + + +@component +class HuggingFaceAPIChatGenerator: + """ + Completes chats using Hugging Face APIs. + + HuggingFaceAPIChatGenerator uses the [ChatMessage](https://docs.haystack.deepset.ai/docs/data-classes#chatmessage) + format for input and output. Use it to generate text with Hugging Face APIs: + - [Free Serverless Inference API](https://huggingface.co/inference-api) + - [Paid Inference Endpoints](https://huggingface.co/inference-endpoints) + - [Self-hosted Text Generation Inference](https://github.com/huggingface/text-generation-inference) + + ### Usage examples + + #### With the free serverless inference API + + ```python + from haystack.components.generators.chat import HuggingFaceAPIChatGenerator + from haystack.dataclasses import ChatMessage + from haystack.utils import Secret + from haystack.utils.hf import HFGenerationAPIType + + messages = [ChatMessage.from_system("\\nYou are a helpful, respectful and honest assistant"), + ChatMessage.from_user("What's Natural Language Processing?")] + + # the api_type can be expressed using the HFGenerationAPIType enum or as a string + api_type = HFGenerationAPIType.SERVERLESS_INFERENCE_API + api_type = "serverless_inference_api" # this is equivalent to the above + + generator = HuggingFaceAPIChatGenerator(api_type=api_type, + api_params={"model": "HuggingFaceH4/zephyr-7b-beta"}, + token=Secret.from_token("")) + + result = generator.run(messages) + print(result) + ``` + + #### With paid inference endpoints + + ```python + from haystack.components.generators.chat import HuggingFaceAPIChatGenerator + from haystack.dataclasses import ChatMessage + from haystack.utils import Secret + + messages = [ChatMessage.from_system("\\nYou are a helpful, respectful and honest assistant"), + ChatMessage.from_user("What's Natural Language Processing?")] + + generator = HuggingFaceAPIChatGenerator(api_type="inference_endpoints", + api_params={"url": ""}, + token=Secret.from_token("")) + + result = generator.run(messages) + print(result) + + #### With self-hosted text generation inference + + ```python + from haystack.components.generators.chat import HuggingFaceAPIChatGenerator + from haystack.dataclasses import ChatMessage + + messages = [ChatMessage.from_system("\\nYou are a helpful, respectful and honest assistant"), + ChatMessage.from_user("What's Natural Language Processing?")] + + generator = HuggingFaceAPIChatGenerator(api_type="text_generation_inference", + api_params={"url": "http://localhost:8080"}) + + result = generator.run(messages) + print(result) + ``` + """ + + def __init__( + self, + api_type: Union[HFGenerationAPIType, str], + api_params: Dict[str, str], + token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + generation_kwargs: Optional[Dict[str, Any]] = None, + stop_words: Optional[List[str]] = None, + streaming_callback: Optional[Callable[[StreamingChunk], None]] = None, + ): + """ + Initialize the HuggingFaceAPIChatGenerator instance. + + :param api_type: + The type of Hugging Face API to use. Available types: + - `text_generation_inference`: See [TGI](https://github.com/huggingface/text-generation-inference). + - `inference_endpoints`: See [Inference Endpoints](https://huggingface.co/inference-endpoints). + - `serverless_inference_api`: See [Serverless Inference API](https://huggingface.co/inference-api). + :param api_params: + A dictionary with the following keys: + - `model`: Hugging Face model ID. Required when `api_type` is `SERVERLESS_INFERENCE_API`. + - `url`: URL of the inference endpoint. Required when `api_type` is `INFERENCE_ENDPOINTS` or + `TEXT_GENERATION_INFERENCE`. + :param token: The Hugging Face token to use as HTTP bearer authorization. + Check your HF token in your [account settings](https://huggingface.co/settings/tokens). + :param generation_kwargs: + A dictionary with keyword arguments to customize text generation. + Some examples: `max_tokens`, `temperature`, `top_p`. + For details, see [Hugging Face chat_completion documentation](https://huggingface.co/docs/huggingface_hub/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion). + :param stop_words: An optional list of strings representing the stop words. + :param streaming_callback: An optional callable for handling streaming responses. + """ + + huggingface_hub_import.check() + + if isinstance(api_type, str): + api_type = HFGenerationAPIType.from_str(api_type) + + if api_type == HFGenerationAPIType.SERVERLESS_INFERENCE_API: + model = api_params.get("model") + if model is None: + raise ValueError( + "To use the Serverless Inference API, you need to specify the `model` parameter in `api_params`." + ) + check_valid_model(model, HFModelType.GENERATION, token) + model_or_url = model + elif api_type in [HFGenerationAPIType.INFERENCE_ENDPOINTS, HFGenerationAPIType.TEXT_GENERATION_INFERENCE]: + url = api_params.get("url") + if url is None: + msg = ( + "To use Text Generation Inference or Inference Endpoints, you need to specify the `url` parameter " + "in `api_params`." + ) + raise ValueError(msg) + if not is_valid_http_url(url): + raise ValueError(f"Invalid URL: {url}") + model_or_url = url + else: + msg = f"Unknown api_type {api_type}" + raise ValueError(api_type) + + # handle generation kwargs setup + generation_kwargs = generation_kwargs.copy() if generation_kwargs else {} + generation_kwargs["stop"] = generation_kwargs.get("stop", []) + generation_kwargs["stop"].extend(stop_words or []) + generation_kwargs.setdefault("max_tokens", 512) + + self.api_type = api_type + self.api_params = api_params + self.token = token + self.generation_kwargs = generation_kwargs + self.streaming_callback = streaming_callback + self._client = InferenceClient(model_or_url, token=token.resolve_value() if token else None) + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + + :returns: + A dictionary containing the serialized component. + """ + callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None + return default_to_dict( + self, + api_type=str(self.api_type), + api_params=self.api_params, + token=self.token.to_dict() if self.token else None, + generation_kwargs=self.generation_kwargs, + streaming_callback=callback_name, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "HuggingFaceAPIChatGenerator": + """ + Deserialize this component from a dictionary. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["token"]) + init_params = data.get("init_parameters", {}) + serialized_callback_handler = init_params.get("streaming_callback") + if serialized_callback_handler: + data["init_parameters"]["streaming_callback"] = deserialize_callable(serialized_callback_handler) + return default_from_dict(cls, data) + + @component.output_types(replies=List[ChatMessage]) + def run(self, messages: List[ChatMessage], generation_kwargs: Optional[Dict[str, Any]] = None): + """ + Invoke the text generation inference based on the provided messages and generation parameters. + + :param messages: A list of ChatMessage objects representing the input messages. + :param generation_kwargs: Additional keyword arguments for text generation. + :returns: A dictionary with the following keys: + - `replies`: A list containing the generated responses as ChatMessage objects. + """ + + # update generation kwargs by merging with the default ones + generation_kwargs = {**self.generation_kwargs, **(generation_kwargs or {})} + + formatted_messages = [_convert_message_to_hfapi_format(message) for message in messages] + + if self.streaming_callback: + return self._run_streaming(formatted_messages, generation_kwargs) + + return self._run_non_streaming(formatted_messages, generation_kwargs) + + def _run_streaming(self, messages: List[Dict[str, str]], generation_kwargs: Dict[str, Any]): + api_output: Iterable[ChatCompletionStreamOutput] = self._client.chat_completion( + messages, stream=True, **generation_kwargs + ) + + generated_text = "" + + for chunk in api_output: # pylint: disable=not-an-iterable + text = chunk.choices[0].delta.content + if text: + generated_text += text + finish_reason = chunk.choices[0].finish_reason + + meta = {} + if finish_reason: + meta["finish_reason"] = finish_reason + + stream_chunk = StreamingChunk(text, meta) + self.streaming_callback(stream_chunk) # type: ignore # streaming_callback is not None (verified in the run method) + + message = ChatMessage.from_assistant(generated_text) + message.meta.update( + { + "model": self._client.model, + "finish_reason": finish_reason, + "index": 0, + "usage": {"prompt_tokens": 0, "completion_tokens": 0}, # not available in streaming + } + ) + return {"replies": [message]} + + def _run_non_streaming( + self, messages: List[Dict[str, str]], generation_kwargs: Dict[str, Any] + ) -> Dict[str, List[ChatMessage]]: + chat_messages: List[ChatMessage] = [] + + api_chat_output: ChatCompletionOutput = self._client.chat_completion(messages, **generation_kwargs) + for choice in api_chat_output.choices: + message = ChatMessage.from_assistant(choice.message.content) + message.meta.update( + { + "model": self._client.model, + "finish_reason": choice.finish_reason, + "index": choice.index, + "usage": api_chat_output.usage or {"prompt_tokens": 0, "completion_tokens": 0}, + } + ) + chat_messages.append(message) + + return {"replies": chat_messages} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/chat/hugging_face_local.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/chat/hugging_face_local.py new file mode 100644 index 0000000000000000000000000000000000000000..419fde20b669317206c52ca81764006c8fe0804d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/chat/hugging_face_local.py @@ -0,0 +1,356 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import sys +from typing import Any, Callable, Dict, List, Literal, Optional, Union + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.dataclasses import ChatMessage, StreamingChunk +from haystack.lazy_imports import LazyImport +from haystack.utils import ( + ComponentDevice, + Secret, + deserialize_callable, + deserialize_secrets_inplace, + serialize_callable, +) + +logger = logging.getLogger(__name__) + +with LazyImport(message="Run 'pip install \"transformers[torch]\"'") as torch_and_transformers_import: + from huggingface_hub import model_info + from transformers import PreTrainedTokenizer, PreTrainedTokenizerFast, StoppingCriteriaList, pipeline + + from haystack.utils.hf import ( # pylint: disable=ungrouped-imports + HFTokenStreamingHandler, + StopWordsCriteria, + deserialize_hf_model_kwargs, + serialize_hf_model_kwargs, + ) + + +PIPELINE_SUPPORTED_TASKS = ["text-generation", "text2text-generation"] + + +@component +class HuggingFaceLocalChatGenerator: + """ + Generates chat responses using models from Hugging Face that run locally. + + Use this component with chat-based models, + such as `HuggingFaceH4/zephyr-7b-beta` or `meta-llama/Llama-2-7b-chat-hf`. + LLMs running locally may need powerful hardware. + + ### Usage example + + ```python + from haystack.components.generators.chat import HuggingFaceLocalChatGenerator + from haystack.dataclasses import ChatMessage + + generator = HuggingFaceLocalChatGenerator(model="HuggingFaceH4/zephyr-7b-beta") + generator.warm_up() + messages = [ChatMessage.from_user("What's Natural Language Processing? Be brief.")] + print(generator.run(messages)) + ``` + + ``` + {'replies': + [ChatMessage(content=' Natural Language Processing (NLP) is a subfield of artificial intelligence that deals + with the interaction between computers and human language. It enables computers to understand, interpret, and + generate human language in a valuable way. NLP involves various techniques such as speech recognition, text + analysis, sentiment analysis, and machine translation. The ultimate goal is to make it easier for computers to + process and derive meaning from human language, improving communication between humans and machines.', + role=, + name=None, + meta={'finish_reason': 'stop', 'index': 0, 'model': + 'mistralai/Mistral-7B-Instruct-v0.2', + 'usage': {'completion_tokens': 90, 'prompt_tokens': 19, 'total_tokens': 109}}) + ] + } + ``` + """ + + def __init__( + self, + model: str = "HuggingFaceH4/zephyr-7b-beta", + task: Optional[Literal["text-generation", "text2text-generation"]] = None, + device: Optional[ComponentDevice] = None, + token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + chat_template: Optional[str] = None, + generation_kwargs: Optional[Dict[str, Any]] = None, + huggingface_pipeline_kwargs: Optional[Dict[str, Any]] = None, + stop_words: Optional[List[str]] = None, + streaming_callback: Optional[Callable[[StreamingChunk], None]] = None, + ): + """ + Initializes the HuggingFaceLocalChatGenerator component. + + :param model: The Hugging Face text generation model name or path, + for example, `mistralai/Mistral-7B-Instruct-v0.2` or `TheBloke/OpenHermes-2.5-Mistral-7B-16k-AWQ`. + The model must be a chat model supporting the ChatML messaging + format. + If the model is specified in `huggingface_pipeline_kwargs`, this parameter is ignored. + :param task: The task for the Hugging Face pipeline. Possible options: + - `text-generation`: Supported by decoder models, like GPT. + - `text2text-generation`: Supported by encoder-decoder models, like T5. + If the task is specified in `huggingface_pipeline_kwargs`, this parameter is ignored. + If not specified, the component calls the Hugging Face API to infer the task from the model name. + :param device: The device for loading the model. If `None`, automatically selects the default device. + If a device or device map is specified in `huggingface_pipeline_kwargs`, it overrides this parameter. + :param token: The token to use as HTTP bearer authorization for remote files. + If the token is specified in `huggingface_pipeline_kwargs`, this parameter is ignored. + :param chat_template: Specifies an optional Jinja template for formatting chat + messages. Most high-quality chat models have their own templates, but for models without this + feature or if you prefer a custom template, use this parameter. + :param generation_kwargs: A dictionary with keyword arguments to customize text generation. + Some examples: `max_length`, `max_new_tokens`, `temperature`, `top_k`, `top_p`. + See Hugging Face's documentation for more information: + - - [customize-text-generation](https://huggingface.co/docs/transformers/main/en/generation_strategies#customize-text-generation) + - - [GenerationConfig](https://huggingface.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationConfig) + The only `generation_kwargs` set by default is `max_new_tokens`, which is set to 512 tokens. + :param huggingface_pipeline_kwargs: Dictionary with keyword arguments to initialize the + Hugging Face pipeline for text generation. + These keyword arguments provide fine-grained control over the Hugging Face pipeline. + In case of duplication, these kwargs override `model`, `task`, `device`, and `token` init parameters. + For kwargs, see [Hugging Face documentation](https://huggingface.co/docs/transformers/en/main_classes/pipelines#transformers.pipeline.task). + In this dictionary, you can also include `model_kwargs` to specify the kwargs for [model initialization](https://huggingface.co/docs/transformers/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) + :param stop_words: A list of stop words. If the model generates a stop word, the generation stops. + If you provide this parameter, don't specify the `stopping_criteria` in `generation_kwargs`. + For some chat models, the output includes both the new text and the original prompt. + In these cases, make sure your prompt has no stop words. + :param streaming_callback: An optional callable for handling streaming responses. + """ + torch_and_transformers_import.check() + + huggingface_pipeline_kwargs = huggingface_pipeline_kwargs or {} + generation_kwargs = generation_kwargs or {} + + self.token = token + token = token.resolve_value() if token else None + + # check if the huggingface_pipeline_kwargs contain the essential parameters + # otherwise, populate them with values from other init parameters + huggingface_pipeline_kwargs.setdefault("model", model) + huggingface_pipeline_kwargs.setdefault("token", token) + + device = ComponentDevice.resolve_device(device) + device.update_hf_kwargs(huggingface_pipeline_kwargs, overwrite=False) + + # task identification and validation + if task is None: + if "task" in huggingface_pipeline_kwargs: + task = huggingface_pipeline_kwargs["task"] + elif isinstance(huggingface_pipeline_kwargs["model"], str): + task = model_info( + huggingface_pipeline_kwargs["model"], token=huggingface_pipeline_kwargs["token"] + ).pipeline_tag + + if task not in PIPELINE_SUPPORTED_TASKS: + raise ValueError( + f"Task '{task}' is not supported. " f"The supported tasks are: {', '.join(PIPELINE_SUPPORTED_TASKS)}." + ) + huggingface_pipeline_kwargs["task"] = task + + # if not specified, set return_full_text to False for text-generation + # only generated text is returned (excluding prompt) + if task == "text-generation": + generation_kwargs.setdefault("return_full_text", False) + + if stop_words and "stopping_criteria" in generation_kwargs: + raise ValueError( + "Found both the `stop_words` init parameter and the `stopping_criteria` key in `generation_kwargs`. " + "Please specify only one of them." + ) + generation_kwargs.setdefault("max_new_tokens", 512) + generation_kwargs["stop_sequences"] = generation_kwargs.get("stop_sequences", []) + generation_kwargs["stop_sequences"].extend(stop_words or []) + + self.huggingface_pipeline_kwargs = huggingface_pipeline_kwargs + self.generation_kwargs = generation_kwargs + self.chat_template = chat_template + self.streaming_callback = streaming_callback + self.pipeline = None + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + if isinstance(self.huggingface_pipeline_kwargs["model"], str): + return {"model": self.huggingface_pipeline_kwargs["model"]} + return {"model": f"[object of type {type(self.huggingface_pipeline_kwargs['model'])}]"} + + def warm_up(self): + """ + Initializes the component. + """ + if self.pipeline is None: + self.pipeline = pipeline(**self.huggingface_pipeline_kwargs) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None + serialization_dict = default_to_dict( + self, + huggingface_pipeline_kwargs=self.huggingface_pipeline_kwargs, + generation_kwargs=self.generation_kwargs, + streaming_callback=callback_name, + token=self.token.to_dict() if self.token else None, + ) + + huggingface_pipeline_kwargs = serialization_dict["init_parameters"]["huggingface_pipeline_kwargs"] + huggingface_pipeline_kwargs.pop("token", None) + + serialize_hf_model_kwargs(huggingface_pipeline_kwargs) + return serialization_dict + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "HuggingFaceLocalChatGenerator": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + torch_and_transformers_import.check() # leave this, cls method + deserialize_secrets_inplace(data["init_parameters"], keys=["token"]) + init_params = data.get("init_parameters", {}) + serialized_callback_handler = init_params.get("streaming_callback") + if serialized_callback_handler: + data["init_parameters"]["streaming_callback"] = deserialize_callable(serialized_callback_handler) + + huggingface_pipeline_kwargs = init_params.get("huggingface_pipeline_kwargs", {}) + deserialize_hf_model_kwargs(huggingface_pipeline_kwargs) + return default_from_dict(cls, data) + + @component.output_types(replies=List[ChatMessage]) + def run(self, messages: List[ChatMessage], generation_kwargs: Optional[Dict[str, Any]] = None): + """ + Invoke text generation inference based on the provided messages and generation parameters. + + :param messages: A list of ChatMessage objects representing the input messages. + :param generation_kwargs: Additional keyword arguments for text generation. + :returns: + A list containing the generated responses as ChatMessage instances. + """ + if self.pipeline is None: + raise RuntimeError("The generation model has not been loaded. Please call warm_up() before running.") + + tokenizer = self.pipeline.tokenizer + + # Check and update generation parameters + generation_kwargs = {**self.generation_kwargs, **(generation_kwargs or {})} + + stop_words = generation_kwargs.pop("stop_words", []) + generation_kwargs.pop("stop_sequences", []) + # pipeline call doesn't support stop_sequences, so we need to pop it + stop_words = self._validate_stop_words(stop_words) + + # Set up stop words criteria if stop words exist + stop_words_criteria = StopWordsCriteria(tokenizer, stop_words, self.pipeline.device) if stop_words else None + if stop_words_criteria: + generation_kwargs["stopping_criteria"] = StoppingCriteriaList([stop_words_criteria]) + + if self.streaming_callback: + num_responses = generation_kwargs.get("num_return_sequences", 1) + if num_responses > 1: + msg = ( + "Streaming is enabled, but the number of responses is set to {num_responses}. " + "Streaming is only supported for single response generation. " + "Setting the number of responses to 1." + ) + logger.warning(msg, num_responses=num_responses) + generation_kwargs["num_return_sequences"] = 1 + # streamer parameter hooks into HF streaming, HFTokenStreamingHandler is an adapter to our streaming + generation_kwargs["streamer"] = HFTokenStreamingHandler(tokenizer, self.streaming_callback, stop_words) + + # Prepare the prompt for the model + prepared_prompt = tokenizer.apply_chat_template( + messages, tokenize=False, chat_template=self.chat_template, add_generation_prompt=True + ) + + # Avoid some unnecessary warnings in the generation pipeline call + generation_kwargs["pad_token_id"] = ( + generation_kwargs.get("pad_token_id", tokenizer.pad_token_id) or tokenizer.eos_token_id + ) + + # Generate responses + output = self.pipeline(prepared_prompt, **generation_kwargs) + replies = [o.get("generated_text", "") for o in output] + + # Remove stop words from replies if present + for stop_word in stop_words: + replies = [reply.replace(stop_word, "").rstrip() for reply in replies] + + # Create ChatMessage instances for each reply + chat_messages = [ + self.create_message(reply, r_index, tokenizer, prepared_prompt, generation_kwargs) + for r_index, reply in enumerate(replies) + ] + return {"replies": chat_messages} + + def create_message( + self, + text: str, + index: int, + tokenizer: Union["PreTrainedTokenizer", "PreTrainedTokenizerFast"], + prompt: str, + generation_kwargs: Dict[str, Any], + ) -> ChatMessage: + """ + Create a ChatMessage instance from the provided text, populated with metadata. + + :param text: The generated text. + :param index: The index of the generated text. + :param tokenizer: The tokenizer used for generation. + :param prompt: The prompt used for generation. + :param generation_kwargs: The generation parameters. + :returns: A ChatMessage instance. + """ + completion_tokens = len(tokenizer.encode(text, add_special_tokens=False)) + prompt_token_count = len(tokenizer.encode(prompt, add_special_tokens=False)) + total_tokens = prompt_token_count + completion_tokens + + # not the most sophisticated finish_reason detection, improve later to match + # https://platform.openai.com/docs/guides/text-generation/chat-completions-response-format + finish_reason = ( + "length" if completion_tokens >= generation_kwargs.get("max_new_tokens", sys.maxsize) else "stop" + ) + + meta = { + "finish_reason": finish_reason, + "index": index, + "model": self.huggingface_pipeline_kwargs["model"], + "usage": { + "completion_tokens": completion_tokens, + "prompt_tokens": prompt_token_count, + "total_tokens": total_tokens, + }, + } + + return ChatMessage.from_assistant(text, meta=meta) + + def _validate_stop_words(self, stop_words: Optional[List[str]]) -> Optional[List[str]]: + """ + Validates the provided stop words. + + :param stop_words: A list of stop words to validate. + :return: A sanitized list of stop words or None if validation fails. + """ + if stop_words and not all(isinstance(word, str) for word in stop_words): + logger.warning( + "Invalid stop words provided. Stop words must be specified as a list of strings. " + "Ignoring stop words: {stop_words}", + stop_words=stop_words, + ) + return None + + # deduplicate stop words + stop_words = list(set(stop_words or [])) + return stop_words diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/chat/openai.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/chat/openai.py new file mode 100644 index 0000000000000000000000000000000000000000..8f54b7ad36e2b5651def8ec569eb6bee5f47b49c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/chat/openai.py @@ -0,0 +1,370 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import copy +import json +import os +from typing import Any, Callable, Dict, List, Optional, Union + +from openai import OpenAI, Stream +from openai.types.chat import ChatCompletion, ChatCompletionChunk, ChatCompletionMessage +from openai.types.chat.chat_completion import Choice +from openai.types.chat.chat_completion_chunk import Choice as ChunkChoice + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.components.generators.openai_utils import _convert_message_to_openai_format +from haystack.dataclasses import ChatMessage, StreamingChunk +from haystack.utils import Secret, deserialize_callable, deserialize_secrets_inplace, serialize_callable + +logger = logging.getLogger(__name__) + + +@component +class OpenAIChatGenerator: + """ + Completes chats using OpenAI's large language models (LLMs). + + It works with the gpt-4 and gpt-3.5-turbo models and supports streaming responses + from OpenAI API. It uses [ChatMessage](https://docs.haystack.deepset.ai/docs/data-classes#chatmessage) + format in input and output. + + You can customize how the text is generated by passing parameters to the + OpenAI API. Use the `**generation_kwargs` argument when you initialize + the component or when you run it. Any parameter that works with + `openai.ChatCompletion.create` will work here too. + + For details on OpenAI API parameters, see + [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat). + + ### Usage example + + ```python + from haystack.components.generators.chat import OpenAIChatGenerator + from haystack.dataclasses import ChatMessage + + messages = [ChatMessage.from_user("What's Natural Language Processing?")] + + client = OpenAIChatGenerator() + response = client.run(messages) + print(response) + ``` + Output: + ``` + {'replies': + [ChatMessage(content='Natural Language Processing (NLP) is a branch of artificial intelligence + that focuses on enabling computers to understand, interpret, and generate human language in + a way that is meaningful and useful.', + role=, name=None, + meta={'model': 'gpt-4o-mini', 'index': 0, 'finish_reason': 'stop', + 'usage': {'prompt_tokens': 15, 'completion_tokens': 36, 'total_tokens': 51}}) + ] + } + ``` + """ + + def __init__( + self, + api_key: Secret = Secret.from_env_var("OPENAI_API_KEY"), + model: str = "gpt-4o-mini", + streaming_callback: Optional[Callable[[StreamingChunk], None]] = None, + api_base_url: Optional[str] = None, + organization: Optional[str] = None, + generation_kwargs: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + max_retries: Optional[int] = None, + ): + """ + Creates an instance of OpenAIChatGenerator. Unless specified otherwise in `model`, uses OpenAI's gpt-4o-mini + + Before initializing the component, you can set the 'OPENAI_TIMEOUT' and 'OPENAI_MAX_RETRIES' + environment variables to override the `timeout` and `max_retries` parameters respectively + in the OpenAI client. + + :param api_key: The OpenAI API key. + You can set it with an environment variable `OPENAI_API_KEY`, or pass with this parameter + during initialization. + :param model: The name of the model to use. + :param streaming_callback: A callback function that is called when a new token is received from the stream. + The callback function accepts [StreamingChunk](https://docs.haystack.deepset.ai/docs/data-classes#streamingchunk) + as an argument. + :param api_base_url: An optional base URL. + :param organization: Your organization ID, defaults to `None`. See + [production best practices](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization). + :param generation_kwargs: Other parameters to use for the model. These parameters are sent directly to + the OpenAI endpoint. See OpenAI [documentation](https://platform.openai.com/docs/api-reference/chat) for + more details. + Some of the supported parameters: + - `max_tokens`: The maximum number of tokens the output text can have. + - `temperature`: What sampling temperature to use. Higher values mean the model will take more risks. + Try 0.9 for more creative applications and 0 (argmax sampling) for ones with a well-defined answer. + - `top_p`: An alternative to sampling with temperature, called nucleus sampling, where the model + considers the results of the tokens with top_p probability mass. For example, 0.1 means only the tokens + comprising the top 10% probability mass are considered. + - `n`: How many completions to generate for each prompt. For example, if the LLM gets 3 prompts and n is 2, + it will generate two completions for each of the three prompts, ending up with 6 completions in total. + - `stop`: One or more sequences after which the LLM should stop generating tokens. + - `presence_penalty`: What penalty to apply if a token is already present at all. Bigger values mean + the model will be less likely to repeat the same token in the text. + - `frequency_penalty`: What penalty to apply if a token has already been generated in the text. + Bigger values mean the model will be less likely to repeat the same token in the text. + - `logit_bias`: Add a logit bias to specific tokens. The keys of the dictionary are tokens, and the + values are the bias to add to that token. + :param timeout: + Timeout for OpenAI client calls. If not set, it defaults to either the + `OPENAI_TIMEOUT` environment variable, or 30 seconds. + :param max_retries: + Maximum number of retries to contact OpenAI after an internal error. + If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5. + """ + self.api_key = api_key + self.model = model + self.generation_kwargs = generation_kwargs or {} + self.streaming_callback = streaming_callback + self.api_base_url = api_base_url + self.organization = organization + + if timeout is None: + timeout = float(os.environ.get("OPENAI_TIMEOUT", 30.0)) + if max_retries is None: + max_retries = int(os.environ.get("OPENAI_MAX_RETRIES", 5)) + + self.client = OpenAI( + api_key=api_key.resolve_value(), + organization=organization, + base_url=api_base_url, + timeout=timeout, + max_retries=max_retries, + ) + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"model": self.model} + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + + :returns: + The serialized component as a dictionary. + """ + callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None + return default_to_dict( + self, + model=self.model, + streaming_callback=callback_name, + api_base_url=self.api_base_url, + organization=self.organization, + generation_kwargs=self.generation_kwargs, + api_key=self.api_key.to_dict(), + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "OpenAIChatGenerator": + """ + Deserialize this component from a dictionary. + + :param data: The dictionary representation of this component. + :returns: + The deserialized component instance. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + init_params = data.get("init_parameters", {}) + serialized_callback_handler = init_params.get("streaming_callback") + if serialized_callback_handler: + data["init_parameters"]["streaming_callback"] = deserialize_callable(serialized_callback_handler) + return default_from_dict(cls, data) + + @component.output_types(replies=List[ChatMessage]) + def run( + self, + messages: List[ChatMessage], + streaming_callback: Optional[Callable[[StreamingChunk], None]] = None, + generation_kwargs: Optional[Dict[str, Any]] = None, + ): + """ + Invokes chat completion based on the provided messages and generation parameters. + + :param messages: A list of ChatMessage instances representing the input messages. + :param streaming_callback: A callback function that is called when a new token is received from the stream. + :param generation_kwargs: Additional keyword arguments for text generation. These parameters will + override the parameters passed during component initialization. + For details on OpenAI API parameters, see + [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat/create). + + :returns: + A list containing the generated responses as ChatMessage instances. + """ + + # update generation kwargs by merging with the generation kwargs passed to the run method + generation_kwargs = {**self.generation_kwargs, **(generation_kwargs or {})} + + # check if streaming_callback is passed + streaming_callback = streaming_callback or self.streaming_callback + + # adapt ChatMessage(s) to the format expected by the OpenAI API + openai_formatted_messages = [_convert_message_to_openai_format(message) for message in messages] + + chat_completion: Union[Stream[ChatCompletionChunk], ChatCompletion] = self.client.chat.completions.create( + model=self.model, + messages=openai_formatted_messages, # type: ignore # openai expects list of specific message types + stream=streaming_callback is not None, + **generation_kwargs, + ) + + completions: List[ChatMessage] = [] + # if streaming is enabled, the completion is a Stream of ChatCompletionChunk + if isinstance(chat_completion, Stream): + num_responses = generation_kwargs.pop("n", 1) + if num_responses > 1: + raise ValueError("Cannot stream multiple responses, please set n=1.") + chunks: List[StreamingChunk] = [] + chunk = None + + # pylint: disable=not-an-iterable + for chunk in chat_completion: + if chunk.choices and streaming_callback: + chunk_delta: StreamingChunk = self._build_chunk(chunk) + chunks.append(chunk_delta) + streaming_callback(chunk_delta) # invoke callback with the chunk_delta + completions = [self._connect_chunks(chunk, chunks)] + # if streaming is disabled, the completion is a ChatCompletion + elif isinstance(chat_completion, ChatCompletion): + completions = [self._build_message(chat_completion, choice) for choice in chat_completion.choices] + + # before returning, do post-processing of the completions + for message in completions: + self._check_finish_reason(message) + + return {"replies": completions} + + def _connect_chunks(self, chunk: Any, chunks: List[StreamingChunk]) -> ChatMessage: + """ + Connects the streaming chunks into a single ChatMessage. + + :param chunk: The last chunk returned by the OpenAI API. + :param chunks: The list of all chunks returned by the OpenAI API. + """ + is_tools_call = bool(chunks[0].meta.get("tool_calls")) + is_function_call = bool(chunks[0].meta.get("function_call")) + # if it's a tool call or function call, we need to build the payload dict from all the chunks + if is_tools_call or is_function_call: + tools_len = 1 if is_function_call else len(chunks[0].meta.get("tool_calls", [])) + # don't change this approach of building payload dicts, otherwise mypy will complain + p_def: Dict[str, Any] = { + "index": 0, + "id": "", + "function": {"arguments": "", "name": ""}, + "type": "function", + } + payloads = [copy.deepcopy(p_def) for _ in range(tools_len)] + for chunk_payload in chunks: + if is_tools_call: + deltas = chunk_payload.meta.get("tool_calls") or [] + else: + deltas = [chunk_payload.meta["function_call"]] if chunk_payload.meta.get("function_call") else [] + + # deltas is a list of ChoiceDeltaToolCall or ChoiceDeltaFunctionCall + for i, delta in enumerate(deltas): + payload = payloads[i] + if is_tools_call: + payload["id"] = delta.id or payload["id"] + payload["type"] = delta.type or payload["type"] + if delta.function: + payload["function"]["name"] += delta.function.name or "" + payload["function"]["arguments"] += delta.function.arguments or "" + elif is_function_call: + payload["function"]["name"] += delta.name or "" + payload["function"]["arguments"] += delta.arguments or "" + complete_response = ChatMessage.from_assistant(json.dumps(payloads)) + else: + complete_response = ChatMessage.from_assistant("".join([chunk.content for chunk in chunks])) + complete_response.meta.update( + { + "model": chunk.model, + "index": 0, + "finish_reason": chunk.choices[0].finish_reason, + "usage": {}, # we don't have usage data for streaming responses + } + ) + return complete_response + + def _build_message(self, completion: ChatCompletion, choice: Choice) -> ChatMessage: + """ + Converts the non-streaming response from the OpenAI API to a ChatMessage. + + :param completion: The completion returned by the OpenAI API. + :param choice: The choice returned by the OpenAI API. + :return: The ChatMessage. + """ + message: ChatCompletionMessage = choice.message + content = message.content or "" + if message.function_call: + # here we mimic the tools format response so that if user passes deprecated `functions` parameter + # she'll get the same output as if new `tools` parameter was passed + # use pydantic model dump to serialize the function call + content = json.dumps( + [{"function": message.function_call.model_dump(), "type": "function", "id": completion.id}] + ) + elif message.tool_calls: + # new `tools` parameter was passed, use pydantic model dump to serialize the tool calls + content = json.dumps([tc.model_dump() for tc in message.tool_calls]) + + chat_message = ChatMessage.from_assistant(content) + chat_message.meta.update( + { + "model": completion.model, + "index": choice.index, + "finish_reason": choice.finish_reason, + "usage": dict(completion.usage or {}), + } + ) + return chat_message + + def _build_chunk(self, chunk: ChatCompletionChunk) -> StreamingChunk: + """ + Converts the streaming response chunk from the OpenAI API to a StreamingChunk. + + :param chunk: The chunk returned by the OpenAI API. + :param choice: The choice returned by the OpenAI API. + :return: The StreamingChunk. + """ + # we stream the content of the chunk if it's not a tool or function call + choice: ChunkChoice = chunk.choices[0] + content = choice.delta.content or "" + chunk_message = StreamingChunk(content) + # but save the tool calls and function call in the meta if they are present + # and then connect the chunks in the _connect_chunks method + chunk_message.meta.update( + { + "model": chunk.model, + "index": choice.index, + "tool_calls": choice.delta.tool_calls, + "function_call": choice.delta.function_call, + "finish_reason": choice.finish_reason, + } + ) + return chunk_message + + def _check_finish_reason(self, message: ChatMessage) -> None: + """ + Check the `finish_reason` returned with the OpenAI completions. + + If the `finish_reason` is `length` or `content_filter`, log a warning. + :param message: The message returned by the LLM. + """ + if message.meta["finish_reason"] == "length": + logger.warning( + "The completion for index {index} has been truncated before reaching a natural stopping point. " + "Increase the max_tokens parameter to allow for longer completions.", + index=message.meta["index"], + finish_reason=message.meta["finish_reason"], + ) + if message.meta["finish_reason"] == "content_filter": + logger.warning( + "The completion for index {index} has been truncated due to the content filter.", + index=message.meta["index"], + finish_reason=message.meta["finish_reason"], + ) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/hugging_face_api.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/hugging_face_api.py new file mode 100644 index 0000000000000000000000000000000000000000..8fe38c0138823d8728ec48f26074315c59501b45 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/hugging_face_api.py @@ -0,0 +1,232 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import asdict +from typing import Any, Callable, Dict, Iterable, List, Optional, Union + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.dataclasses import StreamingChunk +from haystack.lazy_imports import LazyImport +from haystack.utils import Secret, deserialize_callable, deserialize_secrets_inplace, serialize_callable +from haystack.utils.hf import HFGenerationAPIType, HFModelType, check_valid_model +from haystack.utils.url_validation import is_valid_http_url + +with LazyImport(message="Run 'pip install \"huggingface_hub>=0.23.0\"'") as huggingface_hub_import: + from huggingface_hub import ( + InferenceClient, + TextGenerationOutput, + TextGenerationOutputToken, + TextGenerationStreamOutput, + ) + + +logger = logging.getLogger(__name__) + + +@component +class HuggingFaceAPIGenerator: + """ + Generates text using Hugging Face APIs. + + Use it with the following Hugging Face APIs: + - [Free Serverless Inference API]((https://huggingface.co/inference-api) + - [Paid Inference Endpoints](https://huggingface.co/inference-endpoints) + - [Self-hosted Text Generation Inference](https://github.com/huggingface/text-generation-inference) + + ### Usage examples + + #### With the free serverless inference API + + ```python + from haystack.components.generators import HuggingFaceAPIGenerator + from haystack.utils import Secret + + generator = HuggingFaceAPIGenerator(api_type="serverless_inference_api", + api_params={"model": "HuggingFaceH4/zephyr-7b-beta"}, + token=Secret.from_token("")) + + result = generator.run(prompt="What's Natural Language Processing?") + print(result) + ``` + + #### With paid inference endpoints + + ```python + from haystack.components.generators import HuggingFaceAPIGenerator + from haystack.utils import Secret + + generator = HuggingFaceAPIGenerator(api_type="inference_endpoints", + api_params={"url": ""}, + token=Secret.from_token("")) + + result = generator.run(prompt="What's Natural Language Processing?") + print(result) + + #### With self-hosted text generation inference + ```python + from haystack.components.generators import HuggingFaceAPIGenerator + + generator = HuggingFaceAPIGenerator(api_type="text_generation_inference", + api_params={"url": "http://localhost:8080"}) + + result = generator.run(prompt="What's Natural Language Processing?") + print(result) + ``` + """ + + def __init__( + self, + api_type: Union[HFGenerationAPIType, str], + api_params: Dict[str, str], + token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + generation_kwargs: Optional[Dict[str, Any]] = None, + stop_words: Optional[List[str]] = None, + streaming_callback: Optional[Callable[[StreamingChunk], None]] = None, + ): + """ + Initialize the HuggingFaceAPIGenerator instance. + + :param api_type: + The type of Hugging Face API to use. Available types: + - `text_generation_inference`: See [TGI](https://github.com/huggingface/text-generation-inference). + - `inference_endpoints`: See [Inference Endpoints](https://huggingface.co/inference-endpoints). + - `serverless_inference_api`: See [Serverless Inference API](https://huggingface.co/inference-api). + :param api_params: + A dictionary with the following keys: + - `model`: Hugging Face model ID. Required when `api_type` is `SERVERLESS_INFERENCE_API`. + - `url`: URL of the inference endpoint. Required when `api_type` is `INFERENCE_ENDPOINTS` or + `TEXT_GENERATION_INFERENCE`. + :param token: The Hugging Face token to use as HTTP bearer authorization. + Check your HF token in your [account settings](https://huggingface.co/settings/tokens). + :param generation_kwargs: + A dictionary with keyword arguments to customize text generation. Some examples: `max_new_tokens`, + `temperature`, `top_k`, `top_p`. + For details, see [Hugging Face documentation](https://huggingface.co/docs/huggingface_hub/en/package_reference/inference_client#huggingface_hub.InferenceClient.text_generation) + for more information. + :param stop_words: An optional list of strings representing the stop words. + :param streaming_callback: An optional callable for handling streaming responses. + """ + + huggingface_hub_import.check() + + if isinstance(api_type, str): + api_type = HFGenerationAPIType.from_str(api_type) + + if api_type == HFGenerationAPIType.SERVERLESS_INFERENCE_API: + model = api_params.get("model") + if model is None: + raise ValueError( + "To use the Serverless Inference API, you need to specify the `model` parameter in `api_params`." + ) + check_valid_model(model, HFModelType.GENERATION, token) + model_or_url = model + elif api_type in [HFGenerationAPIType.INFERENCE_ENDPOINTS, HFGenerationAPIType.TEXT_GENERATION_INFERENCE]: + url = api_params.get("url") + if url is None: + msg = ( + "To use Text Generation Inference or Inference Endpoints, you need to specify the `url` " + "parameter in `api_params`." + ) + raise ValueError(msg) + if not is_valid_http_url(url): + raise ValueError(f"Invalid URL: {url}") + model_or_url = url + else: + msg = f"Unknown api_type {api_type}" + raise ValueError(api_type) + + # handle generation kwargs setup + generation_kwargs = generation_kwargs.copy() if generation_kwargs else {} + generation_kwargs["stop_sequences"] = generation_kwargs.get("stop_sequences", []) + generation_kwargs["stop_sequences"].extend(stop_words or []) + generation_kwargs.setdefault("max_new_tokens", 512) + + self.api_type = api_type + self.api_params = api_params + self.token = token + self.generation_kwargs = generation_kwargs + self.streaming_callback = streaming_callback + self._client = InferenceClient(model_or_url, token=token.resolve_value() if token else None) + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + + :returns: + A dictionary containing the serialized component. + """ + callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None + return default_to_dict( + self, + api_type=str(self.api_type), + api_params=self.api_params, + token=self.token.to_dict() if self.token else None, + generation_kwargs=self.generation_kwargs, + streaming_callback=callback_name, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "HuggingFaceAPIGenerator": + """ + Deserialize this component from a dictionary. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["token"]) + init_params = data["init_parameters"] + serialized_callback_handler = init_params.get("streaming_callback") + if serialized_callback_handler: + init_params["streaming_callback"] = deserialize_callable(serialized_callback_handler) + return default_from_dict(cls, data) + + @component.output_types(replies=List[str], meta=List[Dict[str, Any]]) + def run(self, prompt: str, generation_kwargs: Optional[Dict[str, Any]] = None): + """ + Invoke the text generation inference for the given prompt and generation parameters. + + :param prompt: + A string representing the prompt. + :param generation_kwargs: + Additional keyword arguments for text generation. + :returns: + A dictionary with the generated replies and metadata. Both are lists of length n. + - replies: A list of strings representing the generated replies. + """ + # update generation kwargs by merging with the default ones + generation_kwargs = {**self.generation_kwargs, **(generation_kwargs or {})} + + if self.streaming_callback: + return self._run_streaming(prompt, generation_kwargs) + + return self._run_non_streaming(prompt, generation_kwargs) + + def _run_streaming(self, prompt: str, generation_kwargs: Dict[str, Any]): + res_chunk: Iterable[TextGenerationStreamOutput] = self._client.text_generation( + prompt, details=True, stream=True, **generation_kwargs + ) + chunks: List[StreamingChunk] = [] + # pylint: disable=not-an-iterable + for chunk in res_chunk: + token: TextGenerationOutputToken = chunk.token + if token.special: + continue + chunk_metadata = {**asdict(token), **(asdict(chunk.details) if chunk.details else {})} + stream_chunk = StreamingChunk(token.text, chunk_metadata) + chunks.append(stream_chunk) + self.streaming_callback(stream_chunk) # type: ignore # streaming_callback is not None (verified in the run method) + metadata = { + "finish_reason": chunks[-1].meta.get("finish_reason", None), + "model": self._client.model, + "usage": {"completion_tokens": chunks[-1].meta.get("generated_tokens", 0)}, + } + return {"replies": ["".join([chunk.content for chunk in chunks])], "meta": [metadata]} + + def _run_non_streaming(self, prompt: str, generation_kwargs: Dict[str, Any]): + tgr: TextGenerationOutput = self._client.text_generation(prompt, details=True, **generation_kwargs) + meta = [ + { + "model": self._client.model, + "finish_reason": tgr.details.finish_reason if tgr.details else None, + "usage": {"completion_tokens": len(tgr.details.tokens) if tgr.details else 0}, + } + ] + return {"replies": [tgr.generated_text], "meta": meta} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/hugging_face_local.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/hugging_face_local.py new file mode 100644 index 0000000000000000000000000000000000000000..178548c61038594c146c074be13b7595305ffeb3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/hugging_face_local.py @@ -0,0 +1,255 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Callable, Dict, List, Literal, Optional + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.dataclasses import StreamingChunk +from haystack.lazy_imports import LazyImport +from haystack.utils import ( + ComponentDevice, + Secret, + deserialize_callable, + deserialize_secrets_inplace, + serialize_callable, +) +from haystack.utils.hf import deserialize_hf_model_kwargs, serialize_hf_model_kwargs + +logger = logging.getLogger(__name__) + +SUPPORTED_TASKS = ["text-generation", "text2text-generation"] + +with LazyImport(message="Run 'pip install \"transformers[torch]\"'") as transformers_import: + from transformers import StoppingCriteriaList, pipeline + + from haystack.utils.hf import ( # pylint: disable=ungrouped-imports + HFTokenStreamingHandler, + StopWordsCriteria, + resolve_hf_pipeline_kwargs, + ) + + +@component +class HuggingFaceLocalGenerator: + """ + Generates text using models from Hugging Face that run locally. + + LLMs running locally may need powerful hardware. + + ### Usage example + + ```python + from haystack.components.generators import HuggingFaceLocalGenerator + + generator = HuggingFaceLocalGenerator( + model="google/flan-t5-large", + task="text2text-generation", + generation_kwargs={"max_new_tokens": 100, "temperature": 0.9}) + + generator.warm_up() + + print(generator.run("Who is the best American actor?")) + # {'replies': ['John Cusack']} + ``` + """ + + def __init__( + self, + model: str = "google/flan-t5-base", + task: Optional[Literal["text-generation", "text2text-generation"]] = None, + device: Optional[ComponentDevice] = None, + token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + generation_kwargs: Optional[Dict[str, Any]] = None, + huggingface_pipeline_kwargs: Optional[Dict[str, Any]] = None, + stop_words: Optional[List[str]] = None, + streaming_callback: Optional[Callable[[StreamingChunk], None]] = None, + ): + """ + Creates an instance of a HuggingFaceLocalGenerator. + + :param model: The Hugging Face text generation model name or path. + :param task: The task for the Hugging Face pipeline. Possible options: + - `text-generation`: Supported by decoder models, like GPT. + - `text2text-generation`: Supported by encoder-decoder models, like T5. + If the task is specified in `huggingface_pipeline_kwargs`, this parameter is ignored. + If not specified, the component calls the Hugging Face API to infer the task from the model name. + :param device: The device for loading the model. If `None`, automatically selects the default device. + If a device or device map is specified in `huggingface_pipeline_kwargs`, it overrides this parameter. + :param token: The token to use as HTTP bearer authorization for remote files. + If the token is specified in `huggingface_pipeline_kwargs`, this parameter is ignored. + :param generation_kwargs: A dictionary with keyword arguments to customize text generation. + Some examples: `max_length`, `max_new_tokens`, `temperature`, `top_k`, `top_p`. + See Hugging Face's documentation for more information: + - [customize-text-generation](https://huggingface.co/docs/transformers/main/en/generation_strategies#customize-text-generation) + - [transformers.GenerationConfig](https://huggingface.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationConfig) + :param huggingface_pipeline_kwargs: Dictionary with keyword arguments to initialize the + Hugging Face pipeline for text generation. + These keyword arguments provide fine-grained control over the Hugging Face pipeline. + In case of duplication, these kwargs override `model`, `task`, `device`, and `token` init parameters. + For available kwargs, see [Hugging Face documentation](https://huggingface.co/docs/transformers/en/main_classes/pipelines#transformers.pipeline.task). + In this dictionary, you can also include `model_kwargs` to specify the kwargs for model initialization: + [transformers.PreTrainedModel.from_pretrained](https://huggingface.co/docs/transformers/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) + :param stop_words: If the model generates a stop word, the generation stops. + If you provide this parameter, don't specify the `stopping_criteria` in `generation_kwargs`. + For some chat models, the output includes both the new text and the original prompt. + In these cases, make sure your prompt has no stop words. + :param streaming_callback: An optional callable for handling streaming responses. + """ + transformers_import.check() + + self.token = token + generation_kwargs = generation_kwargs or {} + + huggingface_pipeline_kwargs = resolve_hf_pipeline_kwargs( + huggingface_pipeline_kwargs=huggingface_pipeline_kwargs or {}, + model=model, + task=task, + supported_tasks=SUPPORTED_TASKS, + device=device, + token=token, + ) + + # if not specified, set return_full_text to False for text-generation + # only generated text is returned (excluding prompt) + task = huggingface_pipeline_kwargs["task"] + if task == "text-generation": + generation_kwargs.setdefault("return_full_text", False) + + if stop_words and "stopping_criteria" in generation_kwargs: + raise ValueError( + "Found both the `stop_words` init parameter and the `stopping_criteria` key in `generation_kwargs`. " + "Please specify only one of them." + ) + generation_kwargs.setdefault("max_new_tokens", 512) + + self.huggingface_pipeline_kwargs = huggingface_pipeline_kwargs + self.generation_kwargs = generation_kwargs + self.stop_words = stop_words + self.pipeline = None + self.stopping_criteria_list = None + self.streaming_callback = streaming_callback + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + if isinstance(self.huggingface_pipeline_kwargs["model"], str): + return {"model": self.huggingface_pipeline_kwargs["model"]} + return {"model": f"[object of type {type(self.huggingface_pipeline_kwargs['model'])}]"} + + @property + def _warmed_up(self) -> bool: + if self.stop_words: + return (self.pipeline is not None) and (self.stopping_criteria_list is not None) + return self.pipeline is not None + + def warm_up(self): + """ + Initializes the component. + """ + if self._warmed_up: + return + + if self.pipeline is None: + self.pipeline = pipeline(**self.huggingface_pipeline_kwargs) + + if self.stop_words: + stop_words_criteria = StopWordsCriteria( + tokenizer=self.pipeline.tokenizer, stop_words=self.stop_words, device=self.pipeline.device + ) + self.stopping_criteria_list = StoppingCriteriaList([stop_words_criteria]) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None + serialization_dict = default_to_dict( + self, + huggingface_pipeline_kwargs=self.huggingface_pipeline_kwargs, + generation_kwargs=self.generation_kwargs, + streaming_callback=callback_name, + stop_words=self.stop_words, + token=self.token.to_dict() if self.token else None, + ) + + huggingface_pipeline_kwargs = serialization_dict["init_parameters"]["huggingface_pipeline_kwargs"] + huggingface_pipeline_kwargs.pop("token", None) + + serialize_hf_model_kwargs(huggingface_pipeline_kwargs) + return serialization_dict + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "HuggingFaceLocalGenerator": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["token"]) + init_params = data.get("init_parameters", {}) + serialized_callback_handler = init_params.get("streaming_callback") + if serialized_callback_handler: + data["init_parameters"]["streaming_callback"] = deserialize_callable(serialized_callback_handler) + + huggingface_pipeline_kwargs = init_params.get("huggingface_pipeline_kwargs", {}) + deserialize_hf_model_kwargs(huggingface_pipeline_kwargs) + return default_from_dict(cls, data) + + @component.output_types(replies=List[str]) + def run(self, prompt: str, generation_kwargs: Optional[Dict[str, Any]] = None): + """ + Run the text generation model on the given prompt. + + :param prompt: + A string representing the prompt. + :param generation_kwargs: + Additional keyword arguments for text generation. + + :returns: + A dictionary containing the generated replies. + - replies: A list of strings representing the generated replies. + """ + if not self._warmed_up: + raise RuntimeError( + "The component HuggingFaceLocalGenerator was not warmed up. Please call warm_up() before running." + ) + + if not prompt: + return {"replies": []} + + # merge generation kwargs from init method with those from run method + updated_generation_kwargs = {**self.generation_kwargs, **(generation_kwargs or {})} + + if self.streaming_callback: + num_responses = updated_generation_kwargs.get("num_return_sequences", 1) + if num_responses > 1: + msg = ( + "Streaming is enabled, but the number of responses is set to {num_responses}. " + "Streaming is only supported for single response generation. " + "Setting the number of responses to 1." + ) + logger.warning(msg, num_responses=num_responses) + updated_generation_kwargs["num_return_sequences"] = 1 + # streamer parameter hooks into HF streaming, HFTokenStreamingHandler is an adapter to our streaming + updated_generation_kwargs["streamer"] = HFTokenStreamingHandler( + self.pipeline.tokenizer, # type: ignore + self.streaming_callback, + self.stop_words, # type: ignore + ) + + output = self.pipeline(prompt, stopping_criteria=self.stopping_criteria_list, **updated_generation_kwargs) # type: ignore + replies = [o["generated_text"] for o in output if "generated_text" in o] + + if self.stop_words: + # the output of the pipeline includes the stop word + replies = [reply.replace(stop_word, "").rstrip() for reply in replies for stop_word in self.stop_words] + + return {"replies": replies} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/openai.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/openai.py new file mode 100644 index 0000000000000000000000000000000000000000..48180fc3217945a730b0db9f2772edc81b26b78f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/openai.py @@ -0,0 +1,327 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +from typing import Any, Callable, Dict, List, Optional, Union + +from openai import OpenAI, Stream +from openai.types.chat import ChatCompletion, ChatCompletionChunk + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.components.generators.openai_utils import _convert_message_to_openai_format +from haystack.dataclasses import ChatMessage, StreamingChunk +from haystack.utils import Secret, deserialize_callable, deserialize_secrets_inplace, serialize_callable + +logger = logging.getLogger(__name__) + + +@component +class OpenAIGenerator: + """ + Generates text using OpenAI's large language models (LLMs). + + It works with the gpt-4 and gpt-3.5-turbo models and supports streaming responses + from OpenAI API. It uses strings as input and output. + + You can customize how the text is generated by passing parameters to the + OpenAI API. Use the `**generation_kwargs` argument when you initialize + the component or when you run it. Any parameter that works with + `openai.ChatCompletion.create` will work here too. + + + For details on OpenAI API parameters, see + [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat). + + ### Usage example + + ```python + from haystack.components.generators import OpenAIGenerator + client = OpenAIGenerator() + response = client.run("What's Natural Language Processing? Be brief.") + print(response) + + >> {'replies': ['Natural Language Processing (NLP) is a branch of artificial intelligence that focuses on + >> the interaction between computers and human language. It involves enabling computers to understand, interpret, + >> and respond to natural human language in a way that is both meaningful and useful.'], 'meta': [{'model': + >> 'gpt-4o-mini', 'index': 0, 'finish_reason': 'stop', 'usage': {'prompt_tokens': 16, + >> 'completion_tokens': 49, 'total_tokens': 65}}]} + ``` + """ + + def __init__( + self, + api_key: Secret = Secret.from_env_var("OPENAI_API_KEY"), + model: str = "gpt-4o-mini", + streaming_callback: Optional[Callable[[StreamingChunk], None]] = None, + api_base_url: Optional[str] = None, + organization: Optional[str] = None, + system_prompt: Optional[str] = None, + generation_kwargs: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + max_retries: Optional[int] = None, + ): + """ + Creates an instance of OpenAIGenerator. Unless specified otherwise in `model`, uses OpenAI's gpt-4o-mini + + By setting the 'OPENAI_TIMEOUT' and 'OPENAI_MAX_RETRIES' you can change the timeout and max_retries parameters + in the OpenAI client. + + :param api_key: The OpenAI API key to connect to OpenAI. + :param model: The name of the model to use. + :param streaming_callback: A callback function that is called when a new token is received from the stream. + The callback function accepts StreamingChunk as an argument. + :param api_base_url: An optional base URL. + :param organization: The Organization ID, defaults to `None`. + :param system_prompt: The system prompt to use for text generation. If not provided, the system prompt is + omitted, and the default system prompt of the model is used. + :param generation_kwargs: Other parameters to use for the model. These parameters are all sent directly to + the OpenAI endpoint. See OpenAI [documentation](https://platform.openai.com/docs/api-reference/chat) for + more details. + Some of the supported parameters: + - `max_tokens`: The maximum number of tokens the output text can have. + - `temperature`: What sampling temperature to use. Higher values mean the model will take more risks. + Try 0.9 for more creative applications and 0 (argmax sampling) for ones with a well-defined answer. + - `top_p`: An alternative to sampling with temperature, called nucleus sampling, where the model + considers the results of the tokens with top_p probability mass. So, 0.1 means only the tokens + comprising the top 10% probability mass are considered. + - `n`: How many completions to generate for each prompt. For example, if the LLM gets 3 prompts and n is 2, + it will generate two completions for each of the three prompts, ending up with 6 completions in total. + - `stop`: One or more sequences after which the LLM should stop generating tokens. + - `presence_penalty`: What penalty to apply if a token is already present at all. Bigger values mean + the model will be less likely to repeat the same token in the text. + - `frequency_penalty`: What penalty to apply if a token has already been generated in the text. + Bigger values mean the model will be less likely to repeat the same token in the text. + - `logit_bias`: Add a logit bias to specific tokens. The keys of the dictionary are tokens, and the + values are the bias to add to that token. + :param timeout: + Timeout for OpenAI Client calls, if not set it is inferred from the `OPENAI_TIMEOUT` environment variable + or set to 30. + :param max_retries: + Maximum retries to establish contact with OpenAI if it returns an internal error, if not set it is inferred + from the `OPENAI_MAX_RETRIES` environment variable or set to 5. + + """ + self.api_key = api_key + self.model = model + self.generation_kwargs = generation_kwargs or {} + self.system_prompt = system_prompt + self.streaming_callback = streaming_callback + + self.api_base_url = api_base_url + self.organization = organization + + if timeout is None: + timeout = float(os.environ.get("OPENAI_TIMEOUT", 30.0)) + if max_retries is None: + max_retries = int(os.environ.get("OPENAI_MAX_RETRIES", 5)) + + self.client = OpenAI( + api_key=api_key.resolve_value(), + organization=organization, + base_url=api_base_url, + timeout=timeout, + max_retries=max_retries, + ) + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"model": self.model} + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + + :returns: + The serialized component as a dictionary. + """ + callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None + return default_to_dict( + self, + model=self.model, + streaming_callback=callback_name, + api_base_url=self.api_base_url, + organization=self.organization, + generation_kwargs=self.generation_kwargs, + system_prompt=self.system_prompt, + api_key=self.api_key.to_dict(), + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "OpenAIGenerator": + """ + Deserialize this component from a dictionary. + + :param data: + The dictionary representation of this component. + :returns: + The deserialized component instance. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + init_params = data.get("init_parameters", {}) + serialized_callback_handler = init_params.get("streaming_callback") + if serialized_callback_handler: + data["init_parameters"]["streaming_callback"] = deserialize_callable(serialized_callback_handler) + return default_from_dict(cls, data) + + @component.output_types(replies=List[str], meta=List[Dict[str, Any]]) + def run( + self, + prompt: str, + system_prompt: Optional[str] = None, + streaming_callback: Optional[Callable[[StreamingChunk], None]] = None, + generation_kwargs: Optional[Dict[str, Any]] = None, + ): + """ + Invoke the text generation inference based on the provided messages and generation parameters. + + :param prompt: + The string prompt to use for text generation. + :param system_prompt: + The system prompt to use for text generation. If this run time system prompt is omitted, the system + prompt, if defined at initialisation time, is used. + :param streaming_callback: + A callback function that is called when a new token is received from the stream. + :param generation_kwargs: + Additional keyword arguments for text generation. These parameters will potentially override the parameters + passed in the `__init__` method. For more details on the parameters supported by the OpenAI API, refer to + the OpenAI [documentation](https://platform.openai.com/docs/api-reference/chat/create). + :returns: + A list of strings containing the generated responses and a list of dictionaries containing the metadata + for each response. + """ + message = ChatMessage.from_user(prompt) + if system_prompt is not None: + messages = [ChatMessage.from_system(system_prompt), message] + elif self.system_prompt: + messages = [ChatMessage.from_system(self.system_prompt), message] + else: + messages = [message] + + # update generation kwargs by merging with the generation kwargs passed to the run method + generation_kwargs = {**self.generation_kwargs, **(generation_kwargs or {})} + + # check if streaming_callback is passed + streaming_callback = streaming_callback or self.streaming_callback + + # adapt ChatMessage(s) to the format expected by the OpenAI API + openai_formatted_messages = [_convert_message_to_openai_format(message) for message in messages] + + completion: Union[Stream[ChatCompletionChunk], ChatCompletion] = self.client.chat.completions.create( + model=self.model, + messages=openai_formatted_messages, # type: ignore + stream=streaming_callback is not None, + **generation_kwargs, + ) + + completions: List[ChatMessage] = [] + if isinstance(completion, Stream): + num_responses = generation_kwargs.pop("n", 1) + if num_responses > 1: + raise ValueError("Cannot stream multiple responses, please set n=1.") + chunks: List[StreamingChunk] = [] + chunk = None + + # pylint: disable=not-an-iterable + for chunk in completion: + if chunk.choices and streaming_callback: + chunk_delta: StreamingChunk = self._build_chunk(chunk) + chunks.append(chunk_delta) + streaming_callback(chunk_delta) # invoke callback with the chunk_delta + completions = [self._connect_chunks(chunk, chunks)] + elif isinstance(completion, ChatCompletion): + completions = [self._build_message(completion, choice) for choice in completion.choices] + + # before returning, do post-processing of the completions + for response in completions: + self._check_finish_reason(response) + + return { + "replies": [message.content for message in completions], + "meta": [message.meta for message in completions], + } + + @staticmethod + def _connect_chunks(chunk: Any, chunks: List[StreamingChunk]) -> ChatMessage: + """ + Connects the streaming chunks into a single ChatMessage. + """ + complete_response = ChatMessage.from_assistant("".join([chunk.content for chunk in chunks])) + complete_response.meta.update( + { + "model": chunk.model, + "index": 0, + "finish_reason": chunk.choices[0].finish_reason, + "usage": {}, # we don't have usage data for streaming responses + } + ) + return complete_response + + @staticmethod + def _build_message(completion: Any, choice: Any) -> ChatMessage: + """ + Converts the response from the OpenAI API to a ChatMessage. + + :param completion: + The completion returned by the OpenAI API. + :param choice: + The choice returned by the OpenAI API. + :returns: + The ChatMessage. + """ + # function or tools calls are not going to happen in non-chat generation + # as users can not send ChatMessage with function or tools calls + chat_message = ChatMessage.from_assistant(choice.message.content or "") + chat_message.meta.update( + { + "model": completion.model, + "index": choice.index, + "finish_reason": choice.finish_reason, + "usage": dict(completion.usage), + } + ) + return chat_message + + @staticmethod + def _build_chunk(chunk: Any) -> StreamingChunk: + """ + Converts the response from the OpenAI API to a StreamingChunk. + + :param chunk: + The chunk returned by the OpenAI API. + :returns: + The StreamingChunk. + """ + # function or tools calls are not going to happen in non-chat generation + # as users can not send ChatMessage with function or tools calls + choice = chunk.choices[0] + content = choice.delta.content or "" + chunk_message = StreamingChunk(content) + chunk_message.meta.update({"model": chunk.model, "index": choice.index, "finish_reason": choice.finish_reason}) + return chunk_message + + @staticmethod + def _check_finish_reason(message: ChatMessage) -> None: + """ + Check the `finish_reason` returned with the OpenAI completions. + + If the `finish_reason` is `length`, log a warning to the user. + + :param message: + The message returned by the LLM. + """ + if message.meta["finish_reason"] == "length": + logger.warning( + "The completion for index {index} has been truncated before reaching a natural stopping point. " + "Increase the max_tokens parameter to allow for longer completions.", + index=message.meta["index"], + finish_reason=message.meta["finish_reason"], + ) + if message.meta["finish_reason"] == "content_filter": + logger.warning( + "The completion for index {index} has been truncated due to the content filter.", + index=message.meta["index"], + finish_reason=message.meta["finish_reason"], + ) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/openai_utils.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/openai_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..555e0ee30b902cf45013a060b881cd8baae7575c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/openai_utils.py @@ -0,0 +1,25 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Dict + +from haystack.dataclasses import ChatMessage + + +def _convert_message_to_openai_format(message: ChatMessage) -> Dict[str, str]: + """ + Convert a message to the format expected by OpenAI's Chat API. + + See the [API reference](https://platform.openai.com/docs/api-reference/chat/create) for details. + + :returns: A dictionary with the following key: + - `role` + - `content` + - `name` (optional) + """ + openai_msg = {"role": message.role.value, "content": message.content} + if message.name: + openai_msg["name"] = message.name + + return openai_msg diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/utils.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4b31f0d06b8b3291fb25f6bb953fb495cab93d5e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/generators/utils.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.dataclasses import StreamingChunk + + +def print_streaming_chunk(chunk: StreamingChunk) -> None: + """ + Default callback function for streaming responses. + + Prints the tokens of the first completion to stdout as soon as they are received + """ + print(chunk.content, flush=True, end="") diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/joiners/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/joiners/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..57878c209c1e8a25bfe90fa631503eaddf36b86c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/joiners/__init__.py @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from .answer_joiner import AnswerJoiner +from .branch import BranchJoiner +from .document_joiner import DocumentJoiner + +__all__ = ["DocumentJoiner", "BranchJoiner", "AnswerJoiner"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/joiners/answer_joiner.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/joiners/answer_joiner.py new file mode 100644 index 0000000000000000000000000000000000000000..3a6a8b824653097ae8ae11d5e90ee35ed558bc83 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/joiners/answer_joiner.py @@ -0,0 +1,172 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import itertools +from enum import Enum +from math import inf +from typing import Any, Callable, Dict, List, Optional, Union + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.core.component.types import Variadic +from haystack.dataclasses.answer import ExtractedAnswer, ExtractedTableAnswer, GeneratedAnswer + +AnswerType = Union[GeneratedAnswer, ExtractedTableAnswer, ExtractedAnswer] + +logger = logging.getLogger(__name__) + + +class JoinMode(Enum): + """ + Enum for AnswerJoiner join modes. + """ + + CONCATENATE = "concatenate" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "JoinMode": + """ + Convert a string to a JoinMode enum. + """ + enum_map = {e.value: e for e in JoinMode} + mode = enum_map.get(string) + if mode is None: + msg = f"Unknown join mode '{string}'. Supported modes in AnswerJoiner are: {list(enum_map.keys())}" + raise ValueError(msg) + return mode + + +@component +class AnswerJoiner: + """ + Merges multiple lists of `Answer` objects into a single list. + + Use this component to combine answers from different Generators into a single list. + Currently, the component supports only one join mode: `CONCATENATE`. + This mode concatenates multiple lists of answers into a single list. + + ### Usage example + + In this example, AnswerJoiner merges answers from two different Generators: + + ```python + from haystack.components.builders import AnswerBuilder + from haystack.components.joiners import AnswerJoiner + + from haystack.core.pipeline import Pipeline + + from haystack.components.generators.chat import OpenAIChatGenerator + from haystack.dataclasses import ChatMessage + + + query = "What's Natural Language Processing?" + messages = [ChatMessage.from_system("You are a helpful, respectful and honest assistant. Be super concise."), + ChatMessage.from_user(query)] + + pipe = Pipeline() + pipe.add_component("gpt-4o", OpenAIChatGenerator(model="gpt-4o")) + pipe.add_component("llama", OpenAIChatGenerator(model="gpt-3.5-turbo")) + pipe.add_component("aba", AnswerBuilder()) + pipe.add_component("abb", AnswerBuilder()) + pipe.add_component("joiner", AnswerJoiner()) + + pipe.connect("gpt-4o.replies", "aba") + pipe.connect("llama.replies", "abb") + pipe.connect("aba.answers", "joiner") + pipe.connect("abb.answers", "joiner") + + results = pipe.run(data={"gpt-4o": {"messages": messages}, + "llama": {"messages": messages}, + "aba": {"query": query}, + "abb": {"query": query}}) + ``` + """ + + def __init__( + self, + join_mode: Union[str, JoinMode] = JoinMode.CONCATENATE, + top_k: Optional[int] = None, + sort_by_score: bool = False, + ): + """ + Creates an AnswerJoiner component. + + :param join_mode: + Specifies the join mode to use. Available modes: + - `concatenate`: Concatenates multiple lists of Answers into a single list. + :param top_k: + The maximum number of Answers to return. + :param sort_by_score: + If `True`, sorts the documents by score in descending order. + If a document has no score, it is handled as if its score is -infinity. + """ + if isinstance(join_mode, str): + join_mode = JoinMode.from_str(join_mode) + join_mode_functions: Dict[JoinMode, Callable[[List[List[AnswerType]]], List[AnswerType]]] = { + JoinMode.CONCATENATE: self._concatenate + } + self.join_mode_function: Callable[[List[List[AnswerType]]], List[AnswerType]] = join_mode_functions[join_mode] + self.join_mode = join_mode + self.top_k = top_k + self.sort_by_score = sort_by_score + + @component.output_types(answers=List[AnswerType]) + def run(self, answers: Variadic[List[AnswerType]], top_k: Optional[int] = None): + """ + Joins multiple lists of Answers into a single list depending on the `join_mode` parameter. + + :param answers: + Nested list of Answers to be merged. + + :param top_k: + The maximum number of Answers to return. Overrides the instance's `top_k` if provided. + + :returns: + A dictionary with the following keys: + - `answers`: Merged list of Answers + """ + answers_list = list(answers) + join_function = self.join_mode_function + output_answers: List[AnswerType] = join_function(answers_list) + + if self.sort_by_score: + output_answers = sorted( + output_answers, key=lambda answer: answer.score if hasattr(answer, "score") else -inf, reverse=True + ) + + top_k = top_k or self.top_k + if top_k: + output_answers = output_answers[:top_k] + return {"answers": output_answers} + + def _concatenate(self, answer_lists: List[List[AnswerType]]) -> List[AnswerType]: + """ + Concatenate multiple lists of Answers, flattening them into a single list and sorting by score. + + :param answer_lists: List of lists of Answers to be flattened. + """ + return list(itertools.chain.from_iterable(answer_lists)) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict(self, join_mode=str(self.join_mode), top_k=self.top_k, sort_by_score=self.sort_by_score) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "AnswerJoiner": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + return default_from_dict(cls, data) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/joiners/branch.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/joiners/branch.py new file mode 100644 index 0000000000000000000000000000000000000000..49404ac4924ce86a66259559052ce17f8c20ef86 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/joiners/branch.py @@ -0,0 +1,141 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, Type + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.core.component.types import GreedyVariadic +from haystack.utils import deserialize_type, serialize_type + +logger = logging.getLogger(__name__) + + +@component() +class BranchJoiner: + """ + A component to join different branches of a pipeline into one single output. + + `BranchJoiner` receives multiple data connections of the same type from other components and passes the first + value coming to its single output, possibly distributing it to various other components. + + `BranchJoiner` is fundamental to close loops in a pipeline, where the two branches it joins are the ones + coming from the previous component and one coming back from a loop. For example, `BranchJoiner` could be used + to send data to a component evaluating errors. `BranchJoiner` would receive two connections, one to get the + original data and another one to get modified data in case there was an error. In both cases, `BranchJoiner` + would send (or re-send in case of a loop) data to the component evaluating errors. See "Usage example" below. + + Another use case with a need for `BranchJoiner` is to reconcile multiple branches coming out of a decision + or Classifier component. For example, in a RAG pipeline, there might be a "query language classifier" component + sending the query to different retrievers, selecting one specifically according to the detected language. After the + retrieval step the pipeline would ideally continue with a `PromptBuilder`, and since we don't know in advance the + language of the query, all the retrievers should be ideally connected to the single `PromptBuilder`. Since the + `PromptBuilder` won't accept more than one connection in input, we would connect all the retrievers to a + `BranchJoiner` component and reconcile them in a single output that can be connected to the `PromptBuilder` + downstream. + + Usage example: + + ```python + import json + from typing import List + + from haystack import Pipeline + from haystack.components.converters import OutputAdapter + from haystack.components.generators.chat import OpenAIChatGenerator + from haystack.components.joiners import BranchJoiner + from haystack.components.validators import JsonSchemaValidator + from haystack.dataclasses import ChatMessage + + person_schema = { + "type": "object", + "properties": { + "first_name": {"type": "string", "pattern": "^[A-Z][a-z]+$"}, + "last_name": {"type": "string", "pattern": "^[A-Z][a-z]+$"}, + "nationality": {"type": "string", "enum": ["Italian", "Portuguese", "American"]}, + }, + "required": ["first_name", "last_name", "nationality"] + } + + # Initialize a pipeline + pipe = Pipeline() + + # Add components to the pipeline + pipe.add_component('joiner', BranchJoiner(List[ChatMessage])) + pipe.add_component('fc_llm', OpenAIChatGenerator(model="gpt-4o-mini")) + pipe.add_component('validator', JsonSchemaValidator(json_schema=person_schema)) + pipe.add_component('adapter', OutputAdapter("{{chat_message}}", List[ChatMessage])), + # And connect them + pipe.connect("adapter", "joiner") + pipe.connect("joiner", "fc_llm") + pipe.connect("fc_llm.replies", "validator.messages") + pipe.connect("validator.validation_error", "joiner") + + result = pipe.run(data={"fc_llm": {"generation_kwargs": {"response_format": {"type": "json_object"}}}, + "adapter": {"chat_message": [ChatMessage.from_user("Create json from Peter Parker")]}}) + + print(json.loads(result["validator"]["validated"][0].content)) + + + >> {'first_name': 'Peter', 'last_name': 'Parker', 'nationality': 'American', 'name': 'Spider-Man', 'occupation': + >> 'Superhero', 'age': 23, 'location': 'New York City'} + ``` + + Note that `BranchJoiner` can manage only one data type at a time. In this case, `BranchJoiner` is created for + passing `List[ChatMessage]`. This determines the type of data that `BranchJoiner` will receive from the upstream + connected components and also the type of data that `BranchJoiner` will send through its output. + + In the code example, `BranchJoiner` receives a looped back `List[ChatMessage]` from the `JsonSchemaValidator` and + sends it down to the `OpenAIChatGenerator` for re-generation. We can have multiple loopback connections in the + pipeline. In this instance, the downstream component is only one (the `OpenAIChatGenerator`), but the pipeline might + have more than one downstream component. + """ + + def __init__(self, type_: Type): + """ + Create a `BranchJoiner` component. + + :param type_: The type of data that the `BranchJoiner` will receive from the upstream connected components and + distribute to the downstream connected components. + """ + self.type_ = type_ + # type_'s type can't be determined statically + component.set_input_types(self, value=GreedyVariadic[type_]) # type: ignore + component.set_output_types(self, value=type_) + + def to_dict(self): + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict(self, type_=serialize_type(self.type_)) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "BranchJoiner": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + data["init_parameters"]["type_"] = deserialize_type(data["init_parameters"]["type_"]) + return default_from_dict(cls, data) + + def run(self, **kwargs): + """ + The run method of the `BranchJoiner` component. + + Multiplexes the input data from the upstream connected components and distributes it to the downstream connected + components. + + :param **kwargs: The input data. Must be of the type declared in `__init__`. + :return: A dictionary with the following keys: + - `value`: The input data. + """ + if (inputs_count := len(kwargs["value"])) != 1: + raise ValueError(f"BranchJoiner expects only one input, but {inputs_count} were received.") + return {"value": kwargs["value"][0]} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/joiners/document_joiner.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/joiners/document_joiner.py new file mode 100644 index 0000000000000000000000000000000000000000..7451f6089ce283798faf86e5b1d38a421d4ddfc5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/joiners/document_joiner.py @@ -0,0 +1,264 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import itertools +from collections import defaultdict +from enum import Enum +from math import inf +from typing import Any, Dict, List, Optional, Union + +from haystack import Document, component, default_from_dict, default_to_dict, logging +from haystack.core.component.types import Variadic + +logger = logging.getLogger(__name__) + + +class JoinMode(Enum): + """ + Enum for join mode. + """ + + CONCATENATE = "concatenate" + MERGE = "merge" + RECIPROCAL_RANK_FUSION = "reciprocal_rank_fusion" + DISTRIBUTION_BASED_RANK_FUSION = "distribution_based_rank_fusion" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "JoinMode": + """ + Convert a string to a JoinMode enum. + """ + enum_map = {e.value: e for e in JoinMode} + mode = enum_map.get(string) + if mode is None: + msg = f"Unknown join mode '{string}'. Supported modes in DocumentJoiner are: {list(enum_map.keys())}" + raise ValueError(msg) + return mode + + +@component +class DocumentJoiner: + """ + Joins multiple lists of documents into a single list. + + It supports different join modes: + - concatenate: Keeps the highest-scored document in case of duplicates. + - merge: Calculates a weighted sum of scores for duplicates and merges them. + - reciprocal_rank_fusion: Merges and assigns scores based on reciprocal rank fusion. + - distribution_based_rank_fusion: Merges and assigns scores based on scores distribution in each Retriever. + + ### Usage example: + + ```python + document_store = InMemoryDocumentStore() + p = Pipeline() + p.add_component(instance=InMemoryBM25Retriever(document_store=document_store), name="bm25_retriever") + p.add_component( + instance=SentenceTransformersTextEmbedder(model="sentence-transformers/all-MiniLM-L6-v2"), + name="text_embedder", + ) + p.add_component(instance=InMemoryEmbeddingRetriever(document_store=document_store), name="embedding_retriever") + p.add_component(instance=DocumentJoiner(), name="joiner") + p.connect("bm25_retriever", "joiner") + p.connect("embedding_retriever", "joiner") + p.connect("text_embedder", "embedding_retriever") + query = "What is the capital of France?" + p.run(data={"query": query}) + ``` + """ + + def __init__( + self, + join_mode: Union[str, JoinMode] = JoinMode.CONCATENATE, + weights: Optional[List[float]] = None, + top_k: Optional[int] = None, + sort_by_score: bool = True, + ): + """ + Creates a DocumentJoiner component. + + :param join_mode: + Specifies the join mode to use. Available modes: + - `concatenate`: Keeps the highest-scored document in case of duplicates. + - `merge`: Calculates a weighted sum of scores for duplicates and merges them. + - `reciprocal_rank_fusion`: Merges and assigns scores based on reciprocal rank fusion. + - `distribution_based_rank_fusion`: Merges and assigns scores based on scores + distribution in each Retriever. + :param weights: + Assign importance to each list of documents to influence how they're joined. + This parameter is ignored for + `concatenate` or `distribution_based_rank_fusion` join modes. + Weight for each list of documents must match the number of inputs. + :param top_k: + The maximum number of documents to return. + :param sort_by_score: + If `True`, sorts the documents by score in descending order. + If a document has no score, it is handled as if its score is -infinity. + """ + if isinstance(join_mode, str): + join_mode = JoinMode.from_str(join_mode) + join_mode_functions = { + JoinMode.CONCATENATE: self._concatenate, + JoinMode.MERGE: self._merge, + JoinMode.RECIPROCAL_RANK_FUSION: self._reciprocal_rank_fusion, + JoinMode.DISTRIBUTION_BASED_RANK_FUSION: self._distribution_based_rank_fusion, + } + self.join_mode_function = join_mode_functions[join_mode] + self.join_mode = join_mode + self.weights = [float(i) / sum(weights) for i in weights] if weights else None + self.top_k = top_k + self.sort_by_score = sort_by_score + + @component.output_types(documents=List[Document]) + def run(self, documents: Variadic[List[Document]], top_k: Optional[int] = None): + """ + Joins multiple lists of Documents into a single list depending on the `join_mode` parameter. + + :param documents: + List of list of documents to be merged. + :param top_k: + The maximum number of documents to return. Overrides the instance's `top_k` if provided. + + :returns: + A dictionary with the following keys: + - `documents`: Merged list of Documents + """ + output_documents = [] + + documents = list(documents) + output_documents = self.join_mode_function(documents) + + if self.sort_by_score: + output_documents = sorted( + output_documents, key=lambda doc: doc.score if doc.score is not None else -inf, reverse=True + ) + if any(doc.score is None for doc in output_documents): + logger.info( + "Some of the Documents DocumentJoiner got have score=None. It was configured to sort Documents by " + "score, so those with score=None were sorted as if they had a score of -infinity." + ) + + if top_k: + output_documents = output_documents[:top_k] + elif self.top_k: + output_documents = output_documents[: self.top_k] + + return {"documents": output_documents} + + def _concatenate(self, document_lists: List[List[Document]]) -> List[Document]: + """ + Concatenate multiple lists of Documents and return only the Document with the highest score for duplicates. + """ + output = [] + docs_per_id = defaultdict(list) + for doc in itertools.chain.from_iterable(document_lists): + docs_per_id[doc.id].append(doc) + for docs in docs_per_id.values(): + doc_with_best_score = max(docs, key=lambda doc: doc.score if doc.score else -inf) + output.append(doc_with_best_score) + return output + + def _merge(self, document_lists: List[List[Document]]) -> List[Document]: + """ + Merge multiple lists of Documents and calculate a weighted sum of the scores of duplicate Documents. + """ + scores_map: dict = defaultdict(int) + documents_map = {} + weights = self.weights if self.weights else [1 / len(document_lists)] * len(document_lists) + + for documents, weight in zip(document_lists, weights): + for doc in documents: + scores_map[doc.id] += (doc.score if doc.score else 0) * weight + documents_map[doc.id] = doc + + for doc in documents_map.values(): + doc.score = scores_map[doc.id] + + return list(documents_map.values()) + + def _reciprocal_rank_fusion(self, document_lists: List[List[Document]]) -> List[Document]: + """ + Merge multiple lists of Documents and assign scores based on reciprocal rank fusion. + + The constant k is set to 61 (60 was suggested by the original paper, + plus 1 as python lists are 0-based and the paper used 1-based ranking). + """ + k = 61 + + scores_map: dict = defaultdict(int) + documents_map = {} + weights = self.weights if self.weights else [1 / len(document_lists)] * len(document_lists) + + # Calculate weighted reciprocal rank fusion score + for documents, weight in zip(document_lists, weights): + for rank, doc in enumerate(documents): + scores_map[doc.id] += (weight * len(document_lists)) / (k + rank) + documents_map[doc.id] = doc + + # Normalize scores. Note: len(results) / k is the maximum possible score, + # achieved by being ranked first in all doc lists with non-zero weight. + for _id in scores_map: + scores_map[_id] /= len(document_lists) / k + + for doc in documents_map.values(): + doc.score = scores_map[doc.id] + + return list(documents_map.values()) + + def _distribution_based_rank_fusion(self, document_lists: List[List[Document]]) -> List[Document]: + """ + Merge multiple lists of Documents and assign scores based on Distribution-Based Score Fusion. + + (https://medium.com/plain-simple-software/distribution-based-score-fusion-dbsf-a-new-approach-to-vector-search-ranking-f87c37488b18) + If a Document is in more than one retriever, the one with the highest score is used. + """ + for documents in document_lists: + scores_list = [] + + for doc in documents: + scores_list.append(doc.score if doc.score is not None else 0) + + mean_score = sum(scores_list) / len(scores_list) + std_dev = (sum((x - mean_score) ** 2 for x in scores_list) / len(scores_list)) ** 0.5 + min_score = mean_score - 3 * std_dev + max_score = mean_score + 3 * std_dev + delta_score = max_score - min_score + + for doc in documents: + doc.score = (doc.score - min_score) / delta_score if delta_score != 0.0 else 0.0 + # if all docs have the same score delta_score is 0, the docs are uninformative for the query + + output = self._concatenate(document_lists=document_lists) + + return output + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + join_mode=str(self.join_mode), + weights=self.weights, + top_k=self.top_k, + sort_by_score=self.sort_by_score, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "DocumentJoiner": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + return default_from_dict(cls, data) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/preprocessors/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/preprocessors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f7e132077a4d8c801acad8aabcd44e70125866d7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/preprocessors/__init__.py @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from .document_cleaner import DocumentCleaner +from .document_splitter import DocumentSplitter +from .nltk_document_splitter import NLTKDocumentSplitter +from .text_cleaner import TextCleaner + +__all__ = ["DocumentSplitter", "DocumentCleaner", "TextCleaner", "NLTKDocumentSplitter"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/preprocessors/document_cleaner.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/preprocessors/document_cleaner.py new file mode 100644 index 0000000000000000000000000000000000000000..d56006130c1ed98ca9087204f8c2175a5288c497 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/preprocessors/document_cleaner.py @@ -0,0 +1,316 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import re +from copy import deepcopy +from functools import partial, reduce +from itertools import chain +from typing import Generator, List, Literal, Optional, Set +from unicodedata import normalize + +from haystack import Document, component, logging + +logger = logging.getLogger(__name__) + + +@component +class DocumentCleaner: + """ + Cleans the text in the documents. + + It removes extra whitespaces, + empty lines, specified substrings, regexes, + page headers and footers (in this order). + + ### Usage example: + + ```python + from haystack import Document + from haystack.components.preprocessors import DocumentCleaner + + doc = Document(content="This is a document to clean\\n\\n\\nsubstring to remove") + + cleaner = DocumentCleaner(remove_substrings = ["substring to remove"]) + result = cleaner.run(documents=[doc]) + + assert result["documents"][0].content == "This is a document to clean " + ``` + """ + + def __init__( + self, + remove_empty_lines: bool = True, + remove_extra_whitespaces: bool = True, + remove_repeated_substrings: bool = False, + keep_id: bool = False, + remove_substrings: Optional[List[str]] = None, + remove_regex: Optional[str] = None, + unicode_normalization: Optional[Literal["NFC", "NFKC", "NFD", "NFKD"]] = None, + ascii_only: bool = False, + ): + """ + Initialize DocumentCleaner. + + :param remove_empty_lines: If `True`, removes empty lines. + :param remove_extra_whitespaces: If `True`, removes extra whitespaces. + :param remove_repeated_substrings: If `True`, removes repeated substrings (headers and footers) from pages. + Pages must be separated by a form feed character "\\f", + which is supported by `TextFileToDocument` and `AzureOCRDocumentConverter`. + :param remove_substrings: List of substrings to remove from the text. + :param remove_regex: Regex to match and replace substrings by "". + :param keep_id: If `True`, keeps the IDs of the original documents. + :param unicode_normalization: Unicode normalization form to apply to the text. + Note: This will run before any other steps. + :param ascii_only: Whether to convert the text to ASCII only. + Will remove accents from characters and replace them with ASCII characters. + Other non-ASCII characters will be removed. + Note: This will run before any pattern matching or removal. + """ + + self._validate_params(unicode_normalization=unicode_normalization) + + self.remove_empty_lines = remove_empty_lines + self.remove_extra_whitespaces = remove_extra_whitespaces + self.remove_repeated_substrings = remove_repeated_substrings + self.remove_substrings = remove_substrings + self.remove_regex = remove_regex + self.keep_id = keep_id + self.unicode_normalization = unicode_normalization + self.ascii_only = ascii_only + + def _validate_params(self, unicode_normalization: Optional[str]): + """ + Validate the parameters of the DocumentCleaner. + + :param unicode_normalization: Unicode normalization form to apply to the text. + :raises ValueError: if the parameters are not valid. + """ + if unicode_normalization and unicode_normalization not in ["NFC", "NFKC", "NFD", "NFKD"]: + raise ValueError("unicode_normalization must be one of 'NFC', 'NFKC', 'NFD', 'NFKD'.") + + @component.output_types(documents=List[Document]) + def run(self, documents: List[Document]): + """ + Cleans up the documents. + + :param documents: List of Documents to clean. + + :returns: A dictionary with the following key: + - `documents`: List of cleaned Documents. + + :raises TypeError: if documents is not a list of Documents. + """ + if not isinstance(documents, list) or documents and not isinstance(documents[0], Document): + raise TypeError("DocumentCleaner expects a List of Documents as input.") + + cleaned_docs = [] + for doc in documents: + if doc.content is None: + logger.warning( + "DocumentCleaner only cleans text documents but document.content for document ID" + " %{document_id} is None.", + document_id=doc.id, + ) + cleaned_docs.append(doc) + continue + text = doc.content + + if self.unicode_normalization: + text = self._normalize_unicode(text, self.unicode_normalization) + if self.ascii_only: + text = self._ascii_only(text) + if self.remove_extra_whitespaces: + text = self._remove_extra_whitespaces(text) + if self.remove_empty_lines: + text = self._remove_empty_lines(text) + if self.remove_substrings: + text = self._remove_substrings(text, self.remove_substrings) + if self.remove_regex: + text = self._remove_regex(text, self.remove_regex) + if self.remove_repeated_substrings: + text = self._remove_repeated_substrings(text) + + cleaned_docs.append(Document(content=text, meta=deepcopy(doc.meta), id=doc.id if self.keep_id else "")) + + return {"documents": cleaned_docs} + + def _normalize_unicode(self, text: str, form: Literal["NFC", "NFKC", "NFD", "NFKD"]) -> str: + """ + Normalize the unicode of the text. + + :param text: Text to normalize. + :param form: Unicode normalization form to apply to the text. + Options: "NFC", "NFKC", "NFD", "NFKD". + :returns: The normalized text. + """ + return normalize(form, text) + + def _ascii_only(self, text: str) -> str: + """ + Convert the text to ASCII only. + + Will remove accents from characters and replace them with ASCII characters. + Other non-ASCII characters will be removed. + + :param text: Text to convert to ASCII only. + :returns: The text in ASCII only. + """ + + # First normalize the text to NFKD to separate the characters and their diacritics + # Then encode it to ASCII and ignore any characters that can't be encoded + return self._normalize_unicode(text, "NFKD").encode("ascii", "ignore").decode("utf-8") + + def _remove_empty_lines(self, text: str) -> str: + """ + Remove empty lines and lines that contain nothing but whitespaces from text. + + :param text: Text to clean. + :returns: The text without empty lines. + """ + pages = text.split("\f") + cleaned_pages = ["\n".join(line for line in page.split("\n") if line.strip()) for page in pages] + return "\f".join(cleaned_pages) + + def _remove_extra_whitespaces(self, text: str) -> str: + """ + Remove extra whitespaces from text. + + :param text: Text to clean. + :returns: The text without extra whitespaces. + """ + texts = text.split("\f") + cleaned_text = [re.sub(r"\s\s+", " ", text).strip() for text in texts] + return "\f".join(cleaned_text) + + def _remove_regex(self, text: str, regex: str) -> str: + """ + Remove substrings that match the specified regex from the text. + + :param text: Text to clean. + :param regex: Regex to match and replace substrings by "". + :returns: The text without the substrings that match the regex. + """ + texts = text.split("\f") + cleaned_text = [re.sub(regex, "", text).strip() for text in texts] + return "\f".join(cleaned_text) + + def _remove_substrings(self, text: str, substrings: List[str]) -> str: + """ + Remove all specified substrings from the text. + + :param text: Text to clean. + :param substrings: Substrings to remove. + :returns: The text without the specified substrings. + """ + for substring in substrings: + text = text.replace(substring, "") + return text + + def _remove_repeated_substrings(self, text: str) -> str: + """ + Remove any substrings from the text that occur repeatedly on every page. For example headers or footers. + + Pages in the text need to be separated by form feed character "\f". + :param text: Text to clean. + :returns: The text without the repeated substrings. + """ + return self._find_and_remove_header_footer( + text, n_chars=300, n_first_pages_to_ignore=1, n_last_pages_to_ignore=1 + ) + + def _find_and_remove_header_footer( + self, text: str, n_chars: int, n_first_pages_to_ignore: int, n_last_pages_to_ignore: int + ) -> str: + """ + Heuristic to find footers and headers across different pages by searching for the longest common string. + + Pages in the text need to be separated by form feed character "\f". + For headers, we only search in the first n_chars characters (for footer: last n_chars). + Note: This heuristic uses exact matches and therefore works well for footers like "Copyright 2019 by XXX", + but won't detect "Page 3 of 4" or similar. + + :param n_chars: The number of first/last characters where the header/footer shall be searched in. + :param n_first_pages_to_ignore: The number of first pages to ignore + (e.g. TOCs often don't contain footer/header). + :param n_last_pages_to_ignore: The number of last pages to ignore. + :returns: The text without the found headers and footers. + """ + + pages = text.split("\f") + + # header + start_of_pages = [p[:n_chars] for p in pages[n_first_pages_to_ignore:-n_last_pages_to_ignore]] + found_header = self._find_longest_common_ngram(start_of_pages) + if found_header: + pages = [page.replace(found_header, "") for page in pages] + + # footer + end_of_pages = [p[-n_chars:] for p in pages[n_first_pages_to_ignore:-n_last_pages_to_ignore]] + found_footer = self._find_longest_common_ngram(end_of_pages) + if found_footer: + pages = [page.replace(found_footer, "") for page in pages] + + logger.debug( + "Removed header '{header}' and footer '{footer}' in document", header=found_header, footer=found_footer + ) + text = "\f".join(pages) + return text + + def _ngram(self, seq: str, n: int) -> Generator[str, None, None]: + """ + Return all ngrams of length n from a text sequence. Each ngram consists of n words split by whitespace. + + :param seq: The sequence to generate ngrams from. + :param n: The length of the ngrams to generate. + :returns: A Generator generating all ngrams of length n from the given sequence. + """ + + # In order to maintain the original whitespace, but still consider \n and \t for n-gram tokenization, + # we add a space here and remove it after creation of the ngrams again (see below) + seq = seq.replace("\n", " \n") + seq = seq.replace("\t", " \t") + + words = seq.split(" ") + ngrams = ( + " ".join(words[i : i + n]).replace(" \n", "\n").replace(" \t", "\t") for i in range(0, len(words) - n + 1) + ) + + return ngrams + + def _allngram(self, seq: str, min_ngram: int, max_ngram: int) -> Set[str]: + """ + Generates all possible ngrams from a given sequence of text. + + Considering all ngram lengths between the minimum and maximum length. + + :param seq: The sequence to generate ngrams from. + :param min_ngram: The minimum length of ngram to consider. + :param max_ngram: The maximum length of ngram to consider. + :returns: A set of all ngrams from the given sequence. + """ + lengths = range(min_ngram, max_ngram) if max_ngram else range(min_ngram, len(seq)) + ngrams = map(partial(self._ngram, seq), lengths) + res = set(chain.from_iterable(ngrams)) + return res + + def _find_longest_common_ngram(self, sequences: List[str], min_ngram: int = 3, max_ngram: int = 30) -> str: + """ + Find the longest common ngram across a list of text sequences (e.g. start of pages). + + Considering all ngram lengths between the minimum and maximum length. Helpful for finding footers, headers etc. + Empty sequences are ignored. + + :param sequences: The list of strings that shall be searched for common n_grams. + :param max_ngram: The maximum length of ngram to consider. + :param min_ngram: The minimum length of ngram to consider. + :returns: The longest ngram that all sequences have in common. + """ + sequences = [s for s in sequences if s] # filter empty sequences + if not sequences: + return "" + seqs_ngrams = map(partial(self._allngram, min_ngram=min_ngram, max_ngram=max_ngram), sequences) + intersection = reduce(set.intersection, seqs_ngrams) + + longest = max(intersection, key=len, default="") + return longest if longest.strip() else "" diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/preprocessors/document_splitter.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/preprocessors/document_splitter.py new file mode 100644 index 0000000000000000000000000000000000000000..556878a9658d4201eb66b7302fa49dd5d91e13eb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/preprocessors/document_splitter.py @@ -0,0 +1,275 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from copy import deepcopy +from typing import Any, Callable, Dict, List, Literal, Optional, Tuple + +from more_itertools import windowed + +from haystack import Document, component +from haystack.core.serialization import default_from_dict, default_to_dict +from haystack.utils import deserialize_callable, serialize_callable + + +@component +class DocumentSplitter: + """ + Splits long documents into smaller chunks. + + This is a common preprocessing step during indexing. + It helps Embedders create meaningful semantic representations + and prevents exceeding language model context limits. + + The DocumentSplitter is compatible with the following DocumentStores: + - [Astra](https://docs.haystack.deepset.ai/docs/astradocumentstore) + - [Chroma](https://docs.haystack.deepset.ai/docs/chromadocumentstore) limited support, overlapping information is + not stored + - [Elasticsearch](https://docs.haystack.deepset.ai/docs/elasticsearch-document-store) + - [OpenSearch](https://docs.haystack.deepset.ai/docs/opensearch-document-store) + - [Pgvector](https://docs.haystack.deepset.ai/docs/pgvectordocumentstore) + - [Pinecone](https://docs.haystack.deepset.ai/docs/pinecone-document-store) limited support, overlapping + information is not stored + - [Qdrant](https://docs.haystack.deepset.ai/docs/qdrant-document-store) + - [Weaviate](https://docs.haystack.deepset.ai/docs/weaviatedocumentstore) + + ### Usage example + + ```python + from haystack import Document + from haystack.components.preprocessors import DocumentSplitter + + doc = Document(content="Moonlight shimmered softly, wolves howled nearby, night enveloped everything.") + + splitter = DocumentSplitter(split_by="word", split_length=3, split_overlap=0) + result = splitter.run(documents=[doc]) + ``` + """ + + def __init__( + self, + split_by: Literal["function", "page", "passage", "sentence", "word"] = "word", + split_length: int = 200, + split_overlap: int = 0, + split_threshold: int = 0, + splitting_function: Optional[Callable[[str], List[str]]] = None, + ): + """ + Initialize DocumentSplitter. + + :param split_by: The unit for splitting your documents. Choose from `word` for splitting by spaces (" "), + `sentence` for splitting by periods ("."), `page` for splitting by form feed ("\\f"), + or `passage` for splitting by double line breaks ("\\n\\n"). + :param split_length: The maximum number of units in each split. + :param split_overlap: The number of overlapping units for each split. + :param split_threshold: The minimum number of units per split. If a split has fewer units + than the threshold, it's attached to the previous split. + :param splitting_function: Necessary when `split_by` is set to "function". + This is a function which must accept a single `str` as input and return a `list` of `str` as output, + representing the chunks after splitting. + """ + + self.split_by = split_by + if split_by not in ["function", "page", "passage", "sentence", "word"]: + raise ValueError("split_by must be one of 'word', 'sentence', 'page' or 'passage'.") + if split_by == "function" and splitting_function is None: + raise ValueError("When 'split_by' is set to 'function', a valid 'splitting_function' must be provided.") + if split_length <= 0: + raise ValueError("split_length must be greater than 0.") + self.split_length = split_length + if split_overlap < 0: + raise ValueError("split_overlap must be greater than or equal to 0.") + self.split_overlap = split_overlap + self.split_threshold = split_threshold + self.splitting_function = splitting_function + + @component.output_types(documents=List[Document]) + def run(self, documents: List[Document]): + """ + Split documents into smaller parts. + + Splits documents by the unit expressed in `split_by`, with a length of `split_length` + and an overlap of `split_overlap`. + + :param documents: The documents to split. + + :returns: A dictionary with the following key: + - `documents`: List of documents with the split texts. Each document includes: + - A metadata field `source_id` to track the original document. + - A metadata field `page_number` to track the original page number. + - All other metadata copied from the original document. + + :raises TypeError: if the input is not a list of Documents. + :raises ValueError: if the content of a document is None. + """ + + if not isinstance(documents, list) or (documents and not isinstance(documents[0], Document)): + raise TypeError("DocumentSplitter expects a List of Documents as input.") + + split_docs = [] + for doc in documents: + if doc.content is None: + raise ValueError( + f"DocumentSplitter only works with text documents but content for document ID {doc.id} is None." + ) + units = self._split_into_units(doc.content, self.split_by) + text_splits, splits_pages, splits_start_idxs = self._concatenate_units( + units, self.split_length, self.split_overlap, self.split_threshold + ) + metadata = deepcopy(doc.meta) + metadata["source_id"] = doc.id + split_docs += self._create_docs_from_splits( + text_splits=text_splits, splits_pages=splits_pages, splits_start_idxs=splits_start_idxs, meta=metadata + ) + return {"documents": split_docs} + + def _split_into_units( + self, text: str, split_by: Literal["function", "page", "passage", "sentence", "word"] + ) -> List[str]: + if split_by == "page": + self.split_at = "\f" + elif split_by == "passage": + self.split_at = "\n\n" + elif split_by == "sentence": + self.split_at = "." + elif split_by == "word": + self.split_at = " " + elif split_by == "function" and self.splitting_function is not None: + return self.splitting_function(text) + else: + raise NotImplementedError( + "DocumentSplitter only supports 'function', 'page', 'passage', 'sentence' or 'word' split_by options." + ) + units = text.split(self.split_at) + # Add the delimiter back to all units except the last one + for i in range(len(units) - 1): + units[i] += self.split_at + return units + + def _concatenate_units( + self, elements: List[str], split_length: int, split_overlap: int, split_threshold: int + ) -> Tuple[List[str], List[int], List[int]]: + """ + Concatenates the elements into parts of split_length units. + + Keeps track of the original page number that each element belongs. If the length of the current units is less + than the pre-defined `split_threshold`, it does not create a new split. Instead, it concatenates the current + units with the last split, preventing the creation of excessively small splits. + """ + + text_splits: List[str] = [] + splits_pages = [] + splits_start_idxs = [] + cur_start_idx = 0 + cur_page = 1 + segments = windowed(elements, n=split_length, step=split_length - split_overlap) + + for seg in segments: + current_units = [unit for unit in seg if unit is not None] + txt = "".join(current_units) + + # check if length of current units is below split_threshold + if len(current_units) < split_threshold and len(text_splits) > 0: + # concatenate the last split with the current one + text_splits[-1] += txt + + elif len(txt) > 0: + text_splits.append(txt) + splits_pages.append(cur_page) + splits_start_idxs.append(cur_start_idx) + + processed_units = current_units[: split_length - split_overlap] + cur_start_idx += len("".join(processed_units)) + + if self.split_by == "page": + num_page_breaks = len(processed_units) + else: + num_page_breaks = sum(processed_unit.count("\f") for processed_unit in processed_units) + + cur_page += num_page_breaks + + return text_splits, splits_pages, splits_start_idxs + + def _create_docs_from_splits( + self, text_splits: List[str], splits_pages: List[int], splits_start_idxs: List[int], meta: Dict + ) -> List[Document]: + """ + Creates Document objects from splits enriching them with page number and the metadata of the original document. + """ + documents: List[Document] = [] + + for i, (txt, split_idx) in enumerate(zip(text_splits, splits_start_idxs)): + meta = deepcopy(meta) + doc = Document(content=txt, meta=meta) + doc.meta["page_number"] = splits_pages[i] + doc.meta["split_id"] = i + doc.meta["split_idx_start"] = split_idx + documents.append(doc) + + if self.split_overlap <= 0: + continue + + doc.meta["_split_overlap"] = [] + + if i == 0: + continue + + doc_start_idx = splits_start_idxs[i] + previous_doc = documents[i - 1] + previous_doc_start_idx = splits_start_idxs[i - 1] + self._add_split_overlap_information(doc, doc_start_idx, previous_doc, previous_doc_start_idx) + + return documents + + @staticmethod + def _add_split_overlap_information( + current_doc: Document, current_doc_start_idx: int, previous_doc: Document, previous_doc_start_idx: int + ): + """ + Adds split overlap information to the current and previous Document's meta. + + :param current_doc: The Document that is being split. + :param current_doc_start_idx: The starting index of the current Document. + :param previous_doc: The Document that was split before the current Document. + :param previous_doc_start_idx: The starting index of the previous Document. + """ + overlapping_range = (current_doc_start_idx - previous_doc_start_idx, len(previous_doc.content)) # type: ignore + + if overlapping_range[0] < overlapping_range[1]: + overlapping_str = previous_doc.content[overlapping_range[0] : overlapping_range[1]] # type: ignore + + if current_doc.content.startswith(overlapping_str): # type: ignore + # add split overlap information to this Document regarding the previous Document + current_doc.meta["_split_overlap"].append({"doc_id": previous_doc.id, "range": overlapping_range}) + + # add split overlap information to previous Document regarding this Document + overlapping_range = (0, overlapping_range[1] - overlapping_range[0]) + previous_doc.meta["_split_overlap"].append({"doc_id": current_doc.id, "range": overlapping_range}) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + """ + serialized = default_to_dict( + self, + split_by=self.split_by, + split_length=self.split_length, + split_overlap=self.split_overlap, + split_threshold=self.split_threshold, + ) + if self.splitting_function: + serialized["init_parameters"]["splitting_function"] = serialize_callable(self.splitting_function) + return serialized + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "DocumentSplitter": + """ + Deserializes the component from a dictionary. + """ + init_params = data.get("init_parameters", {}) + + splitting_function = init_params.get("splitting_function", None) + if splitting_function: + init_params["splitting_function"] = deserialize_callable(splitting_function) + + return default_from_dict(cls, data) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/preprocessors/nltk_document_splitter.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/preprocessors/nltk_document_splitter.py new file mode 100644 index 0000000000000000000000000000000000000000..a521901382607d0265a8d8baa6e6426a75f0240b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/preprocessors/nltk_document_splitter.py @@ -0,0 +1,467 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import re +from copy import deepcopy +from pathlib import Path +from typing import Any, Dict, List, Literal, Tuple + +from haystack import Document, component, logging +from haystack.components.preprocessors.document_splitter import DocumentSplitter +from haystack.lazy_imports import LazyImport + +with LazyImport("Run 'pip install nltk'") as nltk_imports: + import nltk + +logger = logging.getLogger(__name__) + +Language = Literal[ + "ru", "sl", "es", "sv", "tr", "cs", "da", "nl", "en", "et", "fi", "fr", "de", "el", "it", "no", "pl", "pt", "ml" +] + + +@component +class NLTKDocumentSplitter(DocumentSplitter): + def __init__( + self, + split_by: Literal["word", "sentence", "page", "passage", "function"] = "word", + split_length: int = 200, + split_overlap: int = 0, + split_threshold: int = 0, + respect_sentence_boundary: bool = False, + language: Language = "en", + use_split_rules: bool = True, + extend_abbreviations: bool = True, + ): + """ + Splits your documents using NLTK to respect sentence boundaries. + + Initialize the NLTKDocumentSplitter. + + :param split_by: Select the unit for splitting your documents. Choose from `word` for splitting by spaces (" "), + `sentence` for splitting by NLTK sentence tokenizer, `page` for splitting by the form feed ("\\f") or + `passage` for splitting by double line breaks ("\\n\\n"). + :param split_length: The maximum number of units in each split. + :param split_overlap: The number of overlapping units for each split. + :param split_threshold: The minimum number of units per split. If a split has fewer units + than the threshold, it's attached to the previous split. + :param respect_sentence_boundary: Choose whether to respect sentence boundaries when splitting by "word". + If True, uses NLTK to detect sentence boundaries, ensuring splits occur only between sentences. + :param language: Choose the language for the NLTK tokenizer. The default is English ("en"). + :param use_split_rules: Choose whether to use additional split rules when splitting by `sentence`. + :param extend_abbreviations: Choose whether to extend NLTK's PunktTokenizer abbreviations with a list + of curated abbreviations, if available. + This is currently supported for English ("en") and German ("de"). + """ + + super(NLTKDocumentSplitter, self).__init__( + split_by=split_by, split_length=split_length, split_overlap=split_overlap, split_threshold=split_threshold + ) + nltk_imports.check() + if respect_sentence_boundary and split_by != "word": + logger.warning( + "The 'respect_sentence_boundary' option is only supported for `split_by='word'`. " + "The option `respect_sentence_boundary` will be set to `False`." + ) + respect_sentence_boundary = False + self.respect_sentence_boundary = respect_sentence_boundary + self.sentence_splitter = SentenceSplitter( + language=language, + use_split_rules=use_split_rules, + extend_abbreviations=extend_abbreviations, + keep_white_spaces=True, + ) + self.language = language + + def _split_into_units( + self, text: str, split_by: Literal["word", "sentence", "passage", "page", "function"] + ) -> List[str]: + """ + Splits the text into units based on the specified split_by parameter. + + :param text: The text to split. + :param split_by: The unit to split the text by. Choose from "word", "sentence", "passage", or "page". + :returns: A list of units. + """ + + if split_by == "page": + self.split_at = "\f" + units = text.split(self.split_at) + elif split_by == "passage": + self.split_at = "\n\n" + units = text.split(self.split_at) + elif split_by == "sentence": + # whitespace is preserved while splitting text into sentences when using keep_white_spaces=True + # so split_at is set to an empty string + self.split_at = "" + result = self.sentence_splitter.split_sentences(text) + units = [sentence["sentence"] for sentence in result] + elif split_by == "word": + self.split_at = " " + units = text.split(self.split_at) + else: + raise NotImplementedError( + "DocumentSplitter only supports 'word', 'sentence', 'page' or 'passage' split_by options." + ) + + # Add the delimiter back to all units except the last one + for i in range(len(units) - 1): + units[i] += self.split_at + return units + + @component.output_types(documents=List[Document]) + def run(self, documents: List[Document]) -> Dict[str, List[Document]]: + """ + Split documents into smaller parts. + + Splits documents by the unit expressed in `split_by`, with a length of `split_length` + and an overlap of `split_overlap`. + + :param documents: The documents to split. + + :returns: A dictionary with the following key: + - `documents`: List of documents with the split texts. Each document includes: + - A metadata field source_id to track the original document. + - A metadata field page_number to track the original page number. + - All other metadata copied from the original document. + + :raises TypeError: if the input is not a list of Documents. + :raises ValueError: if the content of a document is None. + """ + if not isinstance(documents, list) or (documents and not isinstance(documents[0], Document)): + raise TypeError("DocumentSplitter expects a List of Documents as input.") + + split_docs = [] + for doc in documents: + if doc.content is None: + raise ValueError( + f"DocumentSplitter only works with text documents but content for document ID {doc.id} is None." + ) + + if self.respect_sentence_boundary: + units = self._split_into_units(doc.content, "sentence") + text_splits, splits_pages, splits_start_idxs = self._concatenate_sentences_based_on_word_amount( + sentences=units, split_length=self.split_length, split_overlap=self.split_overlap + ) + else: + units = self._split_into_units(doc.content, self.split_by) + text_splits, splits_pages, splits_start_idxs = self._concatenate_units( + elements=units, + split_length=self.split_length, + split_overlap=self.split_overlap, + split_threshold=self.split_threshold, + ) + metadata = deepcopy(doc.meta) + metadata["source_id"] = doc.id + split_docs += self._create_docs_from_splits( + text_splits=text_splits, splits_pages=splits_pages, splits_start_idxs=splits_start_idxs, meta=metadata + ) + return {"documents": split_docs} + + @staticmethod + def _number_of_sentences_to_keep(sentences: List[str], split_length: int, split_overlap: int) -> int: + """ + Returns the number of sentences to keep in the next chunk based on the `split_overlap` and `split_length`. + + :param sentences: The list of sentences to split. + :param split_length: The maximum number of words in each split. + :param split_overlap: The number of overlapping words in each split. + :returns: The number of sentences to keep in the next chunk. + """ + # If the split_overlap is 0, we don't need to keep any sentences + if split_overlap == 0: + return 0 + + num_sentences_to_keep = 0 + num_words = 0 + for sent in reversed(sentences): + num_words += len(sent.split()) + # If the number of words is larger than the split_length then don't add any more sentences + if num_words > split_length: + break + num_sentences_to_keep += 1 + if num_words > split_overlap: + break + return num_sentences_to_keep + + def _concatenate_sentences_based_on_word_amount( + self, sentences: List[str], split_length: int, split_overlap: int + ) -> Tuple[List[str], List[int], List[int]]: + """ + Groups the sentences into chunks of `split_length` words while respecting sentence boundaries. + + :param sentences: The list of sentences to split. + :param split_length: The maximum number of words in each split. + :param split_overlap: The number of overlapping words in each split. + :returns: A tuple containing the concatenated sentences, the start page numbers, and the start indices. + """ + # Chunk information + chunk_word_count = 0 + chunk_starting_page_number = 1 + chunk_start_idx = 0 + current_chunk: List[str] = [] + # Output lists + split_start_page_numbers = [] + list_of_splits: List[List[str]] = [] + split_start_indices = [] + + for sentence_idx, sentence in enumerate(sentences): + current_chunk.append(sentence) + chunk_word_count += len(sentence.split()) + next_sentence_word_count = ( + len(sentences[sentence_idx + 1].split()) if sentence_idx < len(sentences) - 1 else 0 + ) + + # Number of words in the current chunk plus the next sentence is larger than the split_length + # or we reached the last sentence + if (chunk_word_count + next_sentence_word_count) > split_length or sentence_idx == len(sentences) - 1: + # Save current chunk and start a new one + list_of_splits.append(current_chunk) + split_start_page_numbers.append(chunk_starting_page_number) + split_start_indices.append(chunk_start_idx) + + # Get the number of sentences that overlap with the next chunk + num_sentences_to_keep = self._number_of_sentences_to_keep( + sentences=current_chunk, split_length=split_length, split_overlap=split_overlap + ) + # Set up information for the new chunk + if num_sentences_to_keep > 0: + # Processed sentences are the ones that are not overlapping with the next chunk + processed_sentences = current_chunk[:-num_sentences_to_keep] + chunk_starting_page_number += sum(sent.count("\f") for sent in processed_sentences) + chunk_start_idx += len("".join(processed_sentences)) + # Next chunk starts with the sentences that were overlapping with the previous chunk + current_chunk = current_chunk[-num_sentences_to_keep:] + chunk_word_count = sum(len(s.split()) for s in current_chunk) + else: + # Here processed_sentences is the same as current_chunk since there is no overlap + chunk_starting_page_number += sum(sent.count("\f") for sent in current_chunk) + chunk_start_idx += len("".join(current_chunk)) + current_chunk = [] + chunk_word_count = 0 + + # Concatenate the sentences together within each split + text_splits = [] + for split in list_of_splits: + text = "".join(split) + if len(text) > 0: + text_splits.append(text) + + return text_splits, split_start_page_numbers, split_start_indices + + +if nltk_imports.is_successful(): + ISO639_TO_NLTK = { + "ru": "russian", + "sl": "slovene", + "es": "spanish", + "sv": "swedish", + "tr": "turkish", + "cs": "czech", + "da": "danish", + "nl": "dutch", + "en": "english", + "et": "estonian", + "fi": "finnish", + "fr": "french", + "de": "german", + "el": "greek", + "it": "italian", + "no": "norwegian", + "pl": "polish", + "pt": "portuguese", + "ml": "malayalam", + } + + QUOTE_SPANS_RE = re.compile(r"\W(\"+|\'+).*?\1") + + class CustomPunktLanguageVars(nltk.tokenize.punkt.PunktLanguageVars): + # The following adjustment of PunktSentenceTokenizer is inspired by: + # https://stackoverflow.com/questions/33139531/preserve-empty-lines-with-nltks-punkt-tokenizer + # It is needed for preserving whitespace while splitting text into sentences. + _period_context_fmt = r""" + %(SentEndChars)s # a potential sentence ending + \s* # match potential whitespace [ \t\n\x0B\f\r] + (?=(?P + %(NonWord)s # either other punctuation + | + (?P\S+) # or some other token - original version: \s+(?P\S+) + ))""" + + def period_context_re(self) -> re.Pattern: + """ + Compiles and returns a regular expression to find contexts including possible sentence boundaries. + + :returns: A compiled regular expression pattern. + """ + try: + return self._re_period_context # type: ignore + except: # noqa: E722 + self._re_period_context = re.compile( + self._period_context_fmt + % { + "NonWord": self._re_non_word_chars, + # SentEndChars might be followed by closing brackets, so we match them here. + "SentEndChars": self._re_sent_end_chars + r"[\)\]}]*", + }, + re.UNICODE | re.VERBOSE, + ) + return self._re_period_context + + def load_sentence_tokenizer( + language: Language, keep_white_spaces: bool = False + ) -> nltk.tokenize.punkt.PunktSentenceTokenizer: + """ + Utility function to load the nltk sentence tokenizer. + + :param language: The language for the tokenizer. + :param keep_white_spaces: If True, the tokenizer will keep white spaces between sentences. + :returns: nltk sentence tokenizer. + """ + try: + nltk.data.find("tokenizers/punkt_tab") + except LookupError: + try: + nltk.download("punkt_tab") + except FileExistsError as error: + logger.debug("NLTK punkt tokenizer seems to be already downloaded. Error message: {error}", error=error) + + language_name = ISO639_TO_NLTK.get(language) + + if language_name is not None: + sentence_tokenizer = nltk.data.load(f"tokenizers/punkt_tab/{language_name}.pickle") + else: + logger.warning( + "PreProcessor couldn't find the default sentence tokenizer model for {language}. " + " Using English instead. You may train your own model and use the 'tokenizer_model_folder' parameter.", + language=language, + ) + sentence_tokenizer = nltk.data.load("tokenizers/punkt_tab/english.pickle") + + if keep_white_spaces: + sentence_tokenizer._lang_vars = CustomPunktLanguageVars() + + return sentence_tokenizer + + class SentenceSplitter: # pylint: disable=too-few-public-methods + """ + SentenceSplitter splits a text into sentences using the nltk sentence tokenizer + """ + + def __init__( + self, + language: Language = "en", + use_split_rules: bool = True, + extend_abbreviations: bool = True, + keep_white_spaces: bool = False, + ) -> None: + """ + Initializes the SentenceSplitter with the specified language, split rules, and abbreviation handling. + + :param language: The language for the tokenizer. Default is "en". + :param use_split_rules: If True, the additional split rules are used. If False, the rules are not used. + :param extend_abbreviations: If True, the abbreviations used by NLTK's PunktTokenizer are extended by a list + of curated abbreviations if available. If False, the default abbreviations are used. + Currently supported languages are: en, de. + :param keep_white_spaces: If True, the tokenizer will keep white spaces between sentences. + """ + self.language = language + self.sentence_tokenizer = load_sentence_tokenizer(language, keep_white_spaces=keep_white_spaces) + self.use_split_rules = use_split_rules + if extend_abbreviations: + abbreviations = SentenceSplitter._read_abbreviations(language) + self.sentence_tokenizer._params.abbrev_types.update(abbreviations) + self.keep_white_spaces = keep_white_spaces + + def split_sentences(self, text: str) -> List[Dict[str, Any]]: + """ + Splits a text into sentences including references to original char positions for each split. + + :param text: The text to split. + :returns: list of sentences with positions. + """ + sentence_spans = list(self.sentence_tokenizer.span_tokenize(text)) + if self.use_split_rules: + sentence_spans = SentenceSplitter._apply_split_rules(text, sentence_spans) + + sentences = [{"sentence": text[start:end], "start": start, "end": end} for start, end in sentence_spans] + return sentences + + @staticmethod + def _apply_split_rules(text: str, sentence_spans: List[Tuple[int, int]]) -> List[Tuple[int, int]]: + """ + Applies additional split rules to the sentence spans. + + :param text: The text to split. + :param sentence_spans: The list of sentence spans to split. + :returns: The list of sentence spans after applying the split rules. + """ + new_sentence_spans = [] + quote_spans = [match.span() for match in QUOTE_SPANS_RE.finditer(text)] + while sentence_spans: + span = sentence_spans.pop(0) + next_span = sentence_spans[0] if len(sentence_spans) > 0 else None + while next_span and SentenceSplitter._needs_join(text, span, next_span, quote_spans): + sentence_spans.pop(0) + span = (span[0], next_span[1]) + next_span = sentence_spans[0] if len(sentence_spans) > 0 else None + start, end = span + new_sentence_spans.append((start, end)) + return new_sentence_spans + + @staticmethod + def _needs_join( + text: str, span: Tuple[int, int], next_span: Tuple[int, int], quote_spans: List[Tuple[int, int]] + ) -> bool: + """ + Checks if the spans need to be joined as parts of one sentence. + + :param text: The text containing the spans. + :param span: The current sentence span within text. + :param next_span: The next sentence span within text. + :param quote_spans: All quoted spans within text. + :returns: True if the spans needs to be joined. + """ + start, end = span + next_start, next_end = next_span + + # sentence. sentence"\nsentence -> no split (end << quote_end) + # sentence.", sentence -> no split (end < quote_end) + # sentence?", sentence -> no split (end < quote_end) + if any(quote_start < end < quote_end for quote_start, quote_end in quote_spans): + # sentence boundary is inside a quote + return True + + # sentence." sentence -> split (end == quote_end) + # sentence?" sentence -> no split (end == quote_end) + if any( + quote_start < end == quote_end and text[quote_end - 2] == "?" for quote_start, quote_end in quote_spans + ): + # question is cited + return True + + if re.search(r"(^|\n)\s*\d{1,2}\.$", text[start:end]) is not None: + # sentence ends with a numeration + return True + + # next sentence starts with a bracket or we return False + return re.search(r"^\s*[\(\[]", text[next_start:next_end]) is not None + + @staticmethod + def _read_abbreviations(language: Language) -> List[str]: + """ + Reads the abbreviations for a given language from the abbreviations file. + + :param language: The language to read the abbreviations for. + :returns: List of abbreviations. + """ + abbreviations_file = Path(__file__).parent.parent / f"data/abbreviations/{language}.txt" + if not abbreviations_file.exists(): + logger.warning( + "No abbreviations file found for {language}.Using default abbreviations.", language=language + ) + return [] + + abbreviations = abbreviations_file.read_text().split("\n") + return abbreviations diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/preprocessors/text_cleaner.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/preprocessors/text_cleaner.py new file mode 100644 index 0000000000000000000000000000000000000000..ea31a59fc7efcba22e3a1cfcf7be10c841eae1b9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/preprocessors/text_cleaner.py @@ -0,0 +1,83 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import re +import string +from typing import Any, Dict, List, Optional + +from haystack import component + + +@component +class TextCleaner: + """ + Cleans text strings. + + It can remove substrings matching a list of regular expressions, convert text to lowercase, + remove punctuation, and remove numbers. + Use it to clean up text data before evaluation. + + ### Usage example + + ```python + from haystack.components.preprocessors import TextCleaner + + text_to_clean = "1Moonlight shimmered softly, 300 Wolves howled nearby, Night enveloped everything." + + cleaner = TextCleaner(convert_to_lowercase=True, remove_punctuation=False, remove_numbers=True) + result = cleaner.run(texts=[text_to_clean]) + ``` + """ + + def __init__( + self, + remove_regexps: Optional[List[str]] = None, + convert_to_lowercase: bool = False, + remove_punctuation: bool = False, + remove_numbers: bool = False, + ): + """ + Initializes the TextCleaner component. + + :param remove_regexps: A list of regex patterns to remove matching substrings from the text. + :param convert_to_lowercase: If `True`, converts all characters to lowercase. + :param remove_punctuation: If `True`, removes punctuation from the text. + :param remove_numbers: If `True`, removes numerical digits from the text. + """ + self._remove_regexps = remove_regexps + self._convert_to_lowercase = convert_to_lowercase + self._remove_punctuation = remove_punctuation + self._remove_numbers = remove_numbers + + self._regex = None + if remove_regexps: + self._regex = re.compile("|".join(remove_regexps), flags=re.IGNORECASE) + to_remove = "" + if remove_punctuation: + to_remove = string.punctuation + if remove_numbers: + to_remove += string.digits + + self._translator = str.maketrans("", "", to_remove) if to_remove else None + + @component.output_types(texts=List[str]) + def run(self, texts: List[str]) -> Dict[str, Any]: + """ + Cleans up the given list of strings. + + :param texts: List of strings to clean. + :returns: A dictionary with the following key: + - `texts`: the cleaned list of strings. + """ + + if self._regex: + texts = [self._regex.sub("", text) for text in texts] + + if self._convert_to_lowercase: + texts = [text.lower() for text in texts] + + if self._translator: + texts = [text.translate(self._translator) for text in texts] + + return {"texts": texts} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/rankers/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/rankers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eb2728a3446eb6a3b667e1b54d2153dd9b13f56a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/rankers/__init__.py @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.rankers.lost_in_the_middle import LostInTheMiddleRanker +from haystack.components.rankers.meta_field import MetaFieldRanker +from haystack.components.rankers.sentence_transformers_diversity import SentenceTransformersDiversityRanker +from haystack.components.rankers.transformers_similarity import TransformersSimilarityRanker + +__all__ = [ + "LostInTheMiddleRanker", + "MetaFieldRanker", + "SentenceTransformersDiversityRanker", + "TransformersSimilarityRanker", +] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/rankers/lost_in_the_middle.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/rankers/lost_in_the_middle.py new file mode 100644 index 0000000000000000000000000000000000000000..f757fadddc248c6cce78b72e5ceccf0a4eb19951 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/rankers/lost_in_the_middle.py @@ -0,0 +1,133 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Dict, List, Optional + +from haystack import Document, component + + +@component +class LostInTheMiddleRanker: + """ + A LostInTheMiddle Ranker. + + Ranks documents based on the 'lost in the middle' order so that the most relevant documents are either at the + beginning or end, while the least relevant are in the middle. + + LostInTheMiddleRanker assumes that some prior component in the pipeline has already ranked documents by relevance + and requires no query as input but only documents. It is typically used as the last component before building a + prompt for an LLM to prepare the input context for the LLM. + + Lost in the Middle ranking lays out document contents into LLM context so that the most relevant contents are at + the beginning or end of the input context, while the least relevant is in the middle of the context. See the + paper ["Lost in the Middle: How Language Models Use Long Contexts"](https://arxiv.org/abs/2307.03172) for more + details. + + Usage example: + ```python + from haystack.components.rankers import LostInTheMiddleRanker + from haystack import Document + + ranker = LostInTheMiddleRanker() + docs = [Document(content="Paris"), Document(content="Berlin"), Document(content="Madrid")] + result = ranker.run(documents=docs) + for doc in result["documents"]: + print(doc.content) + ``` + """ + + def __init__(self, word_count_threshold: Optional[int] = None, top_k: Optional[int] = None): + """ + Initialize the LostInTheMiddleRanker. + + If 'word_count_threshold' is specified, this ranker includes all documents up until the point where adding + another document would exceed the 'word_count_threshold'. The last document that causes the threshold to + be breached will be included in the resulting list of documents, but all subsequent documents will be + discarded. + + :param word_count_threshold: The maximum total number of words across all documents selected by the ranker. + :param top_k: The maximum number of documents to return. + """ + if isinstance(word_count_threshold, int) and word_count_threshold <= 0: + raise ValueError( + f"Invalid value for word_count_threshold: {word_count_threshold}. " f"word_count_threshold must be > 0." + ) + if isinstance(top_k, int) and top_k <= 0: + raise ValueError(f"top_k must be > 0, but got {top_k}") + + self.word_count_threshold = word_count_threshold + self.top_k = top_k + + @component.output_types(documents=List[Document]) + def run( + self, documents: List[Document], top_k: Optional[int] = None, word_count_threshold: Optional[int] = None + ) -> Dict[str, List[Document]]: + """ + Reranks documents based on the "lost in the middle" order. + + :param documents: List of Documents to reorder. + :param top_k: The maximum number of documents to return. + :param word_count_threshold: The maximum total number of words across all documents selected by the ranker. + :returns: + A dictionary with the following keys: + - `documents`: Reranked list of Documents + + :raises ValueError: + If any of the documents is not textual. + """ + if isinstance(word_count_threshold, int) and word_count_threshold <= 0: + raise ValueError( + f"Invalid value for word_count_threshold: {word_count_threshold}. " f"word_count_threshold must be > 0." + ) + if isinstance(top_k, int) and top_k <= 0: + raise ValueError(f"top_k must be > 0, but got {top_k}") + + if not documents: + return {"documents": []} + + top_k = top_k or self.top_k + word_count_threshold = word_count_threshold or self.word_count_threshold + + documents_to_reorder = documents[:top_k] if top_k else documents + + # If there's only one document, return it as is + if len(documents_to_reorder) == 1: + return {"documents": documents_to_reorder} + + # Raise an error if any document is not textual + if any(not doc.content_type == "text" for doc in documents_to_reorder): + raise ValueError("Some provided documents are not textual; LostInTheMiddleRanker can process only text.") + + # Initialize word count and indices for the "lost in the middle" order + word_count = 0 + document_index = list(range(len(documents_to_reorder))) + lost_in_the_middle_indices = [0] + + # If word count threshold is set and the first document has content, calculate word count for the first document + if word_count_threshold and documents_to_reorder[0].content: + word_count = len(documents_to_reorder[0].content.split()) + + # If the first document already meets the word count threshold, return it + if word_count >= word_count_threshold: + return {"documents": [documents_to_reorder[0]]} + + # Start from the second document and create "lost in the middle" order + for doc_idx in document_index[1:]: + # Calculate the index at which the current document should be inserted + insertion_index = len(lost_in_the_middle_indices) // 2 + len(lost_in_the_middle_indices) % 2 + + # Insert the document index at the calculated position + lost_in_the_middle_indices.insert(insertion_index, doc_idx) + + # If word count threshold is set and the document has content, calculate the total word count + if word_count_threshold and documents_to_reorder[doc_idx].content: + word_count += len(documents_to_reorder[doc_idx].content.split()) # type: ignore[union-attr] + + # If the total word count meets the threshold, stop processing further documents + if word_count >= word_count_threshold: + break + + # Documents in the "lost in the middle" order + ranked_docs = [documents_to_reorder[idx] for idx in lost_in_the_middle_indices] + return {"documents": ranked_docs} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/rankers/meta_field.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/rankers/meta_field.py new file mode 100644 index 0000000000000000000000000000000000000000..3b28742a0549b8474c28430aa404f2b434a8e87f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/rankers/meta_field.py @@ -0,0 +1,423 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from collections import defaultdict +from typing import Any, Callable, Dict, List, Literal, Optional + +from dateutil.parser import parse as date_parse + +from haystack import Document, component, logging + +logger = logging.getLogger(__name__) + + +@component +class MetaFieldRanker: + """ + Ranks Documents based on the value of their specific meta field. + + The ranking can be performed in descending order or ascending order. + + Usage example: + + ```python + from haystack import Document + from haystack.components.rankers import MetaFieldRanker + + ranker = MetaFieldRanker(meta_field="rating") + docs = [ + Document(content="Paris", meta={"rating": 1.3}), + Document(content="Berlin", meta={"rating": 0.7}), + Document(content="Barcelona", meta={"rating": 2.1}), + ] + + output = ranker.run(documents=docs) + docs = output["documents"] + assert docs[0].content == "Barcelona" + ``` + """ + + def __init__( + self, + meta_field: str, + weight: float = 1.0, + top_k: Optional[int] = None, + ranking_mode: Literal["reciprocal_rank_fusion", "linear_score"] = "reciprocal_rank_fusion", + sort_order: Literal["ascending", "descending"] = "descending", + missing_meta: Literal["drop", "top", "bottom"] = "bottom", + meta_value_type: Optional[Literal["float", "int", "date"]] = None, + ): + """ + Creates an instance of MetaFieldRanker. + + :param meta_field: + The name of the meta field to rank by. + :param weight: + In range [0,1]. + 0 disables ranking by a meta field. + 0.5 ranking from previous component and based on meta field have the same weight. + 1 ranking by a meta field only. + :param top_k: + The maximum number of Documents to return per query. + If not provided, the Ranker returns all documents it receives in the new ranking order. + :param ranking_mode: + The mode used to combine the Retriever's and Ranker's scores. + Possible values are 'reciprocal_rank_fusion' (default) and 'linear_score'. + Use the 'linear_score' mode only with Retrievers or Rankers that return a score in range [0,1]. + :param sort_order: + Whether to sort the meta field by ascending or descending order. + Possible values are `descending` (default) and `ascending`. + :param missing_meta: + What to do with documents that are missing the sorting metadata field. + Possible values are: + - 'drop' will drop the documents entirely. + - 'top' will place the documents at the top of the metadata-sorted list + (regardless of 'ascending' or 'descending'). + - 'bottom' will place the documents at the bottom of metadata-sorted list + (regardless of 'ascending' or 'descending'). + :param meta_value_type: + Parse the meta value into the data type specified before sorting. + This will only work if all meta values stored under `meta_field` in the provided documents are strings. + For example, if we specified `meta_value_type="date"` then for the meta value `"date": "2015-02-01"` + we would parse the string into a datetime object and then sort the documents by date. + The available options are: + - 'float' will parse the meta values into floats. + - 'int' will parse the meta values into integers. + - 'date' will parse the meta values into datetime objects. + - 'None' (default) will do no parsing. + """ + + self.meta_field = meta_field + self.weight = weight + self.top_k = top_k + self.ranking_mode = ranking_mode + self.sort_order = sort_order + self.missing_meta = missing_meta + self._validate_params( + weight=self.weight, + top_k=self.top_k, + ranking_mode=self.ranking_mode, + sort_order=self.sort_order, + missing_meta=self.missing_meta, + meta_value_type=meta_value_type, + ) + self.meta_value_type = meta_value_type + + def _validate_params( + self, + weight: float, + top_k: Optional[int], + ranking_mode: Literal["reciprocal_rank_fusion", "linear_score"], + sort_order: Literal["ascending", "descending"], + missing_meta: Literal["drop", "top", "bottom"], + meta_value_type: Optional[Literal["float", "int", "date"]], + ): + if top_k is not None and top_k <= 0: + raise ValueError("top_k must be > 0, but got %s" % top_k) + + if weight < 0 or weight > 1: + raise ValueError( + "Parameter must be in range [0,1] but is currently set to '%s'.\n'0' disables sorting by a " + "meta field, '0.5' assigns equal weight to the previous relevance scores and the meta field, and " + "'1' ranks by the meta field only.\nChange the parameter to a value in range 0 to 1 when " + "initializing the MetaFieldRanker." % weight + ) + + if ranking_mode not in ["reciprocal_rank_fusion", "linear_score"]: + raise ValueError( + "The value of parameter must be 'reciprocal_rank_fusion' or 'linear_score', but is " + "currently set to '%s'.\nChange the value to 'reciprocal_rank_fusion' or " + "'linear_score' when initializing the MetaFieldRanker." % ranking_mode + ) + + if sort_order not in ["ascending", "descending"]: + raise ValueError( + "The value of parameter must be 'ascending' or 'descending', " + "but is currently set to '%s'.\n" + "Change the value to 'ascending' or 'descending' when initializing the " + "MetaFieldRanker." % sort_order + ) + + if missing_meta not in ["drop", "top", "bottom"]: + raise ValueError( + "The value of parameter must be 'drop', 'top', or 'bottom', " + "but is currently set to '%s'.\n" + "Change the value to 'drop', 'top', or 'bottom' when initializing the " + "MetaFieldRanker." % missing_meta + ) + + if meta_value_type not in ["float", "int", "date", None]: + raise ValueError( + "The value of parameter must be 'float', 'int', 'date' or None but is " + "currently set to '%s'.\n" + "Change the value to 'float', 'int', 'date' or None when initializing the " + "MetaFieldRanker." % meta_value_type + ) + + @component.output_types(documents=List[Document]) + def run( + self, + documents: List[Document], + top_k: Optional[int] = None, + weight: Optional[float] = None, + ranking_mode: Optional[Literal["reciprocal_rank_fusion", "linear_score"]] = None, + sort_order: Optional[Literal["ascending", "descending"]] = None, + missing_meta: Optional[Literal["drop", "top", "bottom"]] = None, + meta_value_type: Optional[Literal["float", "int", "date"]] = None, + ): + """ + Ranks a list of Documents based on the selected meta field by: + + 1. Sorting the Documents by the meta field in descending or ascending order. + 2. Merging the rankings from the previous component and based on the meta field according to ranking mode and + weight. + 3. Returning the top-k documents. + + :param documents: + Documents to be ranked. + :param top_k: + The maximum number of Documents to return per query. + If not provided, the top_k provided at initialization time is used. + :param weight: + In range [0,1]. + 0 disables ranking by a meta field. + 0.5 ranking from previous component and based on meta field have the same weight. + 1 ranking by a meta field only. + If not provided, the weight provided at initialization time is used. + :param ranking_mode: + (optional) The mode used to combine the Retriever's and Ranker's scores. + Possible values are 'reciprocal_rank_fusion' (default) and 'linear_score'. + Use the 'score' mode only with Retrievers or Rankers that return a score in range [0,1]. + If not provided, the ranking_mode provided at initialization time is used. + :param sort_order: + Whether to sort the meta field by ascending or descending order. + Possible values are `descending` (default) and `ascending`. + If not provided, the sort_order provided at initialization time is used. + :param missing_meta: + What to do with documents that are missing the sorting metadata field. + Possible values are: + - 'drop' will drop the documents entirely. + - 'top' will place the documents at the top of the metadata-sorted list + (regardless of 'ascending' or 'descending'). + - 'bottom' will place the documents at the bottom of metadata-sorted list + (regardless of 'ascending' or 'descending'). + If not provided, the missing_meta provided at initialization time is used. + :param meta_value_type: + Parse the meta value into the data type specified before sorting. + This will only work if all meta values stored under `meta_field` in the provided documents are strings. + For example, if we specified `meta_value_type="date"` then for the meta value `"date": "2015-02-01"` + we would parse the string into a datetime object and then sort the documents by date. + The available options are: + -'float' will parse the meta values into floats. + -'int' will parse the meta values into integers. + -'date' will parse the meta values into datetime objects. + -'None' (default) will do no parsing. + :returns: + A dictionary with the following keys: + - `documents`: List of Documents sorted by the specified meta field. + + :raises ValueError: + If `top_k` is not > 0. + If `weight` is not in range [0,1]. + If `ranking_mode` is not 'reciprocal_rank_fusion' or 'linear_score'. + If `sort_order` is not 'ascending' or 'descending'. + If `meta_value_type` is not 'float', 'int', 'date' or `None`. + """ + if not documents: + return {"documents": []} + + top_k = top_k or self.top_k + weight = weight if weight is not None else self.weight + ranking_mode = ranking_mode or self.ranking_mode + sort_order = sort_order or self.sort_order + missing_meta = missing_meta or self.missing_meta + meta_value_type = meta_value_type or self.meta_value_type + self._validate_params( + weight=weight, + top_k=top_k, + ranking_mode=ranking_mode, + sort_order=sort_order, + missing_meta=missing_meta, + meta_value_type=meta_value_type, + ) + + # If the weight is 0 then ranking by meta field is disabled and the original documents should be returned + if weight == 0: + return {"documents": documents[:top_k]} + + docs_with_meta_field = [doc for doc in documents if self.meta_field in doc.meta] + docs_missing_meta_field = [doc for doc in documents if self.meta_field not in doc.meta] + + # If all docs are missing self.meta_field return original documents + if len(docs_with_meta_field) == 0: + logger.warning( + "The parameter is currently set to '{meta_field}', but none of the provided " + "Documents with IDs {document_ids} have this meta key.\n" + "Set to the name of a field that is present within the provided Documents.\n" + "Returning the of the original Documents since there are no values to rank.", + meta_field=self.meta_field, + document_ids=",".join([doc.id for doc in documents]), + ) + return {"documents": documents[:top_k]} + + if len(docs_missing_meta_field) > 0: + warning_start = ( + f"The parameter is currently set to '{self.meta_field}' but the Documents " + f"with IDs {','.join([doc.id for doc in docs_missing_meta_field])} don't have this meta key.\n" + ) + + if missing_meta == "bottom": + logger.warning( + "{warning_start}Because the parameter is set to 'bottom', these Documents will be " + "placed at the end of the sorting order.", + warning_start=warning_start, + ) + elif missing_meta == "top": + logger.warning( + "{warning_start}Because the parameter is set to 'top', these Documents will be " + "placed at the top of the sorting order.", + warning_start=warning_start, + ) + else: + logger.warning( + "{warning_start}Because the parameter is set to 'drop', these Documents will be " + "removed from the list of retrieved Documents.", + warning_start=warning_start, + ) + + # If meta_value_type is provided try to parse the meta values + parsed_meta = self._parse_meta(docs_with_meta_field=docs_with_meta_field, meta_value_type=meta_value_type) + tuple_parsed_meta_and_docs = list(zip(parsed_meta, docs_with_meta_field)) + + # Sort the documents by self.meta_field + reverse = sort_order == "descending" + try: + tuple_sorted_by_meta = sorted(tuple_parsed_meta_and_docs, key=lambda x: x[0], reverse=reverse) + except TypeError as error: + # Return original documents if mixed types that are not comparable are returned (e.g. int and list) + logger.warning( + "Tried to sort Documents with IDs {document_ids}, but got TypeError with the message: {error}\n" + "Returning the of the original Documents since meta field ranking is not possible.", + document_ids=",".join([doc.id for doc in docs_with_meta_field]), + error=error, + ) + return {"documents": documents[:top_k]} + + # Merge rankings and handle missing meta fields as specified in the missing_meta parameter + sorted_by_meta = [doc for meta, doc in tuple_sorted_by_meta] + if missing_meta == "bottom": + sorted_documents = sorted_by_meta + docs_missing_meta_field + sorted_documents = self._merge_rankings(documents, sorted_documents, weight, ranking_mode) + elif missing_meta == "top": + sorted_documents = docs_missing_meta_field + sorted_by_meta + sorted_documents = self._merge_rankings(documents, sorted_documents, weight, ranking_mode) + else: + sorted_documents = sorted_by_meta + sorted_documents = self._merge_rankings(docs_with_meta_field, sorted_documents, weight, ranking_mode) + + return {"documents": sorted_documents[:top_k]} + + def _parse_meta( + self, docs_with_meta_field: List[Document], meta_value_type: Optional[Literal["float", "int", "date"]] + ) -> List[Any]: + """ + Parse the meta values stored under `self.meta_field` for the Documents provided in `docs_with_meta_field`. + """ + if meta_value_type is None: + return [d.meta[self.meta_field] for d in docs_with_meta_field] + + unique_meta_values = {doc.meta[self.meta_field] for doc in docs_with_meta_field} + if not all(isinstance(meta_value, str) for meta_value in unique_meta_values): + logger.warning( + "The parameter is currently set to '{meta_field}', but not all of meta values in the " + "provided Documents with IDs {document_ids} are strings.\n" + "Skipping parsing of the meta values.\n" + "Set all meta values found under the parameter to strings to use .", + meta_field=meta_value_type, + document_ids=",".join([doc.id for doc in docs_with_meta_field]), + ) + return [d.meta[self.meta_field] for d in docs_with_meta_field] + + parse_fn: Callable + if meta_value_type == "float": + parse_fn = float + elif meta_value_type == "int": + parse_fn = int + else: + parse_fn = date_parse + + try: + meta_values = [parse_fn(d.meta[self.meta_field]) for d in docs_with_meta_field] + except ValueError as error: + logger.warning( + "Tried to parse the meta values of Documents with IDs {document_ids}, but got ValueError with the " + "message: {error}\n" + "Skipping parsing of the meta values.", + document_ids=",".join([doc.id for doc in docs_with_meta_field]), + error=error, + ) + meta_values = [d.meta[self.meta_field] for d in docs_with_meta_field] + + return meta_values + + def _merge_rankings( + self, + documents: List[Document], + sorted_documents: List[Document], + weight: float, + ranking_mode: Literal["reciprocal_rank_fusion", "linear_score"], + ) -> List[Document]: + """ + Merge the two different rankings for Documents sorted both by their content and by their meta field. + """ + scores_map: Dict = defaultdict(int) + + if ranking_mode == "reciprocal_rank_fusion": + for i, (document, sorted_doc) in enumerate(zip(documents, sorted_documents)): + scores_map[document.id] += self._calculate_rrf(rank=i) * (1 - weight) + scores_map[sorted_doc.id] += self._calculate_rrf(rank=i) * weight + elif ranking_mode == "linear_score": + for i, (document, sorted_doc) in enumerate(zip(documents, sorted_documents)): + score = float(0) + if document.score is None: + logger.warning("The score wasn't provided; defaulting to 0.") + elif document.score < 0 or document.score > 1: + logger.warning( + "The score {score} for Document {document_id} is outside the [0,1] range; defaulting to 0", + score=document.score, + document_id=document.id, + ) + else: + score = document.score + + scores_map[document.id] += score * (1 - weight) + scores_map[sorted_doc.id] += self._calc_linear_score(rank=i, amount=len(sorted_documents)) * weight + + for document in documents: + document.score = scores_map[document.id] + + new_sorted_documents = sorted(documents, key=lambda doc: doc.score if doc.score else -1, reverse=True) + return new_sorted_documents + + @staticmethod + def _calculate_rrf(rank: int, k: int = 61) -> float: + """ + Calculates the reciprocal rank fusion. + + The constant K is set to 61 (60 was suggested by the original paper, plus 1 as python lists are 0-based and + the [paper](https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf) used 1-based ranking). + """ + return 1 / (k + rank) + + @staticmethod + def _calc_linear_score(rank: int, amount: int) -> float: + """ + Calculate the meta field score as a linear score between the greatest and the lowest score in the list. + + This linear scaling is useful for: + - Reducing the effect of outliers + - Creating scores that are meaningfully distributed in the range [0,1], + similar to scores coming from a Retriever or Ranker. + """ + return (amount - rank) / amount diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/rankers/sentence_transformers_diversity.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/rankers/sentence_transformers_diversity.py new file mode 100644 index 0000000000000000000000000000000000000000..cc5d64d3bfa506ebbb6f604051f719681e0d46e1 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/rankers/sentence_transformers_diversity.py @@ -0,0 +1,253 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Literal, Optional + +from haystack import Document, component, default_from_dict, default_to_dict, logging +from haystack.lazy_imports import LazyImport +from haystack.utils import ComponentDevice, Secret, deserialize_secrets_inplace + +logger = logging.getLogger(__name__) + + +with LazyImport(message="Run 'pip install \"sentence-transformers>=3.0.0\"'") as torch_and_sentence_transformers_import: + import torch + from sentence_transformers import SentenceTransformer + + +@component +class SentenceTransformersDiversityRanker: + """ + A Diversity Ranker based on Sentence Transformers. + + Implements a document ranking algorithm that orders documents in such a way as to maximize the overall diversity + of the documents. + + This component provides functionality to rank a list of documents based on their similarity with respect to the + query to maximize the overall diversity. It uses a pre-trained Sentence Transformers model to embed the query and + the Documents. + + Usage example: + ```python + from haystack import Document + from haystack.components.rankers import SentenceTransformersDiversityRanker + + ranker = SentenceTransformersDiversityRanker(model="sentence-transformers/all-MiniLM-L6-v2", similarity="cosine") + ranker.warm_up() + + docs = [Document(content="Paris"), Document(content="Berlin")] + query = "What is the capital of germany?" + output = ranker.run(query=query, documents=docs) + docs = output["documents"] + ``` + """ + + def __init__( + self, + model: str = "sentence-transformers/all-MiniLM-L6-v2", + top_k: int = 10, + device: Optional[ComponentDevice] = None, + token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + similarity: Literal["dot_product", "cosine"] = "cosine", + query_prefix: str = "", + query_suffix: str = "", + document_prefix: str = "", + document_suffix: str = "", + meta_fields_to_embed: Optional[List[str]] = None, + embedding_separator: str = "\n", + ): + """ + Initialize a SentenceTransformersDiversityRanker. + + :param model: Local path or name of the model in Hugging Face's model hub, + such as `'sentence-transformers/all-MiniLM-L6-v2'`. + :param top_k: The maximum number of Documents to return per query. + :param device: The device on which the model is loaded. If `None`, the default device is automatically + selected. + :param token: The API token used to download private models from Hugging Face. + :param similarity: Similarity metric for comparing embeddings. Can be set to "dot_product" (default) or + "cosine". + :param query_prefix: A string to add to the beginning of the query text before ranking. + Can be used to prepend the text with an instruction, as required by some embedding models, + such as E5 and BGE. + :param query_suffix: A string to add to the end of the query text before ranking. + :param document_prefix: A string to add to the beginning of each Document text before ranking. + Can be used to prepend the text with an instruction, as required by some embedding models, + such as E5 and BGE. + :param document_suffix: A string to add to the end of each Document text before ranking. + :param meta_fields_to_embed: List of meta fields that should be embedded along with the Document content. + :param embedding_separator: Separator used to concatenate the meta fields to the Document content. + """ + torch_and_sentence_transformers_import.check() + + self.model_name_or_path = model + if top_k is None or top_k <= 0: + raise ValueError(f"top_k must be > 0, but got {top_k}") + self.top_k = top_k + self.device = ComponentDevice.resolve_device(device) + self.token = token + self.model = None + if similarity not in ["dot_product", "cosine"]: + raise ValueError(f"Similarity must be one of 'dot_product' or 'cosine', but got {similarity}.") + self.similarity = similarity + self.query_prefix = query_prefix + self.document_prefix = document_prefix + self.query_suffix = query_suffix + self.document_suffix = document_suffix + self.meta_fields_to_embed = meta_fields_to_embed or [] + self.embedding_separator = embedding_separator + + def warm_up(self): + """ + Initializes the component. + """ + if self.model is None: + self.model = SentenceTransformer( + model_name_or_path=self.model_name_or_path, + device=self.device.to_torch_str(), + use_auth_token=self.token.resolve_value() if self.token else None, + ) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + model=self.model_name_or_path, + device=self.device.to_dict(), + token=self.token.to_dict() if self.token else None, + top_k=self.top_k, + similarity=self.similarity, + query_prefix=self.query_prefix, + document_prefix=self.document_prefix, + query_suffix=self.query_suffix, + document_suffix=self.document_suffix, + meta_fields_to_embed=self.meta_fields_to_embed, + embedding_separator=self.embedding_separator, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "SentenceTransformersDiversityRanker": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + init_params = data["init_parameters"] + if init_params.get("device") is not None: + init_params["device"] = ComponentDevice.from_dict(init_params["device"]) + deserialize_secrets_inplace(init_params, keys=["token"]) + return default_from_dict(cls, data) + + def _prepare_texts_to_embed(self, documents: List[Document]) -> List[str]: + """ + Prepare the texts to embed by concatenating the Document text with the metadata fields to embed. + """ + texts_to_embed = [] + for doc in documents: + meta_values_to_embed = [ + str(doc.meta[key]) for key in self.meta_fields_to_embed if key in doc.meta and doc.meta[key] + ] + text_to_embed = ( + self.document_prefix + + self.embedding_separator.join(meta_values_to_embed + [doc.content or ""]) + + self.document_suffix + ) + texts_to_embed.append(text_to_embed) + + return texts_to_embed + + def _greedy_diversity_order(self, query: str, documents: List[Document]) -> List[Document]: + """ + Orders the given list of documents to maximize diversity. + + The algorithm first calculates embeddings for each document and the query. It starts by selecting the document + that is semantically closest to the query. Then, for each remaining document, it selects the one that, on + average, is least similar to the already selected documents. This process continues until all documents are + selected, resulting in a list where each subsequent document contributes the most to the overall diversity of + the selected set. + + :param query: The search query. + :param documents: The list of Document objects to be ranked. + + :return: A list of documents ordered to maximize diversity. + """ + texts_to_embed = self._prepare_texts_to_embed(documents) + + # Calculate embeddings + doc_embeddings = self.model.encode(texts_to_embed, convert_to_tensor=True) # type: ignore[attr-defined] + query_embedding = self.model.encode([self.query_prefix + query + self.query_suffix], convert_to_tensor=True) # type: ignore[attr-defined] + + # Normalize embeddings to unit length for computing cosine similarity + if self.similarity == "cosine": + doc_embeddings /= torch.norm(doc_embeddings, p=2, dim=-1).unsqueeze(-1) + query_embedding /= torch.norm(query_embedding, p=2, dim=-1).unsqueeze(-1) + + n = len(documents) + selected: List[int] = [] + + # Compute the similarity vector between the query and documents + query_doc_sim = query_embedding @ doc_embeddings.T + + # Start with the document with the highest similarity to the query + selected.append(int(torch.argmax(query_doc_sim).item())) + + selected_sum = doc_embeddings[selected[0]] / n + + while len(selected) < n: + # Compute mean of dot products of all selected documents and all other documents + similarities = selected_sum @ doc_embeddings.T + # Mask documents that are already selected + similarities[selected] = torch.inf + # Select the document with the lowest total similarity score + index_unselected = int(torch.argmin(similarities).item()) + selected.append(index_unselected) + # It's enough just to add to the selected vectors because dot product is distributive + # It's divided by n for numerical stability + selected_sum += doc_embeddings[index_unselected] / n + + ranked_docs: List[Document] = [documents[i] for i in selected] + + return ranked_docs + + @component.output_types(documents=List[Document]) + def run(self, query: str, documents: List[Document], top_k: Optional[int] = None): + """ + Rank the documents based on their diversity. + + :param query: The search query. + :param documents: List of Document objects to be ranker. + :param top_k: Optional. An integer to override the top_k set during initialization. + + :returns: A dictionary with the following key: + - `documents`: List of Document objects that have been selected based on the diversity ranking. + + :raises ValueError: If the top_k value is less than or equal to 0. + :raises RuntimeError: If the component has not been warmed up. + """ + if self.model is None: + error_msg = ( + "The component SentenceTransformersDiversityRanker wasn't warmed up. " + "Run 'warm_up()' before calling 'run()'." + ) + raise RuntimeError(error_msg) + + if not documents: + return {"documents": []} + + if top_k is None: + top_k = self.top_k + elif top_k <= 0: + raise ValueError(f"top_k must be > 0, but got {top_k}") + + diversity_sorted = self._greedy_diversity_order(query=query, documents=documents) + + return {"documents": diversity_sorted[:top_k]} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/rankers/transformers_similarity.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/rankers/transformers_similarity.py new file mode 100644 index 0000000000000000000000000000000000000000..d380768d3d018ef47ba51b7fd5f3bc45a0578114 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/rankers/transformers_similarity.py @@ -0,0 +1,309 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from haystack import Document, component, default_from_dict, default_to_dict, logging +from haystack.lazy_imports import LazyImport +from haystack.utils import ComponentDevice, DeviceMap, Secret, deserialize_secrets_inplace +from haystack.utils.hf import deserialize_hf_model_kwargs, resolve_hf_device_map, serialize_hf_model_kwargs + +logger = logging.getLogger(__name__) + + +with LazyImport(message="Run 'pip install transformers[torch,sentencepiece]'") as torch_and_transformers_import: + import accelerate # pylint: disable=unused-import # the library is used but not directly referenced + import torch + from torch.utils.data import DataLoader, Dataset + from transformers import AutoModelForSequenceClassification, AutoTokenizer + + +@component +class TransformersSimilarityRanker: + """ + Ranks documents based on their semantic similarity to the query. + + It uses a pre-trained cross-encoder model from Hugging Face to embed the query and the documents. + + ### Usage example + + ```python + from haystack import Document + from haystack.components.rankers import TransformersSimilarityRanker + + ranker = TransformersSimilarityRanker() + docs = [Document(content="Paris"), Document(content="Berlin")] + query = "City in Germany" + ranker.warm_up() + result = ranker.run(query=query, documents=docs) + docs = result["documents"] + print(docs[0].content) + ``` + """ + + def __init__( # noqa: PLR0913 + self, + model: Union[str, Path] = "cross-encoder/ms-marco-MiniLM-L-6-v2", + device: Optional[ComponentDevice] = None, + token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + top_k: int = 10, + query_prefix: str = "", + document_prefix: str = "", + meta_fields_to_embed: Optional[List[str]] = None, + embedding_separator: str = "\n", + scale_score: bool = True, + calibration_factor: Optional[float] = 1.0, + score_threshold: Optional[float] = None, + model_kwargs: Optional[Dict[str, Any]] = None, + tokenizer_kwargs: Optional[Dict[str, Any]] = None, + batch_size: int = 16, + ): + """ + Creates an instance of TransformersSimilarityRanker. + + :param model: + The ranking model. Pass a local path or the Hugging Face model name of a cross-encoder model. + :param device: + The device on which the model is loaded. If `None`, overrides the default device. + :param token: + The API token to download private models from Hugging Face. + :param top_k: + The maximum number of documents to return per query. + :param query_prefix: + A string to add at the beginning of the query text before ranking. + Use it to prepend the text with an instruction, as required by reranking models like `bge`. + :param document_prefix: + A string to add at the beginning of each document before ranking. You can use it to prepend the document + with an instruction, as required by embedding models like `bge`. + :param meta_fields_to_embed: + List of metadata fields to embed with the document. + :param embedding_separator: + Separator to concatenate metadata fields to the document. + :param scale_score: + If `True`, scales the raw logit predictions using a Sigmoid activation function. + If `False`, disables scaling of the raw logit predictions. + :param calibration_factor: + Use this factor to calibrate probabilities with `sigmoid(logits * calibration_factor)`. + Used only if `scale_score` is `True`. + :param score_threshold: + Use it to return documents with a score above this threshold only. + :param model_kwargs: + Additional keyword arguments for `AutoModelForSequenceClassification.from_pretrained` + when loading the model. Refer to specific model documentation for available kwargs. + :param tokenizer_kwargs: + Additional keyword arguments for `AutoTokenizer.from_pretrained` when loading the tokenizer. + Refer to specific model documentation for available kwargs. + :param batch_size: + The batch size to use for inference. The higher the batch size, the more memory is required. + If you run into memory issues, reduce the batch size. + + :raises ValueError: + If `top_k` is not > 0. + If `scale_score` is True and `calibration_factor` is not provided. + """ + torch_and_transformers_import.check() + + self.model_name_or_path = str(model) + self.model = None + self.query_prefix = query_prefix + self.document_prefix = document_prefix + self.tokenizer = None + self.device = None + self.top_k = top_k + self.token = token + self.meta_fields_to_embed = meta_fields_to_embed or [] + self.embedding_separator = embedding_separator + self.scale_score = scale_score + self.calibration_factor = calibration_factor + self.score_threshold = score_threshold + + model_kwargs = resolve_hf_device_map(device=device, model_kwargs=model_kwargs) + self.model_kwargs = model_kwargs + self.tokenizer_kwargs = tokenizer_kwargs or {} + self.batch_size = batch_size + + # Parameter validation + if self.scale_score and self.calibration_factor is None: + raise ValueError( + f"scale_score is True so calibration_factor must be provided, but got {calibration_factor}" + ) + + if self.top_k <= 0: + raise ValueError(f"top_k must be > 0, but got {top_k}") + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"model": self.model_name_or_path} + + def warm_up(self): + """ + Initializes the component. + """ + if self.model is None: + self.model = AutoModelForSequenceClassification.from_pretrained( + self.model_name_or_path, token=self.token.resolve_value() if self.token else None, **self.model_kwargs + ) + self.tokenizer = AutoTokenizer.from_pretrained( + self.model_name_or_path, + token=self.token.resolve_value() if self.token else None, + **self.tokenizer_kwargs, + ) + self.device = ComponentDevice.from_multiple(device_map=DeviceMap.from_hf(self.model.hf_device_map)) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + serialization_dict = default_to_dict( + self, + device=None, + model=self.model_name_or_path, + token=self.token.to_dict() if self.token else None, + top_k=self.top_k, + query_prefix=self.query_prefix, + document_prefix=self.document_prefix, + meta_fields_to_embed=self.meta_fields_to_embed, + embedding_separator=self.embedding_separator, + scale_score=self.scale_score, + calibration_factor=self.calibration_factor, + score_threshold=self.score_threshold, + model_kwargs=self.model_kwargs, + tokenizer_kwargs=self.tokenizer_kwargs, + ) + + serialize_hf_model_kwargs(serialization_dict["init_parameters"]["model_kwargs"]) + return serialization_dict + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "TransformersSimilarityRanker": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + init_params = data["init_parameters"] + if init_params.get("device") is not None: + init_params["device"] = ComponentDevice.from_dict(init_params["device"]) + if init_params.get("model_kwargs") is not None: + deserialize_hf_model_kwargs(init_params["model_kwargs"]) + deserialize_secrets_inplace(init_params, keys=["token"]) + + return default_from_dict(cls, data) + + @component.output_types(documents=List[Document]) + def run( + self, + query: str, + documents: List[Document], + top_k: Optional[int] = None, + scale_score: Optional[bool] = None, + calibration_factor: Optional[float] = None, + score_threshold: Optional[float] = None, + ): + """ + Returns a list of documents ranked by their similarity to the given query. + + :param query: + The input query to compare the documents to. + :param documents: + A list of documents to be ranked. + :param top_k: + The maximum number of documents to return. + :param scale_score: + If `True`, scales the raw logit predictions using a Sigmoid activation function. + If `False`, disables scaling of the raw logit predictions. + :param calibration_factor: + Use this factor to calibrate probabilities with `sigmoid(logits * calibration_factor)`. + Used only if `scale_score` is `True`. + :param score_threshold: + Use it to return documents only with a score above this threshold. + :returns: + A dictionary with the following keys: + - `documents`: A list of documents closest to the query, sorted from most similar to least similar. + + :raises ValueError: + If `top_k` is not > 0. + If `scale_score` is True and `calibration_factor` is not provided. + :raises RuntimeError: + If the model is not loaded because `warm_up()` was not called before. + """ + # If a model path is provided but the model isn't loaded + if self.model is None: + raise RuntimeError( + "The component TransformersSimilarityRanker wasn't warmed up. Run 'warm_up()' before calling 'run()'." + ) + + if not documents: + return {"documents": []} + + top_k = top_k or self.top_k + scale_score = scale_score or self.scale_score + calibration_factor = calibration_factor or self.calibration_factor + score_threshold = score_threshold or self.score_threshold + + if top_k <= 0: + raise ValueError(f"top_k must be > 0, but got {top_k}") + + if scale_score and calibration_factor is None: + raise ValueError( + f"scale_score is True so calibration_factor must be provided, but got {calibration_factor}" + ) + + query_doc_pairs = [] + for doc in documents: + meta_values_to_embed = [ + str(doc.meta[key]) for key in self.meta_fields_to_embed if key in doc.meta and doc.meta[key] + ] + text_to_embed = self.embedding_separator.join(meta_values_to_embed + [doc.content or ""]) + query_doc_pairs.append([self.query_prefix + query, self.document_prefix + text_to_embed]) + + class _Dataset(Dataset): + def __init__(self, batch_encoding): + self.batch_encoding = batch_encoding + + def __len__(self): + return len(self.batch_encoding["input_ids"]) + + def __getitem__(self, item): + return {key: self.batch_encoding.data[key][item] for key in self.batch_encoding.data.keys()} + + batch_enc = self.tokenizer(query_doc_pairs, padding=True, truncation=True, return_tensors="pt").to( # type: ignore + self.device.first_device.to_torch() + ) + dataset = _Dataset(batch_enc) + inp_dataloader = DataLoader(dataset, batch_size=self.batch_size, shuffle=False) + + similarity_scores = [] + with torch.inference_mode(): + for features in inp_dataloader: + model_preds = self.model(**features).logits.squeeze(dim=1) # type: ignore + similarity_scores.extend(model_preds) + similarity_scores = torch.stack(similarity_scores) + + if scale_score: + similarity_scores = torch.sigmoid(similarity_scores * calibration_factor) + + _, sorted_indices = torch.sort(similarity_scores, descending=True) + + sorted_indices = sorted_indices.cpu().tolist() # type: ignore + similarity_scores = similarity_scores.cpu().tolist() + ranked_docs = [] + for sorted_index in sorted_indices: + i = sorted_index + documents[i].score = similarity_scores[i] + ranked_docs.append(documents[i]) + + if score_threshold is not None: + ranked_docs = [doc for doc in ranked_docs if doc.score >= score_threshold] + + return {"documents": ranked_docs[:top_k]} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/readers/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/readers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..788f8f206b551cb7fa3b82a40523b4f4f528a4f0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/readers/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.readers.extractive import ExtractiveReader + +__all__ = ["ExtractiveReader"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/readers/extractive.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/readers/extractive.py new file mode 100644 index 0000000000000000000000000000000000000000..85d90a74cfe6b6d3dd5b18e49d26bbfc5d7dbed2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/readers/extractive.py @@ -0,0 +1,646 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import math +import warnings +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +from haystack import Document, ExtractedAnswer, component, default_from_dict, default_to_dict, logging +from haystack.lazy_imports import LazyImport +from haystack.utils import ComponentDevice, DeviceMap, Secret, deserialize_secrets_inplace +from haystack.utils.hf import deserialize_hf_model_kwargs, resolve_hf_device_map, serialize_hf_model_kwargs + +with LazyImport("Run 'pip install transformers[torch,sentencepiece]'") as torch_and_transformers_import: + import accelerate # pylint: disable=unused-import # the library is used but not directly referenced + import torch + from tokenizers import Encoding + from transformers import AutoModelForQuestionAnswering, AutoTokenizer + + +logger = logging.getLogger(__name__) + + +@component +class ExtractiveReader: + """ + Locates and extracts answers to a given query from Documents. + + The ExtractiveReader component performs extractive question answering. + It assigns a score to every possible answer span independently of other answer spans. + This fixes a common issue of other implementations which make comparisons across documents harder by normalizing + each document's answers independently. + + Example usage: + ```python + from haystack import Document + from haystack.components.readers import ExtractiveReader + + docs = [ + Document(content="Python is a popular programming language"), + Document(content="python ist eine beliebte Programmiersprache"), + ] + + reader = ExtractiveReader() + reader.warm_up() + + question = "What is a popular programming language?" + result = reader.run(query=question, documents=docs) + assert "Python" in result["answers"][0].data + ``` + """ + + def __init__( + self, + model: Union[Path, str] = "deepset/roberta-base-squad2-distilled", + device: Optional[ComponentDevice] = None, + token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + top_k: int = 20, + score_threshold: Optional[float] = None, + max_seq_length: int = 384, + stride: int = 128, + max_batch_size: Optional[int] = None, + answers_per_seq: Optional[int] = None, + no_answer: bool = True, + calibration_factor: float = 0.1, + overlap_threshold: Optional[float] = 0.01, + model_kwargs: Optional[Dict[str, Any]] = None, + ) -> None: + """ + Creates an instance of ExtractiveReader. + + :param model: + A Hugging Face transformers question answering model. + Can either be a path to a folder containing the model files or an identifier for the Hugging Face hub. + :param device: + The device on which the model is loaded. If `None`, the default device is automatically selected. + :param token: + The API token used to download private models from Hugging Face. + :param top_k: + Number of answers to return per query. It is required even if score_threshold is set. + An additional answer with no text is returned if no_answer is set to True (default). + :param score_threshold: + Returns only answers with the probability score above this threshold. + :param max_seq_length: + Maximum number of tokens. If a sequence exceeds it, the sequence is split. + :param stride: + Number of tokens that overlap when sequence is split because it exceeds max_seq_length. + :param max_batch_size: + Maximum number of samples that are fed through the model at the same time. + :param answers_per_seq: + Number of answer candidates to consider per sequence. + This is relevant when a Document was split into multiple sequences because of max_seq_length. + :param no_answer: + Whether to return an additional `no answer` with an empty text and a score representing the + probability that the other top_k answers are incorrect. + :param calibration_factor: + Factor used for calibrating probabilities. + :param overlap_threshold: + If set this will remove duplicate answers if they have an overlap larger than the + supplied threshold. For example, for the answers "in the river in Maine" and "the river" we would remove + one of these answers since the second answer has a 100% (1.0) overlap with the first answer. + However, for the answers "the river in" and "in Maine" there is only a max overlap percentage of 25% so + both of these answers could be kept if this variable is set to 0.24 or lower. + If None is provided then all answers are kept. + :param model_kwargs: + Additional keyword arguments passed to `AutoModelForQuestionAnswering.from_pretrained` + when loading the model specified in `model`. For details on what kwargs you can pass, + see the model's documentation. + """ + torch_and_transformers_import.check() + self.model_name_or_path = str(model) + self.model = None + self.tokenizer = None + self.device = None + self.token = token + self.max_seq_length = max_seq_length + self.top_k = top_k + self.score_threshold = score_threshold + self.stride = stride + self.max_batch_size = max_batch_size + self.answers_per_seq = answers_per_seq + self.no_answer = no_answer + self.calibration_factor = calibration_factor + self.overlap_threshold = overlap_threshold + + model_kwargs = resolve_hf_device_map(device=device, model_kwargs=model_kwargs) + self.model_kwargs = model_kwargs + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"model": self.model_name_or_path} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + serialization_dict = default_to_dict( + self, + model=self.model_name_or_path, + device=None, + token=self.token.to_dict() if self.token else None, + max_seq_length=self.max_seq_length, + top_k=self.top_k, + score_threshold=self.score_threshold, + stride=self.stride, + max_batch_size=self.max_batch_size, + answers_per_seq=self.answers_per_seq, + no_answer=self.no_answer, + calibration_factor=self.calibration_factor, + model_kwargs=self.model_kwargs, + ) + + serialize_hf_model_kwargs(serialization_dict["init_parameters"]["model_kwargs"]) + return serialization_dict + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "ExtractiveReader": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + init_params = data["init_parameters"] + deserialize_secrets_inplace(init_params, keys=["token"]) + if init_params.get("device") is not None: + init_params["device"] = ComponentDevice.from_dict(init_params["device"]) + if init_params.get("model_kwargs") is not None: + deserialize_hf_model_kwargs(init_params["model_kwargs"]) + + return default_from_dict(cls, data) + + def warm_up(self): + """ + Initializes the component. + """ + # Take the first device used by `accelerate`. Needed to pass inputs from the tokenizer to the correct device. + if self.model is None: + self.model = AutoModelForQuestionAnswering.from_pretrained( + self.model_name_or_path, token=self.token.resolve_value() if self.token else None, **self.model_kwargs + ) + self.tokenizer = AutoTokenizer.from_pretrained( + self.model_name_or_path, token=self.token.resolve_value() if self.token else None + ) + self.device = ComponentDevice.from_multiple(device_map=DeviceMap.from_hf(self.model.hf_device_map)) + + def _flatten_documents( + self, queries: List[str], documents: List[List[Document]] + ) -> Tuple[List[str], List[Document], List[int]]: + """ + Flattens queries and Documents so all query-document pairs are arranged along one batch axis. + """ + flattened_queries = [query for documents_, query in zip(documents, queries) for _ in documents_] + flattened_documents = [document for documents_ in documents for document in documents_] + query_ids = [i for i, documents_ in enumerate(documents) for _ in documents_] + return flattened_queries, flattened_documents, query_ids + + def _preprocess( + self, queries: List[str], documents: List[Document], max_seq_length: int, query_ids: List[int], stride: int + ) -> Tuple["torch.Tensor", "torch.Tensor", "torch.Tensor", List["Encoding"], List[int], List[int]]: + """ + Splits and tokenizes Documents and preserves structures by returning mappings to query and Document IDs. + """ + texts = [] + document_ids = [] + document_contents = [] + for i, doc in enumerate(documents): + if doc.content is None: + warnings.warn( + f"Document with id {doc.id} was passed to ExtractiveReader. The Document doesn't " + f"contain any text and it will be ignored." + ) + continue + texts.append(doc.content) + document_ids.append(i) + document_contents.append(doc.content) + + encodings_pt = self.tokenizer( # type: ignore + queries, + document_contents, + padding=True, + truncation=True, + max_length=max_seq_length, + return_tensors="pt", + return_overflowing_tokens=True, + stride=stride, + ) + + # To make mypy happy even though self.device is set in warm_up() + assert self.device is not None + assert self.device.first_device is not None + + # Take the first device used by `accelerate`. Needed to pass inputs from the tokenizer to the correct device. + first_device = self.device.first_device.to_torch() + + input_ids = encodings_pt.input_ids.to(first_device) + attention_mask = encodings_pt.attention_mask.to(first_device) + + query_ids = [query_ids[index] for index in encodings_pt.overflow_to_sample_mapping] + document_ids = [document_ids[sample_id] for sample_id in encodings_pt.overflow_to_sample_mapping] + + encodings = encodings_pt.encodings + sequence_ids = torch.tensor( + [[id_ if id_ is not None else -1 for id_ in encoding.sequence_ids] for encoding in encodings] + ).to(first_device) + + return input_ids, attention_mask, sequence_ids, encodings, query_ids, document_ids + + def _postprocess( + self, + start: "torch.Tensor", + end: "torch.Tensor", + sequence_ids: "torch.Tensor", + attention_mask: "torch.Tensor", + answers_per_seq: int, + encodings: List["Encoding"], + ) -> Tuple[List[List[int]], List[List[int]], "torch.Tensor"]: + """ + Turns start and end logits into probabilities for each answer span. + + Unlike most other implementations, it doesn't normalize the scores in each split to make them easier to + compare across different splits. Returns the top k answer spans. + """ + mask = sequence_ids == 1 # Only keep tokens from the context (should ignore special tokens) + mask = torch.logical_and(mask, attention_mask == 1) # Definitely remove special tokens + start = torch.where(mask, start, -torch.inf) # Apply the mask on the start logits + end = torch.where(mask, end, -torch.inf) # Apply the mask on the end logits + start = start.unsqueeze(-1) + end = end.unsqueeze(-2) + + logits = start + end # shape: (batch_size, seq_length (start), seq_length (end)) + + # The mask here onwards is the same for all instances in the batch + # As such we do away with the batch dimension + mask = torch.ones(logits.shape[-2:], dtype=torch.bool, device=logits.device) + mask = torch.triu(mask) # End shouldn't be before start + masked_logits = torch.where(mask, logits, -torch.inf) + probabilities = torch.sigmoid(masked_logits * self.calibration_factor) + + flat_probabilities = probabilities.flatten(-2, -1) # necessary for topk + + # topk can return invalid candidates as well if answers_per_seq > num_valid_candidates + # We only keep probability > 0 candidates later on + candidates = torch.topk(flat_probabilities, answers_per_seq) + seq_length = logits.shape[-1] + start_candidates = candidates.indices // seq_length # Recover indices from flattening + end_candidates = candidates.indices % seq_length + candidates_values = candidates.values.cpu() + start_candidates = start_candidates.cpu() + end_candidates = end_candidates.cpu() + + start_candidates_tokens_to_chars = [] + end_candidates_tokens_to_chars = [] + for i, (s_candidates, e_candidates, encoding) in enumerate(zip(start_candidates, end_candidates, encodings)): + # Those with probabilities > 0 are valid + valid = candidates_values[i] > 0 + s_char_spans = [] + e_char_spans = [] + for start_token, end_token in zip(s_candidates[valid], e_candidates[valid]): + # token_to_chars returns `None` for special tokens + # But we shouldn't have special tokens in the answers at this point + # The whole span is given by the start of the start_token (index 0) + # and the end of the end token (index 1) + s_char_spans.append(encoding.token_to_chars(start_token)[0]) + e_char_spans.append(encoding.token_to_chars(end_token)[1]) + start_candidates_tokens_to_chars.append(s_char_spans) + end_candidates_tokens_to_chars.append(e_char_spans) + + return start_candidates_tokens_to_chars, end_candidates_tokens_to_chars, candidates_values + + def _add_answer_page_number(self, answer: ExtractedAnswer) -> ExtractedAnswer: + if answer.meta is None: + answer.meta = {} + + if answer.document_offset is None: + return answer + + if not answer.document or "page_number" not in answer.document.meta: + return answer + + if not isinstance(answer.document.meta["page_number"], int): + logger.warning( + f"Document's page_number must be int but is {type(answer.document.meta['page_number'])}. " + f"No page number will be added to the answer." + ) + return answer + + # Calculate the answer page number + if answer.document.content: + ans_start = answer.document_offset.start + answer_page_number = answer.document.meta["page_number"] + answer.document.content[:ans_start].count("\f") + answer.meta.update({"answer_page_number": answer_page_number}) + + return answer + + def _nest_answers( + self, + start: List[List[int]], + end: List[List[int]], + probabilities: "torch.Tensor", + flattened_documents: List[Document], + queries: List[str], + answers_per_seq: int, + top_k: Optional[int], + score_threshold: Optional[float], + query_ids: List[int], + document_ids: List[int], + no_answer: bool, + overlap_threshold: Optional[float], + ) -> List[List[ExtractedAnswer]]: + """ + Reconstructs the nested structure that existed before flattening. + + Also computes a no answer score. This score is different from most other implementations because it does not + consider the no answer logit introduced with SQuAD 2. Instead, it just computes the probability that the + answer does not exist in the top k or top p. + """ + answers_without_query = [] + for document_id, start_candidates_, end_candidates_, probabilities_ in zip( + document_ids, start, end, probabilities + ): + for start_, end_, probability in zip(start_candidates_, end_candidates_, probabilities_): + doc = flattened_documents[document_id] + answers_without_query.append( + ExtractedAnswer( + query="", # Can't be None but we'll add it later + data=doc.content[start_:end_], # type: ignore + document=doc, + score=probability.item(), + document_offset=ExtractedAnswer.Span(start_, end_), + meta={}, + ) + ) + i = 0 + nested_answers = [] + for query_id in range(query_ids[-1] + 1): + current_answers = [] + while i < len(answers_without_query) and query_ids[i // answers_per_seq] == query_id: + answer = answers_without_query[i] + answer.query = queries[query_id] + current_answers.append(answer) + i += 1 + current_answers = sorted(current_answers, key=lambda ans: ans.score, reverse=True) + current_answers = self.deduplicate_by_overlap(current_answers, overlap_threshold=overlap_threshold) + current_answers = current_answers[:top_k] + + # Calculate the answer page number and add it to meta + current_answers = [self._add_answer_page_number(answer=answer) for answer in current_answers] + + if no_answer: + no_answer_score = math.prod(1 - answer.score for answer in current_answers) + answer_ = ExtractedAnswer( + data=None, query=queries[query_id], meta={}, document=None, score=no_answer_score + ) + current_answers.append(answer_) + current_answers = sorted(current_answers, key=lambda ans: ans.score, reverse=True) + if score_threshold is not None: + current_answers = [answer for answer in current_answers if answer.score >= score_threshold] + nested_answers.append(current_answers) + + return nested_answers + + def _calculate_overlap(self, answer1_start: int, answer1_end: int, answer2_start: int, answer2_end: int) -> int: + """ + Calculates the amount of overlap (in number of characters) between two answer offsets. + + This Stack overflow + [post](https://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap/325964#325964) + explains how to calculate the overlap between two ranges. + """ + # Check for overlap: (StartA <= EndB) and (StartB <= EndA) + if answer1_start <= answer2_end and answer2_start <= answer1_end: + return min( + answer1_end - answer1_start, + answer1_end - answer2_start, + answer2_end - answer1_start, + answer2_end - answer2_start, + ) + return 0 + + def _should_keep( + self, candidate_answer: ExtractedAnswer, current_answers: List[ExtractedAnswer], overlap_threshold: float + ) -> bool: + """ + Determines if the answer should be kept based on how much it overlaps with previous answers. + + NOTE: We might want to avoid throwing away answers that only have a few character (or word) overlap: + - E.g. The answers "the river in" and "in Maine" from the context "I want to go to the river in Maine." + might both want to be kept. + + :param candidate_answer: + Candidate answer that will be checked if it should be kept. + :param current_answers: + Current list of answers that will be kept. + :param overlap_threshold: + If the overlap between two answers is greater than this threshold then return False. + """ + keep = True + + # If the candidate answer doesn't have a document keep it + if not candidate_answer.document: + return keep + + for ans in current_answers: + # If an answer in current_answers doesn't have a document skip the comparison + if not ans.document: + continue + + # If offset is missing then keep both + if ans.document_offset is None: + continue + + # If offset is missing then keep both + if candidate_answer.document_offset is None: + continue + + # If the answers come from different documents then keep both + if candidate_answer.document.id != ans.document.id: + continue + + overlap_len = self._calculate_overlap( + answer1_start=ans.document_offset.start, + answer1_end=ans.document_offset.end, + answer2_start=candidate_answer.document_offset.start, + answer2_end=candidate_answer.document_offset.end, + ) + + # If overlap is 0 then keep + if overlap_len == 0: + continue + + overlap_frac_answer1 = overlap_len / (ans.document_offset.end - ans.document_offset.start) + overlap_frac_answer2 = overlap_len / ( + candidate_answer.document_offset.end - candidate_answer.document_offset.start + ) + + if overlap_frac_answer1 > overlap_threshold or overlap_frac_answer2 > overlap_threshold: + keep = False + break + + return keep + + def deduplicate_by_overlap( + self, answers: List[ExtractedAnswer], overlap_threshold: Optional[float] + ) -> List[ExtractedAnswer]: + """ + De-duplicates overlapping Extractive Answers. + + De-duplicates overlapping Extractive Answers from the same document based on how much the spans of the + answers overlap. + + :param answers: + List of answers to be deduplicated. + :param overlap_threshold: + If set this will remove duplicate answers if they have an overlap larger than the + supplied threshold. For example, for the answers "in the river in Maine" and "the river" we would remove + one of these answers since the second answer has a 100% (1.0) overlap with the first answer. + However, for the answers "the river in" and "in Maine" there is only a max overlap percentage of 25% so + both of these answers could be kept if this variable is set to 0.24 or lower. + If None is provided then all answers are kept. + :returns: + List of deduplicated answers. + """ + if overlap_threshold is None: + return answers + + # Initialize with the first answer and its offsets_in_document + deduplicated_answers = [answers[0]] + + # Loop over remaining answers to check for overlaps + for ans in answers[1:]: + keep = self._should_keep( + candidate_answer=ans, current_answers=deduplicated_answers, overlap_threshold=overlap_threshold + ) + if keep: + deduplicated_answers.append(ans) + + return deduplicated_answers + + @component.output_types(answers=List[ExtractedAnswer]) + def run( + self, + query: str, + documents: List[Document], + top_k: Optional[int] = None, + score_threshold: Optional[float] = None, + max_seq_length: Optional[int] = None, + stride: Optional[int] = None, + max_batch_size: Optional[int] = None, + answers_per_seq: Optional[int] = None, + no_answer: Optional[bool] = None, + overlap_threshold: Optional[float] = None, + ): + """ + Locates and extracts answers from the given Documents using the given query. + + :param query: + Query string. + :param documents: + List of Documents in which you want to search for an answer to the query. + :param top_k: + The maximum number of answers to return. + An additional answer is returned if no_answer is set to True (default). + :param score_threshold: + Returns only answers with the score above this threshold. + :param max_seq_length: + Maximum number of tokens. If a sequence exceeds it, the sequence is split. + :param stride: + Number of tokens that overlap when sequence is split because it exceeds max_seq_length. + :param max_batch_size: + Maximum number of samples that are fed through the model at the same time. + :param answers_per_seq: + Number of answer candidates to consider per sequence. + This is relevant when a Document was split into multiple sequences because of max_seq_length. + :param no_answer: + Whether to return no answer scores. + :param overlap_threshold: + If set this will remove duplicate answers if they have an overlap larger than the + supplied threshold. For example, for the answers "in the river in Maine" and "the river" we would remove + one of these answers since the second answer has a 100% (1.0) overlap with the first answer. + However, for the answers "the river in" and "in Maine" there is only a max overlap percentage of 25% so + both of these answers could be kept if this variable is set to 0.24 or lower. + If None is provided then all answers are kept. + :returns: + List of answers sorted by (desc.) answer score. + + :raises RuntimeError: + If the component was not warmed up by calling 'warm_up()' before. + """ + if self.model is None: + raise RuntimeError( + "The component ExtractiveReader was not warmed up. Run 'warm_up()' before calling 'run()'." + ) + + if not documents: + return {"answers": []} + + queries = [query] # Temporary solution until we have decided what batching should look like in v2 + nested_documents = [documents] + top_k = top_k or self.top_k + score_threshold = score_threshold or self.score_threshold + max_seq_length = max_seq_length or self.max_seq_length + stride = stride or self.stride + max_batch_size = max_batch_size or self.max_batch_size + answers_per_seq = answers_per_seq or self.answers_per_seq or 20 + no_answer = no_answer if no_answer is not None else self.no_answer + overlap_threshold = overlap_threshold or self.overlap_threshold + + flattened_queries, flattened_documents, query_ids = self._flatten_documents(queries, nested_documents) + input_ids, attention_mask, sequence_ids, encodings, query_ids, document_ids = self._preprocess( + flattened_queries, flattened_documents, max_seq_length, query_ids, stride + ) + + num_batches = math.ceil(input_ids.shape[0] / max_batch_size) if max_batch_size else 1 + batch_size = max_batch_size or input_ids.shape[0] + + start_logits_list = [] + end_logits_list = [] + + for i in range(num_batches): + start_index = i * batch_size + end_index = start_index + batch_size + cur_input_ids = input_ids[start_index:end_index] + cur_attention_mask = attention_mask[start_index:end_index] + + with torch.inference_mode(): + output = self.model(input_ids=cur_input_ids, attention_mask=cur_attention_mask) + cur_start_logits = output.start_logits + cur_end_logits = output.end_logits + if num_batches != 1: + cur_start_logits = cur_start_logits.cpu() + cur_end_logits = cur_end_logits.cpu() + start_logits_list.append(cur_start_logits) + end_logits_list.append(cur_end_logits) + + start_logits = torch.cat(start_logits_list) + end_logits = torch.cat(end_logits_list) + + start, end, probabilities = self._postprocess( + start_logits, end_logits, sequence_ids, attention_mask, answers_per_seq, encodings + ) + + answers = self._nest_answers( + start=start, + end=end, + probabilities=probabilities, + flattened_documents=flattened_documents, + queries=queries, + answers_per_seq=answers_per_seq, + top_k=top_k, + score_threshold=score_threshold, + query_ids=query_ids, + document_ids=document_ids, + no_answer=no_answer, + overlap_threshold=overlap_threshold, + ) + + return {"answers": answers[0]} # same temporary batching fix as above diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..91d1288a19553db2b456855cd2af49a3d5a9e4d5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/__init__.py @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.retrievers.filter_retriever import FilterRetriever +from haystack.components.retrievers.in_memory.bm25_retriever import InMemoryBM25Retriever +from haystack.components.retrievers.in_memory.embedding_retriever import InMemoryEmbeddingRetriever +from haystack.components.retrievers.sentence_window_retriever import SentenceWindowRetriever + +__all__ = ["FilterRetriever", "InMemoryEmbeddingRetriever", "InMemoryBM25Retriever", "SentenceWindowRetriever"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/filter_retriever.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/filter_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..6f9ad78b3daf854387c8514440cce94aa99d9095 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/filter_retriever.py @@ -0,0 +1,96 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional + +from haystack import Document, component, default_from_dict, default_to_dict, logging +from haystack.document_stores.types import DocumentStore +from haystack.utils import deserialize_document_store_in_init_params_inplace + +logger = logging.getLogger(__name__) + + +@component +class FilterRetriever: + """ + Retrieves documents that match the provided filters. + + ### Usage example + + ```python + from haystack import Document + from haystack.components.retrievers import FilterRetriever + from haystack.document_stores.in_memory import InMemoryDocumentStore + + docs = [ + Document(content="Python is a popular programming language", meta={"lang": "en"}), + Document(content="python ist eine beliebte Programmiersprache", meta={"lang": "de"}), + ] + + doc_store = InMemoryDocumentStore() + doc_store.write_documents(docs) + retriever = FilterRetriever(doc_store, filters={"field": "lang", "operator": "==", "value": "en"}) + + # if passed in the run method, filters override those provided at initialization + result = retriever.run(filters={"field": "lang", "operator": "==", "value": "de"}) + + print(result["documents"]) + ``` + """ + + def __init__(self, document_store: DocumentStore, filters: Optional[Dict[str, Any]] = None): + """ + Create the FilterRetriever component. + + :param document_store: + An instance of a Document Store to use with the Retriever. + :param filters: + A dictionary with filters to narrow down the search space. + """ + self.document_store = document_store + self.filters = filters + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"document_store": type(self.document_store).__name__} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + docstore = self.document_store.to_dict() + return default_to_dict(self, document_store=docstore, filters=self.filters) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "FilterRetriever": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + # deserialize the document store + deserialize_document_store_in_init_params_inplace(data) + + return default_from_dict(cls, data) + + @component.output_types(documents=List[Document]) + def run(self, filters: Optional[Dict[str, Any]] = None): + """ + Run the FilterRetriever on the given input data. + + :param filters: + A dictionary with filters to narrow down the search space. + If not specified, the FilterRetriever uses the values provided at initialization. + :returns: + A list of retrieved documents. + """ + return {"documents": self.document_store.filter_documents(filters=filters or self.filters)} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/in_memory/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/in_memory/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0a226d480e78ac03992d15676a65f370005a68f7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/in_memory/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.retrievers.in_memory.bm25_retriever import InMemoryBM25Retriever +from haystack.components.retrievers.in_memory.embedding_retriever import InMemoryEmbeddingRetriever + +__all__ = ["InMemoryBM25Retriever", "InMemoryEmbeddingRetriever"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/in_memory/bm25_retriever.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/in_memory/bm25_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..ac3f8486f80d2902b416f2708ddb5d1e913f032e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/in_memory/bm25_retriever.py @@ -0,0 +1,163 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional + +from haystack import DeserializationError, Document, component, default_from_dict, default_to_dict +from haystack.document_stores.in_memory import InMemoryDocumentStore +from haystack.document_stores.types import FilterPolicy + + +@component +class InMemoryBM25Retriever: + """ + Retrieves documents that are most similar to the query using keyword-based algorithm. + + Use this retriever with the InMemoryDocumentStore. + + ### Usage example + + ```python + from haystack import Document + from haystack.components.retrievers.in_memory import InMemoryBM25Retriever + from haystack.document_stores.in_memory import InMemoryDocumentStore + + docs = [ + Document(content="Python is a popular programming language"), + Document(content="python ist eine beliebte Programmiersprache"), + ] + + doc_store = InMemoryDocumentStore() + doc_store.write_documents(docs) + retriever = InMemoryBM25Retriever(doc_store) + + result = retriever.run(query="Programmiersprache") + + print(result["documents"]) + ``` + """ + + def __init__( + self, + document_store: InMemoryDocumentStore, + filters: Optional[Dict[str, Any]] = None, + top_k: int = 10, + scale_score: bool = False, + filter_policy: FilterPolicy = FilterPolicy.REPLACE, + ): + """ + Create the InMemoryBM25Retriever component. + + :param document_store: + An instance of InMemoryDocumentStore where the retriever should search for relevant documents. + :param filters: + A dictionary with filters to narrow down the retriever's search space in the document store. + :param top_k: + The maximum number of documents to retrieve. + :param scale_score: + When `True`, scales the score of retrieved documents to a range of 0 to 1, where 1 means extremely relevant. + When `False`, uses raw similarity scores. + :param filter_policy: The filter policy to apply during retrieval. + Filter policy determines how filters are applied when retrieving documents. You can choose: + - `REPLACE` (default): Overrides the initialization filters with the filters specified at runtime. + Use this policy to dynamically change filtering for specific queries. + - `MERGE`: Combines runtime filters with initialization filters to narrow down the search. + :raises ValueError: + If the specified `top_k` is not > 0. + """ + if not isinstance(document_store, InMemoryDocumentStore): + raise ValueError("document_store must be an instance of InMemoryDocumentStore") + + self.document_store = document_store + + if top_k <= 0: + raise ValueError(f"top_k must be greater than 0. Currently, the top_k is {top_k}") + + self.filters = filters + self.top_k = top_k + self.scale_score = scale_score + self.filter_policy = filter_policy + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"document_store": type(self.document_store).__name__} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + docstore = self.document_store.to_dict() + return default_to_dict( + self, + document_store=docstore, + filters=self.filters, + top_k=self.top_k, + scale_score=self.scale_score, + filter_policy=self.filter_policy.value, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "InMemoryBM25Retriever": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + init_params = data.get("init_parameters", {}) + if "document_store" not in init_params: + raise DeserializationError("Missing 'document_store' in serialization data") + if "type" not in init_params["document_store"]: + raise DeserializationError("Missing 'type' in document store's serialization data") + if "filter_policy" in init_params: + init_params["filter_policy"] = FilterPolicy.from_str(init_params["filter_policy"]) + data["init_parameters"]["document_store"] = InMemoryDocumentStore.from_dict( + data["init_parameters"]["document_store"] + ) + return default_from_dict(cls, data) + + @component.output_types(documents=List[Document]) + def run( + self, + query: str, + filters: Optional[Dict[str, Any]] = None, + top_k: Optional[int] = None, + scale_score: Optional[bool] = None, + ): + """ + Run the InMemoryBM25Retriever on the given input data. + + :param query: + The query string for the Retriever. + :param filters: + A dictionary with filters to narrow down the search space when retrieving documents. + :param top_k: + The maximum number of documents to return. + :param scale_score: + When `True`, scales the score of retrieved documents to a range of 0 to 1, where 1 means extremely relevant. + When `False`, uses raw similarity scores. + :returns: + The retrieved documents. + + :raises ValueError: + If the specified DocumentStore is not found or is not a InMemoryDocumentStore instance. + """ + if self.filter_policy == FilterPolicy.MERGE and filters: + filters = {**(self.filters or {}), **filters} + else: + filters = filters or self.filters + if top_k is None: + top_k = self.top_k + if scale_score is None: + scale_score = self.scale_score + + docs = self.document_store.bm25_retrieval(query=query, filters=filters, top_k=top_k, scale_score=scale_score) + return {"documents": docs} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/in_memory/embedding_retriever.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/in_memory/embedding_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..cddd2cef4103d8fa5e7022ffb80230034a50f16d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/in_memory/embedding_retriever.py @@ -0,0 +1,194 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional + +from haystack import DeserializationError, Document, component, default_from_dict, default_to_dict +from haystack.document_stores.in_memory import InMemoryDocumentStore +from haystack.document_stores.types import FilterPolicy + + +@component +class InMemoryEmbeddingRetriever: + """ + Retrieves documents that are most semantically similar to the query. + + Use this retriever with the InMemoryDocumentStore. + + When using this retriever, make sure it has query and document embeddings available. + In indexing pipelines, use a DocumentEmbedder to embed documents. + In query pipelines, use a TextEmbedder to embed queries and send them to the retriever. + + ### Usage example + ```python + from haystack import Document + from haystack.components.embedders import SentenceTransformersDocumentEmbedder, SentenceTransformersTextEmbedder + from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever + from haystack.document_stores.in_memory import InMemoryDocumentStore + + docs = [ + Document(content="Python is a popular programming language"), + Document(content="python ist eine beliebte Programmiersprache"), + ] + doc_embedder = SentenceTransformersDocumentEmbedder() + doc_embedder.warm_up() + docs_with_embeddings = doc_embedder.run(docs)["documents"] + + doc_store = InMemoryDocumentStore() + doc_store.write_documents(docs_with_embeddings) + retriever = InMemoryEmbeddingRetriever(doc_store) + + query="Programmiersprache" + text_embedder = SentenceTransformersTextEmbedder() + text_embedder.warm_up() + query_embedding = text_embedder.run(query)["embedding"] + + result = retriever.run(query_embedding=query_embedding) + + print(result["documents"]) + ``` + """ + + def __init__( + self, + document_store: InMemoryDocumentStore, + filters: Optional[Dict[str, Any]] = None, + top_k: int = 10, + scale_score: bool = False, + return_embedding: bool = False, + filter_policy: FilterPolicy = FilterPolicy.REPLACE, + ): + """ + Create the InMemoryEmbeddingRetriever component. + + :param document_store: + An instance of InMemoryDocumentStore where the retriever should search for relevant documents. + :param filters: + A dictionary with filters to narrow down the retriever's search space in the document store. + :param top_k: + The maximum number of documents to retrieve. + :param scale_score: + When `True`, scales the score of retrieved documents to a range of 0 to 1, where 1 means extremely relevant. + When `False`, uses raw similarity scores. + :param return_embedding: + When `True`, returns the embedding of the retrieved documents. + When `False`, returns just the documents, without their embeddings. + :param filter_policy: The filter policy to apply during retrieval. + Filter policy determines how filters are applied when retrieving documents. You can choose: + - `REPLACE` (default): Overrides the initialization filters with the filters specified at runtime. + Use this policy to dynamically change filtering for specific queries. + - `MERGE`: Combines runtime filters with initialization filters to narrow down the search. + :raises ValueError: + If the specified top_k is not > 0. + """ + if not isinstance(document_store, InMemoryDocumentStore): + raise ValueError("document_store must be an instance of InMemoryDocumentStore") + + self.document_store = document_store + + if top_k <= 0: + raise ValueError(f"top_k must be greater than 0. Currently, top_k is {top_k}") + + self.filters = filters + self.top_k = top_k + self.scale_score = scale_score + self.return_embedding = return_embedding + self.filter_policy = filter_policy + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"document_store": type(self.document_store).__name__} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + docstore = self.document_store.to_dict() + return default_to_dict( + self, + document_store=docstore, + filters=self.filters, + top_k=self.top_k, + scale_score=self.scale_score, + return_embedding=self.return_embedding, + filter_policy=self.filter_policy.value, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "InMemoryEmbeddingRetriever": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + init_params = data.get("init_parameters", {}) + if "document_store" not in init_params: + raise DeserializationError("Missing 'document_store' in serialization data") + if "type" not in init_params["document_store"]: + raise DeserializationError("Missing 'type' in document store's serialization data") + if "filter_policy" in init_params: + init_params["filter_policy"] = FilterPolicy.from_str(init_params["filter_policy"]) + data["init_parameters"]["document_store"] = InMemoryDocumentStore.from_dict( + data["init_parameters"]["document_store"] + ) + return default_from_dict(cls, data) + + @component.output_types(documents=List[Document]) + def run( + self, + query_embedding: List[float], + filters: Optional[Dict[str, Any]] = None, + top_k: Optional[int] = None, + scale_score: Optional[bool] = None, + return_embedding: Optional[bool] = None, + ): + """ + Run the InMemoryEmbeddingRetriever on the given input data. + + :param query_embedding: + Embedding of the query. + :param filters: + A dictionary with filters to narrow down the search space when retrieving documents. + :param top_k: + The maximum number of documents to return. + :param scale_score: + When `True`, scales the score of retrieved documents to a range of 0 to 1, where 1 means extremely relevant. + When `False`, uses raw similarity scores. + :param return_embedding: + When `True`, returns the embedding of the retrieved documents. + When `False`, returns just the documents, without their embeddings. + :returns: + The retrieved documents. + + :raises ValueError: + If the specified DocumentStore is not found or is not an InMemoryDocumentStore instance. + """ + if self.filter_policy == FilterPolicy.MERGE and filters: + filters = {**(self.filters or {}), **filters} + else: + filters = filters or self.filters + if top_k is None: + top_k = self.top_k + if scale_score is None: + scale_score = self.scale_score + if return_embedding is None: + return_embedding = self.return_embedding + + docs = self.document_store.embedding_retrieval( + query_embedding=query_embedding, + filters=filters, + top_k=top_k, + scale_score=scale_score, + return_embedding=return_embedding, + ) + + return {"documents": docs} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/sentence_window_retriever.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/sentence_window_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..fbc389ed3ebc53205ca8780311cd4cfb5ef172d8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/retrievers/sentence_window_retriever.py @@ -0,0 +1,197 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional + +from haystack import Document, component, default_from_dict, default_to_dict +from haystack.document_stores.types import DocumentStore +from haystack.utils import deserialize_document_store_in_init_params_inplace + + +@component +class SentenceWindowRetriever: + """ + Retrieves documents adjacent to a given document in the Document Store. + + During indexing, documents are broken into smaller chunks, or sentences. When you submit a query, + the Retriever fetches the most relevant sentence. To provide full context, + SentenceWindowRetriever fetches a number of neighboring sentences before and after each + relevant one. You can set this number with the `window_size` parameter. + It uses `source_id` and `doc.meta['split_id']` to locate the surrounding documents. + + This component works with existing Retrievers, like BM25Retriever or + EmbeddingRetriever. First, use a Retriever to find documents based on a query and then use + SentenceWindowRetriever to get the surrounding documents for context. + + The SentenceWindowRetriever is compatible with the following DocumentStores: + - [Astra](https://docs.haystack.deepset.ai/docs/astradocumentstore) + - [Elasticsearch](https://docs.haystack.deepset.ai/docs/elasticsearch-document-store) + - [OpenSearch](https://docs.haystack.deepset.ai/docs/opensearch-document-store) + - [Pgvector](https://docs.haystack.deepset.ai/docs/pgvectordocumentstore) + - [Pinecone](https://docs.haystack.deepset.ai/docs/pinecone-document-store) + - [Qdrant](https://docs.haystack.deepset.ai/docs/qdrant-document-store) + + ### Usage example + + ```python + from haystack import Document, Pipeline + from haystack.components.retrievers.in_memory import InMemoryBM25Retriever + from haystack.components.retrievers import SentenceWindowRetriever + from haystack.components.preprocessors import DocumentSplitter + from haystack.document_stores.in_memory import InMemoryDocumentStore + + splitter = DocumentSplitter(split_length=10, split_overlap=5, split_by="word") + text = ( + "This is a text with some words. There is a second sentence. And there is also a third sentence. " + "It also contains a fourth sentence. And a fifth sentence. And a sixth sentence. And a seventh sentence" + ) + doc = Document(content=text) + docs = splitter.run([doc]) + doc_store = InMemoryDocumentStore() + doc_store.write_documents(docs["documents"]) + + + rag = Pipeline() + rag.add_component("bm25_retriever", InMemoryBM25Retriever(doc_store, top_k=1)) + rag.add_component("sentence_window_retriever", SentenceWindowRetriever(document_store=doc_store, window_size=2)) + rag.connect("bm25_retriever", "sentence_window_retriever") + + rag.run({'bm25_retriever': {"query":"third"}}) + + >> {'sentence_window_retriever': {'context_windows': ['some words. There is a second sentence. + >> And there is also a third sentence. It also contains a fourth sentence. And a fifth sentence. And a sixth + >> sentence. And a'], 'context_documents': [[Document(id=..., content: 'some words. There is a second sentence. + >> And there is ', meta: {'source_id': '...', 'page_number': 1, 'split_id': 1, 'split_idx_start': 20, + >> '_split_overlap': [{'doc_id': '...', 'range': (20, 43)}, {'doc_id': '...', 'range': (0, 30)}]}), + >> Document(id=..., content: 'second sentence. And there is also a third sentence. It ', + >> meta: {'source_id': '74ea87deb38012873cf8c07e...f19d01a26a098447113e1d7b83efd30c02987114', 'page_number': 1, + >> 'split_id': 2, 'split_idx_start': 43, '_split_overlap': [{'doc_id': '...', 'range': (23, 53)}, {'doc_id': '...', + >> 'range': (0, 26)}]}), Document(id=..., content: 'also a third sentence. It also contains a fourth sentence. ', + >> meta: {'source_id': '...', 'page_number': 1, 'split_id': 3, 'split_idx_start': 73, '_split_overlap': + >> [{'doc_id': '...', 'range': (30, 56)}, {'doc_id': '...', 'range': (0, 33)}]}), Document(id=..., content: + >> 'also contains a fourth sentence. And a fifth sentence. And ', meta: {'source_id': '...', 'page_number': 1, + >> 'split_id': 4, 'split_idx_start': 99, '_split_overlap': [{'doc_id': '...', 'range': (26, 59)}, + >> {'doc_id': '...', 'range': (0, 26)}]}), Document(id=..., content: 'And a fifth sentence. And a sixth sentence. + >> And a ', meta: {'source_id': '...', 'page_number': 1, 'split_id': 5, 'split_idx_start': 132, + >> '_split_overlap': [{'doc_id': '...', 'range': (33, 59)}, {'doc_id': '...', 'range': (0, 24)}]})]]}}}} + ``` + """ + + def __init__(self, document_store: DocumentStore, window_size: int = 3): + """ + Creates a new SentenceWindowRetriever component. + + :param document_store: The Document Store to retrieve the surrounding documents from. + :param window_size: The number of documents to retrieve before and after the relevant one. + For example, `window_size: 2` fetches 2 preceding and 2 following documents. + """ + if window_size < 1: + raise ValueError("The window_size parameter must be greater than 0.") + + self.window_size = window_size + self.document_store = document_store + + @staticmethod + def merge_documents_text(documents: List[Document]) -> str: + """ + Merge a list of document text into a single string. + + This functions concatenates the textual content of a list of documents into a single string, eliminating any + overlapping content. + + :param documents: List of Documents to merge. + """ + sorted_docs = sorted(documents, key=lambda doc: doc.meta["split_idx_start"]) + merged_text = "" + last_idx_end = 0 + for doc in sorted_docs: + start = doc.meta["split_idx_start"] # start of the current content + + # if the start of the current content is before the end of the last appended content, adjust it + start = max(start, last_idx_end) + + # append the non-overlapping part to the merged text + merged_text += doc.content[start - doc.meta["split_idx_start"] :] # type: ignore + + # update the last end index + last_idx_end = doc.meta["split_idx_start"] + len(doc.content) # type: ignore + + return merged_text + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + docstore = self.document_store.to_dict() + return default_to_dict(self, document_store=docstore, window_size=self.window_size) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "SentenceWindowRetriever": + """ + Deserializes the component from a dictionary. + + :returns: + Deserialized component. + """ + # deserialize the document store + deserialize_document_store_in_init_params_inplace(data) + + # deserialize the component + return default_from_dict(cls, data) + + @component.output_types(context_windows=List[str], context_documents=List[List[Document]]) + def run(self, retrieved_documents: List[Document], window_size: Optional[int] = None): + """ + Based on the `source_id` and on the `doc.meta['split_id']` get surrounding documents from the document store. + + Implements the logic behind the sentence-window technique, retrieving the surrounding documents of a given + document from the document store. + + :param retrieved_documents: List of retrieved documents from the previous retriever. + :param window_size: The number of documents to retrieve before and after the relevant one. This will overwrite + the `window_size` parameter set in the constructor. + :returns: + A dictionary with the following keys: + - `context_windows`: A list of strings, where each string represents the concatenated text from the + context window of the corresponding document in `retrieved_documents`. + - `context_documents`: A list of lists of `Document` objects, where each inner list contains the + documents that come from the context window for the corresponding document in + `retrieved_documents`. + + """ + window_size = window_size or self.window_size + + if window_size < 1: + raise ValueError("The window_size parameter must be greater than 0.") + + if not all("split_id" in doc.meta for doc in retrieved_documents): + raise ValueError("The retrieved documents must have 'split_id' in the metadata.") + + if not all("source_id" in doc.meta for doc in retrieved_documents): + raise ValueError("The retrieved documents must have 'source_id' in the metadata.") + + context_text = [] + context_documents = [] + for doc in retrieved_documents: + source_id = doc.meta["source_id"] + split_id = doc.meta["split_id"] + min_before = min(list(range(split_id - 1, split_id - window_size - 1, -1))) + max_after = max(list(range(split_id + 1, split_id + window_size + 1, 1))) + context_docs = self.document_store.filter_documents( + { + "operator": "AND", + "conditions": [ + {"field": "meta.source_id", "operator": "==", "value": source_id}, + {"field": "meta.split_id", "operator": ">=", "value": min_before}, + {"field": "meta.split_id", "operator": "<=", "value": max_after}, + ], + } + ) + context_text.append(self.merge_documents_text(context_docs)) + context_documents.append(context_docs) + + return {"context_windows": context_text, "context_documents": context_documents} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f22d69917d2dab1aa5c06b444df4788c5acc15f5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/__init__.py @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.routers.conditional_router import ConditionalRouter +from haystack.components.routers.file_type_router import FileTypeRouter +from haystack.components.routers.metadata_router import MetadataRouter +from haystack.components.routers.text_language_router import TextLanguageRouter +from haystack.components.routers.transformers_text_router import TransformersTextRouter +from haystack.components.routers.zero_shot_text_router import TransformersZeroShotTextRouter + +__all__ = [ + "FileTypeRouter", + "MetadataRouter", + "TextLanguageRouter", + "ConditionalRouter", + "TransformersZeroShotTextRouter", + "TransformersTextRouter", +] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/conditional_router.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/conditional_router.py new file mode 100644 index 0000000000000000000000000000000000000000..b16ae3d3422ed1a9529c2ecac21abde37a057ea9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/conditional_router.py @@ -0,0 +1,290 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import ast +import contextlib +from typing import Any, Callable, Dict, List, Optional, Set +from warnings import warn + +from jinja2 import Environment, TemplateSyntaxError, meta +from jinja2.nativetypes import NativeEnvironment +from jinja2.sandbox import SandboxedEnvironment + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.utils import deserialize_callable, deserialize_type, serialize_callable, serialize_type + +logger = logging.getLogger(__name__) + + +class NoRouteSelectedException(Exception): + """Exception raised when no route is selected in ConditionalRouter.""" + + +class RouteConditionException(Exception): + """Exception raised when there is an error parsing or evaluating the condition expression in ConditionalRouter.""" + + +@component +class ConditionalRouter: + """ + Routes data based on specific conditions. + + You define these conditions in a list of dictionaries called `routes`. + Each dictionary in this list represents a single route. Each route has these four elements: + - `condition`: A Jinja2 string expression that determines if the route is selected. + - `output`: A Jinja2 expression defining the route's output value. + - `output_type`: The type of the output data (for example, `str`, `List[int]`). + - `output_name`: The name you want to use to publish `output`. This name is used to connect + the router to other components in the pipeline. + + ### Usage example + + ```python + from typing import List + from haystack.components.routers import ConditionalRouter + + routes = [ + { + "condition": "{{streams|length > 2}}", + "output": "{{streams}}", + "output_name": "enough_streams", + "output_type": List[int], + }, + { + "condition": "{{streams|length <= 2}}", + "output": "{{streams}}", + "output_name": "insufficient_streams", + "output_type": List[int], + }, + ] + router = ConditionalRouter(routes) + # When 'streams' has more than 2 items, 'enough_streams' output will activate, emitting the list [1, 2, 3] + kwargs = {"streams": [1, 2, 3], "query": "Haystack"} + result = router.run(**kwargs) + assert result == {"enough_streams": [1, 2, 3]} + ``` + + In this example, we configure two routes. The first route sends the 'streams' value to 'enough_streams' if the + stream count exceeds two. The second route directs 'streams' to 'insufficient_streams' if there + are two or fewer streams. + + In the pipeline setup, the Router connects to other components using the output names. For example, + 'enough_streams' might connect to a component that processes streams, while + 'insufficient_streams' might connect to a component that fetches more streams. + + + Here is a pipeline that uses `ConditionalRouter` and routes the fetched `ByteStreams` to + different components depending on the number of streams fetched: + + ```python + from typing import List + from haystack import Pipeline + from haystack.dataclasses import ByteStream + from haystack.components.routers import ConditionalRouter + + routes = [ + { + "condition": "{{streams|length > 2}}", + "output": "{{streams}}", + "output_name": "enough_streams", + "output_type": List[ByteStream], + }, + { + "condition": "{{streams|length <= 2}}", + "output": "{{streams}}", + "output_name": "insufficient_streams", + "output_type": List[ByteStream], + }, + ] + + pipe = Pipeline() + pipe.add_component("router", router) + ... + pipe.connect("router.enough_streams", "some_component_a.streams") + pipe.connect("router.insufficient_streams", "some_component_b.streams_or_some_other_input") + ... + ``` + """ + + def __init__(self, routes: List[Dict], custom_filters: Optional[Dict[str, Callable]] = None, unsafe: bool = False): + """ + Initializes the `ConditionalRouter` with a list of routes detailing the conditions for routing. + + :param routes: A list of dictionaries, each defining a route. + Each route has these four elements: + - `condition`: A Jinja2 string expression that determines if the route is selected. + - `output`: A Jinja2 expression defining the route's output value. + - `output_type`: The type of the output data (for example, `str`, `List[int]`). + - `output_name`: The name you want to use to publish `output`. This name is used to connect + the router to other components in the pipeline. + :param custom_filters: A dictionary of custom Jinja2 filters used in the condition expressions. + For example, passing `{"my_filter": my_filter_fcn}` where: + - `my_filter` is the name of the custom filter. + - `my_filter_fcn` is a callable that takes `my_var:str` and returns `my_var[:3]`. + `{{ my_var|my_filter }}` can then be used inside a route condition expression: + `"condition": "{{ my_var|my_filter == 'foo' }}"`. + :param unsafe: + Enable execution of arbitrary code in the Jinja template. + This should only be used if you trust the source of the template as it can be lead to remote code execution. + """ + self.routes: List[dict] = routes + self.custom_filters = custom_filters or {} + self._unsafe = unsafe + + # Create a Jinja environment to inspect variables in the condition templates + if self._unsafe: + msg = ( + "Unsafe mode is enabled. This allows execution of arbitrary code in the Jinja template. " + "Use this only if you trust the source of the template." + ) + warn(msg) + + self._env = NativeEnvironment() if self._unsafe else SandboxedEnvironment() + self._env.filters.update(self.custom_filters) + + self._validate_routes(routes) + # Inspect the routes to determine input and output types. + input_types: Set[str] = set() # let's just store the name, type will always be Any + output_types: Dict[str, str] = {} + + for route in routes: + # extract inputs + route_input_names = self._extract_variables(self._env, [route["output"], route["condition"]]) + input_types.update(route_input_names) + + # extract outputs + output_types.update({route["output_name"]: route["output_type"]}) + + component.set_input_types(self, **{var: Any for var in input_types}) + component.set_output_types(self, **output_types) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + for route in self.routes: + # output_type needs to be serialized to a string + route["output_type"] = serialize_type(route["output_type"]) + se_filters = {name: serialize_callable(filter_func) for name, filter_func in self.custom_filters.items()} + return default_to_dict(self, routes=self.routes, custom_filters=se_filters, unsafe=self._unsafe) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "ConditionalRouter": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + init_params = data.get("init_parameters", {}) + routes = init_params.get("routes") + for route in routes: + # output_type needs to be deserialized from a string to a type + route["output_type"] = deserialize_type(route["output_type"]) + + # Since the custom_filters are typed as optional in the init signature, we catch the + # case where they are not present in the serialized data and set them to an empty dict. + custom_filters = init_params.get("custom_filters", {}) + if custom_filters is not None: + for name, filter_func in custom_filters.items(): + init_params["custom_filters"][name] = deserialize_callable(filter_func) if filter_func else None + return default_from_dict(cls, data) + + def run(self, **kwargs): + """ + Executes the routing logic. + + Executes the routing logic by evaluating the specified boolean condition expressions for each route in the + order they are listed. The method directs the flow of data to the output specified in the first route whose + `condition` is True. + + :param kwargs: All variables used in the `condition` expressed in the routes. When the component is used in a + pipeline, these variables are passed from the previous component's output. + + :returns: A dictionary where the key is the `output_name` of the selected route and the value is the `output` + of the selected route. + + :raises NoRouteSelectedException: If no `condition' in the routes is `True`. + :raises RouteConditionException: If there is an error parsing or evaluating the `condition` expression in the + routes. + """ + # Create a Jinja native environment to evaluate the condition templates as Python expressions + for route in self.routes: + try: + t = self._env.from_string(route["condition"]) + rendered = t.render(**kwargs) + if not self._unsafe: + rendered = ast.literal_eval(rendered) + if rendered: + # We now evaluate the `output` expression to determine the route output + t_output = self._env.from_string(route["output"]) + output = t_output.render(**kwargs) + # We suppress the exception in case the output is already a string, otherwise + # we try to evaluate it and would fail. + # This must be done cause the output could be different literal structures. + # This doesn't support any user types. + with contextlib.suppress(Exception): + if not self._unsafe: + output = ast.literal_eval(output) + # and return the output as a dictionary under the output_name key + return {route["output_name"]: output} + except Exception as e: + raise RouteConditionException(f"Error evaluating condition for route '{route}': {e}") from e + + raise NoRouteSelectedException(f"No route fired. Routes: {self.routes}") + + def _validate_routes(self, routes: List[Dict]): + """ + Validates a list of routes. + + :param routes: A list of routes. + """ + for route in routes: + try: + keys = set(route.keys()) + except AttributeError: + raise ValueError(f"Route must be a dictionary, got: {route}") + + mandatory_fields = {"condition", "output", "output_type", "output_name"} + has_all_mandatory_fields = mandatory_fields.issubset(keys) + if not has_all_mandatory_fields: + raise ValueError( + f"Route must contain 'condition', 'output', 'output_type' and 'output_name' fields: {route}" + ) + for field in ["condition", "output"]: + if not self._validate_template(self._env, route[field]): + raise ValueError(f"Invalid template for field '{field}': {route[field]}") + + def _extract_variables(self, env: Environment, templates: List[str]) -> Set[str]: + """ + Extracts all variables from a list of Jinja template strings. + + :param env: A Jinja environment. + :param templates: A list of Jinja template strings. + :returns: A set of variable names. + """ + variables = set() + for template in templates: + ast = env.parse(template) + variables.update(meta.find_undeclared_variables(ast)) + return variables + + def _validate_template(self, env: Environment, template_text: str): + """ + Validates a template string by parsing it with Jinja. + + :param env: A Jinja environment. + :param template_text: A Jinja template string. + :returns: `True` if the template is valid, `False` otherwise. + """ + try: + env.parse(template_text) + return True + except TemplateSyntaxError: + return False diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/file_type_router.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/file_type_router.py new file mode 100644 index 0000000000000000000000000000000000000000..df3935cf0c8b037f21c78165bd330f172c15984c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/file_type_router.py @@ -0,0 +1,152 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import mimetypes +import re +from collections import defaultdict +from pathlib import Path +from typing import Dict, List, Optional, Union + +from haystack import component, logging +from haystack.dataclasses import ByteStream + +logger = logging.getLogger(__name__) + + +@component +class FileTypeRouter: + """ + Categorizes files or byte streams by their MIME types, helping in context-based routing. + + FileTypeRouter supports both exact MIME type matching and regex patterns. + + For file paths, MIME types come from extensions, while byte streams use metadata. + You can use regex patterns in the `mime_types` parameter to set broad categories + (such as 'audio/*' or 'text/*') or specific types. + MIME types without regex patterns are treated as exact matches. + + ### Usage example + + ```python + from haystack.components.routers import FileTypeRouter + from pathlib import Path + + # For exact MIME type matching + router = FileTypeRouter(mime_types=["text/plain", "application/pdf"]) + + # For flexible matching using regex, to handle all audio types + router_with_regex = FileTypeRouter(mime_types=[r"audio/.*", r"text/plain"]) + + sources = [Path("file.txt"), Path("document.pdf"), Path("song.mp3")] + print(router.run(sources=sources)) + print(router_with_regex.run(sources=sources)) + + # Expected output: + # {'text/plain': [ + # PosixPath('file.txt')], 'application/pdf': [PosixPath('document.pdf')], 'unclassified': [PosixPath('song.mp3') + # ]} + # {'audio/.*': [ + # PosixPath('song.mp3')], 'text/plain': [PosixPath('file.txt')], 'unclassified': [PosixPath('document.pdf') + # ]} + ``` + + :param mime_types: A list of MIME types or regex patterns to classify the input files or byte streams. + """ + + def __init__(self, mime_types: List[str], additional_mimetypes: Optional[Dict[str, str]] = None): + """ + Initialize the FileTypeRouter component. + + :param mime_types: A list of MIME types or regex patterns to classify the input files or byte streams. + (for example: `["text/plain", "audio/x-wav", "image/jpeg"]`). + + :param additional_mimetypes: A dictionary containing the MIME type to add to the mimetypes package to prevent + unsupported or non native packages from being unclassified. + (for example: `{"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx"}`). + """ + if not mime_types: + raise ValueError("The list of mime types cannot be empty.") + + if additional_mimetypes: + for mime, ext in additional_mimetypes.items(): + mimetypes.add_type(mime, ext) + + self.mime_type_patterns = [] + for mime_type in mime_types: + if not self._is_valid_mime_type_format(mime_type): + raise ValueError(f"Invalid mime type or regex pattern: '{mime_type}'.") + pattern = re.compile(mime_type) + self.mime_type_patterns.append(pattern) + + component.set_output_types(self, unclassified=List[Path], **{mime_type: List[Path] for mime_type in mime_types}) + self.mime_types = mime_types + + def run(self, sources: List[Union[str, Path, ByteStream]]) -> Dict[str, List[Union[ByteStream, Path]]]: + """ + Categorize files or byte streams according to their MIME types. + + :param sources: A list of file paths or byte streams to categorize. + + :returns: A dictionary where the keys are MIME types (or `"unclassified"`) and the values are lists of data + sources. + """ + + mime_types = defaultdict(list) + for source in sources: + if isinstance(source, str): + source = Path(source) + if isinstance(source, Path): + mime_type = self._get_mime_type(source) + elif isinstance(source, ByteStream): + mime_type = source.mime_type + else: + raise ValueError(f"Unsupported data source type: {type(source).__name__}") + + matched = False + if mime_type: + for pattern in self.mime_type_patterns: + if pattern.fullmatch(mime_type): + mime_types[pattern.pattern].append(source) + matched = True + break + if not matched: + mime_types["unclassified"].append(source) + + return dict(mime_types) + + def _get_mime_type(self, path: Path) -> Optional[str]: + """ + Get the MIME type of the provided file path. + + :param path: The file path to get the MIME type for. + + :returns: The MIME type of the provided file path, or `None` if the MIME type cannot be determined. + """ + extension = path.suffix.lower() + mime_type = mimetypes.guess_type(path.as_posix())[0] + # lookup custom mappings if the mime type is not found + return self._get_custom_mime_mappings().get(extension, mime_type) + + def _is_valid_mime_type_format(self, mime_type: str) -> bool: + """ + Checks if the provided MIME type string is a valid regex pattern. + + :param mime_type: The MIME type or regex pattern to validate. + :raises ValueError: If the mime_type is not a valid regex pattern. + :returns: Always True because a ValueError is raised for invalid patterns. + """ + try: + re.compile(mime_type) + return True + except re.error: + raise ValueError(f"Invalid regex pattern '{mime_type}'.") + + @staticmethod + def _get_custom_mime_mappings() -> Dict[str, str]: + """ + Returns a dictionary of custom file extension to MIME type mappings. + """ + # we add markdown because it is not added by the mimetypes module + # see https://github.com/python/cpython/pull/17995 + return {".md": "text/markdown", ".markdown": "text/markdown"} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/metadata_router.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/metadata_router.py new file mode 100644 index 0000000000000000000000000000000000000000..7c6c007d16b3c994dad999a3c1494d392b710ffc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/metadata_router.py @@ -0,0 +1,111 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Dict, List + +from haystack import Document, component +from haystack.utils.filters import document_matches_filter + + +@component +class MetadataRouter: + """ + Routes documents to different connections based on their metadata fields. + + Specify the routing rules in the `init` method. + If a document does not match any of the rules, it's routed to a connection named "unmatched". + + ### Usage example + + ```python + from haystack import Document + from haystack.components.routers import MetadataRouter + + docs = [Document(content="Paris is the capital of France.", meta={"language": "en"}), + Document(content="Berlin ist die Haupststadt von Deutschland.", meta={"language": "de"})] + + router = MetadataRouter(rules={"en": {"field": "meta.language", "operator": "==", "value": "en"}}) + + print(router.run(documents=docs)) + + # {'en': [Document(id=..., content: 'Paris is the capital of France.', meta: {'language': 'en'})], + # 'unmatched': [Document(id=..., content: 'Berlin ist die Haupststadt von Deutschland.', meta: {'language': 'de'})]} + ``` + """ + + def __init__(self, rules: Dict[str, Dict]): + """ + Initializes the MetadataRouter component. + + :param rules: A dictionary defining how to route documents to output connections based on their metadata. + Keys are output connection names, and values are dictionaries of + [filtering expressions](https://docs.haystack.deepset.ai/docs/metadata-filtering) in Haystack. + For example: + ```python + { + "edge_1": { + "operator": "AND", + "conditions": [ + {"field": "meta.created_at", "operator": ">=", "value": "2023-01-01"}, + {"field": "meta.created_at", "operator": "<", "value": "2023-04-01"}, + ], + }, + "edge_2": { + "operator": "AND", + "conditions": [ + {"field": "meta.created_at", "operator": ">=", "value": "2023-04-01"}, + {"field": "meta.created_at", "operator": "<", "value": "2023-07-01"}, + ], + }, + "edge_3": { + "operator": "AND", + "conditions": [ + {"field": "meta.created_at", "operator": ">=", "value": "2023-07-01"}, + {"field": "meta.created_at", "operator": "<", "value": "2023-10-01"}, + ], + }, + "edge_4": { + "operator": "AND", + "conditions": [ + {"field": "meta.created_at", "operator": ">=", "value": "2023-10-01"}, + {"field": "meta.created_at", "operator": "<", "value": "2024-01-01"}, + ], + }, + } + ``` + """ + self.rules = rules + component.set_output_types(self, unmatched=List[Document], **{edge: List[Document] for edge in rules}) + + def run(self, documents: List[Document]): + """ + Routes the documents. + + If a document does not match any of the rules, it's routed to a connection named "unmatched". + + :param documents: A list of documents to route. + + :returns: A dictionary where the keys are the names of the output connections (including `"unmatched"`) + and the values are lists of routed documents. + """ + unmatched_documents = [] + output: Dict[str, List[Document]] = {edge: [] for edge in self.rules} + + for document in documents: + cur_document_matched = False + for edge, rule in self.rules.items(): + if "operator" not in rule: + raise ValueError( + "Invalid filter syntax. " + "See https://docs.haystack.deepset.ai/docs/metadata-filtering for details." + ) + if document_matches_filter(rule, document): + output[edge].append(document) + cur_document_matched = True + + if not cur_document_matched: + unmatched_documents.append(document) + + output["unmatched"] = unmatched_documents + return output diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/text_language_router.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/text_language_router.py new file mode 100644 index 0000000000000000000000000000000000000000..2c517df2fc0919dd1ecd774604e062dc7a7e351d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/text_language_router.py @@ -0,0 +1,102 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Dict, List, Optional + +from haystack import component, logging +from haystack.lazy_imports import LazyImport + +logger = logging.getLogger(__name__) + +with LazyImport("Run 'pip install langdetect'") as langdetect_import: + import langdetect + + +@component +class TextLanguageRouter: + """ + Routes text strings to different output connections based on their language. + + Provide a list of languages during initialization. If the document's text doesn't match any of the + specified languages, the metadata value is set to "unmatched". + For routing documents based on their language, use the DocumentLanguageClassifier component, + followed by the MetaDataRouter. + + ### Usage example + + ```python + from haystack import Pipeline, Document + from haystack.components.routers import TextLanguageRouter + from haystack.document_stores.in_memory import InMemoryDocumentStore + from haystack.components.retrievers.in_memory import InMemoryBM25Retriever + + document_store = InMemoryDocumentStore() + document_store.write_documents([Document(content="Elvis Presley was an American singer and actor.")]) + + p = Pipeline() + p.add_component(instance=TextLanguageRouter(languages=["en"]), name="text_language_router") + p.add_component(instance=InMemoryBM25Retriever(document_store=document_store), name="retriever") + p.connect("text_language_router.en", "retriever.query") + + result = p.run({"text_language_router": {"text": "Who was Elvis Presley?"}}) + assert result["retriever"]["documents"][0].content == "Elvis Presley was an American singer and actor." + + result = p.run({"text_language_router": {"text": "ένα ελληνικό κείμενο"}}) + assert result["text_language_router"]["unmatched"] == "ένα ελληνικό κείμενο" + ``` + """ + + def __init__(self, languages: Optional[List[str]] = None): + """ + Initialize the TextLanguageRouter component. + + :param languages: A list of ISO language codes. + See the supported languages in [`langdetect` documentation](https://github.com/Mimino666/langdetect#languages). + If not specified, defaults to ["en"]. + """ + langdetect_import.check() + if not languages: + languages = ["en"] + self.languages = languages + component.set_output_types(self, unmatched=str, **{language: str for language in languages}) + + def run(self, text: str) -> Dict[str, str]: + """ + Routes the text strings to different output connections based on their language. + + If the document's text doesn't match any of the specified languages, the metadata value is set to "unmatched". + + :param text: A text string to route. + + :returns: A dictionary in which the key is the language (or `"unmatched"`), + and the value is the text. + + :raises TypeError: If the input is not a string. + """ + if not isinstance(text, str): + msg = ( + "TextLanguageRouter expects a string as input. In case you want to classify a document, please use " + "the DocumentLanguageClassifier and MetaDataRouter." + ) + raise TypeError(msg) + + output: Dict[str, str] = {} + + detected_language = self._detect_language(text) + if detected_language in self.languages: + output[detected_language] = text + else: + output["unmatched"] = text + + return output + + def _detect_language(self, text: str) -> Optional[str]: + try: + language = langdetect.detect(text) + except langdetect.LangDetectException as exception: + logger.warning("Langdetect cannot detect the language of text. Error: {error}", error=exception) + # Only log the text in debug mode, as it might contain sensitive information + logger.debug("Langdetect cannot detect the language of text: {text}", text=text) + language = None + return language diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/transformers_text_router.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/transformers_text_router.py new file mode 100644 index 0000000000000000000000000000000000000000..f5a9f9961233d180c45bd2451a3b5ec2b783d4f0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/transformers_text_router.py @@ -0,0 +1,205 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.lazy_imports import LazyImport +from haystack.utils import ComponentDevice, Secret, deserialize_secrets_inplace + +logger = logging.getLogger(__name__) + + +with LazyImport(message="Run 'pip install transformers[torch,sentencepiece]'") as torch_and_transformers_import: + from transformers import AutoConfig, pipeline + + from haystack.utils.hf import ( # pylint: disable=ungrouped-imports + deserialize_hf_model_kwargs, + resolve_hf_pipeline_kwargs, + serialize_hf_model_kwargs, + ) + + +@component +class TransformersTextRouter: + """ + Routes the text strings to different connections based on a category label. + + The labels are specific to each model and can be found it its description on Hugging Face. + + ### Usage example + + ```python + from haystack.core.pipeline import Pipeline + from haystack.components.routers import TransformersTextRouter + from haystack.components.builders import PromptBuilder + from haystack.components.generators import HuggingFaceLocalGenerator + + p = Pipeline() + p.add_component( + instance=TransformersTextRouter(model="papluca/xlm-roberta-base-language-detection"), + name="text_router" + ) + p.add_component( + instance=PromptBuilder(template="Answer the question: {{query}}\\nAnswer:"), + name="english_prompt_builder" + ) + p.add_component( + instance=PromptBuilder(template="Beantworte die Frage: {{query}}\\nAntwort:"), + name="german_prompt_builder" + ) + + p.add_component( + instance=HuggingFaceLocalGenerator(model="DiscoResearch/Llama3-DiscoLeo-Instruct-8B-v0.1"), + name="german_llm" + ) + p.add_component( + instance=HuggingFaceLocalGenerator(model="microsoft/Phi-3-mini-4k-instruct"), + name="english_llm" + ) + + p.connect("text_router.en", "english_prompt_builder.query") + p.connect("text_router.de", "german_prompt_builder.query") + p.connect("english_prompt_builder.prompt", "english_llm.prompt") + p.connect("german_prompt_builder.prompt", "german_llm.prompt") + + # English Example + print(p.run({"text_router": {"text": "What is the capital of Germany?"}})) + + # German Example + print(p.run({"text_router": {"text": "Was ist die Hauptstadt von Deutschland?"}})) + ``` + """ + + def __init__( + self, + model: str, + labels: Optional[List[str]] = None, + device: Optional[ComponentDevice] = None, + token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + huggingface_pipeline_kwargs: Optional[Dict[str, Any]] = None, + ): + """ + Initializes the TransformersTextRouter component. + + :param model: The name or path of a Hugging Face model for text classification. + :param labels: The list of labels. If not provided, the component fetches the labels + from the model configuration file hosted on the Hugging Face Hub using + `transformers.AutoConfig.from_pretrained`. + :param device: The device for loading the model. If `None`, automatically selects the default device. + If a device or device map is specified in `huggingface_pipeline_kwargs`, it overrides this parameter. + :param token: The API token used to download private models from Hugging Face. + If `True`, uses either `HF_API_TOKEN` or `HF_TOKEN` environment variables. + To generate these tokens, run `transformers-cli login`. + :param huggingface_pipeline_kwargs: A dictionary of keyword arguments for initializing the Hugging Face + text classification pipeline. + """ + torch_and_transformers_import.check() + + self.token = token + + huggingface_pipeline_kwargs = resolve_hf_pipeline_kwargs( + huggingface_pipeline_kwargs=huggingface_pipeline_kwargs or {}, + model=model, + task="text-classification", + supported_tasks=["text-classification"], + device=device, + token=token, + ) + self.huggingface_pipeline_kwargs = huggingface_pipeline_kwargs + + if labels is None: + config = AutoConfig.from_pretrained( + huggingface_pipeline_kwargs["model"], token=huggingface_pipeline_kwargs["token"] + ) + self.labels = list(config.label2id.keys()) + else: + self.labels = labels + component.set_output_types(self, **{label: str for label in self.labels}) + + self.pipeline = None + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + if isinstance(self.huggingface_pipeline_kwargs["model"], str): + return {"model": self.huggingface_pipeline_kwargs["model"]} + return {"model": f"[object of type {type(self.huggingface_pipeline_kwargs['model'])}]"} + + def warm_up(self): + """ + Initializes the component. + """ + if self.pipeline is None: + self.pipeline = pipeline(**self.huggingface_pipeline_kwargs) + + # Verify labels from the model configuration file match provided labels + labels = set(self.pipeline.model.config.label2id.keys()) + if set(self.labels) != labels: + raise ValueError( + f"The provided labels do not match the labels in the model configuration file. " + f"Provided labels: {self.labels}. Model labels: {labels}" + ) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + serialization_dict = default_to_dict( + self, + labels=self.labels, + model=self.huggingface_pipeline_kwargs["model"], + huggingface_pipeline_kwargs=self.huggingface_pipeline_kwargs, + token=self.token.to_dict() if self.token else None, + ) + + huggingface_pipeline_kwargs = serialization_dict["init_parameters"]["huggingface_pipeline_kwargs"] + huggingface_pipeline_kwargs.pop("token", None) + + serialize_hf_model_kwargs(huggingface_pipeline_kwargs) + return serialization_dict + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "TransformersTextRouter": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["token"]) + if data["init_parameters"].get("huggingface_pipeline_kwargs") is not None: + deserialize_hf_model_kwargs(data["init_parameters"]["huggingface_pipeline_kwargs"]) + return default_from_dict(cls, data) + + def run(self, text: str) -> Dict[str, str]: + """ + Routes the text strings to different connections based on a category label. + + :param text: A string of text to route. + :returns: + A dictionary with the label as key and the text as value. + + :raises TypeError: + If the input is not a str. + :raises RuntimeError: + If the pipeline has not been loaded because warm_up() was not called before. + """ + if self.pipeline is None: + raise RuntimeError( + "The component TextTransformersRouter wasn't warmed up. Run 'warm_up()' before calling 'run()'." + ) + + if not isinstance(text, str): + raise TypeError("TransformersTextRouter expects a str as input.") + + prediction = self.pipeline([text], return_all_scores=False, function_to_apply="none") + label = prediction[0]["label"] + return {label: text} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/zero_shot_text_router.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/zero_shot_text_router.py new file mode 100644 index 0000000000000000000000000000000000000000..619862f2f2bdd040b2395b8f68ed7447e3351c20 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/routers/zero_shot_text_router.py @@ -0,0 +1,219 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.lazy_imports import LazyImport +from haystack.utils import ComponentDevice, Secret, deserialize_secrets_inplace + +logger = logging.getLogger(__name__) + + +with LazyImport(message="Run 'pip install transformers[torch,sentencepiece]'") as torch_and_transformers_import: + from transformers import pipeline + + from haystack.utils.hf import ( # pylint: disable=ungrouped-imports + deserialize_hf_model_kwargs, + resolve_hf_pipeline_kwargs, + serialize_hf_model_kwargs, + ) + + +@component +class TransformersZeroShotTextRouter: + """ + Routes the text strings to different connections based on a category label. + + Specify the set of labels for categorization when initializing the component. + + ### Usage example + + ```python + from haystack import Document + from haystack.document_stores.in_memory import InMemoryDocumentStore + from haystack.core.pipeline import Pipeline + from haystack.components.routers import TransformersZeroShotTextRouter + from haystack.components.embedders import SentenceTransformersTextEmbedder, SentenceTransformersDocumentEmbedder + from haystack.components.retrievers import InMemoryEmbeddingRetriever + + document_store = InMemoryDocumentStore() + doc_embedder = SentenceTransformersDocumentEmbedder(model="intfloat/e5-base-v2") + doc_embedder.warm_up() + docs = [ + Document( + content="Germany, officially the Federal Republic of Germany, is a country in the western region of " + "Central Europe. The nation's capital and most populous city is Berlin and its main financial centre " + "is Frankfurt; the largest urban area is the Ruhr." + ), + Document( + content="France, officially the French Republic, is a country located primarily in Western Europe. " + "France is a unitary semi-presidential republic with its capital in Paris, the country's largest city " + "and main cultural and commercial centre; other major urban areas include Marseille, Lyon, Toulouse, " + "Lille, Bordeaux, Strasbourg, Nantes and Nice." + ) + ] + docs_with_embeddings = doc_embedder.run(docs) + document_store.write_documents(docs_with_embeddings["documents"]) + + p = Pipeline() + p.add_component(instance=TransformersZeroShotTextRouter(labels=["passage", "query"]), name="text_router") + p.add_component( + instance=SentenceTransformersTextEmbedder(model="intfloat/e5-base-v2", prefix="passage: "), + name="passage_embedder" + ) + p.add_component( + instance=SentenceTransformersTextEmbedder(model="intfloat/e5-base-v2", prefix="query: "), + name="query_embedder" + ) + p.add_component( + instance=InMemoryEmbeddingRetriever(document_store=document_store), + name="query_retriever" + ) + p.add_component( + instance=InMemoryEmbeddingRetriever(document_store=document_store), + name="passage_retriever" + ) + + p.connect("text_router.passage", "passage_embedder.text") + p.connect("passage_embedder.embedding", "passage_retriever.query_embedding") + p.connect("text_router.query", "query_embedder.text") + p.connect("query_embedder.embedding", "query_retriever.query_embedding") + + # Query Example + p.run({"text_router": {"text": "What is the capital of Germany?"}}) + + # Passage Example + p.run({ + "text_router":{ + "text": "The United Kingdom of Great Britain and Northern Ireland, commonly known as the "\ + "United Kingdom (UK) or Britain, is a country in Northwestern Europe, off the north-western coast of "\ + "the continental mainland." + } + }) + ``` + """ + + def __init__( + self, + labels: List[str], + multi_label: bool = False, + model: str = "MoritzLaurer/deberta-v3-base-zeroshot-v1.1-all-33", + device: Optional[ComponentDevice] = None, + token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + huggingface_pipeline_kwargs: Optional[Dict[str, Any]] = None, + ): + """ + Initializes the TransformersZeroShotTextRouter component. + + :param labels: The set of labels to use for classification. Can be a single label, + a string of comma-separated labels, or a list of labels. + :param multi_label: + Indicates if multiple labels can be true. + If `False`, label scores are normalized so their sum equals 1 for each sequence. + If `True`, the labels are considered independent and probabilities are normalized for each candidate by + doing a softmax of the entailment score vs. the contradiction score. + :param model: The name or path of a Hugging Face model for zero-shot text classification. + :param device: The device for loading the model. If `None`, automatically selects the default device. + If a device or device map is specified in `huggingface_pipeline_kwargs`, it overrides this parameter. + :param token: The API token used to download private models from Hugging Face. + If `True`, uses either `HF_API_TOKEN` or `HF_TOKEN` environment variables. + To generate these tokens, run `transformers-cli login`. + :param huggingface_pipeline_kwargs: A dictionary of keyword arguments for initializing the Hugging Face + zero shot text classification. + """ + torch_and_transformers_import.check() + + self.token = token + self.labels = labels + self.multi_label = multi_label + component.set_output_types(self, **{label: str for label in labels}) + + huggingface_pipeline_kwargs = resolve_hf_pipeline_kwargs( + huggingface_pipeline_kwargs=huggingface_pipeline_kwargs or {}, + model=model, + task="zero-shot-classification", + supported_tasks=["zero-shot-classification"], + device=device, + token=token, + ) + self.huggingface_pipeline_kwargs = huggingface_pipeline_kwargs + self.pipeline = None + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + if isinstance(self.huggingface_pipeline_kwargs["model"], str): + return {"model": self.huggingface_pipeline_kwargs["model"]} + return {"model": f"[object of type {type(self.huggingface_pipeline_kwargs['model'])}]"} + + def warm_up(self): + """ + Initializes the component. + """ + if self.pipeline is None: + self.pipeline = pipeline(**self.huggingface_pipeline_kwargs) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + serialization_dict = default_to_dict( + self, + labels=self.labels, + huggingface_pipeline_kwargs=self.huggingface_pipeline_kwargs, + token=self.token.to_dict() if self.token else None, + ) + + huggingface_pipeline_kwargs = serialization_dict["init_parameters"]["huggingface_pipeline_kwargs"] + huggingface_pipeline_kwargs.pop("token", None) + + serialize_hf_model_kwargs(huggingface_pipeline_kwargs) + return serialization_dict + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "TransformersZeroShotTextRouter": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["token"]) + if data["init_parameters"].get("huggingface_pipeline_kwargs") is not None: + deserialize_hf_model_kwargs(data["init_parameters"]["huggingface_pipeline_kwargs"]) + return default_from_dict(cls, data) + + def run(self, text: str) -> Dict[str, str]: + """ + Routes the text strings to different connections based on a category label. + + :param text: A string of text to route. + :returns: + A dictionary with the label as key and the text as value. + + :raises TypeError: + If the input is not a str. + :raises RuntimeError: + If the pipeline has not been loaded because warm_up() was not called before. + """ + if self.pipeline is None: + raise RuntimeError( + "The component TransformersZeroShotTextRouter wasn't warmed up. Run 'warm_up()' before calling 'run()'." + ) + + if not isinstance(text, str): + raise TypeError("TransformersZeroShotTextRouter expects a str as input.") + + prediction = self.pipeline(sequences=[text], candidate_labels=self.labels, multi_label=self.multi_label) + predicted_scores = prediction[0]["scores"] + max_score_index = max(range(len(predicted_scores)), key=predicted_scores.__getitem__) + label = prediction[0]["labels"][max_score_index] + return {label: text} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/samplers/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/samplers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3ae8de18272d870a521b10b21843a29d38981687 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/samplers/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.samplers.top_p import TopPSampler + +__all__ = ["TopPSampler"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/samplers/top_p.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/samplers/top_p.py new file mode 100644 index 0000000000000000000000000000000000000000..2d2327291c2a71a12a495bdfeec3b8ef5c469629 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/samplers/top_p.py @@ -0,0 +1,177 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import List, Optional, Tuple + +from haystack import Document, component, logging +from haystack.lazy_imports import LazyImport + +logger = logging.getLogger(__name__) + + +with LazyImport(message="Run 'pip install \"torch>=1.13\"'") as torch_import: + import torch + + +@component +class TopPSampler: + """ + Implements top-p (nucleus) sampling for document filtering based on cumulative probability scores. + + This component provides functionality to filter a list of documents by selecting those whose scores fall + within the top 'p' percent of the cumulative distribution. It is useful for focusing on high-probability + documents while filtering out less relevant ones based on their assigned scores. + + Usage example: + + ```python + from haystack import Document + from haystack.components.samplers import TopPSampler + + sampler = TopPSampler(top_p=0.95, score_field="similarity_score") + docs = [ + Document(content="Berlin", meta={"similarity_score": -10.6}), + Document(content="Belgrade", meta={"similarity_score": -8.9}), + Document(content="Sarajevo", meta={"similarity_score": -4.6}), + ] + output = sampler.run(documents=docs) + docs = output["documents"] + assert len(docs) == 1 + assert docs[0].content == "Sarajevo" + ``` + """ + + def __init__(self, top_p: float = 1.0, score_field: Optional[str] = None, min_top_k: Optional[int] = None): + """ + Creates an instance of TopPSampler. + + :param top_p: Float between 0 and 1 representing the cumulative probability threshold for document selection. + A value of 1.0 indicates no filtering (all documents are retained). + :param score_field: Name of the field in each document's metadata that contains the score. If None, the default + document score field is used. + :param min_top_k: If specified, the minimum number of documents to return. If the top_p selects + fewer documents, additional ones with the next highest scores are added to the selection. + """ + torch_import.check() + + self.top_p = top_p + if not 0 <= top_p <= 1: + raise ValueError(f"top_p must be between 0 and 1. Got {top_p}.") + self.score_field = score_field + self.min_top_k = min_top_k + + @component.output_types(documents=List[Document]) + def run(self, documents: List[Document], top_p: Optional[float] = None): + """ + Filters documents using top-p sampling based on their scores. + + If the specified top_p results in no documents being selected (especially in cases of a low top_p value), the + method returns the document with the highest score. + + :param documents: List of Document objects to be filtered. + :param top_p: If specified, a float to override the cumulative probability threshold set during initialization. + + :returns: A dictionary with the following key: + - `documents`: List of Document objects that have been selected based on the top-p sampling. + :raises ValueError: If the top_p value is not within the range [0, 1]. + """ + if not documents: + return {"documents": []} + + top_p = top_p or self.top_p + if not 0 <= top_p <= 1: + raise ValueError(f"top_p must be between 0 and 1. Got {top_p}.") + + documents_with_scores, scores = self._get_documents_and_scores(documents) + if len(documents_with_scores) == 0: + logger.warning("No documents with scores found. Returning the original documents.") + return {"documents": documents} + + sorted_docs_with_scores = sorted(zip(documents_with_scores, scores), key=lambda x: x[1], reverse=True) + sorted_documents, sorted_scores = [list(t) for t in zip(*sorted_docs_with_scores)] + + tensor_scores = torch.tensor(sorted_scores, dtype=torch.float32) + probs = torch.nn.functional.softmax(tensor_scores, dim=-1) + cumulative_probs = torch.cumsum(probs, dim=-1) + + # Check if the cumulative probabilities are close to top_p with a 1e-6 tolerance + close_to_top_p = torch.isclose(cumulative_probs, torch.tensor(top_p, device=cumulative_probs.device), atol=1e-6) + + # Combine the close_to_top_p with original condition using logical OR + condition = (cumulative_probs <= top_p) | close_to_top_p + + # Find the indices with cumulative probabilities that exceed top_p + top_p_indices = torch.where(torch.BoolTensor(condition))[0] + + # Map the selected indices back to their original indices + selected_docs = [sorted_documents[i.item()] for i in top_p_indices] + + if self.min_top_k and len(selected_docs) < self.min_top_k: + selected_docs = sorted_documents[: self.min_top_k] + + # If low p resulted in no documents being selected, then return at least one document + if len(selected_docs) == 0: + logger.warning( + "Top-p sampling with p={top_p} resulted in no documents being selected. " + "Returning the document with the highest score.", + top_p=top_p, + ) + selected_docs = [sorted_documents[0]] + + return {"documents": selected_docs} + + @staticmethod + def _get_doc_score(doc: Document, score_field: Optional[str] = None) -> Optional[float]: + """ + Get the score of a document. + + :param doc: Document object. + :param score_field: Name of the field in the document's metadata that contains the score. + If None, the document score field is used. + + :return: Score of the document. + """ + if score_field: + score = doc.meta.get(score_field) + else: + score = doc.score + + if not isinstance(score, float): + score = None + return score + + def _get_documents_and_scores(self, documents: List[Document]) -> Tuple[List[Document], List[float]]: + """ + Checks if documents have scores in their metadata or score field and returns the documents with scores. + + :param documents: List of Documents. + :return: List of scores. + """ + docs_with_scores = [] + scores = [] + docs_missing_scores = [] + for doc in documents: + score = self._get_doc_score(doc=doc, score_field=self.score_field) + if score is None: + docs_missing_scores.append(doc) + else: + scores.append(score) + docs_with_scores.append(doc) + + if len(docs_missing_scores) > 0: + missing_scores_docs_ids = [d.id for d in docs_missing_scores if d.id] + if self.score_field: + logger.warning( + "Score field '{score_field}' not found in metadata of documents with IDs: {doc_ids}." + "Make sure that all documents have a score field '{score_field_2}' in their metadata.", + score_field=self.score_field, + doc_ids=",".join(missing_scores_docs_ids), + score_field_2=self.score_field, + ) + else: + logger.warning( + "Ensure all documents have a valid score value. These documents {doc_ids} are missing scores.", + doc_ids=",".join(missing_scores_docs_ids), + ) + return docs_with_scores, scores diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/validators/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/validators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4fe2bf26ab76557f86a8f386f0f8e49757da22f0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/validators/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.validators.json_schema import JsonSchemaValidator + +__all__ = ["JsonSchemaValidator"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/validators/json_schema.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/validators/json_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..13f35be87e7b8fbc376df7df03ab1ea1ae42723f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/validators/json_schema.py @@ -0,0 +1,263 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +from typing import Any, Dict, List, Optional + +from haystack import component +from haystack.dataclasses import ChatMessage +from haystack.lazy_imports import LazyImport + +with LazyImport(message="Run 'pip install jsonschema'") as jsonschema_import: + from jsonschema import ValidationError, validate + + +def is_valid_json(s: str) -> bool: + """ + Check if the provided string is a valid JSON. + + :param s: The string to be checked. + :returns: `True` if the string is a valid JSON; otherwise, `False`. + """ + try: + json.loads(s) + except ValueError: + return False + return True + + +@component +class JsonSchemaValidator: + """ + Validates JSON content of `ChatMessage` against a specified [JSON Schema](https://json-schema.org/). + + If JSON content of a message conforms to the provided schema, the message is passed along the "validated" output. + If the JSON content does not conform to the schema, the message is passed along the "validation_error" output. + In the latter case, the error message is constructed using the provided `error_template` or a default template. + These error ChatMessages can be used by LLMs in Haystack 2.x recovery loops. + + Usage example: + + ```python + from typing import List + + from haystack import Pipeline + from haystack.components.generators.chat import OpenAIChatGenerator + from haystack.components.joiners import BranchJoiner + from haystack.components.validators import JsonSchemaValidator + from haystack import component + from haystack.dataclasses import ChatMessage + + + @component + class MessageProducer: + + @component.output_types(messages=List[ChatMessage]) + def run(self, messages: List[ChatMessage]) -> dict: + return {"messages": messages} + + + p = Pipeline() + p.add_component("llm", OpenAIChatGenerator(model="gpt-4-1106-preview", + generation_kwargs={"response_format": {"type": "json_object"}})) + p.add_component("schema_validator", JsonSchemaValidator()) + p.add_component("joiner_for_llm", BranchJoiner(List[ChatMessage])) + p.add_component("message_producer", MessageProducer()) + + p.connect("message_producer.messages", "joiner_for_llm") + p.connect("joiner_for_llm", "llm") + p.connect("llm.replies", "schema_validator.messages") + p.connect("schema_validator.validation_error", "joiner_for_llm") + + result = p.run(data={ + "message_producer": { + "messages":[ChatMessage.from_user("Generate JSON for person with name 'John' and age 30")]}, + "schema_validator": { + "json_schema": { + "type": "object", + "properties": {"name": {"type": "string"}, + "age": {"type": "integer"} + } + } + } + }) + print(result) + >> {'schema_validator': {'validated': [ChatMessage(content='\\n{\\n "name": "John",\\n "age": 30\\n}', + role=, name=None, meta={'model': 'gpt-4-1106-preview', 'index': 0, + 'finish_reason': 'stop', 'usage': {'completion_tokens': 17, 'prompt_tokens': 20, 'total_tokens': 37}})]}} + ``` + """ + + # Default error description template + default_error_template = ( + "The following generated JSON does not conform to the provided schema.\n" + "Generated JSON: {failing_json}\n" + "Error details:\n- Message: {error_message}\n" + "- Error Path in JSON: {error_path}\n" + "- Schema Path: {error_schema_path}\n" + "Please match the following schema:\n" + "{json_schema}\n" + "and provide the corrected JSON content ONLY. Please do not output anything else than the raw corrected " + "JSON string, this is the most important part of the task. Don't use any markdown and don't add any comment." + ) + + def __init__(self, json_schema: Optional[Dict[str, Any]] = None, error_template: Optional[str] = None): + """ + Initialize the JsonSchemaValidator component. + + :param json_schema: A dictionary representing the [JSON schema](https://json-schema.org/) against which + the messages' content is validated. + :param error_template: A custom template string for formatting the error message in case of validation failure. + """ + jsonschema_import.check() + self.json_schema = json_schema + self.error_template = error_template + + @component.output_types(validated=List[ChatMessage], validation_error=List[ChatMessage]) + def run( + self, + messages: List[ChatMessage], + json_schema: Optional[Dict[str, Any]] = None, + error_template: Optional[str] = None, + ) -> Dict[str, List[ChatMessage]]: + """ + Validates the last of the provided messages against the specified json schema. + + If it does, the message is passed along the "validated" output. If it does not, the message is passed along + the "validation_error" output. + + :param messages: A list of ChatMessage instances to be validated. The last message in this list is the one + that is validated. + :param json_schema: A dictionary representing the [JSON schema](https://json-schema.org/) + against which the messages' content is validated. If not provided, the schema from the component init + is used. + :param error_template: A custom template string for formatting the error message in case of validation. If not + provided, the `error_template` from the component init is used. + :return: A dictionary with the following keys: + - "validated": A list of messages if the last message is valid. + - "validation_error": A list of messages if the last message is invalid. + :raises ValueError: If no JSON schema is provided or if the message content is not a dictionary or a list of + dictionaries. + """ + last_message = messages[-1] + if not is_valid_json(last_message.content): + return { + "validation_error": [ + ChatMessage.from_user( + f"The message '{last_message.content}' is not a valid JSON object. " + f"Please provide only a valid JSON object in string format." + f"Don't use any markdown and don't add any comment." + ) + ] + } + + last_message_content = json.loads(last_message.content) + json_schema = json_schema or self.json_schema + error_template = error_template or self.error_template or self.default_error_template + + if not json_schema: + raise ValueError("Provide a JSON schema for validation either in the run method or in the component init.") + # fc payload is json object but subtree `parameters` is string - we need to convert to json object + # we need complete json to validate it against schema + last_message_json = self._recursive_json_to_object(last_message_content) + using_openai_schema: bool = self._is_openai_function_calling_schema(json_schema) + if using_openai_schema: + validation_schema = json_schema["parameters"] + else: + validation_schema = json_schema + try: + last_message_json = [last_message_json] if not isinstance(last_message_json, list) else last_message_json + for content in last_message_json: + if using_openai_schema: + validate(instance=content["function"]["arguments"], schema=validation_schema) + else: + validate(instance=content, schema=validation_schema) + + return {"validated": [last_message]} + except ValidationError as e: + error_path = " -> ".join(map(str, e.absolute_path)) if e.absolute_path else "N/A" + error_schema_path = " -> ".join(map(str, e.absolute_schema_path)) if e.absolute_schema_path else "N/A" + + error_template = error_template or self.default_error_template + + recovery_prompt = self._construct_error_recovery_message( + error_template, + str(e), + error_path, + error_schema_path, + validation_schema, + failing_json=last_message.content, + ) + return {"validation_error": [ChatMessage.from_user(recovery_prompt)]} + + def _construct_error_recovery_message( + self, + error_template: str, + error_message: str, + error_path: str, + error_schema_path: str, + json_schema: Dict[str, Any], + failing_json: str, + ) -> str: + """ + Constructs an error recovery message using a specified template or the default one if none is provided. + + :param error_template: A custom template string for formatting the error message in case of validation failure. + :param error_message: The error message returned by the JSON schema validator. + :param error_path: The path in the JSON content where the error occurred. + :param error_schema_path: The path in the JSON schema where the error occurred. + :param json_schema: The JSON schema against which the content is validated. + :param failing_json: The generated invalid JSON string. + """ + error_template = error_template or self.default_error_template + + return error_template.format( + error_message=error_message, + error_path=error_path, + error_schema_path=error_schema_path, + json_schema=json_schema, + failing_json=failing_json, + ) + + def _is_openai_function_calling_schema(self, json_schema: Dict[str, Any]) -> bool: + """ + Checks if the provided schema is a valid OpenAI function calling schema. + + :param json_schema: The JSON schema to check + :return: `True` if the schema is a valid OpenAI function calling schema; otherwise, `False`. + """ + return all(key in json_schema for key in ["name", "description", "parameters"]) + + def _recursive_json_to_object(self, data: Any) -> Any: + """ + Convert any string values that are valid JSON objects into dictionary objects. + + Returns a new data structure. + + :param data: The data structure to be traversed. + :return: A new data structure with JSON strings converted to dictionary objects. + """ + if isinstance(data, list): + return [self._recursive_json_to_object(item) for item in data] + + if isinstance(data, dict): + new_dict = {} + for key, value in data.items(): + if isinstance(value, str): + try: + json_value = json.loads(value) + if isinstance(json_value, (dict, list)): + new_dict[key] = self._recursive_json_to_object(json_value) + else: + new_dict[key] = value # Preserve the original string value + except json.JSONDecodeError: + new_dict[key] = value + elif isinstance(value, dict): + new_dict[key] = self._recursive_json_to_object(value) + else: + new_dict[key] = value + return new_dict + + # If it's neither a list nor a dictionary, return the value directly + raise ValueError("Input must be a dictionary or a list of dictionaries.") diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/websearch/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/websearch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bf5d3af2090d553799752142ed9ffbeb3c4b6b5f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/websearch/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.websearch.searchapi import SearchApiWebSearch +from haystack.components.websearch.serper_dev import SerperDevWebSearch + +__all__ = ["SerperDevWebSearch", "SearchApiWebSearch"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/websearch/searchapi.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/websearch/searchapi.py new file mode 100644 index 0000000000000000000000000000000000000000..4cf22f02109d9c496f0c8b21ad9596e8c7783009 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/websearch/searchapi.py @@ -0,0 +1,179 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional, Union + +import requests + +from haystack import ComponentError, Document, component, default_from_dict, default_to_dict, logging +from haystack.utils import Secret, deserialize_secrets_inplace + +logger = logging.getLogger(__name__) + + +SEARCHAPI_BASE_URL = "https://www.searchapi.io/api/v1/search" + + +class SearchApiError(ComponentError): ... + + +@component +class SearchApiWebSearch: + """ + Uses [SearchApi](https://www.searchapi.io/) to search the web for relevant documents. + + Usage example: + ```python + from haystack.components.websearch import SearchApiWebSearch + from haystack.utils import Secret + + websearch = SearchApiWebSearch(top_k=10, api_key=Secret.from_token("test-api-key")) + results = websearch.run(query="Who is the boyfriend of Olivia Wilde?") + + assert results["documents"] + assert results["links"] + ``` + """ + + def __init__( + self, + api_key: Secret = Secret.from_env_var("SEARCHAPI_API_KEY"), + top_k: Optional[int] = 10, + allowed_domains: Optional[List[str]] = None, + search_params: Optional[Dict[str, Any]] = None, + ): + """ + Initialize the SearchApiWebSearch component. + + :param api_key: API key for the SearchApi API + :param top_k: Number of documents to return. + :param allowed_domains: List of domains to limit the search to. + :param search_params: Additional parameters passed to the SearchApi API. + For example, you can set 'num' to 100 to increase the number of search results. + See the [SearchApi website](https://www.searchapi.io/) for more details. + + The default search engine is Google, however, users can change it by setting the `engine` + parameter in the `search_params`. + """ + + self.api_key = api_key + self.top_k = top_k + self.allowed_domains = allowed_domains + self.search_params = search_params or {} + if "engine" not in self.search_params: + self.search_params["engine"] = "google" + + # Ensure that the API key is resolved. + _ = self.api_key.resolve_value() + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + top_k=self.top_k, + allowed_domains=self.allowed_domains, + search_params=self.search_params, + api_key=self.api_key.to_dict(), + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "SearchApiWebSearch": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + return default_from_dict(cls, data) + + @component.output_types(documents=List[Document], links=List[str]) + def run(self, query: str) -> Dict[str, Union[List[Document], List[str]]]: + """ + Uses [SearchApi](https://www.searchapi.io/) to search the web. + + :param query: Search query. + :returns: A dictionary with the following keys: + - "documents": List of documents returned by the search engine. + - "links": List of links returned by the search engine. + :raises TimeoutError: If the request to the SearchApi API times out. + :raises SearchApiError: If an error occurs while querying the SearchApi API. + """ + query_prepend = "OR ".join(f"site:{domain} " for domain in self.allowed_domains) if self.allowed_domains else "" + payload = {"q": query_prepend + " " + query, **self.search_params} + headers = {"Authorization": f"Bearer {self.api_key.resolve_value()}", "X-SearchApi-Source": "Haystack"} + try: + response = requests.get(SEARCHAPI_BASE_URL, headers=headers, params=payload, timeout=90) + response.raise_for_status() # Will raise an HTTPError for bad responses + except requests.Timeout as error: + raise TimeoutError(f"Request to {self.__class__.__name__} timed out.") from error + + except requests.RequestException as e: + raise SearchApiError(f"An error occurred while querying {self.__class__.__name__}. Error: {e}") from e + + # Request succeeded + json_result = response.json() + + # organic results are the main results from the search engine + organic_results = [] + if "organic_results" in json_result: + for result in json_result["organic_results"]: + organic_results.append( + Document.from_dict({"title": result["title"], "content": result["snippet"], "link": result["link"]}) + ) + + # answer box has a direct answer to the query + answer_box = [] + if "answer_box" in json_result: + answer_box = [ + Document.from_dict( + { + "title": json_result["answer_box"].get("title", ""), + "content": json_result["answer_box"].get("answer", ""), + "link": json_result["answer_box"].get("link", ""), + } + ) + ] + + knowledge_graph = [] + if "knowledge_graph" in json_result: + knowledge_graph = [ + Document.from_dict( + { + "title": json_result["knowledge_graph"].get("title", ""), + "content": json_result["knowledge_graph"].get("description", ""), + } + ) + ] + + related_questions = [] + if "related_questions" in json_result: + for result in json_result["related_questions"]: + related_questions.append( + Document.from_dict( + { + "title": result["question"], + "content": result["answer"] if result.get("answer") else result.get("answer_highlight", ""), + "link": result.get("source", {}).get("link", ""), + } + ) + ) + + documents = answer_box + knowledge_graph + organic_results + related_questions + + links = [result["link"] for result in json_result["organic_results"]] + + logger.debug( + "SearchApi returned {number_documents} documents for the query '{query}'", + number_documents=len(documents), + query=query, + ) + return {"documents": documents[: self.top_k], "links": links[: self.top_k]} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/websearch/serper_dev.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/websearch/serper_dev.py new file mode 100644 index 0000000000000000000000000000000000000000..a992fa38e34368825dac3491069b6e3e90c19dbb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/websearch/serper_dev.py @@ -0,0 +1,175 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +from typing import Any, Dict, List, Optional, Union + +import requests + +from haystack import ComponentError, Document, component, default_from_dict, default_to_dict, logging +from haystack.utils import Secret, deserialize_secrets_inplace + +logger = logging.getLogger(__name__) + + +SERPERDEV_BASE_URL = "https://google.serper.dev/search" + + +class SerperDevError(ComponentError): ... + + +@component +class SerperDevWebSearch: + """ + Uses [Serper](https://serper.dev/) to search the web for relevant documents. + + See the [Serper Dev website](https://serper.dev/) for more details. + + Usage example: + ```python + from haystack.components.websearch import SerperDevWebSearch + from haystack.utils import Secret + + websearch = SerperDevWebSearch(top_k=10, api_key=Secret.from_token("test-api-key")) + results = websearch.run(query="Who is the boyfriend of Olivia Wilde?") + + assert results["documents"] + assert results["links"] + ``` + """ + + def __init__( + self, + api_key: Secret = Secret.from_env_var("SERPERDEV_API_KEY"), + top_k: Optional[int] = 10, + allowed_domains: Optional[List[str]] = None, + search_params: Optional[Dict[str, Any]] = None, + ): + """ + Initialize the SerperDevWebSearch component. + + :param api_key: API key for the Serper API. + :param top_k: Number of documents to return. + :param allowed_domains: List of domains to limit the search to. + :param search_params: Additional parameters passed to the Serper API. + For example, you can set 'num' to 20 to increase the number of search results. + See the [Serper website](https://serper.dev/) for more details. + """ + self.api_key = api_key + self.top_k = top_k + self.allowed_domains = allowed_domains + self.search_params = search_params or {} + + # Ensure that the API key is resolved. + _ = self.api_key.resolve_value() + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + top_k=self.top_k, + allowed_domains=self.allowed_domains, + search_params=self.search_params, + api_key=self.api_key.to_dict(), + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "SerperDevWebSearch": + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + return default_from_dict(cls, data) + + @component.output_types(documents=List[Document], links=List[str]) + def run(self, query: str) -> Dict[str, Union[List[Document], List[str]]]: + """ + Use [Serper](https://serper.dev/) to search the web. + + :param query: Search query. + :returns: A dictionary with the following keys: + - "documents": List of documents returned by the search engine. + - "links": List of links returned by the search engine. + :raises SerperDevError: If an error occurs while querying the SerperDev API. + :raises TimeoutError: If the request to the SerperDev API times out. + """ + query_prepend = "OR ".join(f"site:{domain} " for domain in self.allowed_domains) if self.allowed_domains else "" + + payload = json.dumps( + {"q": query_prepend + query, "gl": "us", "hl": "en", "autocorrect": True, **self.search_params} + ) + headers = {"X-API-KEY": self.api_key.resolve_value(), "Content-Type": "application/json"} + + try: + response = requests.post(SERPERDEV_BASE_URL, headers=headers, data=payload, timeout=30) # type: ignore + response.raise_for_status() # Will raise an HTTPError for bad responses + except requests.Timeout as error: + raise TimeoutError(f"Request to {self.__class__.__name__} timed out.") from error + + except requests.RequestException as e: + raise SerperDevError(f"An error occurred while querying {self.__class__.__name__}. Error: {e}") from e + + # If we reached this point, it means the request was successful and we can proceed + json_result = response.json() + + # we get the snippet from the json result and put it in the content field of the document + organic = [ + Document(meta={k: v for k, v in d.items() if k != "snippet"}, content=d.get("snippet")) + for d in json_result["organic"] + ] + + # answer box is what search engine shows as a direct answer to the query + answer_box = [] + if "answerBox" in json_result: + answer_dict = json_result["answerBox"] + highlighted_answers = answer_dict.get("snippetHighlighted") + answer_box_content = None + # Check if highlighted_answers is a list and has at least one element + if isinstance(highlighted_answers, list) and len(highlighted_answers) > 0: + answer_box_content = highlighted_answers[0] + elif isinstance(highlighted_answers, str): + answer_box_content = highlighted_answers + if not answer_box_content: + for key in ["snippet", "answer", "title"]: + if key in answer_dict: + answer_box_content = answer_dict[key] + break + if answer_box_content: + answer_box = [ + Document( + content=answer_box_content, + meta={"title": answer_dict.get("title", ""), "link": answer_dict.get("link", "")}, + ) + ] + + # these are related questions that search engine shows + people_also_ask = [] + if "peopleAlsoAsk" in json_result: + for result in json_result["peopleAlsoAsk"]: + title = result.get("title", "") + people_also_ask.append( + Document( + content=result["snippet"] if result.get("snippet") else title, + meta={"title": title, "link": result.get("link", None)}, + ) + ) + + documents = answer_box + organic + people_also_ask + + links = [result["link"] for result in json_result["organic"]] + + logger.debug( + "Serper Dev returned {number_documents} documents for the query '{query}'", + number_documents=len(documents), + query=query, + ) + return {"documents": documents[: self.top_k], "links": links[: self.top_k]} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/writers/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/writers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6d609f59d98caabfb410a5a2cba10c433ad7a762 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/writers/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.writers.document_writer import DocumentWriter + +__all__ = ["DocumentWriter"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/writers/document_writer.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/writers/document_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..7e757596389e129ae9906ba9a6a18ee11754e03a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/components/writers/document_writer.py @@ -0,0 +1,102 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional + +from haystack import Document, component, default_from_dict, default_to_dict, logging +from haystack.document_stores.types import DocumentStore, DuplicatePolicy +from haystack.utils import deserialize_document_store_in_init_params_inplace + +logger = logging.getLogger(__name__) + + +@component +class DocumentWriter: + """ + Writes documents to a DocumentStore. + + ### Usage example + ```python + from haystack import Document + from haystack.components.writers import DocumentWriter + from haystack.document_stores.in_memory import InMemoryDocumentStore + docs = [ + Document(content="Python is a popular programming language"), + ] + doc_store = InMemoryDocumentStore() + doc_store.write_documents(docs) + ``` + """ + + def __init__(self, document_store: DocumentStore, policy: DuplicatePolicy = DuplicatePolicy.NONE): + """ + Create a DocumentWriter component. + + :param document_store: + The instance of the document store where you want to store your documents. + :param policy: + The policy to apply when a Document with the same ID already exists in the DocumentStore. + - `DuplicatePolicy.NONE`: Default policy, relies on the DocumentStore settings. + - `DuplicatePolicy.SKIP`: Skips documents with the same ID and doesn't write them to the DocumentStore. + - `DuplicatePolicy.OVERWRITE`: Overwrites documents with the same ID. + - `DuplicatePolicy.FAIL`: Raises an error if a Document with the same ID is already in the DocumentStore. + """ + self.document_store = document_store + self.policy = policy + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"document_store": type(self.document_store).__name__} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict(self, document_store=self.document_store.to_dict(), policy=self.policy.name) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "DocumentWriter": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + + :raises DeserializationError: + If the document store is not properly specified in the serialization data or its type cannot be imported. + """ + # deserialize the document store + deserialize_document_store_in_init_params_inplace(data) + + data["init_parameters"]["policy"] = DuplicatePolicy[data["init_parameters"]["policy"]] + + return default_from_dict(cls, data) + + @component.output_types(documents_written=int) + def run(self, documents: List[Document], policy: Optional[DuplicatePolicy] = None): + """ + Run the DocumentWriter on the given input data. + + :param documents: + A list of documents to write to the document store. + :param policy: + The policy to use when encountering duplicate documents. + :returns: + Number of documents written to the document store. + + :raises ValueError: + If the specified document store is not found. + """ + if policy is None: + policy = self.policy + + documents_written = self.document_store.write_documents(documents=documents, policy=policy) + return {"documents_written": documents_written} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/__pycache__/__init__.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8a1bfc96c66c3fad3a09c62fac5532830920ebb Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/__pycache__/__init__.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/__pycache__/errors.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/__pycache__/errors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8b5da1c4ff51feeada6987a19eee5c2b4f83de3 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/__pycache__/errors.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/__pycache__/serialization.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/__pycache__/serialization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..530c74d41d9d9ec23b3170e9b85cb6f3cfe42701 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/__pycache__/serialization.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/__pycache__/type_utils.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/__pycache__/type_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94e9e3242f07d4e80e7c8c48bd8885db53b7e14f Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/__pycache__/type_utils.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..425b357eb8a681ed6afdcae3d136a61ebda4cd3e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.component.component import Component, component +from haystack.core.component.types import InputSocket, OutputSocket + +__all__ = ["component", "Component", "InputSocket", "OutputSocket"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/__pycache__/__init__.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ae5b7a10fccba9bd950a533ee6edbfcd9f14296 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/__pycache__/__init__.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/__pycache__/component.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/__pycache__/component.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3043063259e0fd786f26c8b5052cf1ed59928c67 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/__pycache__/component.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/__pycache__/sockets.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/__pycache__/sockets.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abeb4e1fe46785d8f63926d37f4055b6a66973d9 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/__pycache__/sockets.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/__pycache__/types.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60dc280a1dc31a3d0f9ae81195de0865e39610c1 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/__pycache__/types.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/component.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/component.py new file mode 100644 index 0000000000000000000000000000000000000000..e1dbf2c5f0723a7cd1d9c0fae17366131fafa65a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/component.py @@ -0,0 +1,560 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +""" +Attributes: + + component: Marks a class as a component. Any class decorated with `@component` can be used by a Pipeline. + +All components must follow the contract below. This docstring is the source of truth for components contract. + +
+ +`@component` decorator + +All component classes must be decorated with the `@component` decorator. This allows Canals to discover them. + +
+ +`__init__(self, **kwargs)` + +Optional method. + +Components may have an `__init__` method where they define: + +- `self.init_parameters = {same parameters that the __init__ method received}`: + In this dictionary you can store any state the components wish to be persisted when they are saved. + These values will be given to the `__init__` method of a new instance when the pipeline is loaded. + Note that by default the `@component` decorator saves the arguments automatically. + However, if a component sets their own `init_parameters` manually in `__init__()`, that will be used instead. + Note: all of the values contained here **must be JSON serializable**. Serialize them manually if needed. + +Components should take only "basic" Python types as parameters of their `__init__` function, or iterables and +dictionaries containing only such values. Anything else (objects, functions, etc) will raise an exception at init +time. If there's the need for such values, consider serializing them to a string. + +_(TODO explain how to use classes and functions in init. In the meantime see `test/components/test_accumulate.py`)_ + +The `__init__` must be extremely lightweight, because it's a frequent operation during the construction and +validation of the pipeline. If a component has some heavy state to initialize (models, backends, etc...) refer to +the `warm_up()` method. + +
+ +`warm_up(self)` + +Optional method. + +This method is called by Pipeline before the graph execution. Make sure to avoid double-initializations, +because Pipeline will not keep track of which components it called `warm_up()` on. + +
+ +`run(self, data)` + +Mandatory method. + +This is the method where the main functionality of the component should be carried out. It's called by +`Pipeline.run()`. + +When the component should run, Pipeline will call this method with an instance of the dataclass returned by the +method decorated with `@component.input`. This dataclass contains: + +- all the input values coming from other components connected to it, +- if any is missing, the corresponding value defined in `self.defaults`, if it exists. + +`run()` must return a single instance of the dataclass declared through the method decorated with +`@component.output`. + +""" + +import inspect +import sys +import warnings +from collections.abc import Callable +from contextlib import contextmanager +from contextvars import ContextVar +from copy import deepcopy +from dataclasses import dataclass +from types import new_class +from typing import Any, Dict, Optional, Protocol, Type, runtime_checkable + +from haystack import logging +from haystack.core.errors import ComponentError + +from .sockets import Sockets +from .types import InputSocket, OutputSocket, _empty + +logger = logging.getLogger(__name__) + + +@dataclass +class PreInitHookPayload: + """ + Payload for the hook called before a component instance is initialized. + + :param callback: + Receives the following inputs: component class and init parameter keyword args. + :param in_progress: + Flag to indicate if the hook is currently being executed. + Used to prevent it from being called recursively (if the component's constructor + instantiates another component). + """ + + callback: Callable + in_progress: bool = False + + +_COMPONENT_PRE_INIT_HOOK: ContextVar[Optional[PreInitHookPayload]] = ContextVar("component_pre_init_hook", default=None) + + +@contextmanager +def _hook_component_init(callback: Callable): + """ + Context manager to set a callback that will be invoked before a component's constructor is called. + + The callback receives the component class and the init parameters (as keyword arguments) and can modify the init + parameters in place. + + :param callback: + Callback function to invoke. + """ + token = _COMPONENT_PRE_INIT_HOOK.set(PreInitHookPayload(callback)) + try: + yield + finally: + _COMPONENT_PRE_INIT_HOOK.reset(token) + + +@runtime_checkable +class Component(Protocol): + """ + Note this is only used by type checking tools. + + In order to implement the `Component` protocol, custom components need to + have a `run` method. The signature of the method and its return value + won't be checked, i.e. classes with the following methods: + + def run(self, param: str) -> Dict[str, Any]: + ... + + and + + def run(self, **kwargs): + ... + + will be both considered as respecting the protocol. This makes the type + checking much weaker, but we have other places where we ensure code is + dealing with actual Components. + + The protocol is runtime checkable so it'll be possible to assert: + + isinstance(MyComponent, Component) + """ + + # This is the most reliable way to define the protocol for the `run` method. + # Defining a method doesn't work as different Components will have different + # arguments. Even defining here a method with `**kwargs` doesn't work as the + # expected signature must be identical. + # This makes most Language Servers and type checkers happy and shows less errors. + # NOTE: This check can be removed when we drop Python 3.8 support. + if sys.version_info >= (3, 9): + run: Callable[..., Dict[str, Any]] + else: + run: Callable + + +class ComponentMeta(type): + @staticmethod + def _positional_to_kwargs(cls_type, args) -> Dict[str, Any]: + """ + Convert positional arguments to keyword arguments based on the signature of the `__init__` method. + """ + init_signature = inspect.signature(cls_type.__init__) + init_params = {name: info for name, info in init_signature.parameters.items() if name != "self"} + + out = {} + for arg, (name, info) in zip(args, init_params.items()): + if info.kind == inspect.Parameter.VAR_POSITIONAL: + raise ComponentError( + "Pre-init hooks do not support components with variadic positional args in their init method" + ) + + assert info.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.POSITIONAL_ONLY) + out[name] = arg + return out + + @staticmethod + def _parse_and_set_output_sockets(instance: Any): + has_async_run = hasattr(instance, "run_async") + + # If `component.set_output_types()` was called in the component constructor, + # `__haystack_output__` is already populated, no need to do anything. + if not hasattr(instance, "__haystack_output__"): + # If that's not the case, we need to populate `__haystack_output__` + # + # If either of the run methods were decorated, they'll have a field assigned that + # stores the output specification. If both run methods were decorated, we ensure that + # outputs are the same. We deepcopy the content of the cache to transfer ownership from + # the class method to the actual instance, so that different instances of the same class + # won't share this data. + + run_output_types = getattr(instance.run, "_output_types_cache", {}) + async_run_output_types = getattr(instance.run_async, "_output_types_cache", {}) if has_async_run else {} + + if has_async_run and run_output_types != async_run_output_types: + raise ComponentError("Output type specifications of 'run' and 'run_async' methods must be the same") + output_types_cache = run_output_types + + instance.__haystack_output__ = Sockets(instance, deepcopy(output_types_cache), OutputSocket) + + @staticmethod + def _parse_and_set_input_sockets(component_cls: Type, instance: Any): + def inner(method, sockets): + from inspect import Parameter + + run_signature = inspect.signature(method) + + for param_name, param_info in run_signature.parameters.items(): + if param_name == "self" or param_info.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD): + continue + + socket_kwargs = {"name": param_name, "type": param_info.annotation} + if param_info.default != Parameter.empty: + socket_kwargs["default_value"] = param_info.default + + new_socket = InputSocket(**socket_kwargs) + + # Also ensure that new sockets don't override existing ones. + existing_socket = sockets.get(param_name) + if existing_socket is not None and existing_socket != new_socket: + raise ComponentError( + "set_input_types()/set_input_type() cannot override the parameters of the 'run' method" + ) + + sockets[param_name] = new_socket + + return run_signature + + # Create the sockets if set_input_types() wasn't called in the constructor. + if not hasattr(instance, "__haystack_input__"): + instance.__haystack_input__ = Sockets(instance, {}, InputSocket) + + inner(getattr(component_cls, "run"), instance.__haystack_input__) + + # Ensure that the sockets are the same for the async method, if it exists. + async_run = getattr(component_cls, "run_async", None) + if async_run is not None: + run_sockets = Sockets(instance, {}, InputSocket) + async_run_sockets = Sockets(instance, {}, InputSocket) + + # Can't use the sockets from above as they might contain + # values set with set_input_types(). + run_sig = inner(getattr(component_cls, "run"), run_sockets) + async_run_sig = inner(async_run, async_run_sockets) + + if async_run_sockets != run_sockets or run_sig != async_run_sig: + raise ComponentError("Parameters of 'run' and 'run_async' methods must be the same") + + def __call__(cls, *args, **kwargs): + """ + This method is called when clients instantiate a Component and runs before __new__ and __init__. + """ + # This will call __new__ then __init__, giving us back the Component instance + pre_init_hook = _COMPONENT_PRE_INIT_HOOK.get() + if pre_init_hook is None or pre_init_hook.in_progress: + instance = super().__call__(*args, **kwargs) + else: + try: + pre_init_hook.in_progress = True + named_positional_args = ComponentMeta._positional_to_kwargs(cls, args) + assert ( + set(named_positional_args.keys()).intersection(kwargs.keys()) == set() + ), "positional and keyword arguments overlap" + kwargs.update(named_positional_args) + pre_init_hook.callback(cls, kwargs) + instance = super().__call__(**kwargs) + finally: + pre_init_hook.in_progress = False + + # Before returning, we have the chance to modify the newly created + # Component instance, so we take the chance and set up the I/O sockets + has_async_run = hasattr(instance, "run_async") + if has_async_run and not inspect.iscoroutinefunction(instance.run_async): + raise ComponentError(f"Method 'run_async' of component '{cls.__name__}' must be a coroutine") + instance.__haystack_supports_async__ = has_async_run + + ComponentMeta._parse_and_set_input_sockets(cls, instance) + ComponentMeta._parse_and_set_output_sockets(instance) + + # Since a Component can't be used in multiple Pipelines at the same time + # we need to know if it's already owned by a Pipeline when adding it to one. + # We use this flag to check that. + instance.__haystack_added_to_pipeline__ = None + + return instance + + +def _component_repr(component: Component) -> str: + """ + All Components override their __repr__ method with this one. + + It prints the component name and the input/output sockets. + """ + result = object.__repr__(component) + if pipeline := getattr(component, "__haystack_added_to_pipeline__", None): + # This Component has been added in a Pipeline, let's get the name from there. + result += f"\n{pipeline.get_component_name(component)}" + + # We're explicitly ignoring the type here because we're sure that the component + # has the __haystack_input__ and __haystack_output__ attributes at this point + return ( + f'{result}\n{getattr(component, "__haystack_input__", "")}' + f'\n{getattr(component, "__haystack_output__", "")}' + ) + + +def _component_run_has_kwargs(component_cls: Type) -> bool: + run_method = getattr(component_cls, "run", None) + if run_method is None: + return False + else: + return any( + param.kind == inspect.Parameter.VAR_KEYWORD for param in inspect.signature(run_method).parameters.values() + ) + + +class _Component: + """ + See module's docstring. + + Args: + class_: the class that Canals should use as a component. + serializable: whether to check, at init time, if the component can be saved with + `save_pipelines()`. + + Returns: + A class that can be recognized as a component. + + Raises: + ComponentError: if the class provided has no `run()` method or otherwise doesn't respect the component contract. + """ + + def __init__(self): + self.registry = {} + + def set_input_type( + self, + instance, + name: str, + type: Any, # noqa: A002 + default: Any = _empty, + ): + """ + Add a single input socket to the component instance. + + Replaces any existing input socket with the same name. + + :param instance: Component instance where the input type will be added. + :param name: name of the input socket. + :param type: type of the input socket. + :param default: default value of the input socket, defaults to _empty + """ + if not _component_run_has_kwargs(instance.__class__): + raise ComponentError( + "Cannot set input types on a component that doesn't have a kwargs parameter in the 'run' method" + ) + + if not hasattr(instance, "__haystack_input__"): + instance.__haystack_input__ = Sockets(instance, {}, InputSocket) + instance.__haystack_input__[name] = InputSocket(name=name, type=type, default_value=default) + + def set_input_types(self, instance, **types): + """ + Method that specifies the input types when 'kwargs' is passed to the run method. + + Use as: + + ```python + @component + class MyComponent: + + def __init__(self, value: int): + component.set_input_types(self, value_1=str, value_2=str) + ... + + @component.output_types(output_1=int, output_2=str) + def run(self, **kwargs): + return {"output_1": kwargs["value_1"], "output_2": ""} + ``` + + Note that if the `run()` method also specifies some parameters, those will take precedence. + + For example: + + ```python + @component + class MyComponent: + + def __init__(self, value: int): + component.set_input_types(self, value_1=str, value_2=str) + ... + + @component.output_types(output_1=int, output_2=str) + def run(self, value_0: str, value_1: Optional[str] = None, **kwargs): + return {"output_1": kwargs["value_1"], "output_2": ""} + ``` + + would add a mandatory `value_0` parameters, make the `value_1` + parameter optional with a default None, and keep the `value_2` + parameter mandatory as specified in `set_input_types`. + + """ + if not _component_run_has_kwargs(instance.__class__): + raise ComponentError( + "Cannot set input types on a component that doesn't have a kwargs parameter in the 'run' method" + ) + + instance.__haystack_input__ = Sockets( + instance, {name: InputSocket(name=name, type=type_) for name, type_ in types.items()}, InputSocket + ) + + def set_output_types(self, instance, **types): + """ + Method that specifies the output types when the 'run' method is not decorated with 'component.output_types'. + + Use as: + + ```python + @component + class MyComponent: + + def __init__(self, value: int): + component.set_output_types(self, output_1=int, output_2=str) + ... + + # no decorators here + def run(self, value: int): + return {"output_1": 1, "output_2": "2"} + ``` + """ + has_decorator = hasattr(instance.run, "_output_types_cache") + if has_decorator: + raise ComponentError( + "Cannot call `set_output_types` on a component that already has " + "the 'output_types' decorator on its `run` method" + ) + + instance.__haystack_output__ = Sockets( + instance, {name: OutputSocket(name=name, type=type_) for name, type_ in types.items()}, OutputSocket + ) + + def output_types(self, **types): + """ + Decorator factory that specifies the output types of a component. + + Use as: + + ```python + @component + class MyComponent: + @component.output_types(output_1=int, output_2=str) + def run(self, value: int): + return {"output_1": 1, "output_2": "2"} + ``` + """ + + def output_types_decorator(run_method): + """ + Decorator that sets the output types of the decorated method. + + This happens at class creation time, and since we don't have the decorated + class available here, we temporarily store the output types as an attribute of + the decorated method. The ComponentMeta metaclass will use this data to create + sockets at instance creation time. + """ + method_name = run_method.__name__ + if method_name not in ("run", "run_async"): + raise ComponentError("'output_types' decorator can only be used on 'run' and 'run_async' methods") + + setattr( + run_method, + "_output_types_cache", + {name: OutputSocket(name=name, type=type_) for name, type_ in types.items()}, + ) + return run_method + + return output_types_decorator + + def _component(self, cls, is_greedy: Optional[bool] = None): + """ + Decorator validating the structure of the component and registering it in the components registry. + """ + logger.debug("Registering {component} as a component", component=cls) + + if is_greedy is not None: + msg = ( + "The 'is_greedy' argument is deprecated and will be removed in version '2.7.0'. " + "Change the 'Variadic' input of your Component to 'GreedyVariadic' instead." + ) + warnings.warn(msg, DeprecationWarning) + else: + is_greedy = False + + # Check for required methods and fail as soon as possible + if not hasattr(cls, "run"): + raise ComponentError(f"{cls.__name__} must have a 'run()' method. See the docs for more information.") + + def copy_class_namespace(namespace): + """ + This is the callback that `typing.new_class` will use to populate the newly created class. + + Simply copy the whole namespace from the decorated class. + """ + for key, val in dict(cls.__dict__).items(): + # __dict__ and __weakref__ are class-bound, we should let Python recreate them. + if key in ("__dict__", "__weakref__"): + continue + namespace[key] = val + + # Recreate the decorated component class so it uses our metaclass. + # We must explicitly redefine the type of the class to make sure language servers + # and type checkers understand that the class is of the correct type. + # mypy doesn't like that we do this though so we explicitly ignore the type check. + cls: cls.__name__ = new_class(cls.__name__, cls.__bases__, {"metaclass": ComponentMeta}, copy_class_namespace) # type: ignore[no-redef] + + # Save the component in the class registry (for deserialization) + class_path = f"{cls.__module__}.{cls.__name__}" + if class_path in self.registry: + # Corner case, but it may occur easily in notebooks when re-running cells. + logger.debug( + "Component {component} is already registered. Previous imported from '{module_name}', \ + new imported from '{new_module_name}'", + component=class_path, + module_name=self.registry[class_path], + new_module_name=cls, + ) + self.registry[class_path] = cls + logger.debug("Registered Component {component}", component=cls) + + # Override the __repr__ method with a default one + cls.__repr__ = _component_repr + + return cls + + def __call__(self, cls: Optional[type] = None, is_greedy: Optional[bool] = None): + # We must wrap the call to the decorator in a function for it to work + # correctly with or without parens + def wrap(cls): + return self._component(cls, is_greedy=is_greedy) + + if cls: + # Decorator is called without parens + return wrap(cls) + + # Decorator is called with parens + return wrap + + +component = _Component() diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/sockets.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/sockets.py new file mode 100644 index 0000000000000000000000000000000000000000..2d84db2bfbc82f1d9d0a28c09b3c483f1fd2fb6b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/sockets.py @@ -0,0 +1,148 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Dict, Optional, Type, Union + +from haystack import logging +from haystack.core.type_utils import _type_name + +from .types import InputSocket, OutputSocket + +logger = logging.getLogger(__name__) + +SocketsDict = Dict[str, Union[InputSocket, OutputSocket]] +SocketsIOType = Union[Type[InputSocket], Type[OutputSocket]] + + +class Sockets: + """ + Represents the inputs or outputs of a `Component`. + + Depending on the type passed to the constructor, it will represent either the inputs or the outputs of + the `Component`. + + Usage: + ```python + from typing import Any + from haystack.components.builders.prompt_builder import PromptBuilder + from haystack.core.component.sockets import Sockets + from haystack.core.component.types import InputSocket, OutputSocket + + + prompt_template = \""" + Given these documents, answer the question.\nDocuments: + {% for doc in documents %} + {{ doc.content }} + {% endfor %} + + \nQuestion: {{question}} + \nAnswer: + \""" + + prompt_builder = PromptBuilder(template=prompt_template) + sockets = {"question": InputSocket("question", Any), "documents": InputSocket("documents", Any)} + inputs = Sockets(component=prompt_builder, sockets_dict=sockets, sockets_io_type=InputSocket) + inputs + >>> Inputs: + >>> - question: Any + >>> - documents: Any + + inputs.question + >>> InputSocket(name='question', type=typing.Any, default_value=, ... + ``` + """ + + # We're using a forward declaration here to avoid a circular import. + def __init__( + self, + component: "Component", # type: ignore[name-defined] # noqa: F821 + sockets_dict: SocketsDict, + sockets_io_type: SocketsIOType, + ): + """ + Create a new Sockets object. + + We don't do any enforcement on the types of the sockets here, the `sockets_type` is only used for + the `__repr__` method. + We could do without it and use the type of a random value in the `sockets` dict, but that wouldn't + work for components that have no sockets at all. Either input or output. + + :param component: + The component that these sockets belong to. + :param sockets_dict: + A dictionary of sockets. + :param sockets_io_type: + The type of the sockets. + """ + self._sockets_io_type = sockets_io_type + self._component = component + self._sockets_dict = sockets_dict + self.__dict__.update(sockets_dict) + + def __eq__(self, value: object) -> bool: + if not isinstance(value, Sockets): + return False + + return ( + self._sockets_io_type == value._sockets_io_type + and self._component == value._component + and self._sockets_dict == value._sockets_dict + ) + + def __setitem__(self, key: str, socket: Union[InputSocket, OutputSocket]): + """ + Adds a new socket to this Sockets object. + + This eases a bit updating the list of sockets after Sockets has been created. + That should happen only in the `component` decorator. + """ + self._sockets_dict[key] = socket + self.__dict__[key] = socket + + def __contains__(self, key: str) -> bool: + return key in self._sockets_dict + + def get( + self, key: str, default: Optional[Union[InputSocket, OutputSocket]] = None + ) -> Optional[Union[InputSocket, OutputSocket]]: + """ + Get a socket from the Sockets object. + + :param key: + The name of the socket to get. + :param default: + The value to return if the key is not found. + :returns: + The socket with the given key or `default` if the key is not found. + """ + return self._sockets_dict.get(key, default) + + def _component_name(self) -> str: + if pipeline := getattr(self._component, "__haystack_added_to_pipeline__"): + # This Component has been added in a Pipeline, let's get the name from there. + return pipeline.get_component_name(self._component) + + # This Component has not been added to a Pipeline yet, so we can't know its name. + # Let's use default __repr__. We don't call repr() directly as Components have a custom + # __repr__ method and that would lead to infinite recursion since we call Sockets.__repr__ in it. + return object.__repr__(self._component) + + def __getattribute__(self, name): + try: + sockets = object.__getattribute__(self, "_sockets") + if name in sockets: + return sockets[name] + except AttributeError: + pass + + return object.__getattribute__(self, name) + + def __repr__(self) -> str: + result = "" + if self._sockets_io_type == InputSocket: + result = "Inputs:\n" + elif self._sockets_io_type == OutputSocket: + result = "Outputs:\n" + + return result + "\n".join([f" - {n}: {_type_name(s.type)}" for n, s in self._sockets_dict.items()]) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/types.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/types.py new file mode 100644 index 0000000000000000000000000000000000000000..b08681a750a581b0f551913590cd71c46db230c7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/component/types.py @@ -0,0 +1,111 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import dataclass, field +from typing import Any, Iterable, List, Type, TypeVar, get_args + +from typing_extensions import Annotated, TypeAlias # Python 3.8 compatibility + +HAYSTACK_VARIADIC_ANNOTATION = "__haystack__variadic_t" +HAYSTACK_GREEDY_VARIADIC_ANNOTATION = "__haystack__greedy_variadic_t" + +# # Generic type variable used in the Variadic container +T = TypeVar("T") + + +# Variadic is a custom annotation type we use to mark input types. +# This type doesn't do anything else than "marking" the contained +# type so it can be used in the `InputSocket` creation where we +# check that its annotation equals to HAYSTACK_VARIADIC_ANNOTATION +Variadic: TypeAlias = Annotated[Iterable[T], HAYSTACK_VARIADIC_ANNOTATION] + +# GreedyVariadic type is similar to Variadic. +# The only difference is the way it's treated by the Pipeline when input is received +# in a socket with this type. +# Instead of waiting for other inputs to be received, Components that have a GreedyVariadic +# input will be run right after receiving the first input. +# Even if there are multiple connections to that socket. +GreedyVariadic: TypeAlias = Annotated[Iterable[T], HAYSTACK_GREEDY_VARIADIC_ANNOTATION] + + +class _empty: + """Custom object for marking InputSocket.default_value as not set.""" + + +@dataclass +class InputSocket: + """ + Represents an input of a `Component`. + + :param name: + The name of the input. + :param type: + The type of the input. + :param default_value: + The default value of the input. If not set, the input is mandatory. + :param is_variadic: + Whether the input is variadic or not. + :param is_greedy + Whether the input is a greedy variadic or not. + :param senders: + The list of components that send data to this input. + """ + + name: str + type: Type + default_value: Any = _empty + is_variadic: bool = field(init=False) + is_greedy: bool = field(init=False) + senders: List[str] = field(default_factory=list) + + @property + def is_mandatory(self): + """Check if the input is mandatory.""" + return self.default_value == _empty + + def __post_init__(self): + try: + # __metadata__ is a tuple + self.is_variadic = self.type.__metadata__[0] in [ + HAYSTACK_VARIADIC_ANNOTATION, + HAYSTACK_GREEDY_VARIADIC_ANNOTATION, + ] + self.is_greedy = self.type.__metadata__[0] == HAYSTACK_GREEDY_VARIADIC_ANNOTATION + except AttributeError: + self.is_variadic = False + self.is_greedy = False + if self.is_variadic: + # We need to "unpack" the type inside the Variadic annotation, + # otherwise the pipeline connection api will try to match + # `Annotated[type, HAYSTACK_VARIADIC_ANNOTATION]`. + # + # Note1: Variadic is expressed as an annotation of one single type, + # so the return value of get_args will always be a one-item tuple. + # + # Note2: a pipeline always passes a list of items when a component + # input is declared as Variadic, so the type itself always wraps + # an iterable of the declared type. For example, Variadic[int] + # is eventually an alias for Iterable[int]. Since we're interested + # in getting the inner type `int`, we call `get_args` twice: the + # first time to get `List[int]` out of `Variadic`, the second time + # to get `int` out of `List[int]`. + self.type = get_args(get_args(self.type)[0])[0] + + +@dataclass +class OutputSocket: + """ + Represents an output of a `Component`. + + :param name: + The name of the output. + :param type: + The type of the output. + :param receivers: + The list of components that receive the output of this component. + """ + + name: str + type: type + receivers: List[str] = field(default_factory=list) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/errors.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..bd76fbcce09b0a656340b2b0f56803fa846321a3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/errors.py @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + + +class PipelineError(Exception): + pass + + +class PipelineRuntimeError(Exception): + pass + + +class PipelineConnectError(PipelineError): + pass + + +class PipelineValidationError(PipelineError): + pass + + +class PipelineDrawingError(PipelineError): + pass + + +class PipelineMaxComponentRuns(PipelineError): + pass + + +class PipelineUnmarshalError(PipelineError): + pass + + +class ComponentError(Exception): + pass + + +class ComponentDeserializationError(Exception): + pass + + +class DeserializationError(Exception): + pass + + +class SerializationError(Exception): + pass diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..744c282f8c0b821df1b8f7e4770860280da2b7b7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from .pipeline import Pipeline +from .template import PredefinedPipeline + +__all__ = ["Pipeline", "PredefinedPipeline"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/__pycache__/__init__.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e63dd46c46478637de643a5b2142503098dd5e25 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/__pycache__/__init__.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/__pycache__/base.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9afb7d898ee3312c0e57d64ba3197a083f764e9e Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/__pycache__/base.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/__pycache__/pipeline.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/__pycache__/pipeline.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eaa2531cc0c97bb921e0947733cbbb1aa418fb64 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/__pycache__/pipeline.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/base.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/base.py new file mode 100644 index 0000000000000000000000000000000000000000..3d1b1c0bba40171c9098f69c9a79a66f7854e8a0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/base.py @@ -0,0 +1,1260 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import importlib +import itertools +from collections import defaultdict +from copy import copy, deepcopy +from datetime import datetime +from pathlib import Path +from typing import Any, Dict, Iterator, List, Optional, Set, TextIO, Tuple, Type, TypeVar, Union + +import networkx # type:ignore + +from haystack import logging +from haystack.core.component import Component, InputSocket, OutputSocket, component +from haystack.core.errors import ( + DeserializationError, + PipelineConnectError, + PipelineDrawingError, + PipelineError, + PipelineUnmarshalError, + PipelineValidationError, +) +from haystack.core.serialization import DeserializationCallbacks, component_from_dict, component_to_dict +from haystack.core.type_utils import _type_name, _types_are_compatible +from haystack.marshal import Marshaller, YamlMarshaller +from haystack.utils import is_in_jupyter + +from .descriptions import find_pipeline_inputs, find_pipeline_outputs +from .draw import _to_mermaid_image +from .template import PipelineTemplate, PredefinedPipeline +from .utils import parse_connect_string + +DEFAULT_MARSHALLER = YamlMarshaller() + +# We use a generic type to annotate the return value of classmethods, +# so that static analyzers won't be confused when derived classes +# use those methods. +T = TypeVar("T", bound="PipelineBase") + +logger = logging.getLogger(__name__) + + +class PipelineBase: + """ + Components orchestration engine. + + Builds a graph of components and orchestrates their execution according to the execution graph. + """ + + def __init__(self, metadata: Optional[Dict[str, Any]] = None, max_runs_per_component: int = 100): + """ + Creates the Pipeline. + + :param metadata: + Arbitrary dictionary to store metadata about this `Pipeline`. Make sure all the values contained in + this dictionary can be serialized and deserialized if you wish to save this `Pipeline` to file. + :param max_runs_per_component: + How many times the `Pipeline` can run the same Component. + If this limit is reached a `PipelineMaxComponentRuns` exception is raised. + If not set defaults to 100 runs per Component. + """ + self._telemetry_runs = 0 + self._last_telemetry_sent: Optional[datetime] = None + self.metadata = metadata or {} + self.graph = networkx.MultiDiGraph() + self._max_runs_per_component = max_runs_per_component + + def __eq__(self, other) -> bool: + """ + Pipeline equality is defined by their type and the equality of their serialized form. + + Pipelines of the same type share every metadata, node and edge, but they're not required to use + the same node instances: this allows pipeline saved and then loaded back to be equal to themselves. + """ + if not isinstance(self, type(other)): + return False + return self.to_dict() == other.to_dict() + + def __repr__(self) -> str: + """ + Returns a text representation of the Pipeline. + """ + res = f"{object.__repr__(self)}\n" + if self.metadata: + res += "🧱 Metadata\n" + for k, v in self.metadata.items(): + res += f" - {k}: {v}\n" + + res += "🚅 Components\n" + for name, instance in self.graph.nodes(data="instance"): # type: ignore # type wrongly defined in networkx + res += f" - {name}: {instance.__class__.__name__}\n" + + res += "🛤️ Connections\n" + for sender, receiver, edge_data in self.graph.edges(data=True): + sender_socket = edge_data["from_socket"].name + receiver_socket = edge_data["to_socket"].name + res += f" - {sender}.{sender_socket} -> {receiver}.{receiver_socket} ({edge_data['conn_type']})\n" + + return res + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the pipeline to a dictionary. + + This is meant to be an intermediate representation but it can be also used to save a pipeline to file. + + :returns: + Dictionary with serialized data. + """ + components = {} + for name, instance in self.graph.nodes(data="instance"): # type:ignore + components[name] = component_to_dict(instance, name) + + connections = [] + for sender, receiver, edge_data in self.graph.edges.data(): + sender_socket = edge_data["from_socket"].name + receiver_socket = edge_data["to_socket"].name + connections.append({"sender": f"{sender}.{sender_socket}", "receiver": f"{receiver}.{receiver_socket}"}) + return { + "metadata": self.metadata, + "max_runs_per_component": self._max_runs_per_component, + "components": components, + "connections": connections, + } + + @classmethod + def from_dict( + cls: Type[T], data: Dict[str, Any], callbacks: Optional[DeserializationCallbacks] = None, **kwargs + ) -> T: + """ + Deserializes the pipeline from a dictionary. + + :param data: + Dictionary to deserialize from. + :param callbacks: + Callbacks to invoke during deserialization. + :param kwargs: + `components`: a dictionary of {name: instance} to reuse instances of components instead of creating new + ones. + :returns: + Deserialized component. + """ + data_copy = deepcopy(data) # to prevent modification of original data + metadata = data_copy.get("metadata", {}) + max_runs_per_component = data_copy.get("max_runs_per_component", 100) + pipe = cls(metadata=metadata, max_runs_per_component=max_runs_per_component) + components_to_reuse = kwargs.get("components", {}) + for name, component_data in data_copy.get("components", {}).items(): + if name in components_to_reuse: + # Reuse an instance + instance = components_to_reuse[name] + else: + if "type" not in component_data: + raise PipelineError(f"Missing 'type' in component '{name}'") + + if component_data["type"] not in component.registry: + try: + # Import the module first... + module, _ = component_data["type"].rsplit(".", 1) + logger.debug("Trying to import module {module_name}", module_name=module) + importlib.import_module(module) + # ...then try again + if component_data["type"] not in component.registry: + raise PipelineError( + f"Successfully imported module {module} but can't find it in the component registry." + "This is unexpected and most likely a bug." + ) + except (ImportError, PipelineError) as e: + raise PipelineError(f"Component '{component_data['type']}' not imported.") from e + + # Create a new one + component_class = component.registry[component_data["type"]] + + try: + instance = component_from_dict(component_class, component_data, name, callbacks) + except Exception as e: + msg = ( + f"Couldn't deserialize component '{name}' of class '{component_class.__name__}' " + f"with the following data: {str(component_data)}. Possible reasons include " + "malformed serialized data, mismatch between the serialized component and the " + "loaded one (due to a breaking change, see " + "https://github.com/deepset-ai/haystack/releases), etc." + ) + raise DeserializationError(msg) from e + pipe.add_component(name=name, instance=instance) + + for connection in data.get("connections", []): + if "sender" not in connection: + raise PipelineError(f"Missing sender in connection: {connection}") + if "receiver" not in connection: + raise PipelineError(f"Missing receiver in connection: {connection}") + pipe.connect(sender=connection["sender"], receiver=connection["receiver"]) + + return pipe + + def dumps(self, marshaller: Marshaller = DEFAULT_MARSHALLER) -> str: + """ + Returns the string representation of this pipeline according to the format dictated by the `Marshaller` in use. + + :param marshaller: + The Marshaller used to create the string representation. Defaults to `YamlMarshaller`. + :returns: + A string representing the pipeline. + """ + return marshaller.marshal(self.to_dict()) + + def dump(self, fp: TextIO, marshaller: Marshaller = DEFAULT_MARSHALLER): + """ + Writes the string representation of this pipeline to the file-like object passed in the `fp` argument. + + :param fp: + A file-like object ready to be written to. + :param marshaller: + The Marshaller used to create the string representation. Defaults to `YamlMarshaller`. + """ + fp.write(marshaller.marshal(self.to_dict())) + + @classmethod + def loads( + cls: Type[T], + data: Union[str, bytes, bytearray], + marshaller: Marshaller = DEFAULT_MARSHALLER, + callbacks: Optional[DeserializationCallbacks] = None, + ) -> T: + """ + Creates a `Pipeline` object from the string representation passed in the `data` argument. + + :param data: + The string representation of the pipeline, can be `str`, `bytes` or `bytearray`. + :param marshaller: + The Marshaller used to create the string representation. Defaults to `YamlMarshaller`. + :param callbacks: + Callbacks to invoke during deserialization. + :raises DeserializationError: + If an error occurs during deserialization. + :returns: + A `Pipeline` object. + """ + try: + deserialized_data = marshaller.unmarshal(data) + except Exception as e: + raise DeserializationError( + "Error while unmarshalling serialized pipeline data. This is usually " + "caused by malformed or invalid syntax in the serialized representation." + ) from e + + return cls.from_dict(deserialized_data, callbacks) + + @classmethod + def load( + cls: Type[T], + fp: TextIO, + marshaller: Marshaller = DEFAULT_MARSHALLER, + callbacks: Optional[DeserializationCallbacks] = None, + ) -> T: + """ + Creates a `Pipeline` object a string representation. + + The string representation is read from the file-like object passed in the `fp` argument. + + + :param fp: + A file-like object ready to be read from. + :param marshaller: + The Marshaller used to create the string representation. Defaults to `YamlMarshaller`. + :param callbacks: + Callbacks to invoke during deserialization. + :raises DeserializationError: + If an error occurs during deserialization. + :returns: + A `Pipeline` object. + """ + return cls.loads(fp.read(), marshaller, callbacks) + + def add_component(self, name: str, instance: Component) -> None: + """ + Add the given component to the pipeline. + + Components are not connected to anything by default: use `Pipeline.connect()` to connect components together. + Component names must be unique, but component instances can be reused if needed. + + :param name: + The name of the component to add. + :param instance: + The component instance to add. + + :raises ValueError: + If a component with the same name already exists. + :raises PipelineValidationError: + If the given instance is not a Canals component. + """ + # Component names are unique + if name in self.graph.nodes: + raise ValueError(f"A component named '{name}' already exists in this pipeline: choose another name.") + + # Components can't be named `_debug` + if name == "_debug": + raise ValueError("'_debug' is a reserved name for debug output. Choose another name.") + + # Component instances must be components + if not isinstance(instance, Component): + raise PipelineValidationError( + f"'{type(instance)}' doesn't seem to be a component. Is this class decorated with @component?" + ) + + if getattr(instance, "__haystack_added_to_pipeline__", None): + msg = ( + "Component has already been added in another Pipeline. Components can't be shared between Pipelines. " + "Create a new instance instead." + ) + raise PipelineError(msg) + + setattr(instance, "__haystack_added_to_pipeline__", self) + + # Add component to the graph, disconnected + logger.debug("Adding component '{component_name}' ({component})", component_name=name, component=instance) + # We're completely sure the fields exist so we ignore the type error + self.graph.add_node( + name, + instance=instance, + input_sockets=instance.__haystack_input__._sockets_dict, # type: ignore[attr-defined] + output_sockets=instance.__haystack_output__._sockets_dict, # type: ignore[attr-defined] + visits=0, + ) + + def remove_component(self, name: str) -> Component: + """ + Remove and returns component from the pipeline. + + Remove an existing component from the pipeline by providing its name. + All edges that connect to the component will also be deleted. + + :param name: + The name of the component to remove. + :returns: + The removed Component instance. + + :raises ValueError: + If there is no component with that name already in the Pipeline. + """ + + # Check that a component with that name is in the Pipeline + try: + instance = self.get_component(name) + except ValueError as exc: + raise ValueError( + f"There is no component named '{name}' in the pipeline. The valid component names are: ", + ", ".join(n for n in self.graph.nodes), + ) from exc + + # Delete component from the graph, deleting all its connections + self.graph.remove_node(name) + + # Reset the Component sockets' senders and receivers + input_sockets = instance.__haystack_input__._sockets_dict # type: ignore[attr-defined] + for socket in input_sockets.values(): + socket.senders = [] + + output_sockets = instance.__haystack_output__._sockets_dict # type: ignore[attr-defined] + for socket in output_sockets.values(): + socket.receivers = [] + + # Reset the Component's pipeline reference + setattr(instance, "__haystack_added_to_pipeline__", None) + + return instance + + def connect(self, sender: str, receiver: str) -> "PipelineBase": # noqa: PLR0915 + """ + Connects two components together. + + All components to connect must exist in the pipeline. + If connecting to a component that has several output connections, specify the inputs and output names as + 'component_name.connections_name'. + + :param sender: + The component that delivers the value. This can be either just a component name or can be + in the format `component_name.connection_name` if the component has multiple outputs. + :param receiver: + The component that receives the value. This can be either just a component name or can be + in the format `component_name.connection_name` if the component has multiple inputs. + :returns: + The Pipeline instance. + + :raises PipelineConnectError: + If the two components cannot be connected (for example if one of the components is + not present in the pipeline, or the connections don't match by type, and so on). + """ + # Edges may be named explicitly by passing 'node_name.edge_name' to connect(). + sender_component_name, sender_socket_name = parse_connect_string(sender) + receiver_component_name, receiver_socket_name = parse_connect_string(receiver) + + if sender_component_name == receiver_component_name: + raise PipelineConnectError("Connecting a Component to itself is not supported.") + + # Get the nodes data. + try: + from_sockets = self.graph.nodes[sender_component_name]["output_sockets"] + except KeyError as exc: + raise ValueError(f"Component named {sender_component_name} not found in the pipeline.") from exc + try: + to_sockets = self.graph.nodes[receiver_component_name]["input_sockets"] + except KeyError as exc: + raise ValueError(f"Component named {receiver_component_name} not found in the pipeline.") from exc + + # If the name of either socket is given, get the socket + sender_socket: Optional[OutputSocket] = None + if sender_socket_name: + sender_socket = from_sockets.get(sender_socket_name) + if not sender_socket: + raise PipelineConnectError( + f"'{sender} does not exist. " + f"Output connections of {sender_component_name} are: " + + ", ".join([f"{name} (type {_type_name(socket.type)})" for name, socket in from_sockets.items()]) + ) + + receiver_socket: Optional[InputSocket] = None + if receiver_socket_name: + receiver_socket = to_sockets.get(receiver_socket_name) + if not receiver_socket: + raise PipelineConnectError( + f"'{receiver} does not exist. " + f"Input connections of {receiver_component_name} are: " + + ", ".join([f"{name} (type {_type_name(socket.type)})" for name, socket in to_sockets.items()]) + ) + + # Look for a matching connection among the possible ones. + # Note that if there is more than one possible connection but two sockets match by name, they're paired. + sender_socket_candidates: List[OutputSocket] = [sender_socket] if sender_socket else list(from_sockets.values()) + receiver_socket_candidates: List[InputSocket] = ( + [receiver_socket] if receiver_socket else list(to_sockets.values()) + ) + + # Find all possible connections between these two components + possible_connections = [ + (sender_sock, receiver_sock) + for sender_sock, receiver_sock in itertools.product(sender_socket_candidates, receiver_socket_candidates) + if _types_are_compatible(sender_sock.type, receiver_sock.type) + ] + + # We need this status for error messages, since we might need it in multiple places we calculate it here + status = _connections_status( + sender_node=sender_component_name, + sender_sockets=sender_socket_candidates, + receiver_node=receiver_component_name, + receiver_sockets=receiver_socket_candidates, + ) + + if not possible_connections: + # There's no possible connection between these two components + if len(sender_socket_candidates) == len(receiver_socket_candidates) == 1: + msg = ( + f"Cannot connect '{sender_component_name}.{sender_socket_candidates[0].name}' with " + f"'{receiver_component_name}.{receiver_socket_candidates[0].name}': " + f"their declared input and output types do not match.\n{status}" + ) + else: + msg = ( + f"Cannot connect '{sender_component_name}' with '{receiver_component_name}': " + f"no matching connections available.\n{status}" + ) + raise PipelineConnectError(msg) + + if len(possible_connections) == 1: + # There's only one possible connection, use it + sender_socket = possible_connections[0][0] + receiver_socket = possible_connections[0][1] + + if len(possible_connections) > 1: + # There are multiple possible connection, let's try to match them by name + name_matches = [ + (out_sock, in_sock) for out_sock, in_sock in possible_connections if in_sock.name == out_sock.name + ] + if len(name_matches) != 1: + # There's are either no matches or more than one, we can't pick one reliably + msg = ( + f"Cannot connect '{sender_component_name}' with " + f"'{receiver_component_name}': more than one connection is possible " + "between these components. Please specify the connection name, like: " + f"pipeline.connect('{sender_component_name}.{possible_connections[0][0].name}', " + f"'{receiver_component_name}.{possible_connections[0][1].name}').\n{status}" + ) + raise PipelineConnectError(msg) + + # Get the only possible match + sender_socket = name_matches[0][0] + receiver_socket = name_matches[0][1] + + # Connection must be valid on both sender/receiver sides + if not sender_socket or not receiver_socket or not sender_component_name or not receiver_component_name: + if sender_component_name and sender_socket: + sender_repr = f"{sender_component_name}.{sender_socket.name} ({_type_name(sender_socket.type)})" + else: + sender_repr = "input needed" + + if receiver_component_name and receiver_socket: + receiver_repr = f"({_type_name(receiver_socket.type)}) {receiver_component_name}.{receiver_socket.name}" + else: + receiver_repr = "output" + msg = f"Connection must have both sender and receiver: {sender_repr} -> {receiver_repr}" + raise PipelineConnectError(msg) + + logger.debug( + "Connecting '{sender_component}.{sender_socket_name}' to '{receiver_component}.{receiver_socket_name}'", + sender_component=sender_component_name, + sender_socket_name=sender_socket.name, + receiver_component=receiver_component_name, + receiver_socket_name=receiver_socket.name, + ) + + if receiver_component_name in sender_socket.receivers and sender_component_name in receiver_socket.senders: + # This is already connected, nothing to do + return self + + if receiver_socket.senders and not receiver_socket.is_variadic: + # Only variadic input sockets can receive from multiple senders + msg = ( + f"Cannot connect '{sender_component_name}.{sender_socket.name}' with " + f"'{receiver_component_name}.{receiver_socket.name}': " + f"{receiver_component_name}.{receiver_socket.name} is already connected to {receiver_socket.senders}.\n" + ) + raise PipelineConnectError(msg) + + # Update the sockets with the new connection + sender_socket.receivers.append(receiver_component_name) + receiver_socket.senders.append(sender_component_name) + + # Create the new connection + self.graph.add_edge( + sender_component_name, + receiver_component_name, + key=f"{sender_socket.name}/{receiver_socket.name}", + conn_type=_type_name(sender_socket.type), + from_socket=sender_socket, + to_socket=receiver_socket, + mandatory=receiver_socket.is_mandatory, + ) + return self + + def get_component(self, name: str) -> Component: + """ + Get the component with the specified name from the pipeline. + + :param name: + The name of the component. + :returns: + The instance of that component. + + :raises ValueError: + If a component with that name is not present in the pipeline. + """ + try: + return self.graph.nodes[name]["instance"] + except KeyError as exc: + raise ValueError(f"Component named {name} not found in the pipeline.") from exc + + def get_component_name(self, instance: Component) -> str: + """ + Returns the name of the Component instance if it has been added to this Pipeline or an empty string otherwise. + + :param instance: + The Component instance to look for. + :returns: + The name of the Component instance. + """ + for name, inst in self.graph.nodes(data="instance"): # type: ignore # type wrongly defined in networkx + if inst == instance: + return name + return "" + + def inputs(self, include_components_with_connected_inputs: bool = False) -> Dict[str, Dict[str, Any]]: + """ + Returns a dictionary containing the inputs of a pipeline. + + Each key in the dictionary corresponds to a component name, and its value is another dictionary that describes + the input sockets of that component, including their types and whether they are optional. + + :param include_components_with_connected_inputs: + If `False`, only components that have disconnected input edges are + included in the output. + :returns: + A dictionary where each key is a pipeline component name and each value is a dictionary of + inputs sockets of that component. + """ + inputs: Dict[str, Dict[str, Any]] = {} + for component_name, data in find_pipeline_inputs(self.graph, include_components_with_connected_inputs).items(): + sockets_description = {} + for socket in data: + sockets_description[socket.name] = {"type": socket.type, "is_mandatory": socket.is_mandatory} + if not socket.is_mandatory: + sockets_description[socket.name]["default_value"] = socket.default_value + + if sockets_description: + inputs[component_name] = sockets_description + return inputs + + def outputs(self, include_components_with_connected_outputs: bool = False) -> Dict[str, Dict[str, Any]]: + """ + Returns a dictionary containing the outputs of a pipeline. + + Each key in the dictionary corresponds to a component name, and its value is another dictionary that describes + the output sockets of that component. + + :param include_components_with_connected_outputs: + If `False`, only components that have disconnected output edges are + included in the output. + :returns: + A dictionary where each key is a pipeline component name and each value is a dictionary of + output sockets of that component. + """ + outputs = { + comp: {socket.name: {"type": socket.type} for socket in data} + for comp, data in find_pipeline_outputs(self.graph, include_components_with_connected_outputs).items() + if data + } + return outputs + + def show(self) -> None: + """ + If running in a Jupyter notebook, display an image representing this `Pipeline`. + + """ + if is_in_jupyter(): + from IPython.display import Image, display # type: ignore + + image_data = _to_mermaid_image(self.graph) + + display(Image(image_data)) + else: + msg = "This method is only supported in Jupyter notebooks. Use Pipeline.draw() to save an image locally." + raise PipelineDrawingError(msg) + + def draw(self, path: Path) -> None: + """ + Save an image representing this `Pipeline` to `path`. + + :param path: + The path to save the image to. + """ + # Before drawing we edit a bit the graph, to avoid modifying the original that is + # used for running the pipeline we copy it. + image_data = _to_mermaid_image(self.graph) + Path(path).write_bytes(image_data) + + def walk(self) -> Iterator[Tuple[str, Component]]: + """ + Visits each component in the pipeline exactly once and yields its name and instance. + + No guarantees are provided on the visiting order. + + :returns: + An iterator of tuples of component name and component instance. + """ + for component_name, instance in self.graph.nodes(data="instance"): # type: ignore # type is wrong in networkx + yield component_name, instance + + def warm_up(self): + """ + Make sure all nodes are warm. + + It's the node's responsibility to make sure this method can be called at every `Pipeline.run()` + without re-initializing everything. + """ + for node in self.graph.nodes: + if hasattr(self.graph.nodes[node]["instance"], "warm_up"): + logger.info("Warming up component {node}...", node=node) + self.graph.nodes[node]["instance"].warm_up() + + def _validate_input(self, data: Dict[str, Any]): + """ + Validates pipeline input data. + + Validates that data: + * Each Component name actually exists in the Pipeline + * Each Component is not missing any input + * Each Component has only one input per input socket, if not variadic + * Each Component doesn't receive inputs that are already sent by another Component + + :param data: + A dictionary of inputs for the pipeline's components. Each key is a component name. + + :raises ValueError: + If inputs are invalid according to the above. + """ + for component_name, component_inputs in data.items(): + if component_name not in self.graph.nodes: + raise ValueError(f"Component named {component_name} not found in the pipeline.") + instance = self.graph.nodes[component_name]["instance"] + for socket_name, socket in instance.__haystack_input__._sockets_dict.items(): + if socket.senders == [] and socket.is_mandatory and socket_name not in component_inputs: + raise ValueError(f"Missing input for component {component_name}: {socket_name}") + for input_name in component_inputs.keys(): + if input_name not in instance.__haystack_input__._sockets_dict: + raise ValueError(f"Input {input_name} not found in component {component_name}.") + + for component_name in self.graph.nodes: + instance = self.graph.nodes[component_name]["instance"] + for socket_name, socket in instance.__haystack_input__._sockets_dict.items(): + component_inputs = data.get(component_name, {}) + if socket.senders == [] and socket.is_mandatory and socket_name not in component_inputs: + raise ValueError(f"Missing input for component {component_name}: {socket_name}") + if socket.senders and socket_name in component_inputs and not socket.is_variadic: + raise ValueError( + f"Input {socket_name} for component {component_name} is already sent by {socket.senders}." + ) + + def _prepare_component_input_data(self, data: Dict[str, Any]) -> Dict[str, Dict[str, Any]]: + """ + Prepares input data for pipeline components. + + Organizes input data for pipeline components and identifies any inputs that are not matched to any + component's input slots. Deep-copies data items to avoid sharing mutables across multiple components. + + This method processes a flat dictionary of input data, where each key-value pair represents an input name + and its corresponding value. It distributes these inputs to the appropriate pipeline components based on + their input requirements. Inputs that don't match any component's input slots are classified as unresolved. + + :param data: + A dictionary potentially having input names as keys and input values as values. + + :returns: + A dictionary mapping component names to their respective matched inputs. + """ + # check whether the data is a nested dictionary of component inputs where each key is a component name + # and each value is a dictionary of input parameters for that component + is_nested_component_input = all(isinstance(value, dict) for value in data.values()) + if not is_nested_component_input: + # flat input, a dict where keys are input names and values are the corresponding values + # we need to convert it to a nested dictionary of component inputs and then run the pipeline + # just like in the previous case + pipeline_input_data: Dict[str, Dict[str, Any]] = defaultdict(dict) + unresolved_kwargs = {} + + # Retrieve the input slots for each component in the pipeline + available_inputs: Dict[str, Dict[str, Any]] = self.inputs() + + # Go through all provided to distribute them to the appropriate component inputs + for input_name, input_value in data.items(): + resolved_at_least_once = False + + # Check each component to see if it has a slot for the current kwarg + for component_name, component_inputs in available_inputs.items(): + if input_name in component_inputs: + # If a match is found, add the kwarg to the component's input data + pipeline_input_data[component_name][input_name] = input_value + resolved_at_least_once = True + + if not resolved_at_least_once: + unresolved_kwargs[input_name] = input_value + + if unresolved_kwargs: + logger.warning( + "Inputs {input_keys} were not matched to any component inputs, please check your run parameters.", + input_keys=list(unresolved_kwargs.keys()), + ) + + data = dict(pipeline_input_data) + + # deepcopying the inputs prevents the Pipeline run logic from being altered unexpectedly + # when the same input reference is passed to multiple components. + for component_name, component_inputs in data.items(): + data[component_name] = {k: deepcopy(v) for k, v in component_inputs.items()} + + return data + + def _init_inputs_state(self, data: Dict[str, Dict[str, Any]]) -> Dict[str, Dict[str, Any]]: + for component_name, component_inputs in data.items(): + if component_name not in self.graph.nodes: + # This is not a component name, it must be the name of one or more input sockets. + # Those are handled in a different way, so we skip them here. + continue + instance = self.graph.nodes[component_name]["instance"] + for component_input, input_value in component_inputs.items(): + # Handle mutable input data + data[component_name][component_input] = copy(input_value) + if instance.__haystack_input__._sockets_dict[component_input].is_variadic: + # Components that have variadic inputs need to receive lists as input. + # We don't want to force the user to always pass lists, so we convert single values to lists here. + # If it's already a list we assume the component takes a variadic input of lists, so we + # convert it in any case. + data[component_name][component_input] = [input_value] + + return {**data} + + def _init_run_queue(self, pipeline_inputs: Dict[str, Any]) -> List[Tuple[str, Component]]: + run_queue: List[Tuple[str, Component]] = [] + + # HACK: Quick workaround for the issue of execution order not being + # well-defined (NB - https://github.com/deepset-ai/haystack/issues/7985). + # We should fix the original execution logic instead. + if networkx.is_directed_acyclic_graph(self.graph): + # If the Pipeline is linear we can easily determine the order of execution with + # a topological sort. + # So use that to get the run order. + for node in networkx.topological_sort(self.graph): + run_queue.append((node, self.graph.nodes[node]["instance"])) + return run_queue + + for node_name in self.graph.nodes: + component = self.graph.nodes[node_name]["instance"] + + if len(component.__haystack_input__._sockets_dict) == 0: + # Component has no input, can run right away + run_queue.append((node_name, component)) + continue + + if node_name in pipeline_inputs: + # This component is in the input data, if it has enough inputs it can run right away + run_queue.append((node_name, component)) + continue + + for socket in component.__haystack_input__._sockets_dict.values(): + if not socket.senders or socket.is_variadic: + # Component has at least one input not connected or is variadic, can run right away. + run_queue.append((node_name, component)) + break + + return run_queue + + @classmethod + def from_template( + cls, predefined_pipeline: PredefinedPipeline, template_params: Optional[Dict[str, Any]] = None + ) -> "PipelineBase": + """ + Create a Pipeline from a predefined template. See `PredefinedPipeline` for available options. + + :param predefined_pipeline: + The predefined pipeline to use. + :param template_params: + An optional dictionary of parameters to use when rendering the pipeline template. + :returns: + An instance of `Pipeline`. + """ + tpl = PipelineTemplate.from_predefined(predefined_pipeline) + # If tpl.render() fails, we let bubble up the original error + rendered = tpl.render(template_params) + + # If there was a problem with the rendered version of the + # template, we add it to the error stack for debugging + try: + return cls.loads(rendered) + except Exception as e: + msg = f"Error unmarshalling pipeline: {e}\n" + msg += f"Source:\n{rendered}" + raise PipelineUnmarshalError(msg) + + def _init_graph(self): + """Resets the visits count for each component""" + for node in self.graph.nodes: + self.graph.nodes[node]["visits"] = 0 + + def _distribute_output( + self, + component_name: str, + component_result: Dict[str, Any], + components_inputs: Dict[str, Dict[str, Any]], + run_queue: List[Tuple[str, Component]], + waiting_queue: List[Tuple[str, Component]], + ) -> Dict[str, Any]: + """ + Distributes the output of a Component to the next Components that need it. + + This also updates the queues that keep track of which Components are ready to run and which are waiting for + input. + + :param component_name: Name of the Component that created the output + :param component_result: The output of the Component + :paramt components_inputs: The current state of the inputs divided by Component name + :param run_queue: Queue of Components to run + :param waiting_queue: Queue of Components waiting for input + + :returns: The updated output of the Component without the keys that were distributed to other Components + """ + # We keep track of which keys to remove from component_result at the end of the loop. + # This is done after the output has been distributed to the next components, so that + # we're sure all components that need this output have received it. + to_remove_from_component_result = set() + + for _, receiver_name, connection in self.graph.edges(nbunch=component_name, data=True): + sender_socket: OutputSocket = connection["from_socket"] + receiver_socket: InputSocket = connection["to_socket"] + + if sender_socket.name not in component_result: + # This output wasn't created by the sender, nothing we can do. + # + # Some Components might have conditional outputs, so we need to check if they actually returned + # some output while iterating over their output sockets. + # + # A perfect example of this would be the ConditionalRouter, which will have an output for each + # condition it has been initialized with. + # Though it will return only one output at a time. + continue + + if receiver_name not in components_inputs: + components_inputs[receiver_name] = {} + + # We keep track of the keys that were distributed to other Components. + # This key will be removed from component_result at the end of the loop. + to_remove_from_component_result.add(sender_socket.name) + + value = component_result[sender_socket.name] + + if receiver_socket.is_variadic: + # Usually Component inputs can only be received from one sender, the Variadic type allows + # instead to receive inputs from multiple senders. + # + # To keep track of all the inputs received internally we always store them in a list. + if receiver_socket.name not in components_inputs[receiver_name]: + # Create the list if it doesn't exist + components_inputs[receiver_name][receiver_socket.name] = [] + else: + # Check if the value is actually a list + assert isinstance(components_inputs[receiver_name][receiver_socket.name], list) + components_inputs[receiver_name][receiver_socket.name].append(value) + else: + components_inputs[receiver_name][receiver_socket.name] = value + + receiver = self.graph.nodes[receiver_name]["instance"] + pair = (receiver_name, receiver) + + if receiver_socket.is_variadic: + if receiver_socket.is_greedy: + # If the receiver is greedy, we can run it as soon as possible. + # First we remove it from the status lists it's in if it's there or + # we risk running it multiple times. + if pair in run_queue: + run_queue.remove(pair) + if pair in waiting_queue: + waiting_queue.remove(pair) + run_queue.append(pair) + else: + # If the receiver Component has a variadic input that is not greedy + # we put it in the waiting queue. + # This make sure that we don't run it earlier than necessary and we can collect + # as many inputs as we can before running it. + if pair not in waiting_queue: + waiting_queue.append(pair) + + if pair not in waiting_queue and pair not in run_queue: + # Queue up the Component that received this input to run, only if it's not already waiting + # for input or already ready to run. + run_queue.append(pair) + + # Returns the output without the keys that were distributed to other Components + return {k: v for k, v in component_result.items() if k not in to_remove_from_component_result} + + def _find_next_runnable_component( + self, components_inputs: Dict[str, Dict[str, Any]], waiting_queue: List[Tuple[str, Component]] + ) -> Tuple[str, Component]: + """ + Finds the next Component that can be run and returns it. + + :param components_inputs: The current state of the inputs divided by Component name + :param waiting_queue: Queue of Components waiting for input + + :returns: The name and the instance of the next Component that can be run + """ + all_lazy_variadic = True + all_with_default_inputs = True + + filtered_waiting_queue = [] + + for name, comp in waiting_queue: + if not _is_lazy_variadic(comp): + # Components with variadic inputs that are not greedy must be removed only if there's nothing else to + # run at this stage. + # We need to wait as long as possible to run them, so we can collect as most inputs as we can. + all_lazy_variadic = False + + if not _has_all_inputs_with_defaults(comp): + # Components that have defaults for all their inputs must be treated the same identical way as we treat + # lazy variadic components. If there are only components with defaults we can run them. + # If we don't do this the order of execution of the Pipeline's Components will be affected cause we + # enqueue the Components in `run_queue` at the start using the order they are added in the Pipeline. + # If a Component A with defaults is added before a Component B that has no defaults, but in the Pipeline + # logic A must be executed after B. However, B could run before A if we don't do this check. + all_with_default_inputs = False + + if not _is_lazy_variadic(comp) and not _has_all_inputs_with_defaults(comp): + # Keep track of the Components that are not lazy variadic and don't have all inputs with defaults. + # We'll handle these later if necessary. + filtered_waiting_queue.append((name, comp)) + + # If all Components are lazy variadic or all Components have all inputs with defaults we can get one to run + if all_lazy_variadic or all_with_default_inputs: + return waiting_queue[0] + + for name, comp in filtered_waiting_queue: + # Find the first component that has all the inputs it needs to run + has_enough_inputs = True + for input_socket in comp.__haystack_input__._sockets_dict.values(): # type: ignore + if input_socket.name not in components_inputs.get(name, {}) and input_socket.is_mandatory: + has_enough_inputs = False + break + + if has_enough_inputs: + return name, comp + + # If we reach this point it means that we found no Component that has enough inputs to run. + # Ideally we should never reach this point, though we can't raise an exception either as + # existing use cases rely on this behavior. + # So we return the last Component, that could be the last from waiting_queue or filtered_waiting_queue. + return name, comp + + def _find_next_runnable_lazy_variadic_or_default_component( + self, waiting_queue: List[Tuple[str, Component]] + ) -> Tuple[str, Component]: + """ + Finds the next Component that can be run and has a lazy variadic input or all inputs with default values. + + :param waiting_queue: Queue of Components waiting for input + + :returns: The name and the instance of the next Component that can be run + """ + for name, comp in waiting_queue: + is_lazy_variadic = _is_lazy_variadic(comp) + has_only_defaults = _has_all_inputs_with_defaults(comp) + if is_lazy_variadic or has_only_defaults: + return name, comp + + # If we reach this point it means that we found no Component that has a lazy variadic input or all inputs with + # default values to run. + # Similar to `_find_next_runnable_component` we might not find the Component we want, so we optimistically + # return the last Component in the list. + # We're probably stuck in a loop in this case, but we can't raise an exception as existing use cases might + # rely on this behaviour. + # The loop detection will be handled later on. + return name, comp + + def _find_components_that_will_receive_no_input( + self, component_name: str, component_result: Dict[str, Any], components_inputs: Dict[str, Dict[str, Any]] + ) -> Set[Tuple[str, Component]]: + """ + Find all the Components that are connected to component_name and didn't receive any input from it. + + Components that have a Variadic input and received already some input from other Components + but not from component_name won't be returned as they have enough inputs to run. + + This includes the descendants of the Components that didn't receive any input from component_name. + That is necessary to avoid getting stuck into infinite loops waiting for inputs that will never arrive. + + :param component_name: Name of the Component that created the output + :param component_result: Output of the Component + :param components_inputs: The current state of the inputs divided by Component name + :return: A set of Components that didn't receive any input from component_name + """ + + # Simplifies the check if a Component is Variadic and received some input from other Components. + def is_variadic_with_existing_inputs(comp: Component) -> bool: + for receiver_socket in comp.__haystack_input__._sockets_dict.values(): # type: ignore + if component_name not in receiver_socket.senders: + continue + if ( + receiver_socket.is_variadic + and len(components_inputs.get(receiver, {}).get(receiver_socket.name, [])) > 0 + ): + # This Component already received some input to its Variadic socket from other Components. + # It should be able to run even if it doesn't receive any input from component_name. + return True + return False + + components = set() + instance: Component = self.graph.nodes[component_name]["instance"] + for socket_name, socket in instance.__haystack_output__._sockets_dict.items(): # type: ignore + if socket_name in component_result: + continue + for receiver in socket.receivers: + receiver_instance: Component = self.graph.nodes[receiver]["instance"] + + if is_variadic_with_existing_inputs(receiver_instance): + continue + + components.add((receiver, receiver_instance)) + # Get the descendants too. When we remove a Component that received no input + # it's extremely likely that its descendants will receive no input as well. + # This is fine even if the Pipeline will merge back into a single Component + # at a certain point. The merging Component will be put back into the run + # queue at a later stage. + components |= {(d, self.graph.nodes[d]["instance"]) for d in networkx.descendants(self.graph, receiver)} + + return components + + def _is_stuck_in_a_loop(self, waiting_queue: List[Tuple[str, Component]]) -> bool: + """ + Checks if the Pipeline is stuck in a loop. + + :param waiting_queue: Queue of Components waiting for input + + :returns: True if the Pipeline is stuck in a loop, False otherwise + """ + # Are we actually stuck or there's a lazy variadic or a component with has only default inputs + # waiting for input? + # This is our last resort, if there's no lazy variadic or component with only default inputs + # waiting for input we're stuck for real and we can't make any progress. + component_found = False + for _, comp in waiting_queue: + if _is_lazy_variadic(comp) or _has_all_inputs_with_defaults(comp): + component_found = True + break + + if not component_found: + # We're stuck in a loop for real, we can't make any progress. + # BAIL! + return True + + # If we have a single component with no variadic input or only default inputs waiting for input + # it means it has been waiting for input for at least 2 iterations. + # This will never run. + # BAIL! + return len(waiting_queue) == 1 + + def _component_has_enough_inputs_to_run(self, name: str, inputs: Dict[str, Dict[str, Any]]) -> bool: + """ + Returns True if the Component has all the inputs it needs to run. + + :param name: Name of the Component as defined in the Pipeline. + :param inputs: The current state of the inputs divided by Component name. + + :return: Whether the Component can run or not. + """ + instance: Component = self.graph.nodes[name]["instance"] + if name not in inputs: + return False + expected_inputs = instance.__haystack_input__._sockets_dict.keys() # type: ignore + current_inputs = inputs[name].keys() + return expected_inputs == current_inputs + + +def _connections_status( + sender_node: str, receiver_node: str, sender_sockets: List[OutputSocket], receiver_sockets: List[InputSocket] +): + """ + Lists the status of the sockets, for error messages. + """ + sender_sockets_entries = [] + for sender_socket in sender_sockets: + sender_sockets_entries.append(f" - {sender_socket.name}: {_type_name(sender_socket.type)}") + sender_sockets_list = "\n".join(sender_sockets_entries) + + receiver_sockets_entries = [] + for receiver_socket in receiver_sockets: + if receiver_socket.senders: + sender_status = f"sent by {','.join(receiver_socket.senders)}" + else: + sender_status = "available" + receiver_sockets_entries.append( + f" - {receiver_socket.name}: {_type_name(receiver_socket.type)} ({sender_status})" + ) + receiver_sockets_list = "\n".join(receiver_sockets_entries) + + return f"'{sender_node}':\n{sender_sockets_list}\n'{receiver_node}':\n{receiver_sockets_list}" + + +def _is_lazy_variadic(c: Component) -> bool: + """ + Small utility function to check if a Component has at least a Variadic input and no GreedyVariadic input. + """ + is_variadic = any( + socket.is_variadic + for socket in c.__haystack_input__._sockets_dict.values() # type: ignore + ) + if not is_variadic: + return False + return not any( + socket.is_greedy + for socket in c.__haystack_input__._sockets_dict.values() # type: ignore + ) + + +def _has_all_inputs_with_defaults(c: Component) -> bool: + """ + Small utility function to check if a Component has all inputs with defaults. + """ + return all( + not socket.is_mandatory + for socket in c.__haystack_input__._sockets_dict.values() # type: ignore + ) + + +def _add_missing_input_defaults(name: str, comp: Component, components_inputs: Dict[str, Dict[str, Any]]): + """ + Updates the inputs with the default values for the inputs that are missing + + :param name: Name of the Component + :param comp: Instance of the Component + :param components_inputs: The current state of the inputs divided by Component name + """ + if name not in components_inputs: + components_inputs[name] = {} + + for input_socket in comp.__haystack_input__._sockets_dict.values(): # type: ignore + if input_socket.is_mandatory: + continue + + if input_socket.name not in components_inputs[name]: + components_inputs[name][input_socket.name] = input_socket.default_value + + +def _enqueue_component( + component_pair: Tuple[str, Component], + run_queue: List[Tuple[str, Component]], + waiting_queue: List[Tuple[str, Component]], +): + """ + Append a Component in the queue of Components to run if not already in it. + + Remove it from the waiting list if it's there. + + :param component_pair: Tuple of Component name and instance + :param run_queue: Queue of Components to run + :param waiting_queue: Queue of Components waiting for input + """ + if component_pair in waiting_queue: + waiting_queue.remove(component_pair) + + if component_pair not in run_queue: + run_queue.append(component_pair) + + +def _dequeue_component( + component_pair: Tuple[str, Component], + run_queue: List[Tuple[str, Component]], + waiting_queue: List[Tuple[str, Component]], +): + """ + Removes a Component both from the queue of Components to run and the waiting list. + + :param component_pair: Tuple of Component name and instance + :param run_queue: Queue of Components to run + :param waiting_queue: Queue of Components waiting for input + """ + if component_pair in waiting_queue: + waiting_queue.remove(component_pair) + + if component_pair in run_queue: + run_queue.remove(component_pair) + + +def _enqueue_waiting_component(component_pair: Tuple[str, Component], waiting_queue: List[Tuple[str, Component]]): + """ + Append a Component in the queue of Components that are waiting for inputs if not already in it. + + :param component_pair: Tuple of Component name and instance + :param waiting_queue: Queue of Components waiting for input + """ + if component_pair not in waiting_queue: + waiting_queue.append(component_pair) + + +def _dequeue_waiting_component(component_pair: Tuple[str, Component], waiting_queue: List[Tuple[str, Component]]): + """ + Removes a Component from the queue of Components that are waiting for inputs. + + :param component_pair: Tuple of Component name and instance + :param waiting_queue: Queue of Components waiting for input + """ + if component_pair in waiting_queue: + waiting_queue.remove(component_pair) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/descriptions.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/descriptions.py new file mode 100644 index 0000000000000000000000000000000000000000..59e4bbcf86bf265e0ae78547aa34147f73882a4f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/descriptions.py @@ -0,0 +1,73 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Dict, List + +import networkx # type:ignore + +from haystack import logging +from haystack.core.component.types import InputSocket, OutputSocket +from haystack.core.type_utils import _type_name + +logger = logging.getLogger(__name__) + + +def find_pipeline_inputs( + graph: networkx.MultiDiGraph, include_connected_sockets: bool = False +) -> Dict[str, List[InputSocket]]: + """ + Collect components that have disconnected/connected input sockets. + + Note that this method returns *ALL* disconnected input sockets, including all such sockets with default values. + """ + return { + name: [ + socket + for socket in data.get("input_sockets", {}).values() + if socket.is_variadic or (include_connected_sockets or not socket.senders) + ] + for name, data in graph.nodes(data=True) + } + + +def find_pipeline_outputs( + graph: networkx.MultiDiGraph, include_connected_sockets: bool = False +) -> Dict[str, List[OutputSocket]]: + """ + Collect components that have disconnected/connected output sockets. They define the pipeline output. + """ + return { + name: [ + socket + for socket in data.get("output_sockets", {}).values() + if (include_connected_sockets or not socket.receivers) + ] + for name, data in graph.nodes(data=True) + } + + +def describe_pipeline_inputs(graph: networkx.MultiDiGraph): + """ + Returns a dictionary with the input names and types that this pipeline accepts. + """ + inputs = { + comp: {socket.name: {"type": socket.type, "is_mandatory": socket.is_mandatory} for socket in data} + for comp, data in find_pipeline_inputs(graph).items() + if data + } + return inputs + + +def describe_pipeline_inputs_as_string(graph: networkx.MultiDiGraph): + """ + Returns a string representation of the input names and types that this pipeline accepts. + """ + inputs = describe_pipeline_inputs(graph) + message = "This pipeline expects the following inputs:\n" + for comp, sockets in inputs.items(): + if sockets: + message += f"- {comp}:\n" + for name, socket in sockets.items(): + message += f" - {name}: {_type_name(socket['type'])}\n" + return message diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/draw.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/draw.py new file mode 100644 index 0000000000000000000000000000000000000000..83df7915153f6da538cf8364c78153a01bf02492 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/draw.py @@ -0,0 +1,154 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import base64 + +import networkx # type:ignore +import requests + +from haystack import logging +from haystack.core.errors import PipelineDrawingError +from haystack.core.pipeline.descriptions import find_pipeline_inputs, find_pipeline_outputs +from haystack.core.type_utils import _type_name + +logger = logging.getLogger(__name__) + + +def _prepare_for_drawing(graph: networkx.MultiDiGraph) -> networkx.MultiDiGraph: + """ + Add some extra nodes to show the inputs and outputs of the pipeline. + + Also adds labels to edges. + """ + # Label the edges + for inp, outp, key, data in graph.edges(keys=True, data=True): + data["label"] = ( + f"{data['from_socket'].name} -> {data['to_socket'].name}{' (opt.)' if not data['mandatory'] else ''}" + ) + graph.add_edge(inp, outp, key=key, **data) + + # Add inputs fake node + graph.add_node("input") + for node, in_sockets in find_pipeline_inputs(graph).items(): + for in_socket in in_sockets: + if not in_socket.senders and in_socket.is_mandatory: + # If this socket has no sender it could be a socket that receives input + # directly when running the Pipeline. We can't know that for sure, in doubt + # we draw it as receiving input directly. + graph.add_edge("input", node, label=in_socket.name, conn_type=_type_name(in_socket.type)) + + # Add outputs fake node + graph.add_node("output") + for node, out_sockets in find_pipeline_outputs(graph).items(): + for out_socket in out_sockets: + graph.add_edge(node, "output", label=out_socket.name, conn_type=_type_name(out_socket.type)) + + return graph + + +ARROWTAIL_MANDATORY = "--" +ARROWTAIL_OPTIONAL = "-." +ARROWHEAD_MANDATORY = "-->" +ARROWHEAD_OPTIONAL = ".->" +MERMAID_STYLED_TEMPLATE = """ +%%{{ init: {{'theme': 'neutral' }} }}%% + +graph TD; + +{connections} + +classDef component text-align:center; +""" + + +def _to_mermaid_image(graph: networkx.MultiDiGraph): + """ + Renders a pipeline using Mermaid (hosted version at 'https://mermaid.ink'). Requires Internet access. + """ + # Copy the graph to avoid modifying the original + graph_styled = _to_mermaid_text(graph.copy()) + + graphbytes = graph_styled.encode("ascii") + base64_bytes = base64.b64encode(graphbytes) + base64_string = base64_bytes.decode("ascii") + url = f"https://mermaid.ink/img/{base64_string}?type=png" + + logger.debug("Rendering graph at {url}", url=url) + try: + resp = requests.get(url, timeout=10) + if resp.status_code >= 400: + logger.warning( + "Failed to draw the pipeline: https://mermaid.ink/img/ returned status {status_code}", + status_code=resp.status_code, + ) + logger.info("Exact URL requested: {url}", url=url) + logger.warning("No pipeline diagram will be saved.") + resp.raise_for_status() + + except Exception as exc: # pylint: disable=broad-except + logger.warning( + "Failed to draw the pipeline: could not connect to https://mermaid.ink/img/ ({error})", error=exc + ) + logger.info("Exact URL requested: {url}", url=url) + logger.warning("No pipeline diagram will be saved.") + raise PipelineDrawingError( + "There was an issue with https://mermaid.ink/, see the stacktrace for details." + ) from exc + + return resp.content + + +def _to_mermaid_text(graph: networkx.MultiDiGraph) -> str: + """ + Converts a Networkx graph into Mermaid syntax. + + The output of this function can be used in the documentation with `mermaid` codeblocks and will be + automatically rendered. + """ + # Copy the graph to avoid modifying the original + graph = _prepare_for_drawing(graph.copy()) + sockets = { + comp: "".join( + [ + f"
  • {name} ({_type_name(socket.type)})
  • " + for name, socket in data.get("input_sockets", {}).items() + if (not socket.is_mandatory and not socket.senders) or socket.is_variadic + ] + ) + for comp, data in graph.nodes(data=True) + } + optional_inputs = { + comp: f"

    Optional inputs:
      {sockets}
    " if sockets else "" + for comp, sockets in sockets.items() + } + + states = { + comp: f"{comp}[\"{comp}
    {type(data['instance']).__name__}{optional_inputs[comp]}\"]:::component" # noqa + for comp, data in graph.nodes(data=True) + if comp not in ["input", "output"] + } + + connections_list = [] + for from_comp, to_comp, conn_data in graph.edges(data=True): + if from_comp != "input" and to_comp != "output": + arrowtail = ARROWTAIL_MANDATORY if conn_data["mandatory"] else ARROWTAIL_OPTIONAL + arrowhead = ARROWHEAD_MANDATORY if conn_data["mandatory"] else ARROWHEAD_OPTIONAL + label = f'"{conn_data["label"]}
    {conn_data["conn_type"]}"' + conn_string = f"{states[from_comp]} {arrowtail} {label} {arrowhead} {states[to_comp]}" + connections_list.append(conn_string) + + input_connections = [ + f"i{{*}}--\"{conn_data['label']}
    {conn_data['conn_type']}\"--> {states[to_comp]}" + for _, to_comp, conn_data in graph.out_edges("input", data=True) + ] + output_connections = [ + f"{states[from_comp]}--\"{conn_data['label']}
    {conn_data['conn_type']}\"--> o{{*}}" + for from_comp, _, conn_data in graph.in_edges("output", data=True) + ] + connections = "\n".join(connections_list + input_connections + output_connections) + + graph_styled = MERMAID_STYLED_TEMPLATE.format(connections=connections) + logger.debug("Mermaid diagram:\n{diagram}", diagram=graph_styled) + + return graph_styled diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/pipeline.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..7da6a74dc1271f1d4abdca5fc92dc9f0281f7c59 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/pipeline.py @@ -0,0 +1,302 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from copy import deepcopy +from typing import Any, Dict, List, Mapping, Optional, Set, Tuple +from warnings import warn + +from haystack import logging, tracing +from haystack.core.component import Component +from haystack.core.errors import PipelineMaxComponentRuns, PipelineRuntimeError +from haystack.core.pipeline.base import ( + _dequeue_component, + _dequeue_waiting_component, + _enqueue_component, + _enqueue_waiting_component, +) +from haystack.telemetry import pipeline_running + +from .base import PipelineBase, _add_missing_input_defaults, _is_lazy_variadic + +logger = logging.getLogger(__name__) + + +class Pipeline(PipelineBase): + """ + Synchronous version of the orchestration engine. + + Orchestrates component execution according to the execution graph, one after the other. + """ + + def _run_component( + self, name: str, inputs: Dict[str, Any], parent_span: Optional[tracing.Span] = None + ) -> Dict[str, Any]: + """ + Runs a Component with the given inputs. + + :param name: Name of the Component as defined in the Pipeline. + :param inputs: Inputs for the Component. + :param parent_span: The parent span to use for the newly created span. + This is to allow tracing to be correctly linked to the pipeline run. + :raises PipelineRuntimeError: If Component doesn't return a dictionary. + :return: The output of the Component. + """ + instance: Component = self.graph.nodes[name]["instance"] + + with tracing.tracer.trace( + "haystack.component.run", + tags={ + "haystack.component.name": name, + "haystack.component.type": instance.__class__.__name__, + "haystack.component.input_types": {k: type(v).__name__ for k, v in inputs.items()}, + "haystack.component.input_spec": { + key: { + "type": (value.type.__name__ if isinstance(value.type, type) else str(value.type)), + "senders": value.senders, + } + for key, value in instance.__haystack_input__._sockets_dict.items() # type: ignore + }, + "haystack.component.output_spec": { + key: { + "type": (value.type.__name__ if isinstance(value.type, type) else str(value.type)), + "receivers": value.receivers, + } + for key, value in instance.__haystack_output__._sockets_dict.items() # type: ignore + }, + }, + parent_span=parent_span, + ) as span: + span.set_content_tag("haystack.component.input", inputs) + logger.info("Running component {component_name}", component_name=name) + res: Dict[str, Any] = instance.run(**inputs) + self.graph.nodes[name]["visits"] += 1 + + # After a Component that has variadic inputs is run, we need to reset the variadic inputs that were consumed + for socket in instance.__haystack_input__._sockets_dict.values(): # type: ignore + if socket.name not in inputs: + continue + if socket.is_variadic: + inputs[socket.name] = [] + + if not isinstance(res, Mapping): + raise PipelineRuntimeError( + f"Component '{name}' didn't return a dictionary. " + "Components must always return dictionaries: check the documentation." + ) + span.set_tag("haystack.component.visits", self.graph.nodes[name]["visits"]) + span.set_content_tag("haystack.component.output", res) + + return res + + def run( # noqa: PLR0915 + self, data: Dict[str, Any], include_outputs_from: Optional[Set[str]] = None + ) -> Dict[str, Any]: + """ + Runs the pipeline with given input data. + + :param data: + A dictionary of inputs for the pipeline's components. Each key is a component name + and its value is a dictionary of that component's input parameters: + ``` + data = { + "comp1": {"input1": 1, "input2": 2}, + } + ``` + For convenience, this format is also supported when input names are unique: + ``` + data = { + "input1": 1, "input2": 2, + } + ``` + + :param include_outputs_from: + Set of component names whose individual outputs are to be + included in the pipeline's output. For components that are + invoked multiple times (in a loop), only the last-produced + output is included. + :returns: + A dictionary where each entry corresponds to a component name + and its output. If `include_outputs_from` is `None`, this dictionary + will only contain the outputs of leaf components, i.e., components + without outgoing connections. + + :raises PipelineRuntimeError: + If a component fails or returns unexpected output. + + Example a - Using named components: + Consider a 'Hello' component that takes a 'word' input and outputs a greeting. + + ```python + @component + class Hello: + @component.output_types(output=str) + def run(self, word: str): + return {"output": f"Hello, {word}!"} + ``` + + Create a pipeline with two 'Hello' components connected together: + + ```python + pipeline = Pipeline() + pipeline.add_component("hello", Hello()) + pipeline.add_component("hello2", Hello()) + pipeline.connect("hello.output", "hello2.word") + result = pipeline.run(data={"hello": {"word": "world"}}) + ``` + + This runs the pipeline with the specified input for 'hello', yielding + {'hello2': {'output': 'Hello, Hello, world!!'}}. + + Example b - Using flat inputs: + You can also pass inputs directly without specifying component names: + + ```python + result = pipeline.run(data={"word": "world"}) + ``` + + The pipeline resolves inputs to the correct components, returning + {'hello2': {'output': 'Hello, Hello, world!!'}}. + """ + pipeline_running(self) + + # Reset the visits count for each component + self._init_graph() + + # TODO: Remove this warmup once we can check reliably whether a component has been warmed up or not + # As of now it's here to make sure we don't have failing tests that assume warm_up() is called in run() + self.warm_up() + + # normalize `data` + data = self._prepare_component_input_data(data) + + # Raise if input is malformed in some way + self._validate_input(data) + + # Initialize the inputs state + components_inputs: Dict[str, Dict[str, Any]] = self._init_inputs_state(data) + + # Take all components that: + # - have no inputs + # - receive input from the user + # - have at least one input not connected + # - have at least one input that is variadic + run_queue: List[Tuple[str, Component]] = self._init_run_queue(data) + + # These variables are used to detect when we're stuck in a loop. + # Stuck loops can happen when one or more components are waiting for input but + # no other component is going to run. + # This can happen when a whole branch of the graph is skipped for example. + # When we find that two consecutive iterations of the loop where the waiting_queue is the same, + # we know we're stuck in a loop and we can't make any progress. + # + # They track the previous two states of the waiting_queue. So if waiting_queue would n, + # before_last_waiting_queue would be n-2 and last_waiting_queue would be n-1. + # When we run a component, we reset both. + before_last_waiting_queue: Optional[Set[str]] = None + last_waiting_queue: Optional[Set[str]] = None + + # The waiting_for_input list is used to keep track of components that are waiting for input. + waiting_queue: List[Tuple[str, Component]] = [] + + include_outputs_from = set() if include_outputs_from is None else include_outputs_from + + # This is what we'll return at the end + final_outputs: Dict[Any, Any] = {} + + with tracing.tracer.trace( + "haystack.pipeline.run", + tags={ + "haystack.pipeline.input_data": data, + "haystack.pipeline.output_data": final_outputs, + "haystack.pipeline.metadata": self.metadata, + "haystack.pipeline.max_runs_per_component": self._max_runs_per_component, + }, + ) as span: + # Cache for extra outputs, if enabled. + extra_outputs: Dict[Any, Any] = {} + + while len(run_queue) > 0: + name, comp = run_queue.pop(0) + + if _is_lazy_variadic(comp) and not all(_is_lazy_variadic(comp) for _, comp in run_queue): + # We run Components with lazy variadic inputs only if there only Components with + # lazy variadic inputs left to run + _enqueue_waiting_component((name, comp), waiting_queue) + continue + + if self._component_has_enough_inputs_to_run(name, components_inputs): + if self.graph.nodes[name]["visits"] > self._max_runs_per_component: + msg = f"Maximum run count {self._max_runs_per_component} reached for component '{name}'" + raise PipelineMaxComponentRuns(msg) + + res: Dict[str, Any] = self._run_component(name, components_inputs[name], parent_span=span) + + if name in include_outputs_from: + # Deepcopy the outputs to prevent downstream nodes from modifying them + # We don't care about loops - Always store the last output. + extra_outputs[name] = deepcopy(res) + + # Reset the waiting for input previous states, we managed to run a component + before_last_waiting_queue = None + last_waiting_queue = None + + # We manage to run this component that was in the waiting list, we can remove it. + # This happens when a component was put in the waiting list but we reached it from another edge. + _dequeue_waiting_component((name, comp), waiting_queue) + + for pair in self._find_components_that_will_receive_no_input(name, res, components_inputs): + _dequeue_component(pair, run_queue, waiting_queue) + res = self._distribute_output(name, res, components_inputs, run_queue, waiting_queue) + + if len(res) > 0: + final_outputs[name] = res + else: + # This component doesn't have enough inputs so we can't run it yet + _enqueue_waiting_component((name, comp), waiting_queue) + + if len(run_queue) == 0 and len(waiting_queue) > 0: + # Check if we're stuck in a loop. + # It's important to check whether previous waitings are None as it could be that no + # Component has actually been run yet. + if ( + before_last_waiting_queue is not None + and last_waiting_queue is not None + and before_last_waiting_queue == last_waiting_queue + ): + if self._is_stuck_in_a_loop(waiting_queue): + # We're stuck! We can't make any progress. + msg = ( + "Pipeline is stuck running in a loop. Partial outputs will be returned. " + "Check the Pipeline graph for possible issues." + ) + warn(RuntimeWarning(msg)) + break + + (name, comp) = self._find_next_runnable_lazy_variadic_or_default_component(waiting_queue) + _add_missing_input_defaults(name, comp, components_inputs) + _enqueue_component((name, comp), run_queue, waiting_queue) + continue + + before_last_waiting_queue = last_waiting_queue.copy() if last_waiting_queue is not None else None + last_waiting_queue = {item[0] for item in waiting_queue} + + (name, comp) = self._find_next_runnable_component(components_inputs, waiting_queue) + _add_missing_input_defaults(name, comp, components_inputs) + _enqueue_component((name, comp), run_queue, waiting_queue) + + if len(include_outputs_from) > 0: + for name, output in extra_outputs.items(): + inner = final_outputs.get(name) + if inner is None: + final_outputs[name] = output + else: + # Let's not override any keys that are already + # in the final_outputs as they might be different + # from what we cached in extra_outputs, e.g. when loops + # are involved. + for k, v in output.items(): + if k not in inner: + inner[k] = v + + return final_outputs diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/predefined/chat_with_website.yaml.jinja2 b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/predefined/chat_with_website.yaml.jinja2 new file mode 100644 index 0000000000000000000000000000000000000000..c4ef14d49d9cb218af9bf9d96cd012e21f8f5c44 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/predefined/chat_with_website.yaml.jinja2 @@ -0,0 +1,52 @@ +components: + converter: + type: haystack.components.converters.html.HTMLToDocument + init_parameters: + extraction_kwargs: null + + fetcher: + init_parameters: + raise_on_failure: true + retry_attempts: 2 + timeout: 3 + user_agents: + - haystack/LinkContentFetcher/2.0.0b8 + type: haystack.components.fetchers.link_content.LinkContentFetcher + + llm: + init_parameters: + api_base_url: null + api_key: + env_vars: + - OPENAI_API_KEY + strict: true + type: env_var + generation_kwargs: {} + model: gpt-4o-mini + streaming_callback: null + system_prompt: null + type: haystack.components.generators.openai.OpenAIGenerator + + prompt: + init_parameters: + template: | + {% raw %} + "According to the contents of this website: + {% for document in documents %} + {{document.content}} + {% endfor %} + Answer the given question: {{query}} + Answer: + " + {% endraw %} + type: haystack.components.builders.prompt_builder.PromptBuilder + +connections: +- receiver: converter.sources + sender: fetcher.streams +- receiver: prompt.documents + sender: converter.documents +- receiver: llm.prompt + sender: prompt.prompt + +metadata: {} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/predefined/generative_qa.yaml.jinja2 b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/predefined/generative_qa.yaml.jinja2 new file mode 100644 index 0000000000000000000000000000000000000000..456689d75c54c6b5c5d18c190358a569c5dd2dcb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/predefined/generative_qa.yaml.jinja2 @@ -0,0 +1,24 @@ +--- + +components: + generator: + init_parameters: + api_key: + env_vars: [ "OPENAI_API_KEY" ] + strict: true + type: "env_var" + model: "gpt-4o-mini" + type: "haystack.components.generators.openai.OpenAIGenerator" + + prompt_builder: + init_parameters: + template: "{% raw %}Answer the question {{question}}.\n Answer:\n{% endraw %}" + type: "haystack.components.builders.prompt_builder.PromptBuilder" + + +connections: +- receiver: generator.prompt + sender: prompt_builder.prompt + +metadata: + {} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/predefined/indexing.yaml.jinja2 b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/predefined/indexing.yaml.jinja2 new file mode 100644 index 0000000000000000000000000000000000000000..69f5008454e3d11277f74d8caa11e9ceec8f4c12 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/predefined/indexing.yaml.jinja2 @@ -0,0 +1,67 @@ +--- + +components: + cleaner: + init_parameters: + remove_empty_lines: true + remove_extra_whitespaces: true + remove_regex: null + remove_repeated_substrings: false + remove_substrings: null + type: haystack.components.preprocessors.document_cleaner.DocumentCleaner + + converter: + init_parameters: + encoding: utf-8 + type: haystack.components.converters.txt.TextFileToDocument + + embedder: + init_parameters: + api_base_url: null + api_key: + env_vars: + - OPENAI_API_KEY + strict: true + type: env_var + batch_size: 32 + dimensions: null + embedding_separator: '\n' + meta_fields_to_embed: [] + model: text-embedding-ada-002 + organization: null + prefix: '' + progress_bar: true + suffix: '' + type: haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder + + splitter: + init_parameters: + split_by: word + split_length: 200 + split_overlap: 0 + type: haystack.components.preprocessors.document_splitter.DocumentSplitter + + writer: + init_parameters: + document_store: + init_parameters: + bm25_tokenization_regex: (?u)\b\w\w+\b + bm25_algorithm: BM25L + bm25_parameters: {} + embedding_similarity_function: dot_product + index: documents + type: haystack.document_stores.in_memory.document_store.InMemoryDocumentStore + policy: NONE + type: haystack.components.writers.document_writer.DocumentWriter + +connections: +- receiver: cleaner.documents + sender: converter.documents +- receiver: splitter.documents + sender: cleaner.documents +- receiver: embedder.documents + sender: splitter.documents +- receiver: writer.documents + sender: embedder.documents + +metadata: {} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/predefined/rag.yaml.jinja2 b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/predefined/rag.yaml.jinja2 new file mode 100644 index 0000000000000000000000000000000000000000..cff8bbb84da670948e141a2a1b5c140b7f7211b6 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/predefined/rag.yaml.jinja2 @@ -0,0 +1,70 @@ +--- + +components: + llm: + init_parameters: + api_base_url: null + api_key: + env_vars: + - OPENAI_API_KEY + strict: true + type: env_var + generation_kwargs: {} + model: gpt-4o-mini + streaming_callback: null + system_prompt: null + type: haystack.components.generators.openai.OpenAIGenerator + + prompt_builder: + init_parameters: + template: | + {% raw %} + "Given these documents, answer the question. + Documents: + {% for doc in documents %}\ + {{ doc.content }} + {% endfor %} + Question: {{query}} + + Answer:" + {% endraw %} + type: haystack.components.builders.prompt_builder.PromptBuilder + + retriever: + init_parameters: + document_store: + init_parameters: + bm25_tokenization_regex: (?u)\b\w\w+\b + bm25_algorithm: BM25L + bm25_parameters: {} + embedding_similarity_function: dot_product + index: documents + type: haystack.document_stores.in_memory.document_store.InMemoryDocumentStore + filters: null + top_k: 10 + type: haystack.components.retrievers.in_memory.embedding_retriever.InMemoryEmbeddingRetriever + + text_embedder: + init_parameters: + api_base_url: null + api_key: + env_vars: + - OPENAI_API_KEY + strict: true + type: env_var + dimensions: null + model: text-embedding-ada-002 + organization: null + prefix: '' + suffix: '' + type: haystack.components.embedders.openai_text_embedder.OpenAITextEmbedder + +connections: +- receiver: retriever.query_embedding + sender: text_embedder.embedding +- receiver: prompt_builder.documents + sender: retriever.documents +- receiver: llm.prompt + sender: prompt_builder.prompt + +metadata: {} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/template.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/template.py new file mode 100644 index 0000000000000000000000000000000000000000..338e6b3fbd1695e7bebaf558f92c236eb79a9184 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/template.py @@ -0,0 +1,130 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from enum import Enum +from pathlib import Path +from typing import Any, Dict, Optional, Union + +from jinja2 import PackageLoader, TemplateSyntaxError, meta +from jinja2.sandbox import SandboxedEnvironment + +TEMPLATE_FILE_EXTENSION = ".yaml.jinja2" +TEMPLATE_HOME_DIR = Path(__file__).resolve().parent / "predefined" + + +class PredefinedPipeline(Enum): + """ + Enumeration of predefined pipeline templates that can be used to create a `PipelineTemplate`. + """ + + # Maintain 1-to-1 mapping between the enum name and the template file name in templates directory + GENERATIVE_QA = "generative_qa" + RAG = "rag" + INDEXING = "indexing" + CHAT_WITH_WEBSITE = "chat_with_website" + + +class PipelineTemplate: + """ + The PipelineTemplate enables the creation of flexible and configurable pipelines. + + The PipelineTemplate class enables the straightforward creation of flexible and configurable pipelines using + Jinja2 templated YAML files. Specifically designed to simplify the setup of complex data processing pipelines for + a range of NLP tasks—including question answering, retriever augmented generation (RAG), document indexing, among + others - PipelineTemplate empowers users to dynamically generate pipeline configurations from templates and + customize components as necessary. Its design philosophy centers on providing an accessible, yet powerful, tool + for constructing pipelines that accommodate both common use cases and specialized requirements with ease. + + Examples of usage: + + - **Default Build**: Instantiating a pipeline with default settings for a "question answering" (qa) task. + ```python + from haystack.templates import PipelineTemplate, PredefinedPipeline + + # Create a pipeline with default components for an extractive QA task + pipe = PipelineTemplate.from_predefined(PredefinedPipeline.GENERATIVE_QA).build() + print(pipe.run(data={"question": "What's the capital of Bosnia and Herzegovina? Be brief"})) + ``` + + - **Customizing for Specific Tasks**: Building a pipeline for document indexing with specific components tailored + to the task. + ```python + from haystack.components.embedders import SentenceTransformersDocumentEmbedder + from haystack.templates import PipelineTemplate, PredefinedPipeline + + # Customize the pipeline for document indexing with specific components, include PDF file converter + pt = PipelineTemplate.from_predefined(PredefinedTemplate.INDEXING) + pipe = pt.build(template_params={"use_pdf_file_converter": True}) + + result = pipe.run(data={"sources": ["some_text_file.txt", "another_pdf_file.pdf"]}) + print(result) + ``` + + The `PipelineTemplate` is designed to offer both ease of use for common pipeline configurations and the + flexibility to customize and extend pipelines as required by advanced users and specific use cases. + """ + + def __init__(self, template_content: str): + """ + Initialize a PipelineTemplate. + + Besides calling the constructor directly, a set of utility methods is provided to conveniently create an + instance of `PipelineTemplate` from different sources. See `from_string`, `from_file`, `from_predefined` + and `from_url`. + + :param template_content: The raw template source to use in the template. + """ + env = SandboxedEnvironment( + loader=PackageLoader("haystack.core.pipeline", "predefined"), trim_blocks=True, lstrip_blocks=True + ) + try: + self._template = env.from_string(template_content) + except TemplateSyntaxError as e: + raise ValueError(f"Invalid pipeline template: {e.message}") from e + + # Store the list of undefined variables in the template. Components' names will be part of this list + self.template_variables = meta.find_undeclared_variables(env.parse(template_content)) + self._template_content = template_content + + def render(self, template_params: Optional[Dict[str, Any]] = None) -> str: + """ + Constructs a `Pipeline` instance based on the template. + + :param template_params: An optional dictionary of parameters to use when rendering the pipeline template. + + :returns: An instance of `Pipeline` constructed from the rendered template and custom component configurations. + """ + template_params = template_params or {} + return self._template.render(**template_params) + + @classmethod + def from_file(cls, file_path: Union[Path, str]) -> "PipelineTemplate": + """ + Create a PipelineTemplate from a file. + + :param file_path: The path to the file containing the template. Must contain valid Jinja2 syntax. + :returns: An instance of `PipelineTemplate`. + """ + with open(file_path, "r") as file: + return cls(file.read()) + + @classmethod + def from_predefined(cls, predefined_pipeline: PredefinedPipeline) -> "PipelineTemplate": + """ + Create a PipelineTemplate from a predefined template. + + See `PredefinedPipeline` for available options. + + :param predefined_pipeline: The predefined pipeline to use. + :returns: An instance of `PipelineTemplate `. + """ + template_path = f"{TEMPLATE_HOME_DIR}/{predefined_pipeline.value}{TEMPLATE_FILE_EXTENSION}" + return cls.from_file(template_path) + + @property + def template_content(self) -> str: + """ + Returns the raw template string as a read-only property. + """ + return self._template_content diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/utils.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f9f858a39d6851dc5365589feaf076b8eceda44b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/pipeline/utils.py @@ -0,0 +1,20 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Optional, Tuple + + +def parse_connect_string(connection: str) -> Tuple[str, Optional[str]]: + """ + Returns component-connection pairs from a connect_to/from string. + + :param connection: + The connection string. + :returns: + A tuple containing the component name and the connection name. + """ + if "." in connection: + split_str = connection.split(".", maxsplit=1) + return (split_str[0], split_str[1]) + return connection, None diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/serialization.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..3477f0c806cd2c14425d90e2455d9a10e6acaafb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/serialization.py @@ -0,0 +1,259 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import inspect +from collections.abc import Callable +from dataclasses import dataclass +from importlib import import_module +from typing import Any, Dict, Iterable, Optional, Type + +from haystack.core.component.component import _hook_component_init, logger +from haystack.core.errors import DeserializationError, SerializationError + + +@dataclass(frozen=True) +class DeserializationCallbacks: + """ + Callback functions that are invoked in specific stages of the pipeline deserialization process. + + :param component_pre_init: + Invoked just before a component instance is + initialized. Receives the following inputs: + `component_name` (`str`), `component_class` (`Type`), `init_params` (`Dict[str, Any]`). + + The callback is allowed to modify the `init_params` + dictionary, which contains all the parameters that + are passed to the component's constructor. + """ + + component_pre_init: Optional[Callable] = None + + +def component_to_dict(obj: Any, name: str) -> Dict[str, Any]: + """ + Converts a component instance into a dictionary. + + If a `to_dict` method is present in the component instance, that will be used instead of the default method. + + :param obj: + The component to be serialized. + :param name: + The name of the component. + :returns: + A dictionary representation of the component. + + :raises SerializationError: + If the component doesn't have a `to_dict` method. + If the values of the init parameters can't be determined. + If a non-basic Python type is used in the serialized data. + """ + if hasattr(obj, "to_dict"): + data = obj.to_dict() + else: + init_parameters = {} + for param_name, param in inspect.signature(obj.__init__).parameters.items(): + # Ignore `args` and `kwargs`, used by the default constructor + if param_name in ("args", "kwargs"): + continue + try: + # This only works if the Component constructor assigns the init + # parameter to an instance variable or property with the same name + param_value = getattr(obj, param_name) + except AttributeError as e: + # If the parameter doesn't have a default value, raise an error + if param.default is param.empty: + raise SerializationError( + f"Cannot determine the value of the init parameter '{param_name}' " + f"for the class {obj.__class__.__name__}." + f"You can fix this error by assigning 'self.{param_name} = {param_name}' or adding a " + f"custom serialization method 'to_dict' to the class." + ) from e + # In case the init parameter was not assigned, we use the default value + param_value = param.default + init_parameters[param_name] = param_value + + data = default_to_dict(obj, **init_parameters) + + _validate_component_to_dict_output(obj, name, data) + return data + + +def _validate_component_to_dict_output(component: Any, name: str, data: Dict[str, Any]) -> None: + # Ensure that only basic Python types are used in the serde data. + def is_allowed_type(obj: Any) -> bool: + return isinstance(obj, (str, int, float, bool, list, dict, set, tuple, type(None))) + + def check_iterable(l: Iterable[Any]): + for v in l: + if not is_allowed_type(v): + raise SerializationError( + f"Component '{name}' of type '{type(component).__name__}' has an unsupported value " + f"of type '{type(v).__name__}' in the serialized data." + ) + if isinstance(v, (list, set, tuple)): + check_iterable(v) + elif isinstance(v, dict): + check_dict(v) + + def check_dict(d: Dict[str, Any]): + if any(not isinstance(k, str) for k in data.keys()): + raise SerializationError( + f"Component '{name}' of type '{type(component).__name__}' has a non-string key in the serialized data." + ) + + for k, v in d.items(): + if not is_allowed_type(v): + raise SerializationError( + f"Component '{name}' of type '{type(component).__name__}' has an unsupported value " + f"of type '{type(v).__name__}' in the serialized data under key '{k}'." + ) + if isinstance(v, (list, set, tuple)): + check_iterable(v) + elif isinstance(v, dict): + check_dict(v) + + check_dict(data) + + +def generate_qualified_class_name(cls: Type[object]) -> str: + """ + Generates a qualified class name for a class. + + :param cls: + The class whose qualified name is to be generated. + :returns: + The qualified name of the class. + """ + return f"{cls.__module__}.{cls.__name__}" + + +def component_from_dict( + cls: Type[object], data: Dict[str, Any], name: str, callbacks: Optional[DeserializationCallbacks] = None +) -> Any: + """ + Creates a component instance from a dictionary. + + If a `from_dict` method is present in the component class, that will be used instead of the default method. + + :param cls: + The class to be used for deserialization. + :param data: + The serialized data. + :param name: + The name of the component. + :param callbacks: + Callbacks to invoke during deserialization. + :returns: + The deserialized component. + """ + + def component_pre_init_callback(component_cls, init_params): + assert callbacks is not None + assert callbacks.component_pre_init is not None + callbacks.component_pre_init(name, component_cls, init_params) + + def do_from_dict(): + if hasattr(cls, "from_dict"): + return cls.from_dict(data) + + return default_from_dict(cls, data) + + if callbacks is None or callbacks.component_pre_init is None: + return do_from_dict() + + with _hook_component_init(component_pre_init_callback): + return do_from_dict() + + +def default_to_dict(obj: Any, **init_parameters) -> Dict[str, Any]: + """ + Utility function to serialize an object to a dictionary. + + This is mostly necessary for components but can be used by any object. + `init_parameters` are parameters passed to the object class `__init__`. + They must be defined explicitly as they'll be used when creating a new + instance of `obj` with `from_dict`. Omitting them might cause deserialisation + errors or unexpected behaviours later, when calling `from_dict`. + + An example usage: + + ```python + class MyClass: + def __init__(self, my_param: int = 10): + self.my_param = my_param + + def to_dict(self): + return default_to_dict(self, my_param=self.my_param) + + + obj = MyClass(my_param=1000) + data = obj.to_dict() + assert data == { + "type": "MyClass", + "init_parameters": { + "my_param": 1000, + }, + } + ``` + + :param obj: + The object to be serialized. + :param init_parameters: + The parameters used to create a new instance of the class. + :returns: + A dictionary representation of the instance. + """ + return {"type": generate_qualified_class_name(type(obj)), "init_parameters": init_parameters} + + +def default_from_dict(cls: Type[object], data: Dict[str, Any]) -> Any: + """ + Utility function to deserialize a dictionary to an object. + + This is mostly necessary for components but can be used by any object. + + The function will raise a `DeserializationError` if the `type` field in `data` is + missing or it doesn't match the type of `cls`. + + If `data` contains an `init_parameters` field it will be used as parameters to create + a new instance of `cls`. + + :param cls: + The class to be used for deserialization. + :param data: + The serialized data. + :returns: + The deserialized object. + + :raises DeserializationError: + If the `type` field in `data` is missing or it doesn't match the type of `cls`. + """ + init_params = data.get("init_parameters", {}) + if "type" not in data: + raise DeserializationError("Missing 'type' in serialization data") + if data["type"] != generate_qualified_class_name(cls): + raise DeserializationError(f"Class '{data['type']}' can't be deserialized as '{cls.__name__}'") + return cls(**init_params) + + +def import_class_by_name(fully_qualified_name: str) -> Type[object]: + """ + Utility function to import (load) a class object based on its fully qualified class name. + + This function dynamically imports a class based on its string name. + It splits the name into module path and class name, imports the module, + and returns the class object. + + :param fully_qualified_name: the fully qualified class name as a string + :returns: the class object. + :raises ImportError: If the class cannot be imported or found. + """ + try: + module_path, class_name = fully_qualified_name.rsplit(".", 1) + logger.debug(f"Attempting to import class '{class_name}' from module '{module_path}'") + module = import_module(module_path) + return getattr(module, class_name) + except (ImportError, AttributeError) as error: + logger.error(f"Failed to import class '{fully_qualified_name}'") + raise ImportError(f"Could not import class '{fully_qualified_name}'") from error diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/type_utils.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/type_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..06651cd568853377d741c492d497226b01aca60e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/core/type_utils.py @@ -0,0 +1,84 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Union, get_args, get_origin + +from haystack import logging + +logger = logging.getLogger(__name__) + + +def _is_optional(type_: type) -> bool: + """ + Utility method that returns whether a type is Optional. + """ + return get_origin(type_) is Union and type(None) in get_args(type_) + + +def _types_are_compatible(sender, receiver): # pylint: disable=too-many-return-statements + """ + Checks whether the source type is equal or a subtype of the destination type. Used to validate pipeline connections. + + Note: this method has no pretense to perform proper type matching. It especially does not deal with aliasing of + typing classes such as `List` or `Dict` to their runtime counterparts `list` and `dict`. It also does not deal well + with "bare" types, so `List` is treated differently from `List[Any]`, even though they should be the same. + + Consider simplifying the typing of your components if you observe unexpected errors during component connection. + """ + if sender == receiver or receiver is Any: + return True + + if sender is Any: + return False + + try: + if issubclass(sender, receiver): + return True + except TypeError: # typing classes can't be used with issubclass, so we deal with them below + pass + + sender_origin = get_origin(sender) + receiver_origin = get_origin(receiver) + + if sender_origin is not Union and receiver_origin is Union: + return any(_types_are_compatible(sender, union_arg) for union_arg in get_args(receiver)) + + if not sender_origin or not receiver_origin or sender_origin != receiver_origin: + return False + + sender_args = get_args(sender) + receiver_args = get_args(receiver) + if len(sender_args) > len(receiver_args): + return False + + return all(_types_are_compatible(*args) for args in zip(sender_args, receiver_args)) + + +def _type_name(type_): + """ + Util methods to get a nice readable representation of a type. + + Handles Optional and Literal in a special way to make it more readable. + """ + # Literal args are strings, so we wrap them in quotes to make it clear + if isinstance(type_, str): + return f"'{type_}'" + + name = getattr(type_, "__name__", str(type_)) + + if name.startswith("typing."): + name = name[7:] + if "[" in name: + name = name.split("[")[0] + args = get_args(type_) + if name == "Union" and type(None) in args and len(args) == 2: + # Optional is technically a Union of type and None + # but we want to display it as Optional + name = "Optional" + + if args: + args = ", ".join([_type_name(a) for a in args if a is not type(None)]) + return f"{name}[{args}]" + + return f"{name}" diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..231ce8071347366c9116f7b9868f9fa1742470be --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/__init__.py @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.dataclasses.answer import Answer, ExtractedAnswer, GeneratedAnswer +from haystack.dataclasses.byte_stream import ByteStream +from haystack.dataclasses.chat_message import ChatMessage, ChatRole +from haystack.dataclasses.document import Document +from haystack.dataclasses.sparse_embedding import SparseEmbedding +from haystack.dataclasses.streaming_chunk import StreamingChunk + +__all__ = [ + "Document", + "ExtractedAnswer", + "GeneratedAnswer", + "Answer", + "ByteStream", + "ChatMessage", + "ChatRole", + "StreamingChunk", + "SparseEmbedding", +] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/answer.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/answer.py new file mode 100644 index 0000000000000000000000000000000000000000..edf0092f55e1eff033897d1263c0962bf1603fd1 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/answer.py @@ -0,0 +1,187 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import io +from dataclasses import asdict, dataclass, field +from typing import Any, Dict, List, Optional, Protocol, runtime_checkable + +from pandas import DataFrame, read_json + +from haystack.core.serialization import default_from_dict, default_to_dict +from haystack.dataclasses.document import Document + + +@runtime_checkable +@dataclass +class Answer(Protocol): + data: Any + query: str + meta: Dict[str, Any] + + def to_dict(self) -> Dict[str, Any]: # noqa: D102 + ... + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "Answer": # noqa: D102 + ... + + +@dataclass +class ExtractedAnswer: + query: str + score: float + data: Optional[str] = None + document: Optional[Document] = None + context: Optional[str] = None + document_offset: Optional["Span"] = None + context_offset: Optional["Span"] = None + meta: Dict[str, Any] = field(default_factory=dict) + + @dataclass + class Span: + start: int + end: int + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize the object to a dictionary. + + :returns: + Serialized dictionary representation of the object. + """ + document = self.document.to_dict(flatten=False) if self.document is not None else None + document_offset = asdict(self.document_offset) if self.document_offset is not None else None + context_offset = asdict(self.context_offset) if self.context_offset is not None else None + return default_to_dict( + self, + data=self.data, + query=self.query, + document=document, + context=self.context, + score=self.score, + document_offset=document_offset, + context_offset=context_offset, + meta=self.meta, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "ExtractedAnswer": + """ + Deserialize the object from a dictionary. + + :param data: + Dictionary representation of the object. + :returns: + Deserialized object. + """ + init_params = data.get("init_parameters", {}) + if (doc := init_params.get("document")) is not None: + data["init_parameters"]["document"] = Document.from_dict(doc) + + if (offset := init_params.get("document_offset")) is not None: + data["init_parameters"]["document_offset"] = ExtractedAnswer.Span(**offset) + + if (offset := init_params.get("context_offset")) is not None: + data["init_parameters"]["context_offset"] = ExtractedAnswer.Span(**offset) + return default_from_dict(cls, data) + + +@dataclass +class ExtractedTableAnswer: + query: str + score: float + data: Optional[str] = None + document: Optional[Document] = None + context: Optional[DataFrame] = None + document_cells: List["Cell"] = field(default_factory=list) + context_cells: List["Cell"] = field(default_factory=list) + meta: Dict[str, Any] = field(default_factory=dict) + + @dataclass + class Cell: + row: int + column: int + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize the object to a dictionary. + + :returns: + Serialized dictionary representation of the object. + """ + document = self.document.to_dict(flatten=False) if self.document is not None else None + context = self.context.to_json() if self.context is not None else None + document_cells = [asdict(c) for c in self.document_cells] + context_cells = [asdict(c) for c in self.context_cells] + return default_to_dict( + self, + data=self.data, + query=self.query, + document=document, + context=context, + score=self.score, + document_cells=document_cells, + context_cells=context_cells, + meta=self.meta, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "ExtractedTableAnswer": + """ + Deserialize the object from a dictionary. + + :param data: + Dictionary representation of the object. + + :returns: + Deserialized object. + """ + init_params = data.get("init_parameters", {}) + if (doc := init_params.get("document")) is not None: + data["init_parameters"]["document"] = Document.from_dict(doc) + + if (context := init_params.get("context")) is not None: + data["init_parameters"]["context"] = read_json(io.StringIO(context)) + + if (cells := init_params.get("document_cells")) is not None: + data["init_parameters"]["document_cells"] = [ExtractedTableAnswer.Cell(**c) for c in cells] + + if (cells := init_params.get("context_cells")) is not None: + data["init_parameters"]["context_cells"] = [ExtractedTableAnswer.Cell(**c) for c in cells] + return default_from_dict(cls, data) + + +@dataclass +class GeneratedAnswer: + data: str + query: str + documents: List[Document] + meta: Dict[str, Any] = field(default_factory=dict) + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize the object to a dictionary. + + :returns: + Serialized dictionary representation of the object. + """ + documents = [doc.to_dict(flatten=False) for doc in self.documents] + return default_to_dict(self, data=self.data, query=self.query, documents=documents, meta=self.meta) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "GeneratedAnswer": + """ + Deserialize the object from a dictionary. + + :param data: + Dictionary representation of the object. + + :returns: + Deserialized object. + """ + init_params = data.get("init_parameters", {}) + if (documents := init_params.get("documents")) is not None: + data["init_parameters"]["documents"] = [Document.from_dict(d) for d in documents] + + return default_from_dict(cls, data) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/byte_stream.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/byte_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..72a2648199503d6a186f13542e01e51ae4e17d59 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/byte_stream.py @@ -0,0 +1,65 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Dict, Optional + + +@dataclass +class ByteStream: + """ + Base data class representing a binary object in the Haystack API. + """ + + data: bytes + meta: Dict[str, Any] = field(default_factory=dict, hash=False) + mime_type: Optional[str] = field(default=None) + + def to_file(self, destination_path: Path): + """ + Write the ByteStream to a file. Note: the metadata will be lost. + + :param destination_path: The path to write the ByteStream to. + """ + with open(destination_path, "wb") as fd: + fd.write(self.data) + + @classmethod + def from_file_path( + cls, filepath: Path, mime_type: Optional[str] = None, meta: Optional[Dict[str, Any]] = None + ) -> "ByteStream": + """ + Create a ByteStream from the contents read from a file. + + :param filepath: A valid path to a file. + :param mime_type: The mime type of the file. + :param meta: Additional metadata to be stored with the ByteStream. + """ + with open(filepath, "rb") as fd: + return cls(data=fd.read(), mime_type=mime_type, meta=meta or {}) + + @classmethod + def from_string( + cls, text: str, encoding: str = "utf-8", mime_type: Optional[str] = None, meta: Optional[Dict[str, Any]] = None + ) -> "ByteStream": + """ + Create a ByteStream encoding a string. + + :param text: The string to encode + :param encoding: The encoding used to convert the string into bytes + :param mime_type: The mime type of the file. + :param meta: Additional metadata to be stored with the ByteStream. + """ + return cls(data=text.encode(encoding), mime_type=mime_type, meta=meta or {}) + + def to_string(self, encoding: str = "utf-8") -> str: + """ + Convert the ByteStream to a string, metadata will not be included. + + :param encoding: The encoding used to convert the bytes to a string. Defaults to "utf-8". + :returns: The string representation of the ByteStream. + :raises: UnicodeDecodeError: If the ByteStream data cannot be decoded with the specified encoding. + """ + return self.data.decode(encoding) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/chat_message.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/chat_message.py new file mode 100644 index 0000000000000000000000000000000000000000..4bfbe55820d7664ca18350fb4a293bce2df72845 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/chat_message.py @@ -0,0 +1,110 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import asdict, dataclass, field +from enum import Enum +from typing import Any, Dict, Optional + + +class ChatRole(str, Enum): + """Enumeration representing the roles within a chat.""" + + ASSISTANT = "assistant" + USER = "user" + SYSTEM = "system" + FUNCTION = "function" + + +@dataclass +class ChatMessage: + """ + Represents a message in a LLM chat conversation. + + :param content: The text content of the message. + :param role: The role of the entity sending the message. + :param name: The name of the function being called (only applicable for role FUNCTION). + :param meta: Additional metadata associated with the message. + """ + + content: str + role: ChatRole + name: Optional[str] + meta: Dict[str, Any] = field(default_factory=dict, hash=False) + + def is_from(self, role: ChatRole) -> bool: + """ + Check if the message is from a specific role. + + :param role: The role to check against. + :returns: True if the message is from the specified role, False otherwise. + """ + return self.role == role + + @classmethod + def from_assistant(cls, content: str, meta: Optional[Dict[str, Any]] = None) -> "ChatMessage": + """ + Create a message from the assistant. + + :param content: The text content of the message. + :param meta: Additional metadata associated with the message. + :returns: A new ChatMessage instance. + """ + return cls(content, ChatRole.ASSISTANT, None, meta or {}) + + @classmethod + def from_user(cls, content: str) -> "ChatMessage": + """ + Create a message from the user. + + :param content: The text content of the message. + :returns: A new ChatMessage instance. + """ + return cls(content, ChatRole.USER, None) + + @classmethod + def from_system(cls, content: str) -> "ChatMessage": + """ + Create a message from the system. + + :param content: The text content of the message. + :returns: A new ChatMessage instance. + """ + return cls(content, ChatRole.SYSTEM, None) + + @classmethod + def from_function(cls, content: str, name: str) -> "ChatMessage": + """ + Create a message from a function call. + + :param content: The text content of the message. + :param name: The name of the function being called. + :returns: A new ChatMessage instance. + """ + return cls(content, ChatRole.FUNCTION, name) + + def to_dict(self) -> Dict[str, Any]: + """ + Converts ChatMessage into a dictionary. + + :returns: + Serialized version of the object. + """ + data = asdict(self) + data["role"] = self.role.value + + return data + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "ChatMessage": + """ + Creates a new ChatMessage object from a dictionary. + + :param data: + The dictionary to build the ChatMessage object. + :returns: + The created object. + """ + data["role"] = ChatRole(data["role"]) + + return cls(**data) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/document.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/document.py new file mode 100644 index 0000000000000000000000000000000000000000..aed35964115b6ffbbaf3eba17ccc99b369958de4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/document.py @@ -0,0 +1,207 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import hashlib +import io +from dataclasses import asdict, dataclass, field, fields +from typing import Any, Dict, List, Optional + +from numpy import ndarray +from pandas import DataFrame, read_json + +from haystack import logging +from haystack.dataclasses.byte_stream import ByteStream +from haystack.dataclasses.sparse_embedding import SparseEmbedding + +logger = logging.getLogger(__name__) + + +class _BackwardCompatible(type): + """ + Metaclass that handles Document backward compatibility. + """ + + def __call__(cls, *args, **kwargs): + """ + Called before Document.__init__, will remap legacy fields to new ones. + + Also handles building a Document from a flattened dictionary. + """ + # Move `content` to new fields depending on the type + content = kwargs.get("content") + if isinstance(content, DataFrame): + kwargs["dataframe"] = content + del kwargs["content"] + + # Not used anymore + if "content_type" in kwargs: + del kwargs["content_type"] + + # Embedding were stored as NumPy arrays in 1.x, so we convert it to the new type + if isinstance(embedding := kwargs.get("embedding"), ndarray): + kwargs["embedding"] = embedding.tolist() + + # id_hash_keys is not used anymore + if "id_hash_keys" in kwargs: + del kwargs["id_hash_keys"] + + return super().__call__(*args, **kwargs) + + +@dataclass +class Document(metaclass=_BackwardCompatible): + """ + Base data class containing some data to be queried. + + Can contain text snippets, tables, and file paths to images or audios. Documents can be sorted by score and saved + to/from dictionary and JSON. + + :param id: Unique identifier for the document. When not set, it's generated based on the Document fields' values. + :param content: Text of the document, if the document contains text. + :param dataframe: Pandas dataframe with the document's content, if the document contains tabular data. + :param blob: Binary data associated with the document, if the document has any binary data associated with it. + :param meta: Additional custom metadata for the document. Must be JSON-serializable. + :param score: Score of the document. Used for ranking, usually assigned by retrievers. + :param embedding: dense vector representation of the document. + :param sparse_embedding: sparse vector representation of the document. + """ + + id: str = field(default="") + content: Optional[str] = field(default=None) + dataframe: Optional[DataFrame] = field(default=None) + blob: Optional[ByteStream] = field(default=None) + meta: Dict[str, Any] = field(default_factory=dict) + score: Optional[float] = field(default=None) + embedding: Optional[List[float]] = field(default=None) + sparse_embedding: Optional[SparseEmbedding] = field(default=None) + + def __repr__(self): + fields = [] + if self.content is not None: + fields.append( + f"content: '{self.content}'" if len(self.content) < 100 else f"content: '{self.content[:100]}...'" + ) + if self.dataframe is not None: + fields.append(f"dataframe: {self.dataframe.shape}") + if self.blob is not None: + fields.append(f"blob: {len(self.blob.data)} bytes") + if len(self.meta) > 0: + fields.append(f"meta: {self.meta}") + if self.score is not None: + fields.append(f"score: {self.score}") + if self.embedding is not None: + fields.append(f"embedding: vector of size {len(self.embedding)}") + if self.sparse_embedding is not None: + fields.append(f"sparse_embedding: vector with {len(self.sparse_embedding.indices)} non-zero elements") + fields_str = ", ".join(fields) + return f"{self.__class__.__name__}(id={self.id}, {fields_str})" + + def __eq__(self, other): + """ + Compares Documents for equality. + + Two Documents are considered equals if their dictionary representation is identical. + """ + if type(self) != type(other): + return False + return self.to_dict() == other.to_dict() + + def __post_init__(self): + """ + Generate the ID based on the init parameters. + """ + # Generate an id only if not explicitly set + self.id = self.id or self._create_id() + + def _create_id(self): + """ + Creates a hash of the given content that acts as the document's ID. + """ + text = self.content or None + dataframe = self.dataframe.to_json() if self.dataframe is not None else None + blob = self.blob.data if self.blob is not None else None + mime_type = self.blob.mime_type if self.blob is not None else None + meta = self.meta or {} + embedding = self.embedding if self.embedding is not None else None + sparse_embedding = self.sparse_embedding.to_dict() if self.sparse_embedding is not None else "" + data = f"{text}{dataframe}{blob}{mime_type}{meta}{embedding}{sparse_embedding}" + return hashlib.sha256(data.encode("utf-8")).hexdigest() + + def to_dict(self, flatten=True) -> Dict[str, Any]: + """ + Converts Document into a dictionary. + + `dataframe` and `blob` fields are converted to JSON-serializable types. + + :param flatten: + Whether to flatten `meta` field or not. Defaults to `True` to be backward-compatible with Haystack 1.x. + """ + data = asdict(self) + if (dataframe := data.get("dataframe")) is not None: + data["dataframe"] = dataframe.to_json() + if (blob := data.get("blob")) is not None: + data["blob"] = {"data": list(blob["data"]), "mime_type": blob["mime_type"]} + + if flatten: + meta = data.pop("meta") + return {**data, **meta} + + return data + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "Document": + """ + Creates a new Document object from a dictionary. + + The `dataframe` and `blob` fields are converted to their original types. + """ + if (dataframe := data.get("dataframe")) is not None: + data["dataframe"] = read_json(io.StringIO(dataframe)) + if blob := data.get("blob"): + data["blob"] = ByteStream(data=bytes(blob["data"]), mime_type=blob["mime_type"]) + if sparse_embedding := data.get("sparse_embedding"): + data["sparse_embedding"] = SparseEmbedding.from_dict(sparse_embedding) + + # Store metadata for a moment while we try un-flattening allegedly flatten metadata. + # We don't expect both a `meta=` keyword and flatten metadata keys so we'll raise a + # ValueError later if this is the case. + meta = data.pop("meta", {}) + # Unflatten metadata if it was flattened. We assume any keyword argument that's not + # a document field is a metadata key. We treat legacy fields as document fields + # for backward compatibility. + flatten_meta = {} + legacy_fields = ["content_type", "id_hash_keys"] + document_fields = legacy_fields + [f.name for f in fields(cls)] + for key in list(data.keys()): + if key not in document_fields: + flatten_meta[key] = data.pop(key) + + # We don't support passing both flatten keys and the `meta` keyword parameter + if meta and flatten_meta: + raise ValueError( + "You can pass either the 'meta' parameter or flattened metadata keys as keyword arguments, " + "but currently you're passing both. Pass either the 'meta' parameter or flattened metadata keys." + ) + + # Finally put back all the metadata + return cls(**data, meta={**meta, **flatten_meta}) + + @property + def content_type(self): + """ + Returns the type of the content for the document. + + This is necessary to keep backward compatibility with 1.x. + + :raises ValueError: + If both `text` and `dataframe` fields are set or both are missing. + """ + if self.content is not None and self.dataframe is not None: + raise ValueError("Both text and dataframe are set.") + + if self.content is not None: + return "text" + elif self.dataframe is not None: + return "table" + raise ValueError("Neither text nor dataframe is set.") diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/sparse_embedding.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/sparse_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..3f3c18c80742acecc69ea3922f3f8f44ec58907c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/sparse_embedding.py @@ -0,0 +1,49 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import asdict, dataclass +from typing import Any, Dict, List + + +@dataclass +class SparseEmbedding: + """ + Class representing a sparse embedding. + + :param indices: List of indices of non-zero elements in the embedding. + :param values: List of values of non-zero elements in the embedding. + """ + + indices: List[int] + values: List[float] + + def __post_init__(self): + """ + Checks if the indices and values lists are of the same length. + + Raises a ValueError if they are not. + """ + if len(self.indices) != len(self.values): + raise ValueError("Length of indices and values must be the same.") + + def to_dict(self) -> Dict[str, Any]: + """ + Convert the SparseEmbedding object to a dictionary. + + :returns: + Serialized sparse embedding. + """ + return asdict(self) + + @classmethod + def from_dict(cls, sparse_embedding_dict: Dict[str, Any]) -> "SparseEmbedding": + """ + Deserializes the sparse embedding from a dictionary. + + :param sparse_embedding_dict: + Dictionary to deserialize from. + :returns: + Deserialized sparse embedding. + """ + return cls(**sparse_embedding_dict) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/streaming_chunk.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/streaming_chunk.py new file mode 100644 index 0000000000000000000000000000000000000000..455caa09e285fd4cf8c9c361e6a83a3fdd063ad8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/dataclasses/streaming_chunk.py @@ -0,0 +1,21 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import dataclass, field +from typing import Any, Dict + + +@dataclass +class StreamingChunk: + """ + The StreamingChunk class encapsulates a segment of streamed content along with associated metadata. + + This structure facilitates the handling and processing of streamed data in a systematic manner. + + :param content: The content of the message chunk as a string. + :param meta: A dictionary containing metadata related to the message chunk. + """ + + content: str + meta: Dict[str, Any] = field(default_factory=dict, hash=False) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/errors/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/errors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d7c22cc78c49a1ff850036d75fbb3580cebecfd6 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/errors/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from .errors import DocumentStoreError, DuplicateDocumentError, MissingDocumentError + +__all__ = ["DocumentStoreError", "DuplicateDocumentError", "MissingDocumentError"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/errors/errors.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/errors/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..cc24e2cad6037c302b4a942d8315c8687b78d917 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/errors/errors.py @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + + +class DocumentStoreError(Exception): + pass + + +class DuplicateDocumentError(DocumentStoreError): + pass + + +class MissingDocumentError(DocumentStoreError): + pass diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/in_memory/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/in_memory/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..94d0b2e97f3a3ffd25033c430e630a96f055843f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/in_memory/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.document_stores.in_memory.document_store import InMemoryDocumentStore + +__all__ = ["InMemoryDocumentStore"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/in_memory/document_store.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/in_memory/document_store.py new file mode 100644 index 0000000000000000000000000000000000000000..245c55f78c9e0a18c430912b08c99cf83eb279f2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/in_memory/document_store.py @@ -0,0 +1,645 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +import math +import re +import uuid +from collections import Counter +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, Iterable, List, Literal, Optional, Tuple + +import numpy as np + +from haystack import default_from_dict, default_to_dict, logging +from haystack.dataclasses import Document +from haystack.document_stores.errors import DocumentStoreError, DuplicateDocumentError +from haystack.document_stores.types import DuplicatePolicy +from haystack.utils import expit +from haystack.utils.filters import document_matches_filter + +logger = logging.getLogger(__name__) + +# document scores are essentially unbounded and will be scaled to values between 0 and 1 if scale_score is set to +# True (default). Scaling uses the expit function (inverse of the logit function) after applying a scaling factor +# (e.g., BM25_SCALING_FACTOR for the bm25_retrieval method). +# Larger scaling factor decreases scaled scores. For example, an input of 10 is scaled to 0.99 with +# BM25_SCALING_FACTOR=2 but to 0.78 with BM25_SCALING_FACTOR=8 (default). The defaults were chosen empirically. +# Increase the default if most unscaled scores are larger than expected (>30) and otherwise would incorrectly all be +# mapped to scores ~1. +BM25_SCALING_FACTOR = 8 +DOT_PRODUCT_SCALING_FACTOR = 100 + + +@dataclass +class BM25DocumentStats: + """ + A dataclass for managing document statistics for BM25 retrieval. + + :param freq_token: A Counter of token frequencies in the document. + :param doc_len: Number of tokens in the document. + """ + + freq_token: Dict[str, int] + doc_len: int + + +# Global storage for all InMemoryDocumentStore instances, indexed by the index name. +_STORAGES: Dict[str, Dict[str, Document]] = {} +_BM25_STATS_STORAGES: Dict[str, Dict[str, BM25DocumentStats]] = {} +_AVERAGE_DOC_LEN_STORAGES: Dict[str, float] = {} +_FREQ_VOCAB_FOR_IDF_STORAGES: Dict[str, Counter] = {} + + +class InMemoryDocumentStore: + """ + Stores data in-memory. It's ephemeral and cannot be saved to disk. + """ + + def __init__( + self, + bm25_tokenization_regex: str = r"(?u)\b\w\w+\b", + bm25_algorithm: Literal["BM25Okapi", "BM25L", "BM25Plus"] = "BM25L", + bm25_parameters: Optional[Dict] = None, + embedding_similarity_function: Literal["dot_product", "cosine"] = "dot_product", + index: Optional[str] = None, + ): + """ + Initializes the DocumentStore. + + :param bm25_tokenization_regex: The regular expression used to tokenize the text for BM25 retrieval. + :param bm25_algorithm: The BM25 algorithm to use. One of "BM25Okapi", "BM25L", or "BM25Plus". + :param bm25_parameters: Parameters for BM25 implementation in a dictionary format. + For example: {'k1':1.5, 'b':0.75, 'epsilon':0.25} + You can learn more about these parameters by visiting https://github.com/dorianbrown/rank_bm25. + :param embedding_similarity_function: The similarity function used to compare Documents embeddings. + One of "dot_product" (default) or "cosine". To choose the most appropriate function, look for information + about your embedding model. + :param index: A specific index to store the documents. If not specified, a random UUID is used. + Using the same index allows you to store documents across multiple InMemoryDocumentStore instances. + """ + self.bm25_tokenization_regex = bm25_tokenization_regex + self.tokenizer = re.compile(bm25_tokenization_regex).findall + + if index is None: + index = str(uuid.uuid4()) + + self.index = index + if self.index not in _STORAGES: + _STORAGES[self.index] = {} + + self.bm25_algorithm = bm25_algorithm + self.bm25_algorithm_inst = self._dispatch_bm25() + self.bm25_parameters = bm25_parameters or {} + self.embedding_similarity_function = embedding_similarity_function + + # Per-document statistics + if self.index not in _BM25_STATS_STORAGES: + _BM25_STATS_STORAGES[self.index] = {} + + if self.index not in _AVERAGE_DOC_LEN_STORAGES: + _AVERAGE_DOC_LEN_STORAGES[self.index] = 0.0 + + if self.index not in _FREQ_VOCAB_FOR_IDF_STORAGES: + _FREQ_VOCAB_FOR_IDF_STORAGES[self.index] = Counter() + + @property + def storage(self) -> Dict[str, Document]: + """ + Utility property that returns the storage used by this instance of InMemoryDocumentStore. + """ + return _STORAGES.get(self.index, {}) + + @property + def _bm25_attr(self) -> Dict[str, BM25DocumentStats]: + return _BM25_STATS_STORAGES.get(self.index, {}) + + @property + def _avg_doc_len(self) -> float: + return _AVERAGE_DOC_LEN_STORAGES.get(self.index, 0.0) + + @_avg_doc_len.setter + def _avg_doc_len(self, value: float): + _AVERAGE_DOC_LEN_STORAGES[self.index] = value + + @property + def _freq_vocab_for_idf(self) -> Counter: + return _FREQ_VOCAB_FOR_IDF_STORAGES.get(self.index, Counter()) + + def _dispatch_bm25(self): + """ + Select the correct BM25 algorithm based on user specification. + + :returns: + The BM25 algorithm method. + """ + table = {"BM25Okapi": self._score_bm25okapi, "BM25L": self._score_bm25l, "BM25Plus": self._score_bm25plus} + + if self.bm25_algorithm not in table: + raise ValueError(f"BM25 algorithm '{self.bm25_algorithm}' is not supported.") + return table[self.bm25_algorithm] + + def _tokenize_bm25(self, text: str) -> List[str]: + """ + Tokenize text using the BM25 tokenization regex. + + Here we explicitly create a tokenization method to encapsulate + all pre-processing logic used to create BM25 tokens, such as + lowercasing. This helps track the exact tokenization process + used for BM25 scoring at any given time. + + :param text: + The text to tokenize. + :returns: + A list of tokens. + """ + text = text.lower() + return self.tokenizer(text) + + def _score_bm25l(self, query: str, documents: List[Document]) -> List[Tuple[Document, float]]: + """ + Calculate BM25L scores for the given query and filtered documents. + + :param query: + The query string. + :param documents: + The list of documents to score, should be produced by + the filter_documents method; may be an empty list. + :returns: + A list of tuples, each containing a Document and its BM25L score. + """ + k = self.bm25_parameters.get("k1", 1.5) + b = self.bm25_parameters.get("b", 0.75) + delta = self.bm25_parameters.get("delta", 0.5) + + def _compute_idf(tokens: List[str]) -> Dict[str, float]: + """Per-token IDF computation for all tokens.""" + idf = {} + n_corpus = len(self._bm25_attr) + for tok in tokens: + n = self._freq_vocab_for_idf.get(tok, 0) + idf[tok] = math.log((n_corpus + 1.0) / (n + 0.5)) * int(n != 0) + return idf + + def _compute_tf(token: str, freq: Dict[str, int], doc_len: int) -> float: + """Per-token BM25L computation.""" + freq_term = freq.get(token, 0.0) + ctd = freq_term / (1 - b + b * doc_len / self._avg_doc_len) + return (1.0 + k) * (ctd + delta) / (k + ctd + delta) + + idf = _compute_idf(self._tokenize_bm25(query)) + bm25_attr = {doc.id: self._bm25_attr[doc.id] for doc in documents} + + ret = [] + for doc in documents: + doc_stats = bm25_attr[doc.id] + freq = doc_stats.freq_token + doc_len = doc_stats.doc_len + + score = 0.0 + for tok in idf.keys(): # pylint: disable=consider-using-dict-items + score += idf[tok] * _compute_tf(tok, freq, doc_len) + ret.append((doc, score)) + + return ret + + def _score_bm25okapi(self, query: str, documents: List[Document]) -> List[Tuple[Document, float]]: + """ + Calculate BM25Okapi scores for the given query and filtered documents. + + :param query: + The query string. + :param documents: + The list of documents to score, should be produced by + the filter_documents method; may be an empty list. + :returns: + A list of tuples, each containing a Document and its BM25L score. + """ + k = self.bm25_parameters.get("k1", 1.5) + b = self.bm25_parameters.get("b", 0.75) + epsilon = self.bm25_parameters.get("epsilon", 0.25) + + def _compute_idf(tokens: List[str]) -> Dict[str, float]: + """Per-token IDF computation for all tokens.""" + sum_idf = 0.0 + neg_idf_tokens = [] + + # Although this is a global statistic, we compute it here + # to make the computation more self-contained. And the + # complexity is O(vocab_size), which is acceptable. + idf = {} + for tok, n in self._freq_vocab_for_idf.items(): + idf[tok] = math.log((len(self._bm25_attr) - n + 0.5) / (n + 0.5)) + sum_idf += idf[tok] + if idf[tok] < 0: + neg_idf_tokens.append(tok) + + eps = epsilon * sum_idf / len(self._freq_vocab_for_idf) + for tok in neg_idf_tokens: + idf[tok] = eps + return {tok: idf.get(tok, 0.0) for tok in tokens} + + def _compute_tf(token: str, freq: Dict[str, int], doc_len: int) -> float: + """Per-token BM25L computation.""" + freq_term = freq.get(token, 0.0) + freq_norm = freq_term + k * (1 - b + b * doc_len / self._avg_doc_len) + return freq_term * (1.0 + k) / freq_norm + + idf = _compute_idf(self._tokenize_bm25(query)) + bm25_attr = {doc.id: self._bm25_attr[doc.id] for doc in documents} + + ret = [] + for doc in documents: + doc_stats = bm25_attr[doc.id] + freq = doc_stats.freq_token + doc_len = doc_stats.doc_len + + score = 0.0 + for tok in idf.keys(): + score += idf[tok] * _compute_tf(tok, freq, doc_len) + ret.append((doc, score)) + + return ret + + def _score_bm25plus(self, query: str, documents: List[Document]) -> List[Tuple[Document, float]]: + """ + Calculate BM25+ scores for the given query and filtered documents. + + This implementation follows the document on BM25 Wikipedia page, + which add 1 (smoothing factor) to document frequency when computing IDF. + + :param query: + The query string. + :param documents: + The list of documents to score, should be produced by + the filter_documents method; may be an empty list. + :returns: + A list of tuples, each containing a Document and its BM25+ score. + """ + k = self.bm25_parameters.get("k1", 1.5) + b = self.bm25_parameters.get("b", 0.75) + delta = self.bm25_parameters.get("delta", 1.0) + + def _compute_idf(tokens: List[str]) -> Dict[str, float]: + """Per-token IDF computation.""" + idf = {} + n_corpus = len(self._bm25_attr) + for tok in tokens: + n = self._freq_vocab_for_idf.get(tok, 0) + idf[tok] = math.log(1 + (n_corpus - n + 0.5) / (n + 0.5)) * int(n != 0) + return idf + + def _compute_tf(token: str, freq: Dict[str, int], doc_len: float) -> float: + """Per-token normalized term frequency.""" + freq_term = freq.get(token, 0.0) + freq_damp = k * (1 - b + b * doc_len / self._avg_doc_len) + return freq_term * (1.0 + k) / (freq_term + freq_damp) + delta + + idf = _compute_idf(self._tokenize_bm25(query)) + bm25_attr = {doc.id: self._bm25_attr[doc.id] for doc in documents} + + ret = [] + for doc in documents: + doc_stats = bm25_attr[doc.id] + freq = doc_stats.freq_token + doc_len = doc_stats.doc_len + + score = 0.0 + for tok in idf.keys(): # pylint: disable=consider-using-dict-items + score += idf[tok] * _compute_tf(tok, freq, doc_len) + ret.append((doc, score)) + + return ret + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + bm25_tokenization_regex=self.bm25_tokenization_regex, + bm25_algorithm=self.bm25_algorithm, + bm25_parameters=self.bm25_parameters, + embedding_similarity_function=self.embedding_similarity_function, + index=self.index, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "InMemoryDocumentStore": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + return default_from_dict(cls, data) + + def save_to_disk(self, path: str) -> None: + """ + Write the database and its' data to disk as a JSON file. + + :param path: The path to the JSON file. + """ + data: Dict[str, Any] = self.to_dict() + data["documents"] = [doc.to_dict(flatten=False) for doc in self.storage.values()] + with open(path, "w") as f: + json.dump(data, f) + + @classmethod + def load_from_disk(cls, path: str) -> "InMemoryDocumentStore": + """ + Load the database and its' data from disk as a JSON file. + + :param path: The path to the JSON file. + :returns: The loaded InMemoryDocumentStore. + """ + if Path(path).exists(): + try: + with open(path, "r") as f: + data = json.load(f) + except Exception as e: + raise Exception(f"Error loading InMemoryDocumentStore from disk. error: {e}") + + documents = data.pop("documents") + cls_object = default_from_dict(cls, data) + cls_object.write_documents( + documents=[Document(**doc) for doc in documents], policy=DuplicatePolicy.OVERWRITE + ) + return cls_object + + else: + raise FileNotFoundError(f"File {path} not found.") + + def count_documents(self) -> int: + """ + Returns the number of how many documents are present in the DocumentStore. + """ + return len(self.storage.keys()) + + def filter_documents(self, filters: Optional[Dict[str, Any]] = None) -> List[Document]: + """ + Returns the documents that match the filters provided. + + For a detailed specification of the filters, refer to the DocumentStore.filter_documents() protocol + documentation. + + :param filters: The filters to apply to the document list. + :returns: A list of Documents that match the given filters. + """ + if filters: + if "operator" not in filters and "conditions" not in filters: + raise ValueError( + "Invalid filter syntax. See https://docs.haystack.deepset.ai/docs/metadata-filtering " + "for details." + ) + return [doc for doc in self.storage.values() if document_matches_filter(filters=filters, document=doc)] + return list(self.storage.values()) + + def write_documents(self, documents: List[Document], policy: DuplicatePolicy = DuplicatePolicy.NONE) -> int: + """ + Refer to the DocumentStore.write_documents() protocol documentation. + + If `policy` is set to `DuplicatePolicy.NONE` defaults to `DuplicatePolicy.FAIL`. + """ + if ( + not isinstance(documents, Iterable) + or isinstance(documents, str) + or any(not isinstance(doc, Document) for doc in documents) + ): + raise ValueError("Please provide a list of Documents.") + + if policy == DuplicatePolicy.NONE: + policy = DuplicatePolicy.FAIL + + written_documents = len(documents) + for document in documents: + if policy != DuplicatePolicy.OVERWRITE and document.id in self.storage.keys(): + if policy == DuplicatePolicy.FAIL: + raise DuplicateDocumentError(f"ID '{document.id}' already exists.") + if policy == DuplicatePolicy.SKIP: + logger.warning("ID '{document_id}' already exists", document_id=document.id) + written_documents -= 1 + continue + + # Since the statistics are updated in an incremental manner, + # we need to explicitly remove the existing document to revert + # the statistics before updating them with the new document. + if document.id in self.storage.keys(): + self.delete_documents([document.id]) + + # This processing logic is extracted from the original bm25_retrieval method. + # Since we are creating index incrementally before the first retrieval, + # we need to determine what content to use for indexing here, not at query time. + if document.content is not None: + if document.dataframe is not None: + logger.warning( + "Document '{document_id}' has both text and dataframe content. " + "Using text content for retrieval and skipping dataframe content.", + document_id=document.id, + ) + tokens = self._tokenize_bm25(document.content) + elif document.dataframe is not None: + str_content = document.dataframe.astype(str) + csv_content = str_content.to_csv(index=False) + tokens = self._tokenize_bm25(csv_content) + else: + tokens = [] + + self.storage[document.id] = document + + self._bm25_attr[document.id] = BM25DocumentStats(Counter(tokens), len(tokens)) + self._freq_vocab_for_idf.update(set(tokens)) + self._avg_doc_len = (len(tokens) + self._avg_doc_len * len(self._bm25_attr)) / (len(self._bm25_attr) + 1) + return written_documents + + def delete_documents(self, document_ids: List[str]) -> None: + """ + Deletes all documents with matching document_ids from the DocumentStore. + + :param document_ids: The object_ids to delete. + """ + for doc_id in document_ids: + if doc_id not in self.storage.keys(): + continue + del self.storage[doc_id] + + # Update statistics accordingly + doc_stats = self._bm25_attr.pop(doc_id) + freq = doc_stats.freq_token + doc_len = doc_stats.doc_len + + self._freq_vocab_for_idf.subtract(Counter(freq.keys())) + try: + self._avg_doc_len = (self._avg_doc_len * (len(self._bm25_attr) + 1) - doc_len) / len(self._bm25_attr) + except ZeroDivisionError: + self._avg_doc_len = 0 + + def bm25_retrieval( + self, query: str, filters: Optional[Dict[str, Any]] = None, top_k: int = 10, scale_score: bool = False + ) -> List[Document]: + """ + Retrieves documents that are most relevant to the query using BM25 algorithm. + + :param query: The query string. + :param filters: A dictionary with filters to narrow down the search space. + :param top_k: The number of top documents to retrieve. Default is 10. + :param scale_score: Whether to scale the scores of the retrieved documents. Default is False. + :returns: A list of the top_k documents most relevant to the query. + """ + if not query: + raise ValueError("Query should be a non-empty string") + + content_type_filter = { + "operator": "OR", + "conditions": [ + {"field": "content", "operator": "!=", "value": None}, + {"field": "dataframe", "operator": "!=", "value": None}, + ], + } + if filters: + if "operator" not in filters: + raise ValueError( + "Invalid filter syntax. See https://docs.haystack.deepset.ai/docs/metadata-filtering " + "for details." + ) + filters = {"operator": "AND", "conditions": [content_type_filter, filters]} + else: + filters = content_type_filter + + all_documents = self.filter_documents(filters=filters) + if len(all_documents) == 0: + logger.info("No documents found for BM25 retrieval. Returning empty list.") + return [] + + results = sorted(self.bm25_algorithm_inst(query, all_documents), key=lambda x: x[1], reverse=True)[:top_k] + + # BM25Okapi can return meaningful negative values, so they should not be filtered out when scale_score is False. + # It's the only algorithm supported by rank_bm25 at the time of writing (2024) that can return negative scores. + # see https://github.com/deepset-ai/haystack/pull/6889 for more context. + negatives_are_valid = self.bm25_algorithm == "BM25Okapi" and not scale_score + + # Create documents with the BM25 score to return them + return_documents = [] + for doc, score in results: + if scale_score: + score = expit(score / BM25_SCALING_FACTOR) + + if not negatives_are_valid and score <= 0.0: + continue + + doc_fields = doc.to_dict() + doc_fields["score"] = score + return_document = Document.from_dict(doc_fields) + return_documents.append(return_document) + + return return_documents + + def embedding_retrieval( + self, + query_embedding: List[float], + filters: Optional[Dict[str, Any]] = None, + top_k: int = 10, + scale_score: bool = False, + return_embedding: bool = False, + ) -> List[Document]: + """ + Retrieves documents that are most similar to the query embedding using a vector similarity metric. + + :param query_embedding: Embedding of the query. + :param filters: A dictionary with filters to narrow down the search space. + :param top_k: The number of top documents to retrieve. Default is 10. + :param scale_score: Whether to scale the scores of the retrieved Documents. Default is False. + :param return_embedding: Whether to return the embedding of the retrieved Documents. Default is False. + :returns: A list of the top_k documents most relevant to the query. + """ + if len(query_embedding) == 0 or not isinstance(query_embedding[0], float): + raise ValueError("query_embedding should be a non-empty list of floats.") + + filters = filters or {} + all_documents = self.filter_documents(filters=filters) + + documents_with_embeddings = [doc for doc in all_documents if doc.embedding is not None] + if len(documents_with_embeddings) == 0: + logger.warning( + "No Documents found with embeddings. Returning empty list. " + "To generate embeddings, use a DocumentEmbedder." + ) + return [] + elif len(documents_with_embeddings) < len(all_documents): + logger.info( + "Skipping some Documents that don't have an embedding. " + "To generate embeddings, use a DocumentEmbedder." + ) + + scores = self._compute_query_embedding_similarity_scores( + embedding=query_embedding, documents=documents_with_embeddings, scale_score=scale_score + ) + + # create Documents with the similarity score for the top k results + top_documents = [] + for doc, score in sorted(zip(documents_with_embeddings, scores), key=lambda x: x[1], reverse=True)[:top_k]: + doc_fields = doc.to_dict() + doc_fields["score"] = score + if return_embedding is False: + doc_fields["embedding"] = None + top_documents.append(Document.from_dict(doc_fields)) + + return top_documents + + def _compute_query_embedding_similarity_scores( + self, embedding: List[float], documents: List[Document], scale_score: bool = False + ) -> List[float]: + """ + Computes the similarity scores between the query embedding and the embeddings of the documents. + + :param embedding: Embedding of the query. + :param documents: A list of Documents. + :param scale_score: Whether to scale the scores of the Documents. Default is False. + :returns: A list of scores. + """ + + query_embedding = np.array(embedding) + if query_embedding.ndim == 1: + query_embedding = np.expand_dims(a=query_embedding, axis=0) + + try: + document_embeddings = np.array([doc.embedding for doc in documents]) + except ValueError as e: + if "inhomogeneous shape" in str(e): + raise DocumentStoreError( + "The embedding size of all Documents should be the same. " + "Please make sure that the Documents have been embedded with the same model." + ) from e + raise e + if document_embeddings.ndim == 1: + document_embeddings = np.expand_dims(a=document_embeddings, axis=0) + + if self.embedding_similarity_function == "cosine": + # cosine similarity is a normed dot product + query_embedding /= np.linalg.norm(x=query_embedding, axis=1, keepdims=True) + document_embeddings /= np.linalg.norm(x=document_embeddings, axis=1, keepdims=True) + + try: + scores = np.dot(a=query_embedding, b=document_embeddings.T)[0].tolist() + except ValueError as e: + if "shapes" in str(e) and "not aligned" in str(e): + raise DocumentStoreError( + "The embedding size of the query should be the same as the embedding size of the Documents. " + "Please make sure that the query has been embedded with the same model as the Documents." + ) from e + raise e + + if scale_score: + if self.embedding_similarity_function == "dot_product": + scores = [expit(float(score / DOT_PRODUCT_SCALING_FACTOR)) for score in scores] + elif self.embedding_similarity_function == "cosine": + scores = [(score + 1) / 2 for score in scores] + + return scores diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/types/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ed6becf8b41f2075c68bf5d8827452bea3d2587c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/types/__init__.py @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from .filter_policy import FilterPolicy, apply_filter_policy +from .policy import DuplicatePolicy +from .protocol import DocumentStore + +__all__ = ["apply_filter_policy", "DocumentStore", "DuplicatePolicy", "FilterPolicy"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/types/filter_policy.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/types/filter_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b0dc58d89563a02211a8e25db17df8f4e4de024c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/types/filter_policy.py @@ -0,0 +1,319 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from enum import Enum +from typing import Any, Dict, Literal, Optional + +from haystack import logging + +logger = logging.getLogger(__name__) + + +class FilterPolicy(Enum): + """ + Policy to determine how filters are applied in retrievers interacting with document stores. + """ + + # Runtime filters replace init filters during retriever run invocation. + REPLACE = "replace" + + # Runtime filters are merged with init filters, with runtime filters overwriting init values. + MERGE = "merge" + + def __str__(self): + return self.value + + @staticmethod + def from_str(filter_policy: str) -> "FilterPolicy": + """ + Convert a string to a FilterPolicy enum. + + :param filter_policy: The string to convert. + :return: The corresponding FilterPolicy enum. + """ + enum_map = {e.value.lower(): e for e in FilterPolicy} + policy = enum_map.get(filter_policy.lower() if filter_policy else "") + if policy is None: + msg = f"Unknown FilterPolicy type '{filter_policy}'. Supported types are: {list(enum_map.keys())}" + raise ValueError(msg) + return policy + + +def is_comparison_filter(filter_item: Dict[str, Any]) -> bool: + """ + Check if the given filter is a comparison filter. + + :param filter_item: The filter to check. + :returns: True if the filter is a comparison filter, False otherwise. + """ + return all(key in filter_item for key in ["field", "operator", "value"]) + + +def is_logical_filter(filter_item: Dict[str, Any]) -> bool: + """ + Check if the given filter is a logical filter. + + :param filter_item: The filter to check. + :returns: True if the filter is a logical filter, False otherwise. + """ + return "operator" in filter_item and "conditions" in filter_item + + +def combine_two_logical_filters( + init_logical_filter: Dict[str, Any], runtime_logical_filter: Dict[str, Any] +) -> Dict[str, Any]: + """ + Combine two logical filters, they must have the same operator. + + If `init_logical_filter["operator"]` and `runtime_logical_filter["operator"]` are the same, the conditions + of both filters are combined. Otherwise, the `init_logical_filter` is ignored and ` + runtime_logical_filter` is returned. + + __Example__: + + ```python + init_logical_filter = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + ] + } + runtime_logical_filter = { + "operator": "AND", + "conditions": [ + {"field": "meta.genre", "operator": "IN", "value": ["economy", "politics"]}, + {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, + ] + } + new_filters = combine_two_logical_filters( + init_logical_filter, runtime_logical_filter, "AND" + ) + # Output: + { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + {"field": "meta.genre", "operator": "IN", "value": ["economy", "politics"]}, + {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, + ] + } + ``` + """ + if init_logical_filter["operator"] == runtime_logical_filter["operator"]: + return { + "operator": str(init_logical_filter["operator"]), + "conditions": init_logical_filter["conditions"] + runtime_logical_filter["conditions"], + } + + logger.warning( + "The provided logical operators, {parsed_operator} and {operator}, do not match so the parsed logical " + "filter, {init_logical_filter}, will be ignored and only the provided logical filter,{runtime_logical_filter}, " + "will be used. Update the logical operators to match to include the parsed filter.", + parsed_operator=init_logical_filter["operator"], + operator=runtime_logical_filter["operator"], + init_logical_filter=init_logical_filter, + runtime_logical_filter=runtime_logical_filter, + ) + runtime_logical_filter["operator"] = str(runtime_logical_filter["operator"]) + return runtime_logical_filter + + +def combine_init_comparison_and_runtime_logical_filters( + init_comparison_filter: Dict[str, Any], + runtime_logical_filter: Dict[str, Any], + logical_operator: Literal["AND", "OR", "NOT"], +) -> Dict[str, Any]: + """ + Combine a runtime logical filter with the init comparison filter using the provided logical_operator. + + We only add the init_comparison_filter if logical_operator matches the existing + runtime_logical_filter["operator"]. Otherwise, we return the runtime_logical_filter unchanged. + + __Example__: + + ```python + runtime_logical_filter = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + ] + } + init_comparison_filter = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"} + new_filters = combine_init_comparison_and_runtime_logical_filters( + init_comparison_filter, runtime_logical_filter, "AND" + ) + # Output: + { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + ] + } + ``` + """ + if runtime_logical_filter["operator"] == logical_operator: + conditions = runtime_logical_filter["conditions"] + fields = {c.get("field") for c in conditions} + if init_comparison_filter["field"] not in fields: + conditions.append(init_comparison_filter) + else: + logger.warning( + "The init filter, {init_filter}, is ignored as the field is already present in the existing " + "filters, {filters}.", + init_filter=init_comparison_filter, + filters=runtime_logical_filter, + ) + return {"operator": str(runtime_logical_filter["operator"]), "conditions": conditions} + + logger.warning( + "The provided logical_operator, {logical_operator}, does not match the logical operator found in " + "the runtime filters, {filters_logical_operator}, so the init filter will be ignored.", + logical_operator=logical_operator, + filters_logical_operator=runtime_logical_filter["operator"], + ) + runtime_logical_filter["operator"] = str(runtime_logical_filter["operator"]) + return runtime_logical_filter + + +def combine_runtime_comparison_and_init_logical_filters( + runtime_comparison_filter: Dict[str, Any], + init_logical_filter: Dict[str, Any], + logical_operator: Literal["AND", "OR", "NOT"], +) -> Dict[str, Any]: + """ + Combine an init logical filter with the runtime comparison filter using the provided logical_operator. + + We only add the runtime_comparison_filter if logical_operator matches the existing + init_logical_filter["operator"]. Otherwise, we return the runtime_comparison_filter unchanged. + + __Example__: + + ```python + init_logical_filter = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + ] + } + runtime_comparison_filter = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"} + new_filters = combine_runtime_comparison_and_init_logical_filters( + runtime_comparison_filter, init_logical_filter, "AND" + ) + # Output: + { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + ] + } + ``` + """ + if init_logical_filter["operator"] == logical_operator: + conditions = init_logical_filter["conditions"] + fields = {c.get("field") for c in conditions} + if runtime_comparison_filter["field"] in fields: + logger.warning( + "The runtime filter, {runtime_filter}, will overwrite the existing filter with the same " + "field in the init logical filter.", + runtime_filter=runtime_comparison_filter, + ) + conditions = [c for c in conditions if c.get("field") != runtime_comparison_filter["field"]] + conditions.append(runtime_comparison_filter) + return {"operator": str(init_logical_filter["operator"]), "conditions": conditions} + + logger.warning( + "The provided logical_operator, {logical_operator}, does not match the logical operator found in " + "the init logical filter, {filters_logical_operator}, so the init logical filter will be ignored.", + logical_operator=logical_operator, + filters_logical_operator=init_logical_filter["operator"], + ) + return runtime_comparison_filter + + +def combine_two_comparison_filters( + init_comparison_filter: Dict[str, Any], + runtime_comparison_filter: Dict[str, Any], + logical_operator: Literal["AND", "OR", "NOT"], +) -> Dict[str, Any]: + """ + Combine a comparison filter with the `init_comparison_filter` using the provided `logical_operator`. + + If `runtime_comparison_filter` and `init_comparison_filter` target the same field, `init_comparison_filter` + is ignored and `runtime_comparison_filter` is returned unchanged. + + __Example__: + + ```python + runtime_comparison_filter = {"field": "meta.type", "operator": "==", "value": "article"}, + init_comparison_filter = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + new_filters = combine_two_comparison_filters( + init_comparison_filter, runtime_comparison_filter, "AND" + ) + # Output: + { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + ] + } + ``` + """ + if runtime_comparison_filter["field"] == init_comparison_filter["field"]: + logger.warning( + "The parsed filter, {parsed_filter}, is ignored as the field is already present in the existing " + "filters, {filters}.", + parsed_filter=init_comparison_filter, + filters=runtime_comparison_filter, + ) + return runtime_comparison_filter + + return {"operator": str(logical_operator), "conditions": [init_comparison_filter, runtime_comparison_filter]} + + +def apply_filter_policy( + filter_policy: FilterPolicy, + init_filters: Optional[Dict[str, Any]] = None, + runtime_filters: Optional[Dict[str, Any]] = None, + default_logical_operator: Literal["AND", "OR", "NOT"] = "AND", +) -> Optional[Dict[str, Any]]: + """ + Apply the filter policy to the given initial and runtime filters to determine the final set of filters used. + + The function combines or replaces the initial and runtime filters based on the specified filter policy. + + :param filter_policy: The policy to apply when handling the filters. It can be one of the following: + - `FilterPolicy.REPLACE`: Runtime filters will replace the initial filters. + - `FilterPolicy.MERGE`: Runtime filters will be merged with the initial filters. If there are overlapping keys, + values from the runtime filters will overwrite those from the initial filters. + :param init_filters: The initial filters set during the initialization of the relevant retriever. + :param runtime_filters: The filters provided at runtime, usually during a query operation execution. These filters + can change for each query/retriever run invocation. + :param default_logical_operator: The default logical operator to use when merging filters (non-legacy filters only). + :returns: A dictionary containing the resulting filters based on the provided policy. + """ + if filter_policy == FilterPolicy.MERGE and runtime_filters and init_filters: + # now we merge filters + if is_comparison_filter(init_filters) and is_comparison_filter(runtime_filters): + return combine_two_comparison_filters(init_filters, runtime_filters, default_logical_operator) + elif is_comparison_filter(init_filters) and is_logical_filter(runtime_filters): + return combine_init_comparison_and_runtime_logical_filters( + init_filters, runtime_filters, default_logical_operator + ) + elif is_logical_filter(init_filters) and is_comparison_filter(runtime_filters): + return combine_runtime_comparison_and_init_logical_filters( + runtime_filters, init_filters, default_logical_operator + ) + elif is_logical_filter(init_filters) and is_logical_filter(runtime_filters): + return combine_two_logical_filters(init_filters, runtime_filters) + + return runtime_filters or init_filters diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/types/policy.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/types/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d392b4914bc63bfae97114494e8385880c5fdb6f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/types/policy.py @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from enum import Enum + + +class DuplicatePolicy(Enum): + NONE = "none" + SKIP = "skip" + OVERWRITE = "overwrite" + FAIL = "fail" diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/types/protocol.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/types/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..e9ad3062cf857c462327fc9b61e308f65ba90bdf --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/document_stores/types/protocol.py @@ -0,0 +1,141 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional, Protocol + +from haystack import logging +from haystack.dataclasses import Document +from haystack.document_stores.types.policy import DuplicatePolicy + +# Ellipsis are needed for the type checker, it's safe to disable module-wide +# pylint: disable=unnecessary-ellipsis + +logger = logging.getLogger(__name__) + + +class DocumentStore(Protocol): + """ + Stores Documents to be used by the components of a Pipeline. + + Classes implementing this protocol often store the documents permanently and allow specialized components to + perform retrieval on them, either by embedding, by keyword, hybrid, and so on, depending on the backend used. + + In order to retrieve documents, consider using a Retriever that supports the DocumentStore implementation that + you're using. + """ + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes this store to a dictionary. + """ + ... + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "DocumentStore": + """ + Deserializes the store from a dictionary. + """ + ... + + def count_documents(self) -> int: + """ + Returns the number of documents stored. + """ + ... + + def filter_documents(self, filters: Optional[Dict[str, Any]] = None) -> List[Document]: + """ + Returns the documents that match the filters provided. + + Filters are defined as nested dictionaries that can be of two types: + - Comparison + - Logic + + Comparison dictionaries must contain the keys: + + - `field` + - `operator` + - `value` + + Logic dictionaries must contain the keys: + + - `operator` + - `conditions` + + The `conditions` key must be a list of dictionaries, either of type Comparison or Logic. + + The `operator` value in Comparison dictionaries must be one of: + + - `==` + - `!=` + - `>` + - `>=` + - `<` + - `<=` + - `in` + - `not in` + + The `operator` values in Logic dictionaries must be one of: + + - `NOT` + - `OR` + - `AND` + + + A simple filter: + ```python + filters = {"field": "meta.type", "operator": "==", "value": "article"} + ``` + + A more complex filter: + ```python + filters = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.date", "operator": ">=", "value": 1420066800}, + {"field": "meta.date", "operator": "<", "value": 1609455600}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + { + "operator": "OR", + "conditions": [ + {"field": "meta.genre", "operator": "in", "value": ["economy", "politics"]}, + {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, + ], + }, + ], + } + + :param filters: the filters to apply to the document list. + :returns: a list of Documents that match the given filters. + """ + ... + + def write_documents(self, documents: List[Document], policy: DuplicatePolicy = DuplicatePolicy.NONE) -> int: + """ + Writes Documents into the DocumentStore. + + :param documents: a list of Document objects. + :param policy: the policy to apply when a Document with the same id already exists in the DocumentStore. + - `DuplicatePolicy.NONE`: Default policy, behaviour depends on the Document Store. + - `DuplicatePolicy.SKIP`: If a Document with the same id already exists, it is skipped and not written. + - `DuplicatePolicy.OVERWRITE`: If a Document with the same id already exists, it is overwritten. + - `DuplicatePolicy.FAIL`: If a Document with the same id already exists, an error is raised. + :raises DuplicateError: If `policy` is set to `DuplicatePolicy.FAIL` and a Document with the same id already + exists. + :returns: The number of Documents written. + If `DuplicatePolicy.OVERWRITE` is used, this number is always equal to the number of documents in input. + If `DuplicatePolicy.SKIP` is used, this number can be lower than the number of documents in the input list. + """ + ... + + def delete_documents(self, document_ids: List[str]) -> None: + """ + Deletes all documents with a matching document_ids from the DocumentStore. + + Fails with `MissingDocumentError` if no document with this id is present in the DocumentStore. + + :param document_ids: the object_ids to delete + """ + ... diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/evaluation/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/evaluation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..734699a03f2ca779a68e9ea8c8baae406b242d75 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/evaluation/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from .base import BaseEvaluationRunResult +from .eval_run_result import EvaluationRunResult + +__all__ = ["BaseEvaluationRunResult", "EvaluationRunResult"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/evaluation/base.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/evaluation/base.py new file mode 100644 index 0000000000000000000000000000000000000000..617fa176381df53468e04dba85d75ee5f0237e70 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/evaluation/base.py @@ -0,0 +1,49 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from abc import ABC, abstractmethod +from typing import List, Optional + +from pandas import DataFrame + + +class BaseEvaluationRunResult(ABC): + """ + Represents the results of an evaluation run. + """ + + @abstractmethod + def to_pandas(self) -> "DataFrame": + """ + Creates a Pandas DataFrame containing the scores of each metric for every input sample. + + :returns: + Pandas DataFrame with the scores. + """ + + @abstractmethod + def score_report(self) -> "DataFrame": + """ + Transforms the results into a Pandas DataFrame with the aggregated scores for each metric. + + :returns: + Pandas DataFrame with the aggregated scores. + """ + + @abstractmethod + def comparative_individual_scores_report( + self, other: "BaseEvaluationRunResult", keep_columns: Optional[List[str]] = None + ) -> "DataFrame": + """ + Creates a Pandas DataFrame with the scores for each metric in the results of two different evaluation runs. + + The inputs to both evaluation runs is assumed to be the same. + + :param other: + Results of another evaluation run to compare with. + :param keep_columns: + List of common column names to keep from the inputs of the evaluation runs to compare. + :returns: + Pandas DataFrame with the score comparison. + """ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/evaluation/eval_run_result.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/evaluation/eval_run_result.py new file mode 100644 index 0000000000000000000000000000000000000000..1d04419ebe38fbd4aa8c115618a212dce13dc0ce --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/evaluation/eval_run_result.py @@ -0,0 +1,135 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from copy import deepcopy +from typing import Any, Dict, List, Optional +from warnings import warn + +from pandas import DataFrame +from pandas import concat as pd_concat + +from .base import BaseEvaluationRunResult + + +class EvaluationRunResult(BaseEvaluationRunResult): + """ + Contains the inputs and the outputs of an evaluation pipeline and provides methods to inspect them. + """ + + def __init__(self, run_name: str, inputs: Dict[str, List[Any]], results: Dict[str, Dict[str, Any]]): + """ + Initialize a new evaluation run result. + + :param run_name: + Name of the evaluation run. + :param inputs: + Dictionary containing the inputs used for the run. + Each key is the name of the input and its value is + a list of input values. The length of the lists should + be the same. + :param results: + Dictionary containing the results of the evaluators + used in the evaluation pipeline. Each key is the name + of the metric and its value is dictionary with the following + keys: + - 'score': The aggregated score for the metric. + - 'individual_scores': A list of scores for each input sample. + """ + self.run_name = run_name + self.inputs = deepcopy(inputs) + self.results = deepcopy(results) + + if len(inputs) == 0: + raise ValueError("No inputs provided.") + if len({len(l) for l in inputs.values()}) != 1: + raise ValueError("Lengths of the inputs should be the same.") + + expected_len = len(next(iter(inputs.values()))) + + for metric, outputs in results.items(): + if "score" not in outputs: + raise ValueError(f"Aggregate score missing for {metric}.") + if "individual_scores" not in outputs: + raise ValueError(f"Individual scores missing for {metric}.") + + if len(outputs["individual_scores"]) != expected_len: + raise ValueError( + f"Length of individual scores for '{metric}' should be the same as the inputs. " + f"Got {len(outputs['individual_scores'])} but expected {expected_len}." + ) + + def score_report(self) -> DataFrame: + """ + Transforms the results into a Pandas DataFrame with the aggregated scores for each metric. + + :returns: + Pandas DataFrame with the aggregated scores. + """ + results = {k: v["score"] for k, v in self.results.items()} + df = DataFrame.from_dict(results, orient="index", columns=["score"]).reset_index() + df.columns = ["metrics", "score"] + return df + + def to_pandas(self) -> DataFrame: + """ + Creates a Pandas DataFrame containing the scores of each metric for every input sample. + + :returns: + Pandas DataFrame with the scores. + """ + inputs_columns = list(self.inputs.keys()) + inputs_values = list(self.inputs.values()) + inputs_values = list(map(list, zip(*inputs_values))) # transpose the values + df_inputs = DataFrame(inputs_values, columns=inputs_columns) + + scores_columns = list(self.results.keys()) + scores_values = [v["individual_scores"] for v in self.results.values()] + scores_values = list(map(list, zip(*scores_values))) # transpose the values + df_scores = DataFrame(scores_values, columns=scores_columns) + + return df_inputs.join(df_scores) + + def comparative_individual_scores_report( + self, other: "BaseEvaluationRunResult", keep_columns: Optional[List[str]] = None + ) -> DataFrame: + """ + Creates a Pandas DataFrame with the scores for each metric in the results of two different evaluation runs. + + The inputs to both evaluation runs is assumed to be the same. + + :param other: + Results of another evaluation run to compare with. + :param keep_columns: + List of common column names to keep from the inputs of the evaluation runs to compare. + :returns: + Pandas DataFrame with the score comparison. + """ + if not isinstance(other, EvaluationRunResult): + raise ValueError("Comparative scores can only be computed between EvaluationRunResults.") + + this_name = self.run_name + other_name = other.run_name + if this_name == other_name: + warn(f"The run names of the two evaluation results are the same ('{this_name}')") + this_name = f"{this_name}_first" + other_name = f"{other_name}_second" + + if self.inputs.keys() != other.inputs.keys(): + warn(f"The input columns differ between the results; using the input columns of '{this_name}'.") + + pipe_a_df = self.to_pandas() + pipe_b_df = other.to_pandas() + + if keep_columns is None: + ignore = list(self.inputs.keys()) + else: + ignore = [col for col in list(self.inputs.keys()) if col not in keep_columns] + + pipe_b_df.drop(columns=ignore, inplace=True, errors="ignore") + pipe_b_df.columns = [f"{other_name}_{column}" for column in pipe_b_df.columns] # type: ignore + pipe_a_df.columns = [f"{this_name}_{col}" if col not in ignore else col for col in pipe_a_df.columns] # type: ignore + + results_df = pd_concat([pipe_a_df, pipe_b_df], axis=1) + + return results_df diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f52f1aa598cfa8121738db47605d60a33403bb1 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.marshal.protocol import Marshaller +from haystack.marshal.yaml import YamlMarshaller + +__all__ = ["Marshaller", "YamlMarshaller"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/__pycache__/__init__.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..007c37cddd26579c96cde3bd6b59f885a3826633 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/__pycache__/__init__.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/__pycache__/protocol.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/__pycache__/protocol.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6f2d6dfc1e68f6844270873cd671cfd202f1bc5 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/__pycache__/protocol.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/__pycache__/yaml.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/__pycache__/yaml.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90c1a895ea65947ec49549cad17d3dd73b4684f8 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/__pycache__/yaml.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/protocol.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..657f3cd67d19429105cd8def1acee19ed38159d4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/protocol.py @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, Protocol, Union + +# Ellipsis are needed for the type checker, it's safe to disable module-wide +# pylint: disable=unnecessary-ellipsis + + +class Marshaller(Protocol): + def marshal(self, dict_: Dict[str, Any]) -> str: + "Convert a dictionary to its string representation" + ... + + def unmarshal(self, data_: Union[str, bytes, bytearray]) -> Dict[str, Any]: + """Convert a marshalled object to its dictionary representation""" + ... diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/yaml.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/yaml.py new file mode 100644 index 0000000000000000000000000000000000000000..615cd1916a9838d700fac279744decd1d12c795e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/marshal/yaml.py @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, Union + +import yaml + + +# Custom YAML safe loader that supports loading Python tuples +class YamlLoader(yaml.SafeLoader): # pylint: disable=too-many-ancestors + def construct_python_tuple(self, node: yaml.SequenceNode): + """Construct a Python tuple from the sequence.""" + return tuple(self.construct_sequence(node)) + + +class YamlDumper(yaml.SafeDumper): # pylint: disable=too-many-ancestors + def represent_tuple(self, data: tuple): + """Represent a Python tuple.""" + return self.represent_sequence("tag:yaml.org,2002:python/tuple", data) + + +YamlDumper.add_representer(tuple, YamlDumper.represent_tuple) +YamlLoader.add_constructor("tag:yaml.org,2002:python/tuple", YamlLoader.construct_python_tuple) + + +class YamlMarshaller: + def marshal(self, dict_: Dict[str, Any]) -> str: + """Return a YAML representation of the given dictionary.""" + try: + return yaml.dump(dict_, Dumper=YamlDumper) + except yaml.representer.RepresenterError as e: + raise TypeError( + "Error dumping pipeline to YAML - Ensure that all pipeline " + "components only serialize basic Python types" + ) from e + + def unmarshal(self, data_: Union[str, bytes, bytearray]) -> Dict[str, Any]: + """Return a dictionary from the given YAML data.""" + try: + return yaml.load(data_, Loader=YamlLoader) + except yaml.constructor.ConstructorError as e: + raise TypeError( + "Error loading pipeline from YAML - Ensure that all pipeline " + "components only serialize basic Python types" + ) from e diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/telemetry/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/telemetry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6fa29de4d15cac65e6bc9c19146d3d9088b78385 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/telemetry/__init__.py @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.telemetry._telemetry import pipeline_running, tutorial_running diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/telemetry/_environment.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/telemetry/_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..f5c92b9e45da1374b1cc35143d81c3cfe0e43f94 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/telemetry/_environment.py @@ -0,0 +1,114 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +import platform +import sys +from typing import Any, Dict, Optional + +from haystack import logging +from haystack.version import __version__ + +logger = logging.getLogger(__name__) + +# This value cannot change during the lifetime of the process +_IS_DOCKER_CACHE = None + + +def _in_podman() -> bool: + """ + Check if the code is running in a Podman container. + + Podman run would create the file /run/.containernv, see: + https://github.com/containers/podman/blob/main/docs/source/markdown/podman-run.1.md.in#L31 + """ + return os.path.exists("/run/.containerenv") + + +def _has_dockerenv() -> bool: + """ + Check if the code is running in a Docker container. + + This might not work anymore at some point (even if it's been a while now), see: + https://github.com/moby/moby/issues/18355#issuecomment-220484748 + """ + return os.path.exists("/.dockerenv") + + +def _has_docker_cgroup_v1() -> bool: + """ + This only works with cgroups v1. + """ + path = "/proc/self/cgroup" # 'self' should be always symlinked to the actual PID + return os.path.isfile(path) and any("docker" in line for line in open(path)) + + +def _has_docker_cgroup_v2() -> bool: + """ + Check if the code is running in a Docker container using the cgroups v2 version. + + inspired from: https://github.com/jenkinsci/docker-workflow-plugin/blob/master/src/main/java/org/jenkinsci/plugins/docker/workflow/client/DockerClient.java + """ + path = "/proc/self/mountinfo" # 'self' should be always symlinked to the actual PID + return os.path.isfile(path) and any("/docker/containers/" in line for line in open(path)) + + +def _is_containerized() -> Optional[bool]: + """ + This code is based on the popular 'is-docker' package for node.js + """ + global _IS_DOCKER_CACHE # pylint: disable=global-statement + + if _IS_DOCKER_CACHE is None: + _IS_DOCKER_CACHE = _in_podman() or _has_dockerenv() or _has_docker_cgroup_v1() or _has_docker_cgroup_v2() + + return _IS_DOCKER_CACHE + + +def collect_system_specs() -> Dict[str, Any]: + """ + Collects meta-data about the setup that is used with Haystack. + + Data collected includes: operating system, python version, Haystack version, transformers version, + pytorch version, number of GPUs, execution environment. + + These values are highly unlikely to change during the runtime of the pipeline, + so they're collected only once. + """ + specs = { + "libraries.haystack": __version__, + "os.containerized": _is_containerized(), + "os.version": platform.release(), + "os.family": platform.system(), + "os.machine": platform.machine(), + "python.version": platform.python_version(), + "hardware.cpus": os.cpu_count(), + "hardware.gpus": 0, + "libraries.transformers": False, + "libraries.torch": False, + "libraries.cuda": False, + "libraries.pytest": sys.modules["pytest"].__version__ if "pytest" in sys.modules.keys() else False, + "libraries.ipython": sys.modules["ipython"].__version__ if "ipython" in sys.modules.keys() else False, + "libraries.colab": sys.modules["google.colab"].__version__ if "google.colab" in sys.modules.keys() else False, + } + + # Try to find out transformer's version + try: + import transformers + + specs["libraries.transformers"] = transformers.__version__ + except ImportError: + pass + + # Try to find out torch's version and info on potential GPU(s) + try: + import torch + + specs["libraries.torch"] = torch.__version__ + if torch.cuda.is_available(): + specs["libraries.cuda"] = torch.version.cuda + specs["libraries.gpus"] = torch.cuda.device_count() + except ImportError: + pass + return specs diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/telemetry/_telemetry.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/telemetry/_telemetry.py new file mode 100644 index 0000000000000000000000000000000000000000..f0cfbf269b0f8782c042b93133d734558275beda --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/telemetry/_telemetry.py @@ -0,0 +1,190 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import datetime +import logging +import os +import uuid +from collections import defaultdict +from pathlib import Path +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple + +import posthog +import yaml + +from haystack import logging as haystack_logging +from haystack.core.serialization import generate_qualified_class_name +from haystack.telemetry._environment import collect_system_specs + +if TYPE_CHECKING: + from haystack.core.pipeline import Pipeline + + +HAYSTACK_TELEMETRY_ENABLED = "HAYSTACK_TELEMETRY_ENABLED" +CONFIG_PATH = Path("~/.haystack/config.yaml").expanduser() + +#: Telemetry sends at most one event every number of seconds specified in this constant +MIN_SECONDS_BETWEEN_EVENTS = 60 + + +logger = haystack_logging.getLogger(__name__) + + +class Telemetry: + """ + Haystack reports anonymous usage statistics to support continuous software improvements for all its users. + + You can opt-out of sharing usage statistics by manually setting the environment + variable `HAYSTACK_TELEMETRY_ENABLED` as described for different operating systems on the + [documentation page](https://docs.haystack.deepset.ai/docs/telemetry#how-can-i-opt-out). + + Check out the documentation for more details: [Telemetry](https://docs.haystack.deepset.ai/docs/telemetry). + """ + + def __init__(self): + """ + Initializes the telemetry. + + Loads the user_id from the config file, or creates a new id and saves it if the file is not found. + + It also collects system information which cannot change across the lifecycle + of the process (for example `is_containerized()`). + """ + posthog.api_key = "phc_C44vUK9R1J6HYVdfJarTEPqVAoRPJzMXzFcj8PIrJgP" + posthog.host = "https://eu.posthog.com" + + # disable posthog logging + for module_name in ["posthog", "backoff"]: + logging.getLogger(module_name).setLevel(logging.CRITICAL) + # Prevent module from sending errors to stderr when an exception is encountered during an emit() call + logging.getLogger(module_name).addHandler(logging.NullHandler()) + logging.getLogger(module_name).propagate = False + + self.user_id = None + + if CONFIG_PATH.exists(): + # Load the config file + try: + with open(CONFIG_PATH, "r", encoding="utf-8") as config_file: + config = yaml.safe_load(config_file) + if "user_id" in config: + self.user_id = config["user_id"] + except Exception as e: + logger.debug( + "Telemetry could not read the config file {config_path}", config_path=CONFIG_PATH, exc_info=e + ) + else: + # Create the config file + logger.info( + "Haystack sends anonymous usage data to understand the actual usage and steer dev efforts " + "towards features that are most meaningful to users. You can opt-out at anytime by manually " + "setting the environment variable HAYSTACK_TELEMETRY_ENABLED as described for different " + "operating systems in the " + "[documentation page](https://docs.haystack.deepset.ai/docs/telemetry#how-can-i-opt-out). " + "More information at [Telemetry](https://docs.haystack.deepset.ai/docs/telemetry)." + ) + CONFIG_PATH.parents[0].mkdir(parents=True, exist_ok=True) + self.user_id = str(uuid.uuid4()) + try: + with open(CONFIG_PATH, "w") as outfile: + yaml.dump({"user_id": self.user_id}, outfile, default_flow_style=False) + except Exception as e: + logger.debug( + "Telemetry could not write config file to {config_path}", config_path=CONFIG_PATH, exc_info=e + ) + + self.event_properties = collect_system_specs() + + def send_event(self, event_name: str, event_properties: Optional[Dict[str, Any]] = None): + """ + Sends a telemetry event. + + :param event_name: The name of the event to show in PostHog. + :param event_properties: Additional event metadata. These are merged with the + system metadata collected in __init__, so take care not to overwrite them. + """ + event_properties = event_properties or {} + try: + posthog.capture( + distinct_id=self.user_id, event=event_name, properties={**self.event_properties, **event_properties} + ) + except Exception as e: + logger.debug("Telemetry couldn't make a POST request to PostHog.", exc_info=e) + + +def send_telemetry(func): + """ + Decorator that sends the output of the wrapped function to PostHog. + + The wrapped function is actually called only if telemetry is enabled. + """ + + # FIXME? Somehow, functools.wraps makes `telemetry` out of scope. Let's take care of it later. + def send_telemetry_wrapper(*args, **kwargs): + try: + if telemetry: + output = func(*args, **kwargs) + if output: + telemetry.send_event(*output) + except Exception as e: + # Never let telemetry break things + logger.debug("There was an issue sending a telemetry event", exc_info=e) + + return send_telemetry_wrapper + + +@send_telemetry +def pipeline_running(pipeline: "Pipeline") -> Optional[Tuple[str, Dict[str, Any]]]: + """ + Collects telemetry data for a pipeline run and sends it to Posthog. + + Collects name, type and the content of the _telemetry_data attribute, if present, for each component in the + pipeline and sends such data to Posthog. + + :param pipeline: the pipeline that is running. + """ + pipeline._telemetry_runs += 1 + if ( + pipeline._last_telemetry_sent + and (datetime.datetime.now() - pipeline._last_telemetry_sent).seconds < MIN_SECONDS_BETWEEN_EVENTS + ): + return None + + pipeline._last_telemetry_sent = datetime.datetime.now() + + # Collect info about components + components: Dict[str, List[Dict[str, Any]]] = defaultdict(list) + for component_name, instance in pipeline.walk(): + component_qualified_class_name = generate_qualified_class_name(type(instance)) + if hasattr(instance, "_get_telemetry_data"): + telemetry_data = getattr(instance, "_get_telemetry_data")() + if not isinstance(telemetry_data, dict): + raise TypeError( + f"Telemetry data for component {component_name} must be a dictionary but is {type(telemetry_data)}." + ) + components[component_qualified_class_name].append({"name": component_name, **telemetry_data}) + else: + components[component_qualified_class_name].append({"name": component_name}) + + # Data sent to Posthog + return "Pipeline run (2.x)", { + "pipeline_id": str(id(pipeline)), + "runs": pipeline._telemetry_runs, + "components": components, + } + + +@send_telemetry +def tutorial_running(tutorial_id: str) -> Tuple[str, Dict[str, Any]]: + """ + Send a telemetry event for a tutorial, if telemetry is enabled. + + :param tutorial_id: identifier of the tutorial + """ + return "Tutorial", {"tutorial.id": tutorial_id} + + +telemetry = None +if os.getenv("HAYSTACK_TELEMETRY_ENABLED", "true").lower() in ("true", "1"): + telemetry = Telemetry() diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/document_store.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/document_store.py new file mode 100644 index 0000000000000000000000000000000000000000..095a89e2a848cccd5941497cba911453c64666fb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/document_store.py @@ -0,0 +1,1349 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import random +from datetime import datetime +from typing import List + +import pandas as pd + +from haystack.dataclasses import Document +from haystack.document_stores.errors import DuplicateDocumentError +from haystack.document_stores.types import DocumentStore, DuplicatePolicy +from haystack.errors import FilterError +from haystack.lazy_imports import LazyImport + +with LazyImport("Run 'pip install pytest'") as pytest_import: + import pytest + + +def _random_embeddings(n): + return [random.random() for _ in range(n)] + + +# pylint: disable=too-many-public-methods + + +# These are random embedding that are used to test filters. +# We declare them here as they're used both in the `filterable_docs` fixture +# and the body of several `filter_documents` tests. +TEST_EMBEDDING_1 = _random_embeddings(768) +TEST_EMBEDDING_2 = _random_embeddings(768) + + +class AssertDocumentsEqualMixin: + def assert_documents_are_equal(self, received: List[Document], expected: List[Document]): + """ + Assert that two lists of Documents are equal. + + This is used in every test, if a Document Store implementation has a different behaviour + it should override this method. This can happen for example when the Document Store sets + a score to returned Documents. Since we can't know what the score will be, we can't compare + the Documents reliably. + """ + assert received == expected + + +class CountDocumentsTest: + """ + Utility class to test a Document Store `count_documents` method. + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(CountDocumentsTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_count_empty(self, document_store: DocumentStore): + """Test count is zero for an empty document store""" + assert document_store.count_documents() == 0 + + def test_count_not_empty(self, document_store: DocumentStore): + """Test count is greater than zero if the document store contains documents""" + document_store.write_documents( + [Document(content="test doc 1"), Document(content="test doc 2"), Document(content="test doc 3")] + ) + assert document_store.count_documents() == 3 + + +class WriteDocumentsTest(AssertDocumentsEqualMixin): + """ + Utility class to test a Document Store `write_documents` method. + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + The Document Store `filter_documents` method must be at least partly implemented to return all stored Documents + for this tests to work correctly. + Example usage: + + ```python + class MyDocumentStoreTest(WriteDocumentsTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_write_documents(self, document_store: DocumentStore): + """ + Test write_documents() default behaviour. + """ + msg = ( + "Default write_documents() behaviour depends on the Document Store implementation, " + "as we don't enforce a default behaviour when no policy is set. " + "Override this test in your custom test class." + ) + raise NotImplementedError(msg) + + def test_write_documents_duplicate_fail(self, document_store: DocumentStore): + """Test write_documents() fails when writing documents with same id and `DuplicatePolicy.FAIL`.""" + doc = Document(content="test doc") + assert document_store.write_documents([doc], policy=DuplicatePolicy.FAIL) == 1 + with pytest.raises(DuplicateDocumentError): + document_store.write_documents(documents=[doc], policy=DuplicatePolicy.FAIL) + self.assert_documents_are_equal(document_store.filter_documents(), [doc]) + + def test_write_documents_duplicate_skip(self, document_store: DocumentStore): + """Test write_documents() skips writing when using DuplicatePolicy.SKIP.""" + doc = Document(content="test doc") + assert document_store.write_documents([doc], policy=DuplicatePolicy.SKIP) == 1 + assert document_store.write_documents(documents=[doc], policy=DuplicatePolicy.SKIP) == 0 + + def test_write_documents_duplicate_overwrite(self, document_store: DocumentStore): + """Test write_documents() overwrites when using DuplicatePolicy.OVERWRITE.""" + doc1 = Document(id="1", content="test doc 1") + doc2 = Document(id="1", content="test doc 2") + + assert document_store.write_documents([doc2], policy=DuplicatePolicy.OVERWRITE) == 1 + self.assert_documents_are_equal(document_store.filter_documents(), [doc2]) + assert document_store.write_documents(documents=[doc1], policy=DuplicatePolicy.OVERWRITE) == 1 + self.assert_documents_are_equal(document_store.filter_documents(), [doc1]) + + def test_write_documents_invalid_input(self, document_store: DocumentStore): + """Test write_documents() fails when providing unexpected input.""" + with pytest.raises(ValueError): + document_store.write_documents(["not a document for sure"]) # type: ignore + with pytest.raises(ValueError): + document_store.write_documents("not a list actually") # type: ignore + + +class DeleteDocumentsTest: + """ + Utility class to test a Document Store `delete_documents` method. + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + The Document Store `write_documents` and `count_documents` methods must be implemented for this tests to work + correctly. + Example usage: + + ```python + class MyDocumentStoreTest(DeleteDocumentsTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_delete_documents(self, document_store: DocumentStore): + """Test delete_documents() normal behaviour.""" + doc = Document(content="test doc") + document_store.write_documents([doc]) + assert document_store.count_documents() == 1 + + document_store.delete_documents([doc.id]) + assert document_store.count_documents() == 0 + + def test_delete_documents_empty_document_store(self, document_store: DocumentStore): + """Test delete_documents() doesn't fail when called using an empty Document Store.""" + document_store.delete_documents(["non_existing_id"]) + + def test_delete_documents_non_existing_document(self, document_store: DocumentStore): + """Test delete_documents() doesn't delete any Document when called with non existing id.""" + doc = Document(content="test doc") + document_store.write_documents([doc]) + assert document_store.count_documents() == 1 + + document_store.delete_documents(["non_existing_id"]) + + # No Document has been deleted + assert document_store.count_documents() == 1 + + +class FilterableDocsFixtureMixin: + """ + Mixin class that adds a filterable_docs() fixture to a test class. + """ + + @pytest.fixture + def filterable_docs(self) -> List[Document]: + """Fixture that returns a list of Documents that can be used to test filtering.""" + documents = [] + for i in range(3): + documents.append( + Document( + content=f"A Foo Document {i}", + meta={ + "name": f"name_{i}", + "page": "100", + "chapter": "intro", + "number": 2, + "date": "1969-07-21T20:17:40", + }, + embedding=_random_embeddings(768), + ) + ) + documents.append( + Document( + content=f"A Bar Document {i}", + meta={ + "name": f"name_{i}", + "page": "123", + "chapter": "abstract", + "number": -2, + "date": "1972-12-11T19:54:58", + }, + embedding=_random_embeddings(768), + ) + ) + documents.append( + Document( + content=f"A Foobar Document {i}", + meta={ + "name": f"name_{i}", + "page": "90", + "chapter": "conclusion", + "number": -10, + "date": "1989-11-09T17:53:00", + }, + embedding=_random_embeddings(768), + ) + ) + documents.append( + Document( + content=f"Document {i} without embedding", + meta={"name": f"name_{i}", "no_embedding": True, "chapter": "conclusion"}, + ) + ) + documents.append(Document(dataframe=pd.DataFrame([i]), meta={"name": f"table_doc_{i}"})) + documents.append( + Document(content=f"Doc {i} with zeros emb", meta={"name": "zeros_doc"}, embedding=TEST_EMBEDDING_1) + ) + documents.append( + Document(content=f"Doc {i} with ones emb", meta={"name": "ones_doc"}, embedding=TEST_EMBEDDING_2) + ) + return documents + + +class LegacyFilterDocumentsInvalidFiltersTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using invalid legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsInvalidFiltersTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_incorrect_filter_type(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(ValueError): + document_store.filter_documents(filters="something odd") # type: ignore + + def test_incorrect_filter_nesting(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"number": {"page": "100"}}) + + def test_deeper_incorrect_filter_nesting(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"number": {"page": {"chapter": "intro"}}}) + + +class LegacyFilterDocumentsEqualTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using implicit and explicit '$eq' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsEqualTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_filter_document_content(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"content": "A Foo Document 1"}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.content == "A Foo Document 1"]) + + def test_filter_simple_metadata_value(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": "100"}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.meta.get("page") == "100"]) + + def test_filter_document_dataframe(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"dataframe": pd.DataFrame([1])}) + self.assert_documents_are_equal( + result, + [doc for doc in filterable_docs if doc.dataframe is not None and doc.dataframe.equals(pd.DataFrame([1]))], + ) + + def test_eq_filter_explicit(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": {"$eq": "100"}}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.meta.get("page") == "100"]) + + def test_eq_filter_implicit(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": "100"}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.meta.get("page") == "100"]) + + def test_eq_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"dataframe": pd.DataFrame([1])}) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if isinstance(doc.dataframe, pd.DataFrame) and doc.dataframe.equals(pd.DataFrame([1])) + ], + ) + + def test_eq_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + embedding = [0.0] * 768 + result = document_store.filter_documents(filters={"embedding": embedding}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if embedding == doc.embedding]) + + +class LegacyFilterDocumentsNotEqualTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using explicit '$ne' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsNotEqualTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_ne_filter(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": {"$ne": "100"}}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.meta.get("page") != "100"]) + + def test_ne_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"dataframe": {"$ne": pd.DataFrame([1])}}) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if not isinstance(doc.dataframe, pd.DataFrame) or not doc.dataframe.equals(pd.DataFrame([1])) + ], + ) + + def test_ne_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"embedding": {"$ne": TEST_EMBEDDING_1}}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.embedding != TEST_EMBEDDING_1]) + + +class LegacyFilterDocumentsInTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using implicit and explicit '$in' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsInTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_filter_simple_list_single_element(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": ["100"]}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.meta.get("page") == "100"]) + + def test_filter_simple_list_one_value(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": ["100"]}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.meta.get("page") in ["100"]]) + + def test_filter_simple_list(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": ["100", "123"]}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if doc.meta.get("page") in ["100", "123"]] + ) + + def test_incorrect_filter_name(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"non_existing_meta_field": ["whatever"]}) + self.assert_documents_are_equal(result, []) + + def test_incorrect_filter_value(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": ["nope"]}) + self.assert_documents_are_equal(result, []) + + def test_in_filter_explicit(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": {"$in": ["100", "123", "n.a."]}}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if doc.meta.get("page") in ["100", "123"]] + ) + + def test_in_filter_implicit(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": ["100", "123", "n.a."]}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if doc.meta.get("page") in ["100", "123"]] + ) + + def test_in_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"dataframe": {"$in": [pd.DataFrame([1]), pd.DataFrame([2])]}}) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if isinstance(doc.dataframe, pd.DataFrame) + and (doc.dataframe.equals(pd.DataFrame([1])) or doc.dataframe.equals(pd.DataFrame([2]))) + ], + ) + + def test_in_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + embedding_zero = [0.0] * 768 + embedding_one = [1.0] * 768 + result = document_store.filter_documents(filters={"embedding": {"$in": [embedding_zero, embedding_one]}}) + self.assert_documents_are_equal( + result, + [doc for doc in filterable_docs if (embedding_zero == doc.embedding or embedding_one == doc.embedding)], + ) + + +class LegacyFilterDocumentsNotInTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using explicit '$nin' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsNotInTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_nin_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + filters={"dataframe": {"$nin": [pd.DataFrame([1]), pd.DataFrame([0])]}} + ) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if not isinstance(doc.dataframe, pd.DataFrame) + or (not doc.dataframe.equals(pd.DataFrame([1])) and not doc.dataframe.equals(pd.DataFrame([0]))) + ], + ) + + def test_nin_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"embedding": {"$nin": [TEST_EMBEDDING_1, TEST_EMBEDDING_2]}}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if doc.embedding not in [TEST_EMBEDDING_1, TEST_EMBEDDING_2]] + ) + + def test_nin_filter(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": {"$nin": ["100", "123", "n.a."]}}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if doc.meta.get("page") not in ["100", "123"]] + ) + + +class LegacyFilterDocumentsGreaterThanTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using explicit '$gt' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsGreaterThanTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_gt_filter(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"number": {"$gt": 0.0}}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if "number" in doc.meta and doc.meta["number"] > 0] + ) + + def test_gt_filter_non_numeric(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"page": {"$gt": "100"}}) + + def test_gt_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"dataframe": {"$gt": pd.DataFrame([[1, 2, 3], [-1, -2, -3]])}}) + + def test_gt_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"embedding": {"$gt": TEST_EMBEDDING_1}}) + + +class LegacyFilterDocumentsGreaterThanEqualTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using explicit '$gte' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsGreaterThanEqualTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_gte_filter(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"number": {"$gte": -2}}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if "number" in doc.meta and doc.meta["number"] >= -2] + ) + + def test_gte_filter_non_numeric(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"page": {"$gte": "100"}}) + + def test_gte_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"dataframe": {"$gte": pd.DataFrame([[1, 2, 3], [-1, -2, -3]])}}) + + def test_gte_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"embedding": {"$gte": TEST_EMBEDDING_1}}) + + +class LegacyFilterDocumentsLessThanTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using explicit '$lt' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsLessThanTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_lt_filter(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"number": {"$lt": 0.0}}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if doc.meta.get("number") is not None and doc.meta["number"] < 0] + ) + + def test_lt_filter_non_numeric(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"page": {"$lt": "100"}}) + + def test_lt_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"dataframe": {"$lt": pd.DataFrame([[1, 2, 3], [-1, -2, -3]])}}) + + def test_lt_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"embedding": {"$lt": TEST_EMBEDDING_2}}) + + +class LegacyFilterDocumentsLessThanEqualTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using explicit '$lte' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsLessThanEqualTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_lte_filter(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"number": {"$lte": 2.0}}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if doc.meta.get("number") is not None and doc.meta["number"] <= 2.0] + ) + + def test_lte_filter_non_numeric(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"page": {"$lte": "100"}}) + + def test_lte_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"dataframe": {"$lte": pd.DataFrame([[1, 2, 3], [-1, -2, -3]])}}) + + def test_lte_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"embedding": {"$lte": TEST_EMBEDDING_1}}) + + +class LegacyFilterDocumentsSimpleLogicalTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using '$and', '$or' and '$not' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsSimpleLogicalTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_filter_simple_or(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + filters = {"$or": {"name": {"$in": ["name_0", "name_1"]}, "number": {"$lt": 1.0}}} + result = document_store.filter_documents(filters=filters) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if (doc.meta.get("number") is not None and doc.meta["number"] < 1) + or doc.meta.get("name") in ["name_0", "name_1"] + ], + ) + + def test_filter_simple_implicit_and_with_multi_key_dict( + self, document_store: DocumentStore, filterable_docs: List[Document] + ): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"number": {"$lte": 2.0, "$gte": 0.0}}) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if "number" in doc.meta and doc.meta["number"] >= 0.0 and doc.meta["number"] <= 2.0 + ], + ) + + def test_filter_simple_explicit_and_with_list(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"number": {"$and": [{"$lte": 2}, {"$gte": 0}]}}) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if "number" in doc.meta and doc.meta["number"] <= 2.0 and doc.meta["number"] >= 0.0 + ], + ) + + def test_filter_simple_implicit_and(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"number": {"$lte": 2.0, "$gte": 0}}) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if "number" in doc.meta and doc.meta["number"] <= 2.0 and doc.meta["number"] >= 0.0 + ], + ) + + +class LegacyFilterDocumentsNestedLogicalTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test `filter_documents` using multiple nested logical '$and', '$or' and '$not' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsNestedLogicalTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_filter_nested_implicit_and(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + filters_simplified = {"number": {"$lte": 2, "$gte": 0}, "name": ["name_0", "name_1"]} + result = document_store.filter_documents(filters=filters_simplified) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if ( + "number" in doc.meta + and doc.meta["number"] <= 2 + and doc.meta["number"] >= 0 + and doc.meta.get("name") in ["name_0", "name_1"] + ) + ], + ) + + def test_filter_nested_or(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + filters = {"$or": {"name": {"$or": [{"$eq": "name_0"}, {"$eq": "name_1"}]}, "number": {"$lt": 1.0}}} + result = document_store.filter_documents(filters=filters) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if ( + doc.meta.get("name") in ["name_0", "name_1"] + or (doc.meta.get("number") is not None and doc.meta["number"] < 1) + ) + ], + ) + + def test_filter_nested_and_or_explicit(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + filters_simplified = { + "$and": {"page": {"$eq": "123"}, "$or": {"name": {"$in": ["name_0", "name_1"]}, "number": {"$lt": 1.0}}} + } + result = document_store.filter_documents(filters=filters_simplified) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if ( + doc.meta.get("page") in ["123"] + and ( + doc.meta.get("name") in ["name_0", "name_1"] + or ("number" in doc.meta and doc.meta["number"] < 1) + ) + ) + ], + ) + + def test_filter_nested_and_or_implicit(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + filters_simplified = { + "page": {"$eq": "123"}, + "$or": {"name": {"$in": ["name_0", "name_1"]}, "number": {"$lt": 1.0}}, + } + result = document_store.filter_documents(filters=filters_simplified) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if ( + doc.meta.get("page") in ["123"] + and ( + doc.meta.get("name") in ["name_0", "name_1"] + or ("number" in doc.meta and doc.meta["number"] < 1) + ) + ) + ], + ) + + def test_filter_nested_or_and(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + filters_simplified = { + "$or": { + "number": {"$lt": 1}, + "$and": {"name": {"$in": ["name_0", "name_1"]}, "$not": {"chapter": {"$eq": "intro"}}}, + } + } + result = document_store.filter_documents(filters=filters_simplified) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if ( + (doc.meta.get("number") is not None and doc.meta["number"] < 1) + or (doc.meta.get("name") in ["name_0", "name_1"] and (doc.meta.get("chapter") != "intro")) + ) + ], + ) + + def test_filter_nested_multiple_identical_operators_same_level( + self, document_store: DocumentStore, filterable_docs: List[Document] + ): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + filters = { + "$or": [ + {"$and": {"name": {"$in": ["name_0", "name_1"]}, "page": "100"}}, + {"$and": {"chapter": {"$in": ["intro", "abstract"]}, "page": "123"}}, + ] + } + result = document_store.filter_documents(filters=filters) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if ( + (doc.meta.get("name") in ["name_0", "name_1"] and doc.meta.get("page") == "100") + or (doc.meta.get("chapter") in ["intro", "abstract"] and doc.meta.get("page") == "123") + ) + ], + ) + + +class LegacyFilterDocumentsTest( # pylint: disable=too-many-ancestors + LegacyFilterDocumentsInvalidFiltersTest, + LegacyFilterDocumentsEqualTest, + LegacyFilterDocumentsNotEqualTest, + LegacyFilterDocumentsInTest, + LegacyFilterDocumentsNotInTest, + LegacyFilterDocumentsGreaterThanTest, + LegacyFilterDocumentsGreaterThanEqualTest, + LegacyFilterDocumentsLessThanTest, + LegacyFilterDocumentsLessThanEqualTest, + LegacyFilterDocumentsSimpleLogicalTest, + LegacyFilterDocumentsNestedLogicalTest, +): + """ + Utility class to test a Document Store `filter_documents` method using different types of legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_no_filter_empty(self, document_store: DocumentStore): + """""" # noqa # pylint: disable=C0112 + assert document_store.filter_documents() == [] + assert document_store.filter_documents(filters={}) == [] + + def test_no_filter_not_empty(self, document_store: DocumentStore): + """""" # noqa # pylint: disable=C0112 + docs = [Document(content="test doc")] + document_store.write_documents(docs) + assert document_store.filter_documents() == docs + assert document_store.filter_documents(filters={}) == docs + + +class FilterDocumentsTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using different types of filters. + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(FilterDocumentsTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_no_filters(self, document_store): + """Test filter_documents() with empty filters""" + self.assert_documents_are_equal(document_store.filter_documents(), []) + self.assert_documents_are_equal(document_store.filter_documents(filters={}), []) + docs = [Document(content="test doc")] + document_store.write_documents(docs) + self.assert_documents_are_equal(document_store.filter_documents(), docs) + self.assert_documents_are_equal(document_store.filter_documents(filters={}), docs) + + # == comparator + def test_comparison_equal(self, document_store, filterable_docs): + """Test filter_documents() with == comparator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"field": "meta.number", "operator": "==", "value": 100}) + self.assert_documents_are_equal(result, [d for d in filterable_docs if d.meta.get("number") == 100]) + + def test_comparison_equal_with_dataframe(self, document_store, filterable_docs): + """Test filter_documents() with == comparator and dataframe""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + filters={"field": "dataframe", "operator": "==", "value": pd.DataFrame([1])} + ) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.dataframe is not None and d.dataframe.equals(pd.DataFrame([1]))] + ) + + def test_comparison_equal_with_none(self, document_store, filterable_docs): + """Test filter_documents() with == comparator and None""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"field": "meta.number", "operator": "==", "value": None}) + self.assert_documents_are_equal(result, [d for d in filterable_docs if d.meta.get("number") is None]) + + # != comparator + def test_comparison_not_equal(self, document_store, filterable_docs): + """Test filter_documents() with != comparator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents({"field": "meta.number", "operator": "!=", "value": 100}) + self.assert_documents_are_equal(result, [d for d in filterable_docs if d.meta.get("number") != 100]) + + def test_comparison_not_equal_with_dataframe(self, document_store, filterable_docs): + """Test filter_documents() with != comparator and dataframe""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + filters={"field": "dataframe", "operator": "!=", "value": pd.DataFrame([1])} + ) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.dataframe is None or not d.dataframe.equals(pd.DataFrame([1]))] + ) + + def test_comparison_not_equal_with_none(self, document_store, filterable_docs): + """Test filter_documents() with != comparator and None""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"field": "meta.number", "operator": "!=", "value": None}) + self.assert_documents_are_equal(result, [d for d in filterable_docs if d.meta.get("number") is not None]) + + # > comparator + def test_comparison_greater_than(self, document_store, filterable_docs): + """Test filter_documents() with > comparator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents({"field": "meta.number", "operator": ">", "value": 0}) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.meta.get("number") is not None and d.meta["number"] > 0] + ) + + def test_comparison_greater_than_with_iso_date(self, document_store, filterable_docs): + """Test filter_documents() with > comparator and datetime""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + {"field": "meta.date", "operator": ">", "value": "1972-12-11T19:54:58"} + ) + self.assert_documents_are_equal( + result, + [ + d + for d in filterable_docs + if d.meta.get("date") is not None + and datetime.fromisoformat(d.meta["date"]) > datetime.fromisoformat("1972-12-11T19:54:58") + ], + ) + + def test_comparison_greater_than_with_string(self, document_store, filterable_docs): + """Test filter_documents() with > comparator and string""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": ">", "value": "1"}) + + def test_comparison_greater_than_with_dataframe(self, document_store, filterable_docs): + """Test filter_documents() with > comparator and dataframe""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "dataframe", "operator": ">", "value": pd.DataFrame([1])}) + + def test_comparison_greater_than_with_list(self, document_store, filterable_docs): + """Test filter_documents() with > comparator and list""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": ">", "value": [1]}) + + def test_comparison_greater_than_with_none(self, document_store, filterable_docs): + """Test filter_documents() with > comparator and None""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"field": "meta.number", "operator": ">", "value": None}) + self.assert_documents_are_equal(result, []) + + # >= comparator + def test_comparison_greater_than_equal(self, document_store, filterable_docs): + """Test filter_documents() with >= comparator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents({"field": "meta.number", "operator": ">=", "value": 0}) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.meta.get("number") is not None and d.meta["number"] >= 0] + ) + + def test_comparison_greater_than_equal_with_iso_date(self, document_store, filterable_docs): + """Test filter_documents() with >= comparator and datetime""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + {"field": "meta.date", "operator": ">=", "value": "1969-07-21T20:17:40"} + ) + self.assert_documents_are_equal( + result, + [ + d + for d in filterable_docs + if d.meta.get("date") is not None + and datetime.fromisoformat(d.meta["date"]) >= datetime.fromisoformat("1969-07-21T20:17:40") + ], + ) + + def test_comparison_greater_than_equal_with_string(self, document_store, filterable_docs): + """Test filter_documents() with >= comparator and string""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": ">=", "value": "1"}) + + def test_comparison_greater_than_equal_with_dataframe(self, document_store, filterable_docs): + """Test filter_documents() with >= comparator and dataframe""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents( + filters={"field": "dataframe", "operator": ">=", "value": pd.DataFrame([1])} + ) + + def test_comparison_greater_than_equal_with_list(self, document_store, filterable_docs): + """Test filter_documents() with >= comparator and list""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": ">=", "value": [1]}) + + def test_comparison_greater_than_equal_with_none(self, document_store, filterable_docs): + """Test filter_documents() with >= comparator and None""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"field": "meta.number", "operator": ">=", "value": None}) + self.assert_documents_are_equal(result, []) + + # < comparator + def test_comparison_less_than(self, document_store, filterable_docs): + """Test filter_documents() with < comparator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents({"field": "meta.number", "operator": "<", "value": 0}) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.meta.get("number") is not None and d.meta["number"] < 0] + ) + + def test_comparison_less_than_with_iso_date(self, document_store, filterable_docs): + """Test filter_documents() with < comparator and datetime""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + {"field": "meta.date", "operator": "<", "value": "1969-07-21T20:17:40"} + ) + self.assert_documents_are_equal( + result, + [ + d + for d in filterable_docs + if d.meta.get("date") is not None + and datetime.fromisoformat(d.meta["date"]) < datetime.fromisoformat("1969-07-21T20:17:40") + ], + ) + + def test_comparison_less_than_with_string(self, document_store, filterable_docs): + """Test filter_documents() with < comparator and string""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": "<", "value": "1"}) + + def test_comparison_less_than_with_dataframe(self, document_store, filterable_docs): + """Test filter_documents() with < comparator and dataframe""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "dataframe", "operator": "<", "value": pd.DataFrame([1])}) + + def test_comparison_less_than_with_list(self, document_store, filterable_docs): + """Test filter_documents() with < comparator and list""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": "<", "value": [1]}) + + def test_comparison_less_than_with_none(self, document_store, filterable_docs): + """Test filter_documents() with < comparator and None""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"field": "meta.number", "operator": "<", "value": None}) + self.assert_documents_are_equal(result, []) + + # <= comparator + def test_comparison_less_than_equal(self, document_store, filterable_docs): + """Test filter_documents() with <=""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents({"field": "meta.number", "operator": "<=", "value": 0}) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.meta.get("number") is not None and d.meta["number"] <= 0] + ) + + def test_comparison_less_than_equal_with_iso_date(self, document_store, filterable_docs): + """Test filter_documents() with <= comparator and datetime""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + {"field": "meta.date", "operator": "<=", "value": "1969-07-21T20:17:40"} + ) + self.assert_documents_are_equal( + result, + [ + d + for d in filterable_docs + if d.meta.get("date") is not None + and datetime.fromisoformat(d.meta["date"]) <= datetime.fromisoformat("1969-07-21T20:17:40") + ], + ) + + def test_comparison_less_than_equal_with_string(self, document_store, filterable_docs): + """Test filter_documents() with <= comparator and string""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": "<=", "value": "1"}) + + def test_comparison_less_than_equal_with_dataframe(self, document_store, filterable_docs): + """Test filter_documents() with <= comparator and dataframe""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents( + filters={"field": "dataframe", "operator": "<=", "value": pd.DataFrame([1])} + ) + + def test_comparison_less_than_equal_with_list(self, document_store, filterable_docs): + """Test filter_documents() with <= comparator and list""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": "<=", "value": [1]}) + + def test_comparison_less_than_equal_with_none(self, document_store, filterable_docs): + """Test filter_documents() with <= comparator and None""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"field": "meta.number", "operator": "<=", "value": None}) + self.assert_documents_are_equal(result, []) + + # in comparator + def test_comparison_in(self, document_store, filterable_docs): + """Test filter_documents() with 'in' comparator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents({"field": "meta.number", "operator": "in", "value": [10, -10]}) + assert len(result) + expected = [d for d in filterable_docs if d.meta.get("number") is not None and d.meta["number"] in [10, -10]] + self.assert_documents_are_equal(result, expected) + + def test_comparison_in_with_with_non_list(self, document_store, filterable_docs): + """Test filter_documents() with 'in' comparator and non-iterable""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents({"field": "meta.number", "operator": "in", "value": 9}) + + def test_comparison_in_with_with_non_list_iterable(self, document_store, filterable_docs): + """Test filter_documents() with 'in' comparator and iterable""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents({"field": "meta.number", "operator": "in", "value": (10, 11)}) + + # not in comparator + def test_comparison_not_in(self, document_store, filterable_docs): + """Test filter_documents() with 'not in' comparator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents({"field": "meta.number", "operator": "not in", "value": [9, 10]}) + self.assert_documents_are_equal(result, [d for d in filterable_docs if d.meta.get("number") not in [9, 10]]) + + def test_comparison_not_in_with_with_non_list(self, document_store, filterable_docs): + """Test filter_documents() with 'not in' comparator and non-iterable""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents({"field": "meta.number", "operator": "not in", "value": 9}) + + def test_comparison_not_in_with_with_non_list_iterable(self, document_store, filterable_docs): + """Test filter_documents() with 'not in' comparator and iterable""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents({"field": "meta.number", "operator": "not in", "value": (10, 11)}) + + # Logical operator + def test_and_operator(self, document_store, filterable_docs): + """Test filter_documents() with 'AND' operator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + filters={ + "operator": "AND", + "conditions": [ + {"field": "meta.number", "operator": "==", "value": 100}, + {"field": "meta.name", "operator": "==", "value": "name_0"}, + ], + } + ) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.meta.get("number") == 100 and d.meta.get("name") == "name_0"] + ) + + def test_or_operator(self, document_store, filterable_docs): + """Test filter_documents() with 'OR' operator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + filters={ + "operator": "OR", + "conditions": [ + {"field": "meta.number", "operator": "==", "value": 100}, + {"field": "meta.name", "operator": "==", "value": "name_0"}, + ], + } + ) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.meta.get("number") == 100 or d.meta.get("name") == "name_0"] + ) + + def test_not_operator(self, document_store, filterable_docs): + """Test filter_documents() with 'NOT' operator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + filters={ + "operator": "NOT", + "conditions": [ + {"field": "meta.number", "operator": "==", "value": 100}, + {"field": "meta.name", "operator": "==", "value": "name_0"}, + ], + } + ) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if not (d.meta.get("number") == 100 and d.meta.get("name") == "name_0")] + ) + + # Malformed filters + def test_missing_top_level_operator_key(self, document_store, filterable_docs): + """Test filter_documents() with top-level operator""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents( + filters={"conditions": [{"field": "meta.name", "operator": "==", "value": "test"}]} + ) + + def test_missing_top_level_conditions_key(self, document_store, filterable_docs): + """Test filter_documents() with missing top-level condition key""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"operator": "AND"}) + + def test_missing_condition_field_key(self, document_store, filterable_docs): + """Test filter_documents() with missing condition key""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents( + filters={"operator": "AND", "conditions": [{"operator": "==", "value": "test"}]} + ) + + def test_missing_condition_operator_key(self, document_store, filterable_docs): + """Test filter_documents() with missing operator key""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents( + filters={"operator": "AND", "conditions": [{"field": "meta.name", "value": "test"}]} + ) + + def test_missing_condition_value_key(self, document_store, filterable_docs): + """Test filter_documents() with missing condition value""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents( + filters={"operator": "AND", "conditions": [{"field": "meta.name", "operator": "=="}]} + ) + + +class DocumentStoreBaseTests(CountDocumentsTest, WriteDocumentsTest, DeleteDocumentsTest, FilterDocumentsTest): + @pytest.fixture + def document_store(self) -> DocumentStore: + """Base fixture, to be reimplemented when deriving from DocumentStoreBaseTests""" + raise NotImplementedError() diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/factory.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..29d8fa7738109b536ba2d23ccfd2209cd0e593fd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/factory.py @@ -0,0 +1,233 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional, Tuple, Type, Union + +from haystack.core.component import Component, component +from haystack.core.serialization import default_from_dict, default_to_dict +from haystack.dataclasses import Document +from haystack.document_stores.types import DocumentStore, DuplicatePolicy + + +def document_store_class( + name: str, + documents: Optional[List[Document]] = None, + documents_count: Optional[int] = None, + bases: Optional[Tuple[type, ...]] = None, + extra_fields: Optional[Dict[str, Any]] = None, +) -> Type[DocumentStore]: + """ + Utility function to create a DocumentStore class with the given name and list of documents. + + If `documents` is set but `documents_count` is not, `documents_count` will be the length + of `documents`. + If both are set explicitly they don't influence each other. + + `write_documents()` and `delete_documents()` are no-op. + You can override them using `extra_fields`. + + ### Usage + + Create a DocumentStore class that returns no documents: + ```python + MyFakeStore = document_store_class("MyFakeComponent") + document_store = MyFakeStore() + assert document_store.documents_count() == 0 + assert document_store.filter_documents() == [] + ``` + + Create a DocumentStore class that returns a single document: + ```python + doc = Document(id="fake_id", content="Fake content") + MyFakeStore = document_store_class("MyFakeComponent", documents=[doc]) + document_store = MyFakeStore() + assert document_store.documents_count() == 1 + assert document_store.filter_documents() == [doc] + ``` + + Create a DocumentStore class that returns no document but returns a custom count: + ```python + MyFakeStore = document_store_class("MyFakeComponent", documents_count=100) + document_store = MyFakeStore() + assert document_store.documents_count() == 100 + assert document_store.filter_documents() == [] + ``` + + Create a DocumentStore class that returns a document and a custom count: + ```python + doc = Document(id="fake_id", content="Fake content") + MyFakeStore = document_store_class("MyFakeComponent", documents=[doc], documents_count=100) + document_store = MyFakeStore() + assert document_store.documents_count() == 100 + assert document_store.filter_documents() == [doc] + ``` + + Create a DocumentStore class with a custom base class: + ```python + MyFakeStore = document_store_class( + "MyFakeStore", + bases=(MyBaseClass,) + ) + document_store = MyFakeStore() + assert isinstance(store, MyBaseClass) + ``` + + Create a DocumentStore class with an extra field `my_field`: + ```python + MyFakeStore = document_store_class( + "MyFakeStore", + extra_fields={"my_field": 10} + ) + document_store = MyFakeStore() + assert document_store.my_field == 10 + ``` + """ + if documents is not None and documents_count is None: + documents_count = len(documents) + elif documents_count is None: + documents_count = 0 + + def count_documents(self) -> Union[int, None]: + return documents_count + + def filter_documents(self, filters: Optional[Dict[str, Any]] = None) -> List[Document]: + if documents is not None: + return documents + return [] + + def write_documents(self, documents: List[Document], policy: DuplicatePolicy = DuplicatePolicy.FAIL) -> None: + return + + def delete_documents(self, document_ids: List[str]) -> None: + return + + def to_dict(self) -> Dict[str, Any]: + return default_to_dict(self) + + fields = { + "count_documents": count_documents, + "filter_documents": filter_documents, + "write_documents": write_documents, + "delete_documents": delete_documents, + "to_dict": to_dict, + "from_dict": classmethod(default_from_dict), + } + + if extra_fields is not None: + fields = {**fields, **extra_fields} + + if bases is None: + bases = (object,) + + cls = type(name, bases, fields) + return cls + + +def component_class( + name: str, + input_types: Optional[Dict[str, Any]] = None, + output_types: Optional[Dict[str, Any]] = None, + output: Optional[Dict[str, Any]] = None, + bases: Optional[Tuple[type, ...]] = None, + extra_fields: Optional[Dict[str, Any]] = None, +) -> Type[Component]: + """ + Utility class to create a Component class with the given name and input and output types. + + If `output` is set but `output_types` is not, `output_types` will be set to the types of the values in `output`. + Though if `output_types` is set but `output` is not the component's `run` method will return a dictionary + of the same keys as `output_types` all with a value of None. + + ### Usage + + Create a component class with default input and output types: + ```python + MyFakeComponent = component_class_factory("MyFakeComponent") + component = MyFakeComponent() + output = component.run(value=1) + assert output == {"value": None} + ``` + + Create a component class with an "value" input of type `int` and with a "value" output of `10`: + ```python + MyFakeComponent = component_class_factory( + "MyFakeComponent", + input_types={"value": int}, + output={"value": 10} + ) + component = MyFakeComponent() + output = component.run(value=1) + assert output == {"value": 10} + ``` + + Create a component class with a custom base class: + ```python + MyFakeComponent = component_class_factory( + "MyFakeComponent", + bases=(MyBaseClass,) + ) + component = MyFakeComponent() + assert isinstance(component, MyBaseClass) + ``` + + Create a component class with an extra field `my_field`: + ```python + MyFakeComponent = component_class_factory( + "MyFakeComponent", + extra_fields={"my_field": 10} + ) + component = MyFakeComponent() + assert component.my_field == 10 + ``` + + Args: + name: Name of the component class + input_types: Dictionary of string and type that defines the inputs of the component, + if set to None created component will expect a single input "value" of Any type. + Defaults to None. + output_types: Dictionary of string and type that defines the outputs of the component, + if set to None created component will return a single output "value" of NoneType and None value. + Defaults to None. + output: Actual output dictionary returned by the created component run, + is set to None it will return a dictionary of string and None values. + Keys will be the same as the keys of output_types. Defaults to None. + bases: Base classes for this component, if set to None only base is object. Defaults to None. + extra_fields: Extra fields for the Component, defaults to None. + + :return: A class definition that can be used as a component. + """ + if input_types is None: + input_types = {"value": Any} + if output_types is None and output is not None: + output_types = {key: type(value) for key, value in output.items()} + elif output_types is None: + output_types = {"value": type(None)} + + def init(self): + component.set_input_types(self, **input_types) + component.set_output_types(self, **output_types) + + # Both arguments are necessary to correctly define + # run but pylint doesn't like that we don't use them. + # It's fine ignoring the warning here. + def run(self, **kwargs): # pylint: disable=unused-argument + if output is not None: + return output + return {name: None for name in output_types.keys()} + + def to_dict(self): + return default_to_dict(self) + + def from_dict(cls, data: Dict[str, Any]): + return default_from_dict(cls, data) + + fields = {"__init__": init, "run": run, "to_dict": to_dict, "from_dict": classmethod(from_dict)} + if extra_fields is not None: + fields = {**fields, **extra_fields} + + if bases is None: + bases = (object,) + + cls = type(name, bases, fields) + return component(cls) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1a42faf7a3d8deddeae8df3144981ae7eb6989ac --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/__init__.py @@ -0,0 +1,40 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.testing.sample_components.accumulate import Accumulate +from haystack.testing.sample_components.add_value import AddFixedValue +from haystack.testing.sample_components.concatenate import Concatenate +from haystack.testing.sample_components.double import Double +from haystack.testing.sample_components.fstring import FString +from haystack.testing.sample_components.greet import Greet +from haystack.testing.sample_components.hello import Hello +from haystack.testing.sample_components.joiner import StringJoiner, StringListJoiner +from haystack.testing.sample_components.parity import Parity +from haystack.testing.sample_components.remainder import Remainder +from haystack.testing.sample_components.repeat import Repeat +from haystack.testing.sample_components.self_loop import SelfLoop +from haystack.testing.sample_components.subtract import Subtract +from haystack.testing.sample_components.sum import Sum +from haystack.testing.sample_components.text_splitter import TextSplitter +from haystack.testing.sample_components.threshold import Threshold + +__all__ = [ + "Concatenate", + "Subtract", + "Parity", + "Remainder", + "Accumulate", + "Threshold", + "AddFixedValue", + "Repeat", + "Sum", + "Greet", + "Double", + "StringJoiner", + "Hello", + "TextSplitter", + "StringListJoiner", + "SelfLoop", + "FString", +] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/accumulate.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/accumulate.py new file mode 100644 index 0000000000000000000000000000000000000000..b2d0acec300cbf91d2af0bce91d250484775b642 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/accumulate.py @@ -0,0 +1,82 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import builtins +import sys +from importlib import import_module +from typing import Any, Callable, Dict, Optional + +from haystack.core.component import component +from haystack.core.errors import ComponentDeserializationError +from haystack.core.serialization import default_to_dict + + +def _default_function(first: int, second: int) -> int: + return first + second + + +@component +class Accumulate: + """ + Accumulates the value flowing through the connection into an internal attribute. + + The sum function can be customized. Example of how to deal with serialization when some of the parameters + are not directly serializable. + """ + + def __init__(self, function: Optional[Callable] = None): + """ + Class constructor + + :param function: + the function to use to accumulate the values. + The function must take exactly two values. + If it's a callable, it's used as it is. + If it's a string, the component will look for it in sys.modules and + import it at need. This is also a parameter. + """ + self.state = 0 + self.function: Callable = _default_function if function is None else function # type: ignore + + def to_dict(self) -> Dict[str, Any]: + """Converts the component to a dictionary""" + module = sys.modules.get(self.function.__module__) + if not module: + raise ValueError("Could not locate the import module.") + if module == builtins: + function_name = self.function.__name__ + else: + function_name = f"{module.__name__}.{self.function.__name__}" + + return default_to_dict(self, function=function_name) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "Accumulate": + """Loads the component from a dictionary""" + if "type" not in data: + raise ComponentDeserializationError("Missing 'type' in component serialization data") + if data["type"] != f"{cls.__module__}.{cls.__name__}": + raise ComponentDeserializationError(f"Class '{data['type']}' can't be deserialized as '{cls.__name__}'") + + init_params = data.get("init_parameters", {}) + + accumulator_function = None + if "function" in init_params: + parts = init_params["function"].split(".") + module_name = ".".join(parts[:-1]) + function_name = parts[-1] + module = import_module(module_name) + accumulator_function = getattr(module, function_name) + + return cls(function=accumulator_function) + + @component.output_types(value=int) + def run(self, value: int): + """ + Accumulates the value flowing through the connection into an internal attribute. + + The sum function can be customized. + """ + self.state = self.function(self.state, value) + return {"value": self.state} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/add_value.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/add_value.py new file mode 100644 index 0000000000000000000000000000000000000000..cc445a4cf6d4a2719f6c6064d11bf1540f42783a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/add_value.py @@ -0,0 +1,26 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Optional + +from haystack.core.component import component + + +@component +class AddFixedValue: + """ + Adds two values together. + """ + + def __init__(self, add: int = 1): + self.add = add + + @component.output_types(result=int) + def run(self, value: int, add: Optional[int] = None): + """ + Adds two values together. + """ + if add is None: + add = self.add + return {"result": value + add} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/concatenate.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/concatenate.py new file mode 100644 index 0000000000000000000000000000000000000000..023237ea78b4614e442c6b400616bdd50e7d8468 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/concatenate.py @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import List, Union + +from haystack.core.component import component + + +@component +class Concatenate: + """ + Concatenates two values + """ + + @component.output_types(value=List[str]) + def run(self, first: Union[List[str], str], second: Union[List[str], str]): + """ + Concatenates two values + """ + if isinstance(first, str) and isinstance(second, str): + res = [first, second] + elif isinstance(first, list) and isinstance(second, list): + res = first + second + elif isinstance(first, list) and isinstance(second, str): + res = first + [second] + elif isinstance(first, str) and isinstance(second, list): + res = [first] + second + else: + res = None + return {"value": res} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/double.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/double.py new file mode 100644 index 0000000000000000000000000000000000000000..42286ce141aa150c21818f9f7a4bc669165db0d2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/double.py @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.component import component + + +@component +class Double: + """ + Doubles the input value. + """ + + @component.output_types(value=int) + def run(self, value: int): + """ + Doubles the input value. + """ + return {"value": value * 2} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/fstring.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/fstring.py new file mode 100644 index 0000000000000000000000000000000000000000..a95bc3f41ba97b2828d4c0abbe7a3f6156c7888d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/fstring.py @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, List, Optional + +from haystack.core.component import component + + +@component +class FString: + """ + Takes a template string and a list of variables in input and returns the formatted string in output. + """ + + def __init__(self, template: str, variables: Optional[List[str]] = None): + self.template = template + self.variables = variables or [] + if "template" in self.variables: + raise ValueError("The variable name 'template' is reserved and cannot be used.") + component.set_input_types(self, **{variable: Any for variable in self.variables}) + + @component.output_types(string=str) + def run(self, template: Optional[str] = None, **kwargs): + """ + Takes a template string and a list of variables in input and returns the formatted string in output. + + If the template is not given, the component will use the one given at initialization. + """ + if not template: + template = self.template + return {"string": template.format(**kwargs)} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/greet.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/greet.py new file mode 100644 index 0000000000000000000000000000000000000000..4deed973a30bef0c225b441bcb47be68ef6069d2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/greet.py @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import logging +from typing import Optional + +import haystack.logging as haystack_logging +from haystack.core.component import component + +logger = haystack_logging.getLogger(__name__) + + +@component +class Greet: + """ + Logs a greeting message without affecting the value passing on the connection. + """ + + def __init__(self, message: str = "\nGreeting component says: Hi! The value is {value}\n", log_level: str = "INFO"): + """ + Class constructor + + :param message: the message to log. Can use `{value}` to embed the value. + :param log_level: the level to log at. + """ + if log_level and not getattr(logging, log_level): + raise ValueError(f"This log level does not exist: {log_level}") + self.message = message + self.log_level = log_level + + @component.output_types(value=int) + def run(self, value: int, message: Optional[str] = None, log_level: Optional[str] = None): + """ + Logs a greeting message without affecting the value passing on the connection. + """ + if not message: + message = self.message + if not log_level: + log_level = self.log_level + + level = getattr(logging, log_level, None) + if not level: + raise ValueError(f"This log level does not exist: {log_level}") + + logger.log(level=level, msg=message.format(value=value)) + return {"value": value} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/hello.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/hello.py new file mode 100644 index 0000000000000000000000000000000000000000..b60c57f3e839b3a546853fad6b7f1d4a4a5c1252 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/hello.py @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.component import component + + +@component +class Hello: + @component.output_types(output=str) + def run(self, word: str): + """Takes a string in input and returns "Hello, !"in output.""" + return {"output": f"Hello, {word}!"} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/joiner.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/joiner.py new file mode 100644 index 0000000000000000000000000000000000000000..8912c2ac9fde4e500d1c156bf7b9c55893f3ba2f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/joiner.py @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import List + +from haystack.core.component import component +from haystack.core.component.types import Variadic + + +@component +class StringJoiner: + @component.output_types(output=str) + def run(self, input_str: Variadic[str]): + """ + Take strings from multiple input nodes and join them into a single one returned in output. + + Since `input_str` is Variadic, we know we'll receive a List[str]. + """ + return {"output": " ".join(input_str)} + + +@component +class StringListJoiner: + @component.output_types(output=str) + def run(self, inputs: Variadic[List[str]]): + """ + Take list of strings from multiple input nodes and join them into a single one returned in output. + + Since `input_str` is Variadic, we know we'll receive a List[List[str]]. + """ + retval: List[str] = [] + for list_of_strings in inputs: + retval += list_of_strings + + return {"output": retval} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/parity.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/parity.py new file mode 100644 index 0000000000000000000000000000000000000000..5d219275abb39c4a745a82b7571599dfb00b84f9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/parity.py @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.component import component + + +@component +class Parity: # pylint: disable=too-few-public-methods + """ + Redirects the value, unchanged, along the 'even' connection if even, or along the 'odd' one if odd. + """ + + @component.output_types(even=int, odd=int) + def run(self, value: int): + """ + :param value: The value to check for parity + """ + remainder = value % 2 + if remainder: + return {"odd": value} + return {"even": value} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/remainder.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/remainder.py new file mode 100644 index 0000000000000000000000000000000000000000..89d74240bcfbf906a06eabb1c2c81bb983da0162 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/remainder.py @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.component import component + + +@component +class Remainder: + def __init__(self, divisor=3): + if divisor == 0: + raise ValueError("Can't divide by zero") + self.divisor = divisor + component.set_output_types(self, **{f"remainder_is_{val}": int for val in range(divisor)}) + + def run(self, value: int): + """ + :param value: the value to check the remainder of. + """ + remainder = value % self.divisor + output = {f"remainder_is_{remainder}": value} + return output diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/repeat.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/repeat.py new file mode 100644 index 0000000000000000000000000000000000000000..5cc41d742a9d76260a3a05b8e785bc0ea55bed07 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/repeat.py @@ -0,0 +1,20 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import List + +from haystack.core.component import component + + +@component +class Repeat: + def __init__(self, outputs: List[str]): + self._outputs = outputs + component.set_output_types(self, **{k: int for k in outputs}) + + def run(self, value: int): + """ + :param value: the value to repeat. + """ + return {val: value for val in self._outputs} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/self_loop.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/self_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..b29962ea89d9d5ad926c8f27f68fa5f0551be5c7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/self_loop.py @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.component import component +from haystack.core.component.types import Variadic + + +@component +class SelfLoop: + """ + Decreases the initial value in steps of 1 until the target value is reached. + + For no good reason it uses a self-loop to do so :) + """ + + def __init__(self, target: int = 0): + self.target = target + + @component.output_types(current_value=int, final_result=int) + def run(self, values: Variadic[int]): + """Decreases the input value in steps of 1 until the target value is reached.""" + value = values[0] # type: ignore + value -= 1 + if value == self.target: + return {"final_result": value} + return {"current_value": value} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/subtract.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/subtract.py new file mode 100644 index 0000000000000000000000000000000000000000..c0f8867f0158ff39aeb37699bcae26394fc9eef9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/subtract.py @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.component import component + + +@component +class Subtract: + """ + Compute the difference between two values. + """ + + @component.output_types(difference=int) + def run(self, first_value: int, second_value: int): + """ + Run the component. + + :param first_value: name of the connection carrying the value to subtract from. + :param second_value: name of the connection carrying the value to subtract. + """ + return {"difference": first_value - second_value} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/sum.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/sum.py new file mode 100644 index 0000000000000000000000000000000000000000..ca475f898b2229c7f6effac8512f3f7b0c8d771f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/sum.py @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.component import component +from haystack.core.component.types import Variadic + + +@component +class Sum: + @component.output_types(total=int) + def run(self, values: Variadic[int]): + """ + :param value: the values to sum. + """ + return {"total": sum(values)} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/text_splitter.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/text_splitter.py new file mode 100644 index 0000000000000000000000000000000000000000..8ad00460b87f5a3b508c763f1789742f3c522717 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/text_splitter.py @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import List + +from haystack.core.component import component + + +@component +class TextSplitter: + @component.output_types(output=List[str]) + def run(self, sentence: str): + """Takes a sentence in input and returns its words in output.""" + return {"output": sentence.split()} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/threshold.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/threshold.py new file mode 100644 index 0000000000000000000000000000000000000000..9cec4fa30fea1ceb81315924a5d6b730fd00a022 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/sample_components/threshold.py @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Optional + +from haystack.core.component import component + + +@component +class Threshold: # pylint: disable=too-few-public-methods + """ + Redirects the value, along a different connection whether the value is above or below the given threshold. + + :param threshold: the number to compare the input value against. This is also a parameter. + """ + + def __init__(self, threshold: int = 10): + """ + :param threshold: the number to compare the input value against. + """ + self.threshold = threshold + + @component.output_types(above=int, below=int) + def run(self, value: int, threshold: Optional[int] = None): + """ + Redirects the value, along a different connection whether the value is above or below the given threshold. + + :param threshold: the number to compare the input value against. This is also a parameter. + """ + if threshold is None: + threshold = self.threshold + + if value < threshold: + return {"below": value} + return {"above": value} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/test_utils.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..247bb2e3b6d2024e8477023dbab52988b52b7d56 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/testing/test_utils.py @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +import random + +from haystack import logging + +logger = logging.getLogger(__name__) + + +def set_all_seeds(seed: int, deterministic_cudnn: bool = False) -> None: + """ + Setting multiple seeds to make runs reproducible. + + Important: Enabling `deterministic_cudnn` gives you full reproducibility with CUDA, + but might slow down your training (see https://pytorch.org/docs/stable/notes/randomness.html#cudnn) ! + + :param seed:number to use as seed + :param deterministic_cudnn: Enable for full reproducibility when using CUDA. Caution: might slow down training. + """ + random.seed(seed) + os.environ["PYTHONHASHSEED"] = str(seed) + + try: + import torch + + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + if deterministic_cudnn: + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + + except (ImportError, ModuleNotFoundError) as exc: + logger.info("Could not set PyTorch seed because torch is not installed. Exception: {exception}", exception=exc) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ce07a0471d8ffc4706c8a6aafa02a603b15cc46b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/__init__.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.tracing.tracer import ( # noqa: I001 (otherwise we end up with partial imports) + Span, + Tracer, + auto_enable_tracing, + disable_tracing, + enable_tracing, + is_tracing_enabled, + tracer, +) +from haystack.tracing.opentelemetry import OpenTelemetryTracer diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/__pycache__/__init__.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88f68f64d9030c65bce5ad60e24895af4895998b Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/__pycache__/__init__.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/__pycache__/opentelemetry.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/__pycache__/opentelemetry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cabdc587abc1e2efefc0a62094293385690c962 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/__pycache__/opentelemetry.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/__pycache__/tracer.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/__pycache__/tracer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..643b21c8a892931465dd8459def53f9523d5d8dd Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/__pycache__/tracer.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/__pycache__/utils.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa9d1801aa2ae078732456371794f79316f4ec9a Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/__pycache__/utils.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/datadog.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/datadog.py new file mode 100644 index 0000000000000000000000000000000000000000..a1d0808e55eff347eb126fb63463c5b60f02ca9b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/datadog.py @@ -0,0 +1,79 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import contextlib +from typing import Any, Dict, Iterator, Optional + +from haystack.lazy_imports import LazyImport +from haystack.tracing import Span, Tracer +from haystack.tracing import utils as tracing_utils + +with LazyImport("Run 'pip install ddtrace'") as ddtrace_import: + import ddtrace + + +class DatadogSpan(Span): + def __init__(self, span: "ddtrace.Span") -> None: + self._span = span + + def set_tag(self, key: str, value: Any) -> None: + """ + Set a single tag on the span. + + :param key: the name of the tag. + :param value: the value of the tag. + """ + coerced_value = tracing_utils.coerce_tag_value(value) + self._span.set_tag(key, coerced_value) + + def raw_span(self) -> Any: + """ + Provides access to the underlying span object of the tracer. + + :return: The underlying span object. + """ + return self._span + + def get_correlation_data_for_logs(self) -> Dict[str, Any]: + """Return a dictionary with correlation data for logs.""" + raw_span = self.raw_span() + if not raw_span: + return {} + + # https://docs.datadoghq.com/tracing/other_telemetry/connect_logs_and_traces/python/#no-standard-library-logging + trace_id, span_id = (str((1 << 64) - 1 & raw_span.trace_id), raw_span.span_id) + + return { + "dd.trace_id": trace_id, + "dd.span_id": span_id, + "dd.service": ddtrace.config.service or "", + "dd.env": ddtrace.config.env or "", + "dd.version": ddtrace.config.version or "", + } + + +class DatadogTracer(Tracer): + def __init__(self, tracer: "ddtrace.Tracer") -> None: + ddtrace_import.check() + self._tracer = tracer + + @contextlib.contextmanager + def trace( + self, operation_name: str, tags: Optional[Dict[str, Any]] = None, parent_span: Optional[Span] = None + ) -> Iterator[Span]: + """Activate and return a new span that inherits from the current active span.""" + with self._tracer.trace(operation_name) as span: + custom_span = DatadogSpan(span) + if tags: + custom_span.set_tags(tags) + + yield custom_span + + def current_span(self) -> Optional[Span]: + """Return the current active span""" + current_span = self._tracer.current_span() + if current_span is None: + return None + + return DatadogSpan(current_span) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/logging_tracer.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/logging_tracer.py new file mode 100644 index 0000000000000000000000000000000000000000..166c484a903c6974ad11263f64a09f8d91aec6ed --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/logging_tracer.py @@ -0,0 +1,85 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import contextlib +import dataclasses +from typing import Any, Dict, Iterator, Optional + +from haystack import logging +from haystack.tracing import Span, Tracer + +logger = logging.getLogger(__name__) + +RESET_COLOR = "\033[0m" + + +@dataclasses.dataclass +class LoggingSpan(Span): + operation_name: str + tags: Dict[str, Any] = dataclasses.field(default_factory=dict) + + def set_tag(self, key: str, value: Any) -> None: + """ + Set a single tag on the span. + + :param key: the name of the tag. + :param value: the value of the tag. + """ + self.tags[key] = value + + +class LoggingTracer(Tracer): + """ + A simple tracer that logs the operation name and tags of a span. + """ + + def __init__(self, tags_color_strings: Optional[Dict[str, str]] = None) -> None: + """ + Initialize the LoggingTracer. + + :param tags_color_strings: + A dictionary that maps tag names to color strings that should be used when logging the tags. + The color strings should be in the format of + [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors). + For example, to color the tag "haystack.component.input" in red, you would pass + `tags_color_strings={"haystack.component.input": "\x1b[1;31m"}`. + """ + + self.tags_color_strings = tags_color_strings or {} + + @contextlib.contextmanager + def trace( + self, operation_name: str, tags: Optional[Dict[str, Any]] = None, parent_span: Optional[Span] = None + ) -> Iterator[Span]: + """ + Trace the execution of a block of code. + + :param operation_name: the name of the operation being traced. + :param tags: tags to apply to the newly created span. + :param parent_span: the parent span to use for the newly created span. Not used in this simple tracer. + :returns: the newly created span. + """ + + custom_span = LoggingSpan(operation_name, tags=tags or {}) + + try: + yield custom_span + except Exception as e: + raise e + # we make sure to log the operation name and tags of the span when the context manager exits + # both in case of success and error + finally: + operation_name = custom_span.operation_name + tags = custom_span.tags or {} + logger.debug("Operation: {operation_name}", operation_name=operation_name) + for tag_name, tag_value in tags.items(): + color_string = self.tags_color_strings.get(tag_name, "") + logger.debug( + color_string + "{tag_name}={tag_value}" + RESET_COLOR, tag_name=tag_name, tag_value=tag_value + ) + + def current_span(self) -> Optional[Span]: + """Return the current active span, if any.""" + # we don't store spans in this simple tracer + return None diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/opentelemetry.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/opentelemetry.py new file mode 100644 index 0000000000000000000000000000000000000000..88c61301cd60132cd1cac8f91573d2f08f68aa68 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/opentelemetry.py @@ -0,0 +1,68 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import contextlib +from typing import Any, Dict, Iterator, Optional + +from haystack.lazy_imports import LazyImport +from haystack.tracing import Span, Tracer +from haystack.tracing import utils as tracing_utils + +with LazyImport("Run 'pip install opentelemetry-sdk'") as opentelemetry_import: + import opentelemetry + import opentelemetry.trace + + +class OpenTelemetrySpan(Span): + def __init__(self, span: "opentelemetry.trace.Span") -> None: + self._span = span + + def set_tag(self, key: str, value: Any) -> None: + """ + Set a single tag on the span. + + :param key: the name of the tag. + :param value: the value of the tag. + """ + coerced_value = tracing_utils.coerce_tag_value(value) + self._span.set_attribute(key, coerced_value) + + def raw_span(self) -> Any: + """ + Provides access to the underlying span object of the tracer. + + :return: The underlying span object. + """ + return self._span + + def get_correlation_data_for_logs(self) -> Dict[str, Any]: + """Return a dictionary with correlation data for logs.""" + span_context = self._span.get_span_context() + return {"trace_id": span_context.trace_id, "span_id": span_context.span_id} + + +class OpenTelemetryTracer(Tracer): + def __init__(self, tracer: "opentelemetry.trace.Tracer") -> None: + opentelemetry_import.check() + self._tracer = tracer + + @contextlib.contextmanager + def trace( + self, operation_name: str, tags: Optional[Dict[str, Any]] = None, parent_span: Optional[Span] = None + ) -> Iterator[Span]: + """Activate and return a new span that inherits from the current active span.""" + with self._tracer.start_as_current_span(operation_name) as raw_span: + span = OpenTelemetrySpan(raw_span) + if tags: + span.set_tags(tags) + + yield span + + def current_span(self) -> Optional[Span]: + """Return the current active span""" + current_span = opentelemetry.trace.get_current_span() + if isinstance(current_span, opentelemetry.trace.NonRecordingSpan): + return None + + return OpenTelemetrySpan(current_span) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/tracer.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/tracer.py new file mode 100644 index 0000000000000000000000000000000000000000..4afe7e3db7cfdad73eba4abe7a164a5f89fbfaa9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/tracer.py @@ -0,0 +1,239 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import abc +import contextlib +import os +from typing import Any, Dict, Iterator, Optional + +from haystack import logging + +HAYSTACK_AUTO_TRACE_ENABLED_ENV_VAR = "HAYSTACK_AUTO_TRACE_ENABLED" +HAYSTACK_CONTENT_TRACING_ENABLED_ENV_VAR = "HAYSTACK_CONTENT_TRACING_ENABLED" + +logger = logging.getLogger(__name__) + + +class Span(abc.ABC): + """Interface for an instrumented operation.""" + + @abc.abstractmethod + def set_tag(self, key: str, value: Any) -> None: + """ + Set a single tag on the span. + + Note that the value will be serialized to a string, so it's best to use simple types like strings, numbers, or + booleans. + + :param key: the name of the tag. + :param value: the value of the tag. + """ + pass + + def set_tags(self, tags: Dict[str, Any]) -> None: + """ + Set multiple tags on the span. + + :param tags: a mapping of tag names to tag values. + """ + for key, value in tags.items(): + self.set_tag(key, value) + + def raw_span(self) -> Any: + """ + Provides access to the underlying span object of the tracer. + + Use this if you need full access to the underlying span object. + + :return: The underlying span object. + """ + return self + + def set_content_tag(self, key: str, value: Any) -> None: + """ + Set a single tag containing content information. + + Content is sensitive information such as + - the content of a query + - the content of a document + - the content of an answer + + By default, this behavior is disabled. To enable it + - set the environment variable `HAYSTACK_CONTENT_TRACING_ENABLED` to `true` or + - override the `set_content_tag` method in a custom tracer implementation. + + :param key: the name of the tag. + :param value: the value of the tag. + """ + if tracer.is_content_tracing_enabled: + self.set_tag(key, value) + + def get_correlation_data_for_logs(self) -> Dict[str, Any]: + """ + Return a dictionary with correlation data for logs. + + This is useful if you want to correlate logs with traces. + """ + return {} + + +class Tracer(abc.ABC): + """Interface for instrumenting code by creating and submitting spans.""" + + @abc.abstractmethod + @contextlib.contextmanager + def trace( + self, operation_name: str, tags: Optional[Dict[str, Any]] = None, parent_span: Optional[Span] = None + ) -> Iterator[Span]: + """ + Trace the execution of a block of code. + + :param operation_name: the name of the operation being traced. + :param tags: tags to apply to the newly created span. + :param parent_span: the parent span to use for the newly created span. + If `None`, the newly created span will be a root span. + :return: the newly created span. + """ + pass + + @abc.abstractmethod + def current_span(self) -> Optional[Span]: + """ + Returns the currently active span. If no span is active, returns `None`. + + :return: Currently active span or `None` if no span is active. + """ + pass + + +class ProxyTracer(Tracer): + """ + Container for the actual tracer instance. + + This eases + - replacing the actual tracer instance without having to change the global tracer instance + - implementing default behavior for the tracer + """ + + def __init__(self, provided_tracer: Tracer) -> None: + self.actual_tracer: Tracer = provided_tracer + self.is_content_tracing_enabled = os.getenv(HAYSTACK_CONTENT_TRACING_ENABLED_ENV_VAR, "false").lower() == "true" + + @contextlib.contextmanager + def trace( + self, operation_name: str, tags: Optional[Dict[str, Any]] = None, parent_span: Optional[Span] = None + ) -> Iterator[Span]: + """Activate and return a new span that inherits from the current active span.""" + with self.actual_tracer.trace(operation_name, tags=tags, parent_span=parent_span) as span: + yield span + + def current_span(self) -> Optional[Span]: + """Return the current active span""" + return self.actual_tracer.current_span() + + +class NullSpan(Span): + """A no-op implementation of the `Span` interface. This is used when tracing is disabled.""" + + def set_tag(self, key: str, value: Any) -> None: + """Set a single tag on the span.""" + pass + + +class NullTracer(Tracer): + """A no-op implementation of the `Tracer` interface. This is used when tracing is disabled.""" + + @contextlib.contextmanager + def trace( + self, operation_name: str, tags: Optional[Dict[str, Any]] = None, parent_span: Optional[Span] = None + ) -> Iterator[Span]: + """Activate and return a new span that inherits from the current active span.""" + yield NullSpan() + + def current_span(self) -> Optional[Span]: + """Return the current active span""" + return NullSpan() + + +# We use the proxy pattern to allow for easy enabling and disabling of tracing without having to change the global +# tracer instance. That's especially convenient if users import the object directly +# (in that case we'd have to monkey-patch it in all of these modules). +tracer: ProxyTracer = ProxyTracer(provided_tracer=NullTracer()) + + +def enable_tracing(provided_tracer: Tracer) -> None: + """Enable tracing by setting the global tracer instance.""" + tracer.actual_tracer = provided_tracer + + +def disable_tracing() -> None: + """Disable tracing by setting the global tracer instance to a no-op tracer.""" + tracer.actual_tracer = NullTracer() + + +def is_tracing_enabled() -> bool: + """Return whether tracing is enabled.""" + return not isinstance(tracer.actual_tracer, NullTracer) + + +def auto_enable_tracing() -> None: + """ + Auto-enable the right tracing backend. + + This behavior can be disabled by setting the environment variable `HAYSTACK_AUTO_TRACE_ENABLED` to `false`. + Note that it will only work correctly if tracing was configured _before_ Haystack is imported. + """ + if os.getenv(HAYSTACK_AUTO_TRACE_ENABLED_ENV_VAR, "true").lower() == "false": + logger.info( + "Tracing disabled via environment variable '{env_key}'", env_key=HAYSTACK_AUTO_TRACE_ENABLED_ENV_VAR + ) + return + + if is_tracing_enabled(): + return # tracing already enabled + + tracer = _auto_configured_opentelemetry_tracer() or _auto_configured_datadog_tracer() + if tracer: + enable_tracing(tracer) + logger.info("Auto-enabled tracing for '{tracer}'", tracer=tracer.__class__.__name__) + + +def _auto_configured_opentelemetry_tracer() -> Optional[Tracer]: + # we implement this here and not in the `opentelemetry` module to avoid import warnings when OpenTelemetry is not + # installed + try: + import opentelemetry.trace + + # the safest way to check if tracing is enabled is to try to start a span and see if it's a no-op span + # alternatively we could of course check `opentelemetry.trace._TRACER_PROVIDER` + # but that's not part of the public API and could change in the future + with opentelemetry.trace.get_tracer("haystack").start_as_current_span("haystack.tracing.auto_enable") as span: + if isinstance(span, opentelemetry.trace.NonRecordingSpan): + return None + + from haystack.tracing.opentelemetry import OpenTelemetryTracer + + return OpenTelemetryTracer(opentelemetry.trace.get_tracer("haystack")) + except ImportError: + pass + + return None + + +def _auto_configured_datadog_tracer() -> Optional[Tracer]: + # we implement this here and not in the `datadog` module to avoid import warnings when Datadog is not installed + try: + from ddtrace import tracer + + from haystack.tracing.datadog import DatadogTracer + + if tracer.enabled: + return DatadogTracer(tracer=tracer) + except ImportError: + pass + + return None + + +auto_enable_tracing() diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/utils.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0e87c63600848a70531b08877924f01774db1eeb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/tracing/utils.py @@ -0,0 +1,52 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +from typing import Any, Union + +from haystack import logging + +logger = logging.getLogger(__name__) + +PRIMITIVE_TYPES = (bool, str, int, float) + + +def coerce_tag_value(value: Any) -> Union[bool, str, int, float]: + """ + Coerces span tag values to compatible types for the tracing backend. + + Most tracing libraries don't support sending complex types to the backend. Hence, we need to convert them to + compatible types. + + :param value: an arbitrary value which should be coerced to a compatible type + :return: the value coerced to a compatible type + """ + if isinstance(value, PRIMITIVE_TYPES): + return value + + if value is None: + return "" + + try: + # do that with-in try-except because who knows what kind of objects are being passed + serializable = _serializable_value(value) + return json.dumps(serializable) + except Exception as error: + logger.debug("Failed to coerce tag value to string: {error}", error=error) + + # Our last resort is to convert the value to a string + return str(value) + + +def _serializable_value(value: Any) -> Any: + if isinstance(value, list): + return [_serializable_value(v) for v in value] + + if isinstance(value, dict): + return {k: _serializable_value(v) for k, v in value.items()} + + if getattr(value, "to_dict", None): + return _serializable_value(value.to_dict()) + + return value diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cc46f07f438832373b7bbabef6847606e2879446 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__init__.py @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from .auth import Secret, deserialize_secrets_inplace +from .callable_serialization import deserialize_callable, serialize_callable +from .device import ComponentDevice, Device, DeviceMap, DeviceType +from .docstore_deserialization import deserialize_document_store_in_init_params_inplace +from .expit import expit +from .filters import document_matches_filter, raise_on_invalid_filter_syntax +from .jinja2_extensions import Jinja2TimeExtension +from .jupyter import is_in_jupyter +from .requests_utils import request_with_retry +from .type_serialization import deserialize_type, serialize_type + +__all__ = [ + "Secret", + "deserialize_secrets_inplace", + "ComponentDevice", + "Device", + "DeviceMap", + "DeviceType", + "expit", + "document_matches_filter", + "raise_on_invalid_filter_syntax", + "is_in_jupyter", + "request_with_retry", + "serialize_callable", + "deserialize_callable", + "serialize_type", + "deserialize_type", + "deserialize_document_store_in_init_params_inplace", + "Jinja2TimeExtension", +] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/__init__.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c63df97b8cf45d943bcabd38f72f3216a0b5dfcd Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/auth.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/auth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bed5ef25761d8f19e3c45b641c1ba0bcb2c2998c Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/auth.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/callable_serialization.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/callable_serialization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92470f8e6e3d099beefd9176fba3a3c3f8186b3a Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/callable_serialization.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/device.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/device.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cffaf5d4f86d6b001352e11b8ee637bb34a006f Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/device.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/docstore_deserialization.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/docstore_deserialization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5228c33361bece67bc9f0f4b60e811c1c80a69bc Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/docstore_deserialization.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/expit.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/expit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae08fd47a4cf844eb58960ae67d62f6e182d09dc Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/__pycache__/expit.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/auth.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..61638f2057312a0668280dae009d47ef5d92629d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/auth.py @@ -0,0 +1,229 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +from abc import ABC, abstractmethod +from dataclasses import dataclass +from enum import Enum +from typing import Any, Dict, Iterable, List, Optional, Tuple, Union + + +class SecretType(Enum): + TOKEN = "token" + ENV_VAR = "env_var" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "SecretType": + """ + Convert a string to a SecretType. + + :param string: The string to convert. + """ + mapping = {e.value: e for e in SecretType} + _type = mapping.get(string) + if _type is None: + raise ValueError(f"Unknown secret type '{string}'") + return _type + + +class Secret(ABC): + """ + Encapsulates a secret used for authentication. + + Usage example: + ```python + from haystack.components.generators import OpenAIGenerator + from haystack.utils import Secret + + generator = OpenAIGenerator(api_key=Secret.from_token("")) + ``` + """ + + @staticmethod + def from_token(token: str) -> "Secret": + """ + Create a token-based secret. Cannot be serialized. + + :param token: + The token to use for authentication. + """ + return TokenSecret(_token=token) + + @staticmethod + def from_env_var(env_vars: Union[str, List[str]], *, strict: bool = True) -> "Secret": + """ + Create an environment variable-based secret. Accepts one or more environment variables. + + Upon resolution, it returns a string token from the first environment variable that is set. + + :param env_vars: + A single environment variable or an ordered list of + candidate environment variables. + :param strict: + Whether to raise an exception if none of the environment + variables are set. + """ + if isinstance(env_vars, str): + env_vars = [env_vars] + return EnvVarSecret(_env_vars=tuple(env_vars), _strict=strict) + + def to_dict(self) -> Dict[str, Any]: + """ + Convert the secret to a JSON-serializable dictionary. + + Some secrets may not be serializable. + + :returns: + The serialized policy. + """ + out = {"type": self.type.value} + inner = self._to_dict() + assert all(k not in inner for k in out.keys()) + out.update(inner) + return out + + @staticmethod + def from_dict(dict: Dict[str, Any]) -> "Secret": # noqa:A002 + """ + Create a secret from a JSON-serializable dictionary. + + :param dict: + The dictionary with the serialized data. + :returns: + The deserialized secret. + """ + secret_map = {SecretType.TOKEN: TokenSecret, SecretType.ENV_VAR: EnvVarSecret} + secret_type = SecretType.from_str(dict["type"]) + return secret_map[secret_type]._from_dict(dict) # type: ignore + + @abstractmethod + def resolve_value(self) -> Optional[Any]: + """ + Resolve the secret to an atomic value. The semantics of the value is secret-dependent. + + :returns: + The value of the secret, if any. + """ + pass + + @property + @abstractmethod + def type(self) -> SecretType: + """ + The type of the secret. + """ + pass + + @abstractmethod + def _to_dict(self) -> Dict[str, Any]: + pass + + @staticmethod + @abstractmethod + def _from_dict(_: Dict[str, Any]) -> "Secret": + pass + + +@dataclass(frozen=True) +class TokenSecret(Secret): + """ + A secret that uses a string token/API key. + + Cannot be serialized. + """ + + _token: str + _type: SecretType = SecretType.TOKEN + + def __post_init__(self): + super().__init__() + assert self._type == SecretType.TOKEN + + if len(self._token) == 0: + raise ValueError("Authentication token cannot be empty.") + + def _to_dict(self) -> Dict[str, Any]: + raise ValueError( + "Cannot serialize token-based secret. Use an alternative secret type like environment variables." + ) + + @staticmethod + def _from_dict(_: Dict[str, Any]) -> "Secret": + raise ValueError( + "Cannot deserialize token-based secret. Use an alternative secret type like environment variables." + ) + + def resolve_value(self) -> Optional[Any]: + """Return the token.""" + return self._token + + @property + def type(self) -> SecretType: + """The type of the secret.""" + return self._type + + +@dataclass(frozen=True) +class EnvVarSecret(Secret): + """ + A secret that accepts one or more environment variables. + + Upon resolution, it returns a string token from the first environment variable that is set. Can be serialized. + """ + + _env_vars: Tuple[str, ...] + _strict: bool = True + _type: SecretType = SecretType.ENV_VAR + + def __post_init__(self): + super().__init__() + assert self._type == SecretType.ENV_VAR + + if len(self._env_vars) == 0: + raise ValueError("One or more environment variables must be provided for the secret.") + + def _to_dict(self) -> Dict[str, Any]: + return {"env_vars": list(self._env_vars), "strict": self._strict} + + @staticmethod + def _from_dict(dictionary: Dict[str, Any]) -> "Secret": + return EnvVarSecret(tuple(dictionary["env_vars"]), _strict=dictionary["strict"]) + + def resolve_value(self) -> Optional[Any]: + """Resolve the secret to an atomic value. The semantics of the value is secret-dependent.""" + out = None + for env_var in self._env_vars: + value = os.getenv(env_var) + if value is not None: + out = value + break + if out is None and self._strict: + raise ValueError(f"None of the following authentication environment variables are set: {self._env_vars}") + return out + + @property + def type(self) -> SecretType: + """The type of the secret.""" + return self._type + + +def deserialize_secrets_inplace(data: Dict[str, Any], keys: Iterable[str], *, recursive: bool = False): + """ + Deserialize secrets in a dictionary inplace. + + :param data: + The dictionary with the serialized data. + :param keys: + The keys of the secrets to deserialize. + :param recursive: + Whether to recursively deserialize nested dictionaries. + """ + for k, v in data.items(): + if isinstance(v, dict) and recursive: + deserialize_secrets_inplace(v, keys) + elif k in keys and v is not None: + data[k] = Secret.from_dict(v) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/base_serialization.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/base_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..f18f352a62316750621034cc0b24f2d619376fdd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/base_serialization.py @@ -0,0 +1,54 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict + +from haystack.core.errors import DeserializationError, SerializationError +from haystack.core.serialization import generate_qualified_class_name, import_class_by_name + + +def serialize_class_instance(obj: Any) -> Dict[str, Any]: + """ + Serializes an object that has a `to_dict` method into a dictionary. + + :param obj: + The object to be serialized. + :returns: + A dictionary representation of the object. + :raises SerializationError: + If the object does not have a `to_dict` method. + """ + if not hasattr(obj, "to_dict"): + raise SerializationError(f"Object of class '{type(obj).__name__}' does not have a 'to_dict' method") + + output = obj.to_dict() + return {"type": generate_qualified_class_name(type(obj)), "data": output} + + +def deserialize_class_instance(data: Dict[str, Any]) -> Any: + """ + Deserializes an object from a dictionary representation generated by `auto_serialize_class_instance`. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized object. + :raises DeserializationError: + If the serialization data is malformed, the class type cannot be imported, or the + class does not have a `from_dict` method. + """ + if "type" not in data: + raise DeserializationError("Missing 'type' in serialization data") + if "data" not in data: + raise DeserializationError("Missing 'data' in serialization data") + + try: + obj_class = import_class_by_name(data["type"]) + except ImportError as e: + raise DeserializationError(f"Class '{data['type']}' not correctly imported") from e + + if not hasattr(obj_class, "from_dict"): + raise DeserializationError(f"Class '{data['type']}' does not have a 'from_dict' method") + + return obj_class.from_dict(data["data"]) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/callable_serialization.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/callable_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..72a57c5ab395c25bbb09fa168da2f7523c5ac296 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/callable_serialization.py @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import inspect +import sys +from typing import Callable, Optional + +from haystack import DeserializationError + + +def serialize_callable(callable_handle: Callable) -> str: + """ + Serializes a callable to its full path. + + :param callable_handle: The callable to serialize + :return: The full path of the callable + """ + module = inspect.getmodule(callable_handle) + + # Get the full package path of the function + if module is not None: + full_path = f"{module.__name__}.{callable_handle.__name__}" + else: + full_path = callable_handle.__name__ + return full_path + + +def deserialize_callable(callable_handle: str) -> Optional[Callable]: + """ + Deserializes a callable given its full import path as a string. + + :param callable_handle: The full path of the callable_handle + :return: The callable + :raises DeserializationError: If the callable cannot be found + """ + parts = callable_handle.split(".") + module_name = ".".join(parts[:-1]) + function_name = parts[-1] + module = sys.modules.get(module_name, None) + if not module: + raise DeserializationError(f"Could not locate the module of the callable: {module_name}") + deserialized_callable = getattr(module, function_name, None) + if not deserialized_callable: + raise DeserializationError(f"Could not locate the callable: {function_name}") + return deserialized_callable diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/device.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/device.py new file mode 100644 index 0000000000000000000000000000000000000000..ab635184ed817d621e50fc8bb0c4fa914cb5f6c8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/device.py @@ -0,0 +1,532 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, Dict, Optional, Tuple, Union + +from haystack import logging +from haystack.lazy_imports import LazyImport + +logger = logging.getLogger(__name__) + +with LazyImport( + message="PyTorch must be installed to use torch.device or use GPU support in HuggingFace transformers. " + "Run 'pip install \"transformers[torch]\"'" +) as torch_import: + import torch + + +class DeviceType(Enum): + """ + Represents device types supported by Haystack. + + This also includes devices that are not directly used by models - for example, the disk device is exclusively used + in device maps for frameworks that support offloading model weights to disk. + """ + + CPU = "cpu" + GPU = "cuda" + DISK = "disk" + MPS = "mps" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "DeviceType": + """ + Create a device type from a string. + + :param string: + The string to convert. + :returns: + The device type. + """ + mapping = {e.value: e for e in DeviceType} + _type = mapping.get(string) + if _type is None: + raise ValueError(f"Unknown device type string '{string}'") + return _type + + +@dataclass +class Device: + """ + A generic representation of a device. + + :param type: + The device type. + :param id: + The optional device id. + """ + + type: DeviceType + id: Optional[int] = field(default=None) + + def __init__(self, type: DeviceType, id: Optional[int] = None): # noqa:A002 + """ + Create a generic device. + + :param type: + The device type. + :param id: + The device id. + """ + if id is not None and id < 0: + raise ValueError(f"Device id must be >= 0, got {id}") + + self.type = type + self.id = id + + def __str__(self): + if self.id is None: + return str(self.type) + else: + return f"{self.type}:{self.id}" + + @staticmethod + def cpu() -> "Device": + """ + Create a generic CPU device. + + :returns: + The CPU device. + """ + return Device(DeviceType.CPU) + + @staticmethod + def gpu(id: int = 0) -> "Device": # noqa:A002 + """ + Create a generic GPU device. + + :param id: + The GPU id. + :returns: + The GPU device. + """ + return Device(DeviceType.GPU, id) + + @staticmethod + def disk() -> "Device": + """ + Create a generic disk device. + + :returns: + The disk device. + """ + return Device(DeviceType.DISK) + + @staticmethod + def mps() -> "Device": + """ + Create a generic Apple Metal Performance Shader device. + + :returns: + The MPS device. + """ + return Device(DeviceType.MPS) + + @staticmethod + def from_str(string: str) -> "Device": + """ + Create a generic device from a string. + + :returns: + The device. + + """ + device_type_str, device_id = _split_device_string(string) + return Device(DeviceType.from_str(device_type_str), device_id) + + +@dataclass +class DeviceMap: + """ + A generic mapping from strings to devices. + + The semantics of the strings are dependent on target framework. Primarily used to deploy HuggingFace models to + multiple devices. + + :param mapping: + Dictionary mapping strings to devices. + """ + + mapping: Dict[str, Device] = field(default_factory=dict, hash=False) + + def __getitem__(self, key: str) -> Device: + return self.mapping[key] + + def __setitem__(self, key: str, value: Device): + self.mapping[key] = value + + def __contains__(self, key: str) -> bool: + return key in self.mapping + + def __len__(self) -> int: + return len(self.mapping) + + def __iter__(self): + return iter(self.mapping.items()) + + def to_dict(self) -> Dict[str, str]: + """ + Serialize the mapping to a JSON-serializable dictionary. + + :returns: + The serialized mapping. + """ + return {key: str(device) for key, device in self.mapping.items()} + + @property + def first_device(self) -> Optional[Device]: + """ + Return the first device in the mapping, if any. + + :returns: + The first device. + """ + if not self.mapping: + return None + else: + return next(iter(self.mapping.values())) + + @staticmethod + def from_dict(dict: Dict[str, str]) -> "DeviceMap": # noqa:A002 + """ + Create a generic device map from a JSON-serialized dictionary. + + :param dict: + The serialized mapping. + :returns: + The generic device map. + """ + mapping = {} + for key, device_str in dict.items(): + mapping[key] = Device.from_str(device_str) + return DeviceMap(mapping) + + @staticmethod + def from_hf(hf_device_map: Dict[str, Union[int, str, "torch.device"]]) -> "DeviceMap": + """ + Create a generic device map from a HuggingFace device map. + + :param hf_device_map: + The HuggingFace device map. + :returns: + The deserialized device map. + """ + mapping = {} + for key, device in hf_device_map.items(): + if isinstance(device, int): + mapping[key] = Device(DeviceType.GPU, device) + elif isinstance(device, str): + device_type, device_id = _split_device_string(device) + mapping[key] = Device(DeviceType.from_str(device_type), device_id) + elif isinstance(device, torch.device): + device_type = device.type + device_id = device.index + mapping[key] = Device(DeviceType.from_str(device_type), device_id) + else: + raise ValueError( + f"Couldn't convert HuggingFace device map - unexpected device '{str(device)}' for '{key}'" + ) + return DeviceMap(mapping) + + +@dataclass(frozen=True) +class ComponentDevice: + """ + A representation of a device for a component. + + This can be either a single device or a device map. + """ + + _single_device: Optional[Device] = field(default=None) + _multiple_devices: Optional[DeviceMap] = field(default=None) + + @classmethod + def from_str(cls, device_str: str) -> "ComponentDevice": + """ + Create a component device representation from a device string. + + The device string can only represent a single device. + + :param device_str: + The device string. + :returns: + The component device representation. + """ + device = Device.from_str(device_str) + return cls.from_single(device) + + @classmethod + def from_single(cls, device: Device) -> "ComponentDevice": + """ + Create a component device representation from a single device. + + Disks cannot be used as single devices. + + :param device: + The device. + :returns: + The component device representation. + """ + if device.type == DeviceType.DISK: + raise ValueError("The disk device can only be used as a part of device maps") + + return cls(_single_device=device) + + @classmethod + def from_multiple(cls, device_map: DeviceMap) -> "ComponentDevice": + """ + Create a component device representation from a device map. + + :param device_map: + The device map. + :returns: + The component device representation. + """ + return cls(_multiple_devices=device_map) + + def _validate(self): + """ + Validate the component device representation. + """ + if not (self._single_device is not None) ^ (self._multiple_devices is not None): + raise ValueError( + "The component device can neither be empty nor contain both a single device and a device map" + ) + + def to_torch(self) -> "torch.device": + """ + Convert the component device representation to PyTorch format. + + Device maps are not supported. + + :returns: + The PyTorch device representation. + """ + self._validate() + + if self._single_device is None: + raise ValueError("Only single devices can be converted to PyTorch format") + + torch_import.check() + assert self._single_device is not None + return torch.device(str(self._single_device)) + + def to_torch_str(self) -> str: + """ + Convert the component device representation to PyTorch string format. + + Device maps are not supported. + + :returns: + The PyTorch device string representation. + """ + self._validate() + + if self._single_device is None: + raise ValueError("Only single devices can be converted to PyTorch format") + + assert self._single_device is not None + return str(self._single_device) + + def to_spacy(self) -> int: + """ + Convert the component device representation to spaCy format. + + Device maps are not supported. + + :returns: + The spaCy device representation. + """ + self._validate() + + if self._single_device is None: + raise ValueError("Only single devices can be converted to spaCy format") + + assert self._single_device is not None + if self._single_device.type == DeviceType.GPU: + assert self._single_device.id is not None + return self._single_device.id + else: + return -1 + + def to_hf(self) -> Union[Union[int, str], Dict[str, Union[int, str]]]: + """ + Convert the component device representation to HuggingFace format. + + :returns: + The HuggingFace device representation. + """ + self._validate() + + def convert_device(device: Device, *, gpu_id_only: bool = False) -> Union[int, str]: + if gpu_id_only and device.type == DeviceType.GPU: + assert device.id is not None + return device.id + else: + return str(device) + + if self._single_device is not None: + return convert_device(self._single_device) + + assert self._multiple_devices is not None + return {key: convert_device(device, gpu_id_only=True) for key, device in self._multiple_devices.mapping.items()} + + def update_hf_kwargs(self, hf_kwargs: Dict[str, Any], *, overwrite: bool) -> Dict[str, Any]: + """ + Convert the component device representation to HuggingFace format. + + Add them as canonical keyword arguments to the keyword arguments dictionary. + + :param hf_kwargs: + The HuggingFace keyword arguments dictionary. + :param overwrite: + Whether to overwrite existing device arguments. + :returns: + The HuggingFace keyword arguments dictionary. + """ + self._validate() + + if not overwrite and any(x in hf_kwargs for x in ("device", "device_map")): + return hf_kwargs + + converted = self.to_hf() + key = "device_map" if self.has_multiple_devices else "device" + hf_kwargs[key] = converted + return hf_kwargs + + @property + def has_multiple_devices(self) -> bool: + """ + Whether this component device representation contains multiple devices. + """ + self._validate() + + return self._multiple_devices is not None + + @property + def first_device(self) -> Optional["ComponentDevice"]: + """ + Return either the single device or the first device in the device map, if any. + + :returns: + The first device. + """ + self._validate() + + if self._single_device is not None: + return self.from_single(self._single_device) + + assert self._multiple_devices is not None + assert self._multiple_devices.first_device is not None + return self.from_single(self._multiple_devices.first_device) + + @staticmethod + def resolve_device(device: Optional["ComponentDevice"] = None) -> "ComponentDevice": + """ + Select a device for a component. If a device is specified, it's used. Otherwise, the default device is used. + + :param device: + The provided device, if any. + :returns: + The resolved device. + """ + if not isinstance(device, ComponentDevice) and device is not None: + raise ValueError( + f"Invalid component device type '{type(device).__name__}'. Must either be None or ComponentDevice." + ) + + if device is None: + device = ComponentDevice.from_single(_get_default_device()) + + return device + + def to_dict(self) -> Dict[str, Any]: + """ + Convert the component device representation to a JSON-serializable dictionary. + + :returns: + The dictionary representation. + """ + if self._single_device is not None: + return {"type": "single", "device": str(self._single_device)} + elif self._multiple_devices is not None: + return {"type": "multiple", "device_map": self._multiple_devices.to_dict()} + else: + # Unreachable + assert False + + @classmethod + def from_dict(cls, dict: Dict[str, Any]) -> "ComponentDevice": # noqa:A002 + """ + Create a component device representation from a JSON-serialized dictionary. + + :param dict: + The serialized representation. + :returns: + The deserialized component device. + """ + if dict["type"] == "single": + return cls.from_str(dict["device"]) + elif dict["type"] == "multiple": + return cls.from_multiple(DeviceMap.from_dict(dict["device_map"])) + else: + raise ValueError(f"Unknown component device type '{dict['type']}' in serialized data") + + +def _get_default_device() -> Device: + """ + Return the default device for Haystack. + + Precedence: + GPU > MPS > CPU. If PyTorch is not installed, only CPU is available. + + :returns: + The default device. + """ + try: + torch_import.check() + + has_mps = ( + hasattr(torch.backends, "mps") + and torch.backends.mps.is_available() + and os.getenv("HAYSTACK_MPS_ENABLED", "true") != "false" + ) + has_cuda = torch.cuda.is_available() + except ImportError: + has_mps = False + has_cuda = False + + if has_cuda: + return Device.gpu() + elif has_mps: + return Device.mps() + else: + return Device.cpu() + + +def _split_device_string(string: str) -> Tuple[str, Optional[int]]: + """ + Split a device string into device type and device id. + + :param string: + The device string to split. + :returns: + The device type and device id, if any. + """ + if ":" in string: + device_type, device_id_str = string.split(":") + try: + device_id = int(device_id_str) + except ValueError: + raise ValueError(f"Device id must be an integer, got {device_id_str}") + else: + device_type = string + device_id = None + return device_type, device_id diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/docstore_deserialization.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/docstore_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..41d8b2714dd47d26f35f99d92e9063f712688176 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/docstore_deserialization.py @@ -0,0 +1,39 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict + +from haystack import DeserializationError +from haystack.core.serialization import default_from_dict, import_class_by_name + + +def deserialize_document_store_in_init_params_inplace(data: Dict[str, Any], key: str = "document_store"): + """ + Deserializes a generic document store from the init_parameters of a serialized component in place. + + :param data: + The dictionary to deserialize from. + :param key: + The key in the `data["init_parameters"]` dictionary where the document store is specified. + :returns: + The dictionary, with the document store deserialized. + + :raises DeserializationError: + If the document store is not properly specified in the serialization data or its type cannot be imported. + """ + init_params = data.get("init_parameters", {}) + if key not in init_params: + raise DeserializationError(f"Missing '{key}' in serialization data") + if "type" not in init_params[key]: + raise DeserializationError(f"Missing 'type' in {key} serialization data") + + doc_store_data = data["init_parameters"][key] + try: + doc_store_class = import_class_by_name(doc_store_data["type"]) + except ImportError as e: + raise DeserializationError(f"Class '{doc_store_data['type']}' not correctly imported") from e + if hasattr(doc_store_class, "from_dict"): + data["init_parameters"][key] = doc_store_class.from_dict(doc_store_data) + else: + data["init_parameters"][key] = default_from_dict(doc_store_class, doc_store_data) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/expit.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/expit.py new file mode 100644 index 0000000000000000000000000000000000000000..2f29ce99bd184f1a0a5e08955223d01dd69fd662 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/expit.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from numpy import exp + + +def expit(x) -> float: + """ + Compute logistic sigmoid function. Maps input values to a range between 0 and 1 + + :param x: input value. Can be a scalar or a numpy array. + """ + return 1 / (1 + exp(-x)) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/filters.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..a24affaf1b7bba8edde868f3fddc790190279311 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/filters.py @@ -0,0 +1,187 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import fields +from datetime import datetime +from typing import Any, Dict, List, Optional + +import pandas as pd + +from haystack.dataclasses import Document +from haystack.errors import FilterError + + +def raise_on_invalid_filter_syntax(filters: Optional[Dict[str, Any]] = None): + """ + Raise an error if the filter syntax is invalid. + """ + if filters and "operator" not in filters and "conditions" not in filters: + msg = "Invalid filter syntax. See https://docs.haystack.deepset.ai/docs/metadata-filtering for details." + raise ValueError(msg) + + +def document_matches_filter(filters: Dict[str, Any], document: Document) -> bool: + """ + Return whether `filters` match the Document. + + For a detailed specification of the filters, refer to the + `DocumentStore.filter_documents()` protocol documentation. + """ + if "field" in filters: + return _comparison_condition(filters, document) + return _logic_condition(filters, document) + + +def _and(document: Document, conditions: List[Dict[str, Any]]) -> bool: + return all(_comparison_condition(condition, document) for condition in conditions) + + +def _or(document: Document, conditions: List[Dict[str, Any]]) -> bool: + return any(_comparison_condition(condition, document) for condition in conditions) + + +def _not(document: Document, conditions: List[Dict[str, Any]]) -> bool: + return not _and(document, conditions) + + +LOGICAL_OPERATORS = {"NOT": _not, "OR": _or, "AND": _and} + + +def _equal(document_value: Any, filter_value: Any) -> bool: + if isinstance(document_value, pd.DataFrame): + document_value = document_value.to_json() + + if isinstance(filter_value, pd.DataFrame): + filter_value = filter_value.to_json() + + return document_value == filter_value + + +def _not_equal(document_value: Any, filter_value: Any) -> bool: + return not _equal(document_value=document_value, filter_value=filter_value) + + +def _greater_than(document_value: Any, filter_value: Any) -> bool: + if document_value is None or filter_value is None: + # We can't compare None values reliably using operators '>', '>=', '<', '<=' + return False + + if isinstance(document_value, str) or isinstance(filter_value, str): + try: + document_value = datetime.fromisoformat(document_value) + filter_value = datetime.fromisoformat(filter_value) + except (ValueError, TypeError) as exc: + msg = ( + "Can't compare strings using operators '>', '>=', '<', '<='. " + "Strings are only comparable if they are ISO formatted dates." + ) + raise FilterError(msg) from exc + if type(filter_value) in [list, pd.DataFrame]: + msg = f"Filter value can't be of type {type(filter_value)} using operators '>', '>=', '<', '<='" + raise FilterError(msg) + return document_value > filter_value + + +def _greater_than_equal(document_value: Any, filter_value: Any) -> bool: + if document_value is None or filter_value is None: + # We can't compare None values reliably using operators '>', '>=', '<', '<=' + return False + + return _equal(document_value=document_value, filter_value=filter_value) or _greater_than( + document_value=document_value, filter_value=filter_value + ) + + +def _less_than(document_value: Any, filter_value: Any) -> bool: + if document_value is None or filter_value is None: + # We can't compare None values reliably using operators '>', '>=', '<', '<=' + return False + + return not _greater_than_equal(document_value=document_value, filter_value=filter_value) + + +def _less_than_equal(document_value: Any, filter_value: Any) -> bool: + if document_value is None or filter_value is None: + # We can't compare None values reliably using operators '>', '>=', '<', '<=' + return False + + return not _greater_than(document_value=document_value, filter_value=filter_value) + + +def _in(document_value: Any, filter_value: Any) -> bool: + if not isinstance(filter_value, list): + msg = ( + f"Filter value must be a `list` when using operator 'in' or 'not in', " + f"received type '{type(filter_value)}'" + ) + raise FilterError(msg) + return any(_equal(e, document_value) for e in filter_value) + + +def _not_in(document_value: Any, filter_value: Any) -> bool: + return not _in(document_value=document_value, filter_value=filter_value) + + +COMPARISON_OPERATORS = { + "==": _equal, + "!=": _not_equal, + ">": _greater_than, + ">=": _greater_than_equal, + "<": _less_than, + "<=": _less_than_equal, + "in": _in, + "not in": _not_in, +} + + +def _logic_condition(condition: Dict[str, Any], document: Document) -> bool: + if "operator" not in condition: + msg = f"'operator' key missing in {condition}" + raise FilterError(msg) + if "conditions" not in condition: + msg = f"'conditions' key missing in {condition}" + raise FilterError(msg) + operator: str = condition["operator"] + conditions: List[Dict[str, Any]] = condition["conditions"] + return LOGICAL_OPERATORS[operator](document, conditions) + + +def _comparison_condition(condition: Dict[str, Any], document: Document) -> bool: + if "field" not in condition: + # 'field' key is only found in comparison dictionaries. + # We assume this is a logic dictionary since it's not present. + return _logic_condition(condition, document) + field: str = condition["field"] + + if "operator" not in condition: + msg = f"'operator' key missing in {condition}" + raise FilterError(msg) + if "value" not in condition: + msg = f"'value' key missing in {condition}" + raise FilterError(msg) + + if "." in field: + # Handles fields formatted like so: + # 'meta.person.name' + parts = field.split(".") + document_value = getattr(document, parts[0]) + for part in parts[1:]: + if part not in document_value: + # If a field is not found we treat it as None + document_value = None + break + document_value = document_value[part] + elif field not in [f.name for f in fields(document)]: + # Converted legacy filters don't add the `meta.` prefix, so we assume + # that all filter fields that are not actual fields in Document are converted + # filters. + # + # We handle this to avoid breaking compatibility with converted legacy filters. + # This will be removed as soon as we stop supporting legacy filters. + document_value = document.meta.get(field) + else: + document_value = getattr(document, field) + operator: str = condition["operator"] + filter_value: Any = condition["value"] + return COMPARISON_OPERATORS[operator](filter_value=filter_value, document_value=document_value) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/hf.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/hf.py new file mode 100644 index 0000000000000000000000000000000000000000..89f036a70545e54e337f1ff55842649fb2c2746f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/hf.py @@ -0,0 +1,357 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import copy +import inspect +from enum import Enum +from typing import Any, Callable, Dict, List, Optional, Union + +from haystack import logging +from haystack.dataclasses import StreamingChunk +from haystack.lazy_imports import LazyImport +from haystack.utils.auth import Secret +from haystack.utils.device import ComponentDevice + +with LazyImport(message="Run 'pip install \"transformers[torch]\"'") as torch_import: + import torch + +with LazyImport(message="Run 'pip install \"huggingface_hub>=0.23.0\"'") as huggingface_hub_import: + from huggingface_hub import HfApi, InferenceClient, model_info + from huggingface_hub.utils import RepositoryNotFoundError + +logger = logging.getLogger(__name__) + + +class HFGenerationAPIType(Enum): + """ + API type to use for Hugging Face API Generators. + """ + + # HF [Text Generation Inference (TGI)](https://github.com/huggingface/text-generation-inference). + TEXT_GENERATION_INFERENCE = "text_generation_inference" + + # HF [Inference Endpoints](https://huggingface.co/inference-endpoints). + INFERENCE_ENDPOINTS = "inference_endpoints" + + # HF [Serverless Inference API](https://huggingface.co/inference-api). + SERVERLESS_INFERENCE_API = "serverless_inference_api" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "HFGenerationAPIType": + """ + Convert a string to a HFGenerationAPIType enum. + + :param string: The string to convert. + :return: The corresponding HFGenerationAPIType enum. + + """ + enum_map = {e.value: e for e in HFGenerationAPIType} + mode = enum_map.get(string) + if mode is None: + msg = f"Unknown Hugging Face API type '{string}'. Supported types are: {list(enum_map.keys())}" + raise ValueError(msg) + return mode + + +class HFEmbeddingAPIType(Enum): + """ + API type to use for Hugging Face API Embedders. + """ + + # HF [Text Embeddings Inference (TEI)](https://github.com/huggingface/text-embeddings-inference). + TEXT_EMBEDDINGS_INFERENCE = "text_embeddings_inference" + + # HF [Inference Endpoints](https://huggingface.co/inference-endpoints). + INFERENCE_ENDPOINTS = "inference_endpoints" + + # HF [Serverless Inference API](https://huggingface.co/inference-api). + SERVERLESS_INFERENCE_API = "serverless_inference_api" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "HFEmbeddingAPIType": + """ + Convert a string to a HFEmbeddingAPIType enum. + + :param string: + :return: The corresponding HFEmbeddingAPIType enum. + """ + enum_map = {e.value: e for e in HFEmbeddingAPIType} + mode = enum_map.get(string) + if mode is None: + msg = f"Unknown Hugging Face API type '{string}'. Supported types are: {list(enum_map.keys())}" + raise ValueError(msg) + return mode + + +class HFModelType(Enum): + EMBEDDING = 1 + GENERATION = 2 + + +def serialize_hf_model_kwargs(kwargs: Dict[str, Any]): + """ + Recursively serialize HuggingFace specific model keyword arguments in-place to make them JSON serializable. + + :param kwargs: The keyword arguments to serialize + """ + torch_import.check() + + for k, v in kwargs.items(): + # torch.dtype + if isinstance(v, torch.dtype): + kwargs[k] = str(v) + + if isinstance(v, dict): + serialize_hf_model_kwargs(v) + + +def deserialize_hf_model_kwargs(kwargs: Dict[str, Any]): + """ + Recursively deserialize HuggingFace specific model keyword arguments in-place to make them JSON serializable. + + :param kwargs: The keyword arguments to deserialize + """ + torch_import.check() + + for k, v in kwargs.items(): + # torch.dtype + if isinstance(v, str) and v.startswith("torch."): + dtype_str = v.split(".")[1] + dtype = getattr(torch, dtype_str, None) + if dtype is not None and isinstance(dtype, torch.dtype): + kwargs[k] = dtype + + if isinstance(v, dict): + deserialize_hf_model_kwargs(v) + + +def resolve_hf_device_map(device: Optional[ComponentDevice], model_kwargs: Optional[Dict[str, Any]]) -> Dict[str, Any]: + """ + Update `model_kwargs` to include the keyword argument `device_map`. + + This method is useful you want to force loading a transformers model when using `AutoModel.from_pretrained` to + use `device_map`. + + We handle the edge case where `device` and `device_map` is specified by ignoring the `device` parameter and printing + a warning. + + :param device: The device on which the model is loaded. If `None`, the default device is automatically + selected. + :param model_kwargs: Additional HF keyword arguments passed to `AutoModel.from_pretrained`. + For details on what kwargs you can pass, see the model's documentation. + """ + model_kwargs = copy.copy(model_kwargs) or {} + if model_kwargs.get("device_map"): + if device is not None: + logger.warning( + "The parameters `device` and `device_map` from `model_kwargs` are both provided. " + "Ignoring `device` and using `device_map`." + ) + # Resolve device if device_map is provided in model_kwargs + device_map = model_kwargs["device_map"] + else: + device_map = ComponentDevice.resolve_device(device).to_hf() + + # Set up device_map which allows quantized loading and multi device inference + # requires accelerate which is always installed when using `pip install transformers[torch]` + model_kwargs["device_map"] = device_map + + return model_kwargs + + +def resolve_hf_pipeline_kwargs( + huggingface_pipeline_kwargs: Dict[str, Any], + model: str, + task: Optional[str], + supported_tasks: List[str], + device: Optional[ComponentDevice], + token: Optional[Secret], +) -> Dict[str, Any]: + """ + Resolve the HuggingFace pipeline keyword arguments based on explicit user inputs. + + :param huggingface_pipeline_kwargs: Dictionary containing keyword arguments used to initialize a + Hugging Face pipeline. + :param model: The name or path of a Hugging Face model for on the HuggingFace Hub. + :param task: The task for the Hugging Face pipeline. + :param supported_tasks: The list of supported tasks to check the task of the model against. If the task of the model + is not present within this list then a ValueError is thrown. + :param device: The device on which the model is loaded. If `None`, the default device is automatically + selected. If a device/device map is specified in `huggingface_pipeline_kwargs`, it overrides this parameter. + :param token: The token to use as HTTP bearer authorization for remote files. + If the token is also specified in the `huggingface_pipeline_kwargs`, this parameter will be ignored. + """ + huggingface_hub_import.check() + + token = token.resolve_value() if token else None + # check if the huggingface_pipeline_kwargs contain the essential parameters + # otherwise, populate them with values from other init parameters + huggingface_pipeline_kwargs.setdefault("model", model) + huggingface_pipeline_kwargs.setdefault("token", token) + + device = ComponentDevice.resolve_device(device) + device.update_hf_kwargs(huggingface_pipeline_kwargs, overwrite=False) + + # task identification and validation + task = task or huggingface_pipeline_kwargs.get("task") + if task is None and isinstance(huggingface_pipeline_kwargs["model"], str): + task = model_info(huggingface_pipeline_kwargs["model"], token=huggingface_pipeline_kwargs["token"]).pipeline_tag + + if task not in supported_tasks: + raise ValueError(f"Task '{task}' is not supported. " f"The supported tasks are: {', '.join(supported_tasks)}.") + huggingface_pipeline_kwargs["task"] = task + return huggingface_pipeline_kwargs + + +def check_valid_model(model_id: str, model_type: HFModelType, token: Optional[Secret]) -> None: + """ + Check if the provided model ID corresponds to a valid model on HuggingFace Hub. + + Also check if the model is an embedding or generation model. + + :param model_id: A string representing the HuggingFace model ID. + :param model_type: the model type, HFModelType.EMBEDDING or HFModelType.GENERATION + :param token: The optional authentication token. + :raises ValueError: If the model is not found or is not a embedding model. + """ + huggingface_hub_import.check() + + api = HfApi() + try: + model_info = api.model_info(model_id, token=token.resolve_value() if token else None) + except RepositoryNotFoundError as e: + raise ValueError( + f"Model {model_id} not found on HuggingFace Hub. Please provide a valid HuggingFace model_id." + ) from e + + if model_type == HFModelType.EMBEDDING: + allowed_model = model_info.pipeline_tag in ["sentence-similarity", "feature-extraction"] + error_msg = f"Model {model_id} is not a embedding model. Please provide a embedding model." + elif model_type == HFModelType.GENERATION: + allowed_model = model_info.pipeline_tag in ["text-generation", "text2text-generation"] + error_msg = f"Model {model_id} is not a text generation model. Please provide a text generation model." + else: + allowed_model = False + error_msg = f"Unknown model type for {model_id}" + + if not allowed_model: + raise ValueError(error_msg) + + +def check_generation_params(kwargs: Optional[Dict[str, Any]], additional_accepted_params: Optional[List[str]] = None): + """ + Check the provided generation parameters for validity. + + :param kwargs: A dictionary containing the generation parameters. + :param additional_accepted_params: An optional list of strings representing additional accepted parameters. + :raises ValueError: If any unknown text generation parameters are provided. + """ + huggingface_hub_import.check() + + if kwargs: + accepted_params = { + param + for param in inspect.signature(InferenceClient.text_generation).parameters.keys() + if param not in ["self", "prompt"] + } + if additional_accepted_params: + accepted_params.update(additional_accepted_params) + unknown_params = set(kwargs.keys()) - accepted_params + if unknown_params: + raise ValueError( + f"Unknown text generation parameters: {unknown_params}. The valid parameters are: {accepted_params}." + ) + + +with LazyImport(message="Run 'pip install \"transformers[torch]\"'") as transformers_import: + from transformers import PreTrainedTokenizer, PreTrainedTokenizerFast, StoppingCriteria, TextStreamer + + torch_import.check() + transformers_import.check() + + class StopWordsCriteria(StoppingCriteria): + """ + Stops text generation in HuggingFace generators if any one of the stop words is generated. + + Note: When a stop word is encountered, the generation of new text is stopped. + However, if the stop word is in the prompt itself, it can stop generating new text + prematurely after the first token. This is particularly important for LLMs designed + for dialogue generation. For these models, like for example mosaicml/mpt-7b-chat, + the output includes both the new text and the original prompt. Therefore, it's important + to make sure your prompt has no stop words. + """ + + def __init__( + self, + tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast], + stop_words: List[str], + device: Union[str, torch.device] = "cpu", + ): + super().__init__() + # check if tokenizer is a valid tokenizer + if not isinstance(tokenizer, (PreTrainedTokenizer, PreTrainedTokenizerFast)): + raise ValueError( + f"Invalid tokenizer provided for StopWordsCriteria - {tokenizer}. " + f"Please provide a valid tokenizer from the HuggingFace Transformers library." + ) + if not tokenizer.pad_token: + if tokenizer.eos_token: + tokenizer.pad_token = tokenizer.eos_token + else: + tokenizer.add_special_tokens({"pad_token": "[PAD]"}) + encoded_stop_words = tokenizer(stop_words, add_special_tokens=False, padding=True, return_tensors="pt") + self.stop_ids = encoded_stop_words.input_ids.to(device) + + def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: + """Check if any of the stop words are generated in the current text generation step.""" + for stop_id in self.stop_ids: + found_stop_word = self.is_stop_word_found(input_ids, stop_id) + if found_stop_word: + return True + return False + + @staticmethod + def is_stop_word_found(generated_text_ids: torch.Tensor, stop_id: torch.Tensor) -> bool: + """ + Performs phrase matching. + + Checks if a sequence of stop tokens appears in a continuous or sequential order within the generated text. + """ + generated_text_ids = generated_text_ids[-1] + len_generated_text_ids = generated_text_ids.size(0) + len_stop_id = stop_id.size(0) + result = all(generated_text_ids[len_generated_text_ids - len_stop_id :].eq(stop_id)) + return result + + class HFTokenStreamingHandler(TextStreamer): + """ + Streaming handler for HuggingFaceLocalGenerator and HuggingFaceLocalChatGenerator. + + Note: This is a helper class for HuggingFaceLocalGenerator & HuggingFaceLocalChatGenerator enabling streaming + of generated text via Haystack Callable[StreamingChunk, None] callbacks. + + Do not use this class directly. + """ + + def __init__( + self, + tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast], + stream_handler: Callable[[StreamingChunk], None], + stop_words: Optional[List[str]] = None, + ): + super().__init__(tokenizer=tokenizer, skip_prompt=True) # type: ignore + self.token_handler = stream_handler + self.stop_words = stop_words or [] + + def on_finalized_text(self, word: str, stream_end: bool = False): + """Callback function for handling the generated text.""" + word_to_send = word + "\n" if stream_end else word + if word_to_send.strip() not in self.stop_words: + self.token_handler(StreamingChunk(content=word_to_send)) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/jinja2_extensions.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/jinja2_extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..94d0dc8fdd869b48a4f3583260fbc0f9ac7d3c68 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/jinja2_extensions.py @@ -0,0 +1,96 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, List, Optional, Union + +from jinja2 import Environment, nodes +from jinja2.ext import Extension + +from haystack.lazy_imports import LazyImport + +with LazyImport(message='Run "pip install arrow>=1.3.0"') as arrow_import: + import arrow + + +class Jinja2TimeExtension(Extension): + # Syntax for current date + tags = {"now"} + + def __init__(self, environment: Environment): # pylint: disable=useless-parent-delegation + """ + Initializes the JinjaTimeExtension object. + + :param environment: The Jinja2 environment to initialize the extension with. + It provides the context where the extension will operate. + """ + arrow_import.check() + super().__init__(environment) + + @staticmethod + def _get_datetime( + timezone: str, + operator: Optional[str] = None, + offset: Optional[str] = None, + datetime_format: Optional[str] = None, + ) -> str: + """ + Get the current datetime based on timezone, apply any offset if provided, and format the result. + + :param timezone: The timezone string (e.g., 'UTC' or 'America/New_York') for which the current + time should be fetched. + :param operator: The operator ('+' or '-') to apply to the offset (used for adding/subtracting intervals). + Defaults to None if no offset is applied, otherwise default is '+'. + :param offset: The offset string in the format 'interval=value' (e.g., 'hours=2,days=1') specifying how much + to adjust the datetime. The intervals can be any valid interval accepted + by Arrow (e.g., hours, days, weeks, months). Defaults to None if no adjustment is needed. + :param datetime_format: The format string to use for formatting the output datetime. + Defaults to '%Y-%m-%d %H:%M:%S' if not provided. + """ + try: + dt = arrow.now(timezone) + except Exception as e: + raise ValueError(f"Invalid timezone {timezone}: {e}") + + if offset and operator: + try: + # Parse the offset and apply it to the datetime object + replace_params = { + interval.strip(): float(operator + value.strip()) + for param in offset.split(",") + for interval, value in [param.split("=")] + } + # Shift the datetime fields based on the parsed offset + dt = dt.shift(**replace_params) + except (ValueError, AttributeError) as e: + raise ValueError(f"Invalid offset or operator {offset}, {operator}: {e}") + + # Use the provided format or fallback to the default one + datetime_format = datetime_format or "%Y-%m-%d %H:%M:%S" + + return dt.strftime(datetime_format) + + def parse(self, parser: Any) -> Union[nodes.Node, List[nodes.Node]]: + """ + Parse the template expression to determine how to handle the datetime formatting. + + :param parser: The parser object that processes the template expressions and manages the syntax tree. + It's used to interpret the template's structure. + """ + lineno = next(parser.stream).lineno + node = parser.parse_expression() + # Check if a custom datetime format is provided after a comma + datetime_format = parser.parse_expression() if parser.stream.skip_if("comma") else nodes.Const(None) + + # Default Add when no operator is provided + operator = "+" if isinstance(node, nodes.Add) else "-" + # Call the _get_datetime method with the appropriate operator and offset, if exist + call_method = self.call_method( + "_get_datetime", + [node.left, nodes.Const(operator), node.right, datetime_format] + if isinstance(node, (nodes.Add, nodes.Sub)) + else [node, nodes.Const(None), nodes.Const(None), datetime_format], + lineno=lineno, + ) + + return nodes.Output([call_method], lineno=lineno) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/jupyter.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/jupyter.py new file mode 100644 index 0000000000000000000000000000000000000000..95de65b7900f2237726adda36630d86897b1551b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/jupyter.py @@ -0,0 +1,20 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + + +def is_in_jupyter() -> bool: + """ + Returns `True` if in Jupyter or Google Colab, `False` otherwise. + """ + # Inspired by: + # https://github.com/explosion/spaCy/blob/e1249d3722765aaca56f538e830add7014d20e2a/spacy/util.py#L1079 + try: + # We don't need to import `get_ipython` as it's always present in Jupyter notebooks + if get_ipython().__class__.__name__ == "ZMQInteractiveShell": # type: ignore[name-defined] + return True # Jupyter notebook or qtconsole + if get_ipython().__class__.__module__ == "google.colab._shell": # type: ignore[name-defined] + return True # Colab notebook + except NameError: + pass # Probably standard Python interpreter + return False diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/requests_utils.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/requests_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..07893934e463f9be015b31bd90816856ae381dde --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/requests_utils.py @@ -0,0 +1,97 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import logging +from typing import List, Optional + +import requests +from tenacity import after_log, before_log, retry, retry_if_exception_type, stop_after_attempt, wait_exponential + +logger = logging.getLogger(__file__) + + +def request_with_retry( + attempts: int = 3, status_codes_to_retry: Optional[List[int]] = None, **kwargs +) -> requests.Response: + """ + Executes an HTTP request with a configurable exponential backoff retry on failures. + + Usage example: + ```python + from haystack.utils import request_with_retry + + # Sending an HTTP request with default retry configs + res = request_with_retry(method="GET", url="https://example.com") + + # Sending an HTTP request with custom number of attempts + res = request_with_retry(method="GET", url="https://example.com", attempts=10) + + # Sending an HTTP request with custom HTTP codes to retry + res = request_with_retry(method="GET", url="https://example.com", status_codes_to_retry=[408, 503]) + + # Sending an HTTP request with custom timeout in seconds + res = request_with_retry(method="GET", url="https://example.com", timeout=5) + + # Sending an HTTP request with custom authorization handling + class CustomAuth(requests.auth.AuthBase): + def __call__(self, r): + r.headers["authorization"] = "Basic " + return r + + res = request_with_retry(method="GET", url="https://example.com", auth=CustomAuth()) + + # All of the above combined + res = request_with_retry( + method="GET", + url="https://example.com", + auth=CustomAuth(), + attempts=10, + status_codes_to_retry=[408, 503], + timeout=5 + ) + + # Sending a POST request + res = request_with_retry(method="POST", url="https://example.com", data={"key": "value"}, attempts=10) + + # Retry all 5xx status codes + res = request_with_retry(method="GET", url="https://example.com", status_codes_to_retry=list(range(500, 600))) + ``` + + :param attempts: + Maximum number of attempts to retry the request. + :param status_codes_to_retry: + List of HTTP status codes that will trigger a retry. + When param is `None`, HTTP 408, 418, 429 and 503 will be retried. + :param kwargs: + Optional arguments that `request` accepts. + :returns: + The `Response` object. + """ + + if status_codes_to_retry is None: + status_codes_to_retry = [408, 418, 429, 503] + + @retry( + reraise=True, + wait=wait_exponential(), + retry=retry_if_exception_type((requests.HTTPError, TimeoutError)), + stop=stop_after_attempt(attempts), + before=before_log(logger, logging.DEBUG), + after=after_log(logger, logging.DEBUG), + ) + def run(): + timeout = kwargs.pop("timeout", 10) + res = requests.request(**kwargs, timeout=timeout) + + if res.status_code in status_codes_to_retry: + # We raise only for the status codes that must trigger a retry + res.raise_for_status() + + return res + + res = run() + # We raise here too in case the request failed with a status code that + # won't trigger a retry, this way the call will still cause an explicit exception + res.raise_for_status() + return res diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/type_serialization.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/type_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..b2dd319d52fe48e245392ee1beb7edee30816d0e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/type_serialization.py @@ -0,0 +1,143 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import importlib +import inspect +import sys +import typing +from typing import Any, get_args, get_origin + +from haystack import DeserializationError + + +def serialize_type(target: Any) -> str: + """ + Serializes a type or an instance to its string representation, including the module name. + + This function handles types, instances of types, and special typing objects. + It assumes that non-typing objects will have a '__name__' attribute and raises + an error if a type cannot be serialized. + + :param target: + The object to serialize, can be an instance or a type. + :return: + The string representation of the type. + :raises ValueError: + If the type cannot be serialized. + """ + # If the target is a string and contains a dot, treat it as an already serialized type + if isinstance(target, str) and "." in target: + return target + + # Determine if the target is a type or an instance of a typing object + is_type_or_typing = isinstance(target, type) or bool(get_origin(target)) + type_obj = target if is_type_or_typing else type(target) + type_obj_repr = repr(type_obj) + + if type_obj_repr.startswith("typing."): + # e.g., typing.List[int] -> List[int], we'll add the module below + type_name = type_obj_repr.split(".", 1)[1] + elif origin := get_origin(type_obj): # get the origin (base type of the parameterized generic type) + # get the arguments of the generic type + args = get_args(type_obj) + args_repr = ", ".join(serialize_type(arg) for arg in args) + type_name = f"{origin.__name__}[{args_repr}]" + elif hasattr(type_obj, "__name__"): + type_name = type_obj.__name__ + else: + # If type cannot be serialized, raise an error + raise ValueError(f"Could not serialize type: {type_obj_repr}") + + module = inspect.getmodule(type_obj) + if module and hasattr(module, "__name__"): + if module.__name__ == "builtins": + # omit the module name for builtins, it just clutters the output + # e.g. instead of 'builtins.str', we'll just return 'str' + full_path = type_name + else: + full_path = f"{module.__name__}.{type_name}" + else: + full_path = type_name + + return full_path + + +def deserialize_type(type_str: str) -> Any: + """ + Deserializes a type given its full import path as a string, including nested generic types. + + This function will dynamically import the module if it's not already imported + and then retrieve the type object from it. It also handles nested generic types like + `typing.List[typing.Dict[int, str]]`. + + :param type_str: + The string representation of the type's full import path. + :returns: + The deserialized type object. + :raises DeserializationError: + If the type cannot be deserialized due to missing module or type. + """ + + type_mapping = { + list: typing.List, + dict: typing.Dict, + set: typing.Set, + tuple: typing.Tuple, + frozenset: typing.FrozenSet, + } + + def parse_generic_args(args_str): + args = [] + bracket_count = 0 + current_arg = "" + + for char in args_str: + if char == "[": + bracket_count += 1 + elif char == "]": + bracket_count -= 1 + + if char == "," and bracket_count == 0: + args.append(current_arg.strip()) + current_arg = "" + else: + current_arg += char + + if current_arg: + args.append(current_arg.strip()) + + return args + + if "[" in type_str and type_str.endswith("]"): + # Handle generics + main_type_str, generics_str = type_str.split("[", 1) + generics_str = generics_str[:-1] + + main_type = deserialize_type(main_type_str) + generic_args = tuple(deserialize_type(arg) for arg in parse_generic_args(generics_str)) + + # Reconstruct + if sys.version_info >= (3, 9) or repr(main_type).startswith("typing."): + return main_type[generic_args] + else: + return type_mapping[main_type][generic_args] # type: ignore + + else: + # Handle non-generics + parts = type_str.split(".") + module_name = ".".join(parts[:-1]) or "builtins" + type_name = parts[-1] + + module = sys.modules.get(module_name) + if not module: + try: + module = importlib.import_module(module_name) + except ImportError as e: + raise DeserializationError(f"Could not import the module: {module_name}") from e + + deserialized_type = getattr(module, type_name, None) + if not deserialized_type: + raise DeserializationError(f"Could not locate the type: {type_name} in the module: {module_name}") + + return deserialized_type diff --git a/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/url_validation.py b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/url_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..06b6cf2ed7c62a07b07d50a30454937cc965c8af --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/haystack/utils/url_validation.py @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from urllib.parse import urlparse + + +def is_valid_http_url(url: str) -> bool: + """Check if a URL is a valid HTTP/HTTPS URL.""" + r = urlparse(url) + return all([r.scheme in ["http", "https"], r.netloc]) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/AnalyzeResult-forward-declaration-5ed1bd9b6dc62c6f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/AnalyzeResult-forward-declaration-5ed1bd9b6dc62c6f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..15986221c016da17c64d42eb5b0310fb7403e9ae --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/AnalyzeResult-forward-declaration-5ed1bd9b6dc62c6f.yaml @@ -0,0 +1,7 @@ +--- +fixes: + - | + Forward declaration of `AnalyzeResult` type in `AzureOCRDocumentConverter`. + + `AnalyzeResult` is already imported in a lazy import block. + The forward declaration avoids issues when `azure-ai-formrecognizer>=3.2.0b2` is not installed. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adapt-chat-promp-builder-message-copy-6aa4de39363ffbf2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adapt-chat-promp-builder-message-copy-6aa4de39363ffbf2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c3a9e049d658405dbeb6fb7d4d033a79f6ebe8ac --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adapt-chat-promp-builder-message-copy-6aa4de39363ffbf2.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Adapts how ChatPromptBuilder creates ChatMessages. Messages are deep copied to ensure all meta fields are copied correctly. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adapt-gpt-generator-bb7f52bd67f6b197.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adapt-gpt-generator-bb7f52bd67f6b197.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8382ecf14f89280430e1957f6aba4392c06c2033 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adapt-gpt-generator-bb7f52bd67f6b197.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adapt GPTGenerator to use strings for input and output diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-CohereGenerator-ca55e5b8e46df754.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-CohereGenerator-ca55e5b8e46df754.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bd639cceb20672efbf5ed3b83e82624bd830b540 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-CohereGenerator-ca55e5b8e46df754.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add CohereGenerator compatible with Cohere generate endpoint diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-MarkdownToTextDocument-f97ec6c5fb35527d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-MarkdownToTextDocument-f97ec6c5fb35527d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ceedb7eaaa98ec6b17c1be04539df3f639de2ad3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-MarkdownToTextDocument-f97ec6c5fb35527d.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add MarkdownToTextDocument, a file converter that converts Markdown files into a text Documents. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-azure-embedders-fd5f4fbcab0e1c48.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-azure-embedders-fd5f4fbcab0e1c48.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d66d3207d22c697b97f780e3ebfbb422bc0eb2de --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-azure-embedders-fd5f4fbcab0e1c48.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Adds AzureOpenAIDocumentEmbedder and AzureOpenAITextEmbedder as new embedders. These embedders are very similar to + their OpenAI counterparts, but they use the Azure API instead of the OpenAI API. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-azure-generators-a30c786204b22e48.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-azure-generators-a30c786204b22e48.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2a3422cfebbdcf47c4bdafbaee9dfae11678cfc5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-azure-generators-a30c786204b22e48.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Adds support for Azure OpenAI models with AzureOpenAIGenerator and AzureOpenAIChatGenerator components. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-chat-message-c456e4603529ae85.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-chat-message-c456e4603529ae85.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3d15712852058cb14823add1d33fb4a934918616 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-chat-message-c456e4603529ae85.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Introduce ChatMessage data class to facilitate structured handling and processing of message content + within LLM chat interactions. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-chatpromptbuilder-19acd18a6486909d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-chatpromptbuilder-19acd18a6486909d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8d80cb47d106dfc36f0f6958658010b87449b248 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-chatpromptbuilder-19acd18a6486909d.yaml @@ -0,0 +1,7 @@ +--- +enhancements: + - | + `ChatPromptBuilder` now supports changing its template at runtime. This allows you to define a default template and then change it based on your needs at runtime. +deprecations: + - | + `DynamicChatPromptBuilder` has been deprecated as `ChatPromptBuilder` fully covers its functionality. Use `ChatPromptBuilder` instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-csv-converter-5c0d52f180d498f5.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-csv-converter-5c0d52f180d498f5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5a01c94578615a5ad91fc7b2ae11270a18f84de --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-csv-converter-5c0d52f180d498f5.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add a CSV to Document converter component. Loads the file as bytes object. Adds the loaded string as a new document that can be used for further processing by the Document Splitter. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-current-date-promptbuilder-ff60c846f5a70dc6.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-current-date-promptbuilder-ff60c846f5a70dc6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..07dacf43a8d296df2048d1f10cf72fe26d625786 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-current-date-promptbuilder-ff60c846f5a70dc6.yaml @@ -0,0 +1,16 @@ +--- +enhancements: + - | + Allow the ability to add the current date inside a template in `PromptBuilder` using the following syntax: + + - `{% now 'UTC' %}`: Get the current date for the UTC timezone. + + - `{% now 'America/Chicago' + 'hours=2' %}`: Add two hours to the current date in the Chicago timezone. + + - `{% now 'Europe/Berlin' - 'weeks=2' %}`: Subtract two weeks from the current date in the Berlin timezone. + + - `{% now 'Pacific/Fiji' + 'hours=2', '%H' %}`: Display only the number of hours after adding two hours to the Fiji timezone. + + - `{% now 'Etc/GMT-4', '%I:%M %p' %}`: Change the date format to AM/PM for the GMT-4 timezone. + + Note that if no date format is provided, the default will be `%Y-%m-%d %H:%M:%S`. Please refer to [list of tz database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) for a list of timezones. \ No newline at end of file diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-custom-converter-hook-to-pypdf-cc7c333a6e7fc5f7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-custom-converter-hook-to-pypdf-cc7c333a6e7fc5f7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7e8ec760a62f1737f6f2a33d777ffd52b659d6e9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-custom-converter-hook-to-pypdf-cc7c333a6e7fc5f7.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add callable hook to PyPDFToDocument to enable easier customization of pdf to Document conversion. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-deprecation-warning-context-relevance-937df7e807ac1a8d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-deprecation-warning-context-relevance-937df7e807ac1a8d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5942aced037736f9afc5ab97d7102ea30e68f4e3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-deprecation-warning-context-relevance-937df7e807ac1a8d.yaml @@ -0,0 +1,4 @@ +--- +deprecations: + - | + The output of the ContextRelevanceEvaluator will change in Haystack 2.4.0. Contexts will be scored as a whole instead of individual statements and only the relevant sentences will be returned. A score of 1 is now returned if a relevant sentence is found, and 0 otherwise. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-dimensions-parameter-azureopeaniembedders-ef48fcc7c064b45c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-dimensions-parameter-azureopeaniembedders-ef48fcc7c064b45c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..62277a5f16f4a41ae7228e96be9a75a13c9d76bd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-dimensions-parameter-azureopeaniembedders-ef48fcc7c064b45c.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + add dimensions parameter to Azure OpenAI Embedders (AzureOpenAITextEmbedder and AzureOpenAIDocumentEmbedder) to fully support new embedding models like text-embedding-3-small, text-embedding-3-large and upcoming ones diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-dimensions-parameter-to-OpenAI-Embedders-to-fully-support-the-new-models-1393cc235e457733.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-dimensions-parameter-to-OpenAI-Embedders-to-fully-support-the-new-models-1393cc235e457733.yaml new file mode 100644 index 0000000000000000000000000000000000000000..777047af0b641be56c5b5b86378935661cf4eeac --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-dimensions-parameter-to-OpenAI-Embedders-to-fully-support-the-new-models-1393cc235e457733.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + add dimensions parameter to OpenAI Embedders to fully support new embedding models like text-embedding-3-small, text-embedding-3-large and upcoming ones diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-distribution-based-rank-fusion-mode-JoinDocuments-6fca30b82fd535ce.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-distribution-based-rank-fusion-mode-JoinDocuments-6fca30b82fd535ce.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e7bb46a8a5bb03b903fd1582c8fa0734a79d8bf2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-distribution-based-rank-fusion-mode-JoinDocuments-6fca30b82fd535ce.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Added a new mode in JoinDocuments, + Distribution-based rank fusion as + [the article](https://medium.com/plain-simple-software/distribution-based-score-fusion-dbsf-a-new-approach-to-vector-search-ranking-f87c37488b18) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-diversity-ranker-6ecee21134eda673.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-diversity-ranker-6ecee21134eda673.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0a9dfa90587ca5d64b0fc456c32d2ae6494b1be6 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-diversity-ranker-6ecee21134eda673.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Add `SentenceTransformersDiversityRanker`. + The Diversity Ranker orders documents in such a way as to maximize the overall diversity of the given documents. + The ranker leverages sentence-transformer models to calculate semantic embeddings for each document and the query. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-docx-file-to-document-47b603755a00fbe6.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-docx-file-to-document-47b603755a00fbe6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eb52b968f7681930e7be324b124d736de971192e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-docx-file-to-document-47b603755a00fbe6.yaml @@ -0,0 +1,6 @@ +--- +highlights: > + Adding the `DocxToDocument` component to convert Docx files to Documents. +features: + - | + Adding the `DocxToDocument` component inside the `converters` category. It uses the `python-docx` library to convert Docx files to haystack Documents. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-dynamic-per-message-templating-908468226c5e3d45.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-dynamic-per-message-templating-908468226c5e3d45.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ce3f40f6f1e92a3d32e71fcc1cdd1e27bdac723c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-dynamic-per-message-templating-908468226c5e3d45.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adds `ChatMessage` templating in `PromptBuilder` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-eval-and-evaluation-result-5e9ac742e323bda8.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-eval-and-evaluation-result-5e9ac742e323bda8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b270143ed12348d8a6f296659be6719cc2f19a40 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-eval-and-evaluation-result-5e9ac742e323bda8.yaml @@ -0,0 +1,4 @@ +preview: + - | + Add eval function for evaluation of components and Pipelines. + Adds EvaluationResult to store results of evaluation. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-failsafe-for-LLM-based-evaluators-34cdc183ab545315.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-failsafe-for-LLM-based-evaluators-34cdc183ab545315.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a97d33c8a2b70718e74f5286d5608fc8efd41e2f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-failsafe-for-LLM-based-evaluators-34cdc183ab545315.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + If an LLM-based evaluator (e.g., `Faithfulness` or `ContextRelevance`) is initialised with `raise_on_failure=False`, and if a call to an LLM fails or an LLM outputs an invalid JSON, the score of the sample is set to `NaN` instead of raising an exception. + The user is notified with a warning indicating the number of requests that failed. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-file-extension-classifier-preview-40f31c27bbd7cff9.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-file-extension-classifier-preview-40f31c27bbd7cff9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a9d6f9c9b2f38c7bf1a01546840602741b9913bd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-file-extension-classifier-preview-40f31c27bbd7cff9.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adds FileExtensionClassifier to preview components. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-filter-retriever-8901af26144d1a17.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-filter-retriever-8901af26144d1a17.yaml new file mode 100644 index 0000000000000000000000000000000000000000..12fc6794a4c9f037a1bf905844d965200d9dfce8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-filter-retriever-8901af26144d1a17.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Add FilterRetriever. + It retrieves documents that match the provided (either at init or runtime) filters. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-haystack-experimental-dependency-96ff02e71bc2af13.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-haystack-experimental-dependency-96ff02e71bc2af13.yaml new file mode 100644 index 0000000000000000000000000000000000000000..caa98d0d0a4ecb50db4bcd030079e44b9a54995b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-haystack-experimental-dependency-96ff02e71bc2af13.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Added haystack-experimental to the project's dependencies to enable automatic use of cutting-edge features from Haystack. Users can now access components from haystack-experimental by simply importing them from haystack_experimental instead of haystack. For more information, visit https://github.com/deepset-ai/haystack-experimental. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-hf-free-tier-checks-99384060139d5d30.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-hf-free-tier-checks-99384060139d5d30.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a56e4dd60c1e3246479fbaad853c5c8d56f9b4a6 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-hf-free-tier-checks-99384060139d5d30.yaml @@ -0,0 +1,7 @@ +--- +fixes: + - | + Resolves a bug where the HuggingFaceTGIGenerator and HuggingFaceTGIChatGenerator encountered issues if provided + with valid models that were not available on the HuggingFace inference API rate-limited tier. The fix, detailed + in [GitHub issue #6816](https://github.com/deepset-ai/haystack/issues/6816) and its GitHub PR, ensures these + components now correctly handle model availability, eliminating previous limitations. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-html-to-document-21fe38b244388f4d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-html-to-document-21fe38b244388f4d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1ff9b25b6b3b2e9f050e72abaf4f14e238b88ffe --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-html-to-document-21fe38b244388f4d.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adds HTMLToDocument component to convert HTML to a Document. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-hugging-face-chat-local-5fe7a88e24fde11b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-hugging-face-chat-local-5fe7a88e24fde11b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4722814426ded4d0331688aa815310531780196a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-hugging-face-chat-local-5fe7a88e24fde11b.yaml @@ -0,0 +1,19 @@ +--- +features: + - | + Introducing the HuggingFaceLocalChatGenerator, a new chat-based generator designed for leveraging chat models from + Hugging Face's (HF) model hub. Users can now perform inference with chat-based models in a local runtime, utilizing + familiar HF generation parameters, stop words, and even employing custom chat templates for custom message formatting. + This component also supports streaming responses and is optimized for compatibility with a variety of devices. + + Here is an example of how to use the HuggingFaceLocalChatGenerator: + + ```python + from haystack.components.generators.chat import HuggingFaceLocalChatGenerator + from haystack.dataclasses import ChatMessage + + generator = HuggingFaceLocalChatGenerator(model="HuggingFaceH4/zephyr-7b-beta") + generator.warm_up() + messages = [ChatMessage.from_user("What's Natural Language Processing? Be brief.")] + print(generator.run(messages)) + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-huggingface-tgi-chat-c63f4879a5d81342.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-huggingface-tgi-chat-c63f4879a5d81342.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d5b17782868054f6f180ba76b8538f2ad553e133 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-huggingface-tgi-chat-c63f4879a5d81342.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Adds `HuggingFaceTGIChatGenerator` for text and chat generation. This components support remote inferencing for + Hugging Face LLMs via text-generation-inference (TGI) protocol. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-inf-mode-reader-e6eb79920e73c956.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-inf-mode-reader-e6eb79920e73c956.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4dbe549f133e29c415bcb59c387bae589a13b3c0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-inf-mode-reader-e6eb79920e73c956.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Adds inference mode to model call of the ExtractiveReader. This prevents gradients from being calculated during inference time in pytorch. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-keep-columns-to-EvalRunResult-comparative-be3e15ce45de3e0b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-keep-columns-to-EvalRunResult-comparative-be3e15ce45de3e0b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3720a0ca7dfec15d74bff519376420719781dbdf --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-keep-columns-to-EvalRunResult-comparative-be3e15ce45de3e0b.yaml @@ -0,0 +1,5 @@ +--- + +enhancements: + - | + Added a new parameter to `EvaluationRunResult.comparative_individual_scores_report()` to specify columns to keep in the comparative DataFrame. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-metadata-field-ranker-a8afd5bf15f29a0a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-metadata-field-ranker-a8afd5bf15f29a0a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f8f3110f4842e902eeeafe5430ff539307012aa3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-metadata-field-ranker-a8afd5bf15f29a0a.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adds MetaFieldRanker, a component that ranks a list of Documents based on the value of a metadata field of choice. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-model-and-tokenizer-kwargs-4b7618806665f8ba.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-model-and-tokenizer-kwargs-4b7618806665f8ba.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5f0395d94ea644eef184c574419a2a56fa1f13f8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-model-and-tokenizer-kwargs-4b7618806665f8ba.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Adds model_kwargs and tokenizer_kwargs to the components TransformersSimilarityRanker, SentenceTransformersDocumentEmbedder, SentenceTransformersTextEmbedder. + This allows passing things like model_max_length or torch_dtype for better management of model inference. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-model-kwargs-extractive-reader-c0b65ab34572408f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-model-kwargs-extractive-reader-c0b65ab34572408f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b647329e79036ab95727a29c49b7a6c2b7b0ebbd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-model-kwargs-extractive-reader-c0b65ab34572408f.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Add new variable model_kwargs to the ExtractiveReader so we can pass different loading options supported by + HuggingFace. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-most-diverse-ranker-21cf310be4554551.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-most-diverse-ranker-21cf310be4554551.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8f475dd609b1a4fee84d6e317104db9a90173104 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-most-diverse-ranker-21cf310be4554551.yaml @@ -0,0 +1,17 @@ +--- +prelude: > + We're introducing a new ranker to Haystack - DiversityRanker. This + ranker aims to maximize the overall diversity of the given documents. + It leverages sentence-transformer models to calculate semantic embeddings + for each document. It orders documents so that the next one, on average, + is least similar to the already selected documents. Such ranking results in a + list where each subsequent document contributes the most to the overall + diversity of the selected document set. +features: + - | + The DiversityRanker can be used like other rankers in Haystack and + it can be particularly helpful in cases where you have highly relevant + yet similar sets of documents. By ensuring a diversity of documents, + this new ranker facilitates a more comprehensive utilization of the + documents and, particularly in RAG pipelines, potentially contributes + to more accurate and rich model responses. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-on_agent_final_answer_to_agent_base-7798ea8de2f43af0.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-on_agent_final_answer_to_agent_base-7798ea8de2f43af0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..347fe8a0be07c3473221018c05b79c0666a70cf0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-on_agent_final_answer_to_agent_base-7798ea8de2f43af0.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + added support for using `on_final_answer` trough `Agent` `callback_manager` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-openai-async-1f65701142f77181.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-openai-async-1f65701142f77181.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7d97d8064eed5bc9cb5ea663b5a2b9380cc57a88 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-openai-async-1f65701142f77181.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Add asyncio support to the OpenAI invocation layer. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-page-number-to-answer-1b6d68dc93508314.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-page-number-to-answer-1b6d68dc93508314.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6a834919a7107f285aafe34ba3d7af2c042cda8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-page-number-to-answer-1b6d68dc93508314.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + The ExtractiveReader can now add page numbers to the meta data of ExtractedAnswers. + It's done automatically if the source document of the ExtractedAnswer contains a page number in its meta data. + The ExtractedAnswer will then contain a key "answer_page_number" in its meta data. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-page-number-to-document-splitter-162e9dc7443575f0.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-page-number-to-document-splitter-162e9dc7443575f0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8c97663cf1fb134ba2fa126e039dd7da3fa1a147 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-page-number-to-document-splitter-162e9dc7443575f0.yaml @@ -0,0 +1,7 @@ +--- +highlights: > + Add the "page_number" field to the metadata of all output documents. + +enhancements: + - | + Now the DocumentSplitter adds the "page_number" field to the metadata of all output documents to keep track of the page of the original document it belongs to. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-pdfminer-converter-f08f68e38ef82f4a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-pdfminer-converter-f08f68e38ef82f4a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7eb656a571eea4e871b57f947f203304ccbaf2c2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-pdfminer-converter-f08f68e38ef82f4a.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Provides users the ability to customize text extraction from PDF files. It is particularly useful for PDFs with unusual layouts, such as those containing multiple text columns. For instance, users can configure the object to retain the reading order. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-pipeline-templates-831f857c6387f8c3.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-pipeline-templates-831f857c6387f8c3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eb7f21c19a1db0a00363c48f8f5e716ffa07d8f7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-pipeline-templates-831f857c6387f8c3.yaml @@ -0,0 +1,13 @@ +--- +highlights: > + Introducing a flexible and dynamic approach to creating NLP pipelines with predefined templates. + This innovative feature allows users to easily construct and customize complex data processing pipelines for various + NLP tasks. + + For example, the following pipeline template can be used to create an indexing pipeline: + ```python + from haystack import Pipeline, PredefinedPipeline + + pipe = Pipeline.from_template(PredefinedPipeline.INDEXING) + result = pipe.run({"converter": {"sources": ["some_file.txt"]}}) + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-remove-method-to-pipeline-base-c7ca1aa68b0f396b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-remove-method-to-pipeline-base-c7ca1aa68b0f396b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bfc1dc44260608fd924a3ce1b8a65679fc73591c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-remove-method-to-pipeline-base-c7ca1aa68b0f396b.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Added the 'remove_component' method in 'PipelineBase' to delete components and its connections. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-router-f1f0cec79b1efe9a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-router-f1f0cec79b1efe9a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7d6084f508647831313491210cd1697d6e297e07 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-router-f1f0cec79b1efe9a.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Add `ConditionalRouter` component to enhance the conditional pipeline routing capabilities. + The `ConditionalRouter` component orchestrates the flow of data by evaluating specified route conditions + to determine the appropriate route among a set of provided route alternatives. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-sas-b8dbf61c0d78ba19.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-sas-b8dbf61c0d78ba19.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5078a4c93b5a8a11cd8b012c97167b6f9aab6012 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-sas-b8dbf61c0d78ba19.yaml @@ -0,0 +1,10 @@ +--- +features: + - | + Adds support for the Semantic Answer Similarity (SAS) metric to `EvaluationResult.calculate_metrics(...)`: + ```python + from haystack.evaluation.metrics import Metric + sas_metric = eval_result.calculate_metrics( + Metric.SAS, output_key="answers", model="sentence-transformers/paraphrase-multilingual-mpnet-base-v2" + ) + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-search_engine_kwargs-to-web-retriever-67fac44ef0039b7f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-search_engine_kwargs-to-web-retriever-67fac44ef0039b7f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c3dcf8c96aad7eb8fb9aaf88e8c0e9517a4cbc3a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-search_engine_kwargs-to-web-retriever-67fac44ef0039b7f.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Add `search_engine_kwargs` param to WebRetriever so it can be propagated + to WebSearch. This is useful, for example, to pass the engine id when + using Google Custom Search. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-sentence-transformers-text-embedder-2ce0de6f7a1149e1.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-sentence-transformers-text-embedder-2ce0de6f7a1149e1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..15d65d00a1816270a04294ae0f3272d568009116 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-sentence-transformers-text-embedder-2ce0de6f7a1149e1.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Add Sentence Transformers Text Embedder. + It is a simple component that embeds strings into vectors. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-serialization-to-inmemorydocumentstore-2aa4d9ac85b961c5.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-serialization-to-inmemorydocumentstore-2aa4d9ac85b961c5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..48e3c8e427e09c7efb0b67da4e6eff1d99da7ffc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-serialization-to-inmemorydocumentstore-2aa4d9ac85b961c5.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Added serialization methods save_to_disk and write_to_disk to InMemoryDocumentStore. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-serper-dev-8c582749728e3699.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-serper-dev-8c582749728e3699.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8ce2fd9bba9224c9bfa38e8a07c56f3acbeb96ca --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-serper-dev-8c582749728e3699.yaml @@ -0,0 +1,3 @@ +--- +preview: + - Adds SerperDevWebSearch component to retrieve URLs from the web. See https://serper.dev/ for more information. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-similarity-ranker-401bf595cea7318a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-similarity-ranker-401bf595cea7318a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a0d3217a6703613bf98e3ee2f2052760cf8837a8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-similarity-ranker-401bf595cea7318a.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adds SimilarityRanker, a component that ranks a list of Documents based on their similarity to the query. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-skip-prompt-for-hf-model-agent-89aef2838edb907c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-skip-prompt-for-hf-model-agent-89aef2838edb907c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..51760da92480c05bec44c3fb3ef15db1561ab830 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-skip-prompt-for-hf-model-agent-89aef2838edb907c.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix the bug that the responses of Agents using local HF models contain the prompt text. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-split_id_and_overlap_to_DocumentSplitter-8180ad8f13495741.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-split_id_and_overlap_to_DocumentSplitter-8180ad8f13495741.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e3eba2d57bca8eca3b91a6c1ce7acb1c1fbd92a7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-split_id_and_overlap_to_DocumentSplitter-8180ad8f13495741.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + The `DocumentSplitter` now has support for the `split_id` and `split_overlap` to allow for more control over the splitting process. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-streaming-chunk-67897d7cb2c0d7c0.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-streaming-chunk-67897d7cb2c0d7c0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..428d2c77e658fe014c3ed92d2fed65c3928bd6a0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-streaming-chunk-67897d7cb2c0d7c0.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Introduce the StreamingChunk dataclass for efficiently handling chunks of data streamed from a language model, + encapsulating both the content and associated metadata for systematic processing. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-tikaconverter-2.0-ef637f93114e6c96.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-tikaconverter-2.0-ef637f93114e6c96.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e1ec435153d9e26691e0045d618a0405875e483c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-tikaconverter-2.0-ef637f93114e6c96.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add TikaDocumentConverter component to convert files of different types to Documents. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-timeout-arg-to-promptnode-de11f17733344052.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-timeout-arg-to-promptnode-de11f17733344052.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c1ff4630c74f19663c71f4217fbe8078111bdb10 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-timeout-arg-to-promptnode-de11f17733344052.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Introduces a new timeout keyword argument in PromptNode, addressing and fixing the issue #5380 for enhanced control over individual calls to OpenAI. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-trust-remote-code-feature-c133b2b245d2ea7a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-trust-remote-code-feature-c133b2b245d2ea7a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a4cf31426d1b9bb640ea3a289b3d8949d906df45 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-trust-remote-code-feature-c133b2b245d2ea7a.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add trust_remote_code parameter to SentenceTransformersDocumentEmbedder and SentenceTransformersTextEmbedder for allowing custom models and scripts. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-unicode-normalization-and-ascii-mode-to-document-cleaner-ba536b46e499663c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-unicode-normalization-and-ascii-mode-to-document-cleaner-ba536b46e499663c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d4d28ee47bc108c19b1b47076c5e395522c3ca8e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-unicode-normalization-and-ascii-mode-to-document-cleaner-ba536b46e499663c.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Added `unicode_normalization` parameter to the DocumentCleaner, allowing to normalize the text to NFC, NFD, NFKC, or NFKD. + - | + Added `ascii_only` parameter to the DocumentCleaner, transforming letters with diacritics to their ASCII equivalent and removing other non-ASCII characters. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-zero-shot-document-classifier-3ab1d7bbdc04db05.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-zero-shot-document-classifier-3ab1d7bbdc04db05.yaml new file mode 100644 index 0000000000000000000000000000000000000000..82f35c467116265f2200eaece2151dad113d5a27 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-zero-shot-document-classifier-3ab1d7bbdc04db05.yaml @@ -0,0 +1,7 @@ +--- +highlights: > + Adds support for zero shot document classification +features: + - | + Adds support for zero shot document classification. This allows you to classify documents into user-defined + classes (binary and multi-label classification) using pre-trained models from huggingface. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adding-metadata-info-from-OpenAI-f5309af5f59bb6a7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adding-metadata-info-from-OpenAI-f5309af5f59bb6a7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f8de43bb1d780ccbb5e42bb8b1efc6e26955362c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adding-metadata-info-from-OpenAI-f5309af5f59bb6a7.yaml @@ -0,0 +1,5 @@ +--- + +enhancements: + - | + When using "openai" for the LLM-based evaluators the metadata from OpenAI will be in the output dictionary, under the key "meta". diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adjust-max-new-tokens-to-512-in-huggingface-generators-76d9aba116b65e70.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adjust-max-new-tokens-to-512-in-huggingface-generators-76d9aba116b65e70.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1103cfb613b56ab9febbfd311ca920945e064752 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adjust-max-new-tokens-to-512-in-huggingface-generators-76d9aba116b65e70.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Set max_new_tokens default to 512 in Hugging Face generators. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adjust-web-retriever-caching-logic-2e05fbc972a86f29.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adjust-web-retriever-caching-logic-2e05fbc972a86f29.yaml new file mode 100644 index 0000000000000000000000000000000000000000..41f6bc498569262b923a0715bf8294d35ad4b541 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adjust-web-retriever-caching-logic-2e05fbc972a86f29.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + The WebRetriever now employs an enhanced caching mechanism that caches web page content based on search engine + results rather than the query. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adopt-hf-token-770edaccf6278ad9.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adopt-hf-token-770edaccf6278ad9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0a0f1e63e4baebf3e5ca05d39a04b55273e5a636 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/adopt-hf-token-770edaccf6278ad9.yaml @@ -0,0 +1,8 @@ +--- +preview: + - | + Adopt Hugging Face `token` instead of the deprecated `use_auth_token`. + Add this parameter to `ExtractiveReader` and `SimilarityRanker` to allow + loading private models. + Proper handling of `token` during serialization: if it is a string (a possible valid token) + it is not serialized. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/allow-connecting-same-components-again-e63cf719b9bf2a14.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/allow-connecting-same-components-again-e63cf719b9bf2a14.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b97c2674c6a558cd16fefe91a30518a5650eebb5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/allow-connecting-same-components-again-e63cf719b9bf2a14.yaml @@ -0,0 +1,5 @@ +--- +issues: + - | + Make `connect` idempotent, allowing connecting the same components more than once. Specially useful + in Jupiter notebooks. Fixes https://github.com/deepset-ai/haystack/issues/6359. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/allow-parameters-for-openai-generator-8ce86ba1bac80817.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/allow-parameters-for-openai-generator-8ce86ba1bac80817.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0c5e2b93b7ab1c27890c5c42019fde9be5d7f7d5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/allow-parameters-for-openai-generator-8ce86ba1bac80817.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + LLM based evaluators can pass in supported OpenAIGenerator parameters via api_params. + This allows for custom generation_kwargs, changing the api_base_url (for local evaluation), + and all other supported parameters as described in the OpenAIGenerator docs. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/answer-refactoring-b617afa946311ac8.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/answer-refactoring-b617afa946311ac8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1c2f609804f6e1e773c10d65f61d9a4cbe7db679 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/answer-refactoring-b617afa946311ac8.yaml @@ -0,0 +1,8 @@ +--- +enhancements: + - | + Refactor `Answer` dataclass and classes that inherited it. + Now `Answer` is a Protocol, classes that used to inherit it now respect that interface. + We also added a new `ExtractiveTableAnswer` to be used for table question answering. + + All classes now are easily serializable using `to_dict()` and `from_dict()` like `Document` and components. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/async-component-support-machinery-6ea4496241aeb3b2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/async-component-support-machinery-6ea4496241aeb3b2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5dc43dccd212a8c87815d27fde68ee575bbc22e3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/async-component-support-machinery-6ea4496241aeb3b2.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Extend core component machinery to support an optional asynchronous `run_async` method in components. + If it's present, it should have the same parameters (and output types) as the run method and must be + implemented as a coroutine. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/avoid-LLM-based-evaluators-returning-NaN-579bc4593febb691.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/avoid-LLM-based-evaluators-returning-NaN-579bc4593febb691.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5245f35260efe45aa65ee69de9ed8483bc5f3280 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/avoid-LLM-based-evaluators-returning-NaN-579bc4593febb691.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + `FaithfullnessEvaluator` and `ContextRelevanceEvaluator` now return `0` instead of `NaN` when applied to an empty context or empty statements. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/azure-ocr-converter-enhancements-c882456cad9a5efc.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/azure-ocr-converter-enhancements-c882456cad9a5efc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dcce43c091d2dea746ad2b03cb763fb447b41a37 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/azure-ocr-converter-enhancements-c882456cad9a5efc.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Enhanced the AzureOCRDocumentConverter to include advanced handling of tables and text. Features such as extracting preceding and following context for tables, merging multiple column headers, and enabling single column page layout for text have been introduced. This update furthers the flexibility and accuracy of document conversion within complex layouts. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/azure-openai-generator-timeout-c39ecd6d4b0cdb4b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/azure-openai-generator-timeout-c39ecd6d4b0cdb4b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..49217671fce8cf5a72cd942ad994ab6721f78c71 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/azure-openai-generator-timeout-c39ecd6d4b0cdb4b.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + `AzureOpenAIGenerator` and `AzureOpenAIChatGenerator` can now be configured passing a timeout for the underlying `AzureOpenAI` client. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/better-deserialization-errors-f2b0e226534f4cd2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/better-deserialization-errors-f2b0e226534f4cd2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..af2ea1986c5cf14bed3aaeb628627e94a490c64f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/better-deserialization-errors-f2b0e226534f4cd2.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Improved error messages for deserialization errors. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/bump-transformers-to-4-32-1-5b800ceff440b871.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/bump-transformers-to-4-32-1-5b800ceff440b871.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ad1991e6b92f949774dff5702dd1a1edbdee88ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/bump-transformers-to-4-32-1-5b800ceff440b871.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Upgrade transformers to the latest version 4.32.1 so that Haystack benefits from Llama and T5 bugfixes: https://github.com/huggingface/transformers/releases/tag/v4.32.1 diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/bump-transformers-to-4-32-341a42ff09796725.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/bump-transformers-to-4-32-341a42ff09796725.yaml new file mode 100644 index 0000000000000000000000000000000000000000..59be09fac8bf5465c81d0f375cfaf78d4bb7ec45 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/bump-transformers-to-4-32-341a42ff09796725.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Upgrade Transformers to the latest version 4.32.0. + This version adds support for the GPTQ quantization and integrates MPT models. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/bump-transformers-to-4-34-38d045d8e42ea0a2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/bump-transformers-to-4-34-38d045d8e42ea0a2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a147f7ef95b78b36163c93637772bccca9983ec3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/bump-transformers-to-4-34-38d045d8e42ea0a2.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Upgrade Transformers to the latest version 4.34.1. + This version adds support for the new Mistral, Persimmon, BROS, ViTMatte, and Nougat models. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/byte-stream-mime-type-b060e96791c4993a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/byte-stream-mime-type-b060e96791c4993a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3771e5bd774e12ef59ea7baa62351d35ad12286c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/byte-stream-mime-type-b060e96791c4993a.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add `mime_type` field to `ByteStream` dataclass. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/canals-0.4.0-b69b19069c4a9e0f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/canals-0.4.0-b69b19069c4a9e0f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..da1aeb54be8de83e0ccd95c92b3699f777a75b2b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/canals-0.4.0-b69b19069c4a9e0f.yaml @@ -0,0 +1,4 @@ +--- +preview: + - "Migrate existing v2 components to Canals 0.4.0" + - "Fix TextFileToDocument using wrong Document class" diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/change-metadata-to-meta-0fada93f04628c79.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/change-metadata-to-meta-0fada93f04628c79.yaml new file mode 100644 index 0000000000000000000000000000000000000000..339c6536c354a9d9e3c223724e372802579e786a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/change-metadata-to-meta-0fada93f04628c79.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Rename `metadata` to `meta`. + Rename `metadata_fields_to_embed` to `meta_fields_to_embed` in all Embedders. + Rename `metadata_field` to `meta_field` in `MetaFieldRanker`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/chatgpt-llm-generator-d043532654efe684.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/chatgpt-llm-generator-d043532654efe684.yaml new file mode 100644 index 0000000000000000000000000000000000000000..db9a092492cf46958e69856e84020b00c5343c4d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/chatgpt-llm-generator-d043532654efe684.yaml @@ -0,0 +1,2 @@ +preview: + - Introduce `GPTGenerator`, a class that can generate completions using OpenAI Chat models like GPT3.5 and GPT4. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/check-id-hash-keys-postinit-28b012cdeada2c1e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/check-id-hash-keys-postinit-28b012cdeada2c1e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..95dd463dc21e864e60f26ca7289a7385b85ad812 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/check-id-hash-keys-postinit-28b012cdeada2c1e.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + The Document dataclass checks if `id_hash_keys` is None or empty in + __post_init__. If so, it uses the default factory to set a default valid value. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/component-greedy-d6630af901e96a4c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/component-greedy-d6630af901e96a4c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c973a150d362029163f5c30813098712f658c566 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/component-greedy-d6630af901e96a4c.yaml @@ -0,0 +1,12 @@ +--- +features: + - | + Add `is_greedy` argument to `@component` decorator. + This flag will change the behaviour of `Component`s with inputs that have a `Variadic` type + when running inside a `Pipeline`. + + Variadic `Component`s that are marked as greedy will run as soon as they receive their first input. + If not marked as greedy instead they'll wait as long as possible before running to make sure they + receive as many inputs as possible from their senders. + + It will be ignored for all other `Component`s even if set explicitly. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/component-kw-only-run-args-eedee8907232d2d4.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/component-kw-only-run-args-eedee8907232d2d4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..68ef50fbffae8249c0a723298b52ed6f6ccbc775 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/component-kw-only-run-args-eedee8907232d2d4.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix ComponentMeta ignoring keyword-only parameters in the `run` method. ComponentMeta.__call__ handles the creation of InputSockets for the component's inputs when the latter has not explicitly called _Component.set_input_types(). This logic was not correctly handling keyword-only parameters. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/component-repr-a6486af81530bc3b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/component-repr-a6486af81530bc3b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3a7439e9266298b8feba2595b12d30661ba45445 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/component-repr-a6486af81530bc3b.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Add `__repr__` to all Components to print their I/O. + This can also be useful in Jupyter notebooks as this will be shown as a cell output + if the it's the last expression in a cell. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/component-set-input-type-constraints-0b1130c1b49d9648.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/component-set-input-type-constraints-0b1130c1b49d9648.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fa7c3bc06cab784812f143537aa7e07f9bad52e3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/component-set-input-type-constraints-0b1130c1b49d9648.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Add constraints to `component.set_input_type` and `component.set_input_types` to prevent undefined behaviour + when the `run` method does not contain a variadic keyword argument. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/component-set-output-type-override-852a19b3f0621fb0.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/component-set-output-type-override-852a19b3f0621fb0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2a06faddebff161d431dffd3dbd4ce5676d81542 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/component-set-output-type-override-852a19b3f0621fb0.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Prevent `set_output_types`` from being called when the `output_types`` decorator is used. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/components-reuse-ccc5f2d4b9d7f9ff.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/components-reuse-ccc5f2d4b9d7f9ff.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1ef055441178b398614510e8414ca82afe4aa345 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/components-reuse-ccc5f2d4b9d7f9ff.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Change `Pipeline.add_component()` to fail if the `Component` instance has already been added in another `Pipeline`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/converters-allow-passing-meta-70fb498b6eb80468.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/converters-allow-passing-meta-70fb498b6eb80468.yaml new file mode 100644 index 0000000000000000000000000000000000000000..839fe16a7336e3ffd22131fe472acd5417b6523b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/converters-allow-passing-meta-70fb498b6eb80468.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Make all Converters accept `meta` in the `run` method, so that users can + provide their own metadata. + The length of this list should match the number of `sources`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/converters-standardize-inputs-ed2ba9c97b762974.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/converters-standardize-inputs-ed2ba9c97b762974.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1b1724da3cd9de31233ace160027de26406051b2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/converters-standardize-inputs-ed2ba9c97b762974.yaml @@ -0,0 +1,22 @@ +--- +upgrade: + - | + If you are using `AzureOCRDocumentConverter` or `TikaDocumentConverter`, + you need to change `paths` to `sources` in the `run` method. + + An example: + ```python + from haystack.components.converters import TikaDocumentConverter + converter = TikaDocumentConverter() + converter.run(paths=["paths/to/file1.pdf", "path/to/file2.pdf"]) + ``` + + The last line should be changed to: + ```python + converter.run(sources=["paths/to/file1.pdf", "path/to/file2.pdf"]) + ``` + +enhancements: + - | + Make all the Converters accept the `sources` parameter in the `run` method. + `sources` is a list that can contain str, Path or ByteStream objects. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deepset-cloud-document-store-search-fields-40b2322466f808a3.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deepset-cloud-document-store-search-fields-40b2322466f808a3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..679a14276d45122b797395da0dcb6e63bca7d2d3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deepset-cloud-document-store-search-fields-40b2322466f808a3.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + `DeepsetCloudDocumentStore` supports searching multiple fields in sparse queries. This enables you to search meta fields as well when using `BM25Retriever`. For example set `search_fields=["content", "title"]` to search the `title` meta field along with the document `content`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-chatmessage-toopenaiformat-9b1b2987a568d3d7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-chatmessage-toopenaiformat-9b1b2987a568d3d7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8b861068a3882243055993f65afce04f7f592afc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-chatmessage-toopenaiformat-9b1b2987a568d3d7.yaml @@ -0,0 +1,4 @@ +--- +upgrade: + - | + Remove `ChatMessage.to_openai_format` method. Use `haystack.components.generators.openai_utils._convert_message_to_openai_format` instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-debug-path-976bb5a851365233.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-debug-path-976bb5a851365233.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e80ab8aa9303d11d055e9956714a6bde6a1284e8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-debug-path-976bb5a851365233.yaml @@ -0,0 +1,4 @@ +--- +deprecations: + - | + `Pipeline` init argument `debug_path` is deprecated and will be remove in version `2.7.0`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-dynamic-promptbuilders-14de431d98ae3e39.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-dynamic-promptbuilders-14de431d98ae3e39.yaml new file mode 100644 index 0000000000000000000000000000000000000000..aed37439b0ba5e9d1aad6adbff6be3ad1a8aad26 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-dynamic-promptbuilders-14de431d98ae3e39.yaml @@ -0,0 +1,4 @@ +--- +upgrade: + - | + Removed the deprecated `DynamicPromptBuilder` and `DynamicChatPromptBuilder` components. Use `PromptBuilder` and `ChatPromptBuilder` instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-legacy-filters-7c9530644d972089.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-legacy-filters-7c9530644d972089.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eeb29132f64509d63a0cacfd0cc15c72e782a06e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-legacy-filters-7c9530644d972089.yaml @@ -0,0 +1,5 @@ +--- +deprecations: + - | + Haystack 1.x legacy filters are deprecated and will be removed in a future release. Please use the new + filter style as described in the documentation - https://docs.haystack.deepset.ai/docs/metadata-filtering diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-method-to-openai-format-fb2538cf3f610d2a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-method-to-openai-format-fb2538cf3f610d2a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f42c7ac92d27d4cfc2a2ca49d69cd76831b27bad --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-method-to-openai-format-fb2538cf3f610d2a.yaml @@ -0,0 +1,7 @@ +--- +deprecations: + - | + Deprecate the method `to_openai_format` of the `ChatMessage` dataclass. + This method was never intended to be public and was only used internally. + Now, each Chat Generator will know internally how to convert the messages to + the format of their specific provider. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-self-connection-665647384ae2792b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-self-connection-665647384ae2792b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7a19a292dc25937c4b2926a5008168e910a6598c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-self-connection-665647384ae2792b.yaml @@ -0,0 +1,4 @@ +--- +deprecations: + - | + Deprecate connecting a Component to itself when calling `Pipeline.connect()`, it will raise an error from version `2.7.0` onwards diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate_max_loops_allowed-2b17a9b442b68199.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate_max_loops_allowed-2b17a9b442b68199.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6cce5d86484f3bd3e9c4cf202cd72eab1f051aa1 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate_max_loops_allowed-2b17a9b442b68199.yaml @@ -0,0 +1,12 @@ +--- +enhancements: + - | + Add new `Pipeline` init argument `max_runs_per_component`, this has the same identical + behaviour as the existing `max_loops_allowed` argument but is more descriptive of its actual effects. + - | + Add new `PipelineMaxLoops` to reflect new `max_runs_per_component` init argument +deprecations: + - | + `Pipeline` init argument `max_loops_allowed` is deprecated and will be remove in version `2.7.0`. Use `max_runs_per_component` instead. + - | + `PipelineMaxLoops` exception is deprecated and will be remove in version `2.7.0`. Use `PipelineMaxComponentRuns` instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecated-gpt-3.5-as-default-model-d03cafe1fdc2ada2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecated-gpt-3.5-as-default-model-d03cafe1fdc2ada2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6dd7ba5dff13668bc8fa529ccc0408f839b80e44 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecated-gpt-3.5-as-default-model-d03cafe1fdc2ada2.yaml @@ -0,0 +1,4 @@ +--- +deprecations: + - | + The 'gpt-3.5-turbo' as the default model for the `OpenAIGenerator` and `OpenAIChatGenerator` will be replaced by 'gpt-4o-mini'. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/device-map-2ced24b510e45774.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/device-map-2ced24b510e45774.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e2317df42ecd40e4a3351de471d1e988960171a6 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/device-map-2ced24b510e45774.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Use `device_map` when loading a TransformersSimilarityRanker and ExtractiveReader. + This allows for multi-device inference and for loading quantized models (e.g. load_in_8bit=True) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/doc-id-rework-85e82b5359282f7e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/doc-id-rework-85e82b5359282f7e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c3d87ba2c6e08da50428f1ac4e9ef056d17eef54 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/doc-id-rework-85e82b5359282f7e.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Rework `Document.id` generation, if an `id` is not explicitly set it's generated + using all `Document` field' values, `score` is not used. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-backward-compatible-07c4151e98ef8511.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-backward-compatible-07c4151e98ef8511.yaml new file mode 100644 index 0000000000000000000000000000000000000000..23e883d22502a907d2e0940f8668492000572791 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-backward-compatible-07c4151e98ef8511.yaml @@ -0,0 +1,20 @@ +--- +prelude: > + The `Document` serialisation has been changed quite a bit, this will make it easier to implement + new Document Stores. + + The most notable change is that the `Document.flatten()` method has been removed. + `Document.to_dict()` now has a `flatten` parameter, that defaults to `True` for backward compatibility. + It will flatten metadata keys at the same level of other `Document` fields when converting to `dict`. + + `to_json` and `from_json` have been removed, as `to_dict` and `from_dict` already handle serialisation + of `dataframe` and `blob` fields. + Now `metadata` must only contain primitives that can be serialised to JSON with no custom encoders. + If any Document Store needs custom serialisation they can implement their own logic. + + `Document` has also been made backward compatible so that it can be created using dictionaries + structured as the legacy 1.x `Document`. The legacy fields will be converted automatically to + their new counterparts, or ignored if there's none. +preview: + - | + Refactor Document serialisation and make it backward compatible with Haystack 1.x diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-embedding-type-d66c44ac6878fbdd.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-embedding-type-d66c44ac6878fbdd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c01c4a250169fbe095bc7f08c36a15509d1e46e3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-embedding-type-d66c44ac6878fbdd.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Change `Document`'s `embedding` field type from `numpy.ndarray` to `List[float]` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-equality-4bc1b5273bd5b7f1.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-equality-4bc1b5273bd5b7f1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..880fb9ebb64a13a3a99d7a6153c81894bf783db7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-equality-4bc1b5273bd5b7f1.yaml @@ -0,0 +1,14 @@ +--- +preview: + - | + Refactor `Document.__eq__()` so it compares the `Document`s dictionary + representation instead of only their `id`. + Previously this comparison would have unexpectedly worked: + ```python + first_doc = Document(id="1", content="Hey!") + second_doc = Document(id="1", content="Hello!") + assert first_doc == second_doc + first_doc.content = "Howdy!" + assert first_doc == second_doc + ``` + With this change the last comparison would rightly fail. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-language-classifier-1ec0b3c4d08989c0.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-language-classifier-1ec0b3c4d08989c0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..07372290f3ddce8a2f6c3abc12e101fd1738d793 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-language-classifier-1ec0b3c4d08989c0.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Added DocumentLanguageClassifier component so that Documents can be routed to different components based on the detected language for example during preprocessing. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-ndcg-evaluator-d579f51dd76ae76a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-ndcg-evaluator-d579f51dd76ae76a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eae5d3207981771aa8d00d571304b6347f6f412a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-ndcg-evaluator-d579f51dd76ae76a.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Added a new component DocumentNDCGEvaluator, which is similar to DocumentMRREvaluator and useful for retrieval evaluation. It calculates the normalized discounted cumulative gain, an evaluation metric useful when there are multiple ground truth relevant documents and the order in which they are retrieved is important. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-text-to-content-39b5439480af5c41.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-text-to-content-39b5439480af5c41.yaml new file mode 100644 index 0000000000000000000000000000000000000000..95e7d818e6aa38e1aa8ba2ac6b008b0884ffebd8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-text-to-content-39b5439480af5c41.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Rename `Document`'s `text` field to `content` to enhance backward compatibility diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-writer-v2-bbe0a62b3066f9cf.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-writer-v2-bbe0a62b3066f9cf.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7423892b84e148d8d746302f14f589895cf3fe56 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-writer-v2-bbe0a62b3066f9cf.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Added new DocumentWriter component to Haystack v2 preview so that documents can be written to stores. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/docx-para-forwardref-31941f54ab3b679f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/docx-para-forwardref-31941f54ab3b679f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..46dc52bb059676bb808fcf66cc134db1b7db33bb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/docx-para-forwardref-31941f54ab3b679f.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Use a forward reference for the `Paragraph` class in the `DOCXToDocument` converter + to prevent import errors. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/docxtodocument-rename-3acf592c89aea430.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/docxtodocument-rename-3acf592c89aea430.yaml new file mode 100644 index 0000000000000000000000000000000000000000..706a244142165b13fc05abb6b75730e38c260593 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/docxtodocument-rename-3acf592c89aea430.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Renamed component from DocxToDocument to DOCXToDocument to follow the naming convention of other converter components. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/dynamic-chat-prompt-templating-enhancement-e8d36cbf3be46da7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/dynamic-chat-prompt-templating-enhancement-e8d36cbf3be46da7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a94b688a17c4166a09b7952fb20afb86c657ce29 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/dynamic-chat-prompt-templating-enhancement-e8d36cbf3be46da7.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Enhanced DynamicChatPromptBuilder's capabilities by allowing all user and system messages to be templated with provided variables. This update ensures a more versatile and dynamic templating process, making chat prompt generation more efficient and customized to user needs. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhance-inmemorydocumentstore-bm25-incremental-indexing-ebaf43b7163f3a24.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhance-inmemorydocumentstore-bm25-incremental-indexing-ebaf43b7163f3a24.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1c8d3f380018f8b7720bf0bb9d35faf2c0862984 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhance-inmemorydocumentstore-bm25-incremental-indexing-ebaf43b7163f3a24.yaml @@ -0,0 +1,7 @@ +--- +enhancements: + - | + Re-implement `InMemoryDocumentStore` BM25 search with incremental indexing by avoiding re-creating + the entire inverse index for every new query. This change also removes the dependency on + `haystack_bm25`. Please refer to [PR #7549](https://github.com/deepset-ai/haystack/pull/7549) + for the full context. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhance-numpy-dependency-reduced-f8a8afa08be098d3.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhance-numpy-dependency-reduced-f8a8afa08be098d3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cc72e68db641cf6114e7519ce7e46dd8dfe0ed8e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhance-numpy-dependency-reduced-f8a8afa08be098d3.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Reduced numpy usage to speed up imports. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhanced-htmltodocument-content-extraction-229d63e7c7119807.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhanced-htmltodocument-content-extraction-229d63e7c7119807.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e7aab3e330f4b62fb72da9d8a2c4d6c3064d37f4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhanced-htmltodocument-content-extraction-229d63e7c7119807.yaml @@ -0,0 +1,3 @@ +enhancements: + - | + Improved HTML content extraction by attempting to use multiple extractors in order of priority until successful. An additional try_others parameter in HTMLToDocument, which is true by default, determines whether subsequent extractors are used after a failure. This enhancement decreases extraction failures, ensuring more dependable content retrieval. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhanced-mime-type-handling-182fb64a0f5fb852.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhanced-mime-type-handling-182fb64a0f5fb852.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c0e7d07445353a4924ea4d3d57a88f238875d2eb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhanced-mime-type-handling-182fb64a0f5fb852.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Improved MIME type management by directly setting MIME types on ByteStreams, enhancing the overall handling and routing of different file types. This update makes MIME type data more consistently accessible and simplifies the process of working with various document formats. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/extend-promptbuilder-0322790d82248039.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/extend-promptbuilder-0322790d82248039.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ff6e5bfaa01ebc85a81cfe8dce64ccaba86738f0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/extend-promptbuilder-0322790d82248039.yaml @@ -0,0 +1,7 @@ +--- +enhancements: + - | + `PromptBuilder` now supports changing its template at runtime (e.g. for Prompt Engineering). This allows you to define a default template and then change it based on your needs at runtime. +deprecations: + - | + `DynamicPromptBuilder` has been deprecated as `PromptBuilder` fully covers its functionality. Use `PromptBuilder` instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/extend-write-documents-855ffc315974f03b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/extend-write-documents-855ffc315974f03b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e29d345423dc307db33d18a90058ca35e2701333 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/extend-write-documents-855ffc315974f03b.yaml @@ -0,0 +1,2 @@ +preview: + - Change `write_documents()` method in `DocumentStore` protocol to return the number of document written diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/extract_type_serialization-fc3ea6418ba5632d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/extract_type_serialization-fc3ea6418ba5632d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b380f9ec8d492c2ad527d1f8e963f47cdeb65196 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/extract_type_serialization-fc3ea6418ba5632d.yaml @@ -0,0 +1,3 @@ +enhancements: + - | + Move `serialize_type` and `deserialize_type` in the `utils` module. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/extractive-qa-answer-dedup-7ca3b94b79b38854.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/extractive-qa-answer-dedup-7ca3b94b79b38854.yaml new file mode 100644 index 0000000000000000000000000000000000000000..12b79fa2aa4887f5595a5b5c3e5ea7a125bd4234 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/extractive-qa-answer-dedup-7ca3b94b79b38854.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Introduces answer deduplication on the Document level based on an overlap threshold. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/extractive-reader-invalid-ans-a88e6b1d1ee897aa.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/extractive-reader-invalid-ans-a88e6b1d1ee897aa.yaml new file mode 100644 index 0000000000000000000000000000000000000000..edec36fc43f1fa6776cb916fd8043ea980d30140 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/extractive-reader-invalid-ans-a88e6b1d1ee897aa.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix issue with `ExtractiveReader` picking invalid answers when `answers_per_seq` > num of valid answers diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/feat-widen-support-of-envars-vars-on-openai-components-efe6203c0c6bd7b3.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/feat-widen-support-of-envars-vars-on-openai-components-efe6203c0c6bd7b3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6b2b47a6cdf2078e4e4a7665189ef4a8b638cc33 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/feat-widen-support-of-envars-vars-on-openai-components-efe6203c0c6bd7b3.yaml @@ -0,0 +1,6 @@ +--- +highlights: > + Add the 'OPENAI_TIMEOUT' and 'OPENAI_MAX_RETRIES' to the OpenAI components. +enhancements: + - | + Now you can set the timeout and max_retries parameters on OpenAI components by setting the 'OPENAI_TIMEOUT' and 'OPENAI_MAX_RETRIES' environment vars or passing them at __init__. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/feature-regex-mime-type-support-36381e74f593eb84.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/feature-regex-mime-type-support-36381e74f593eb84.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e22b30602537f5ecd8d5ce690623380b30b52f39 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/feature-regex-mime-type-support-36381e74f593eb84.yaml @@ -0,0 +1,24 @@ +--- +enhancements: + - | + Enhanced FileTypeRouter with Regex Pattern Support for MIME Types: This introduces a significant enhancement to the `FileTypeRouter`, now featuring support for regex pattern matching for MIME types. This powerful addition allows for more granular control and flexibility in routing files based on their MIME types, enabling the handling of broad categories or specific MIME type patterns with ease. This feature is particularly beneficial for applications requiring sophisticated file classification and routing logic. + + Usage example: + ```python + from haystack.components.routers import FileTypeRouter + + router = FileTypeRouter(mime_types=[r"text/.*", r"application/(pdf|json)"]) + + # Example files to classify + file_paths = [ + Path("document.pdf"), + Path("report.json"), + Path("notes.txt"), + Path("image.png"), + ] + + result = router.run(sources=file_paths) + + for mime_type, files in result.items(): + print(f"MIME Type: {mime_type}, Files: {[str(file) for file in files]}") + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/file-classifier-add-media-files-support-e970524f726dd844.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/file-classifier-add-media-files-support-e970524f726dd844.yaml new file mode 100644 index 0000000000000000000000000000000000000000..97a42ee98281085e905fdaabfbbfbc6c56ce884f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/file-classifier-add-media-files-support-e970524f726dd844.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Enhance FileTypeClassifier to detect media file types like mp3, mp4, mpeg, m4a, and similar. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-auto-tracing-51ed3a590000d6c8.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-auto-tracing-51ed3a590000d6c8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..63dc2645ad82d97bbaf81ed9e37695412e234bb5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-auto-tracing-51ed3a590000d6c8.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Auto enable tracing upon import if `ddtrace` or `opentelemetry` is installed. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-azure-generators-serialization-18fcdc9cbcb3732e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-azure-generators-serialization-18fcdc9cbcb3732e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..071969e62ed8568d8bae5ba634f823b848c63bce --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-azure-generators-serialization-18fcdc9cbcb3732e.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Azure generators components fixed, they were missing the `@component` decorator. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-caching-filters-syntax-d4c165ce0b0f258f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-caching-filters-syntax-d4c165ce0b0f258f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7c7cf8df4068c979992fe82875f728db5867f957 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-caching-filters-syntax-d4c165ce0b0f258f.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Use new filter syntax in the CacheChecker component instead of legacy one. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-chat-prompt-builder-serialization-345605337ca2584e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-chat-prompt-builder-serialization-345605337ca2584e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b9df38134df6585543dc9ab41be4dc7c37867411 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-chat-prompt-builder-serialization-345605337ca2584e.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Solve serialization bug on 'ChatPromptBuilder' by creating 'to_dict' and 'from_dict' methods on 'ChatMessage' and 'ChatPromptBuilder'. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-chatgpt-invocation-layer-bc25d0ea5f77f05c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-chatgpt-invocation-layer-bc25d0ea5f77f05c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2be3084dd78477fc9964c4bd6059fcaefa3691d2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-chatgpt-invocation-layer-bc25d0ea5f77f05c.yaml @@ -0,0 +1,6 @@ +--- +fixes: + - | + Fixed the bug that prevented the correct usage of ChatGPT invocation layer + in 1.21.1. + Added async support for ChatGPT invocation layer. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-components-autocompletion-a2d87708309262b6.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-components-autocompletion-a2d87708309262b6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..393abbc0e6fbe17b620bcda457a07c540ecb0846 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-components-autocompletion-a2d87708309262b6.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix auto-complete never working for any Component diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-conditional-branching-a0f0d65c7ac97f71.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-conditional-branching-a0f0d65c7ac97f71.yaml new file mode 100644 index 0000000000000000000000000000000000000000..426ad87140b63e4e2e9b1ef4d7b54d012a9e60b5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-conditional-branching-a0f0d65c7ac97f71.yaml @@ -0,0 +1,7 @@ +--- +fixes: + - | + Fix some bugs running a Pipeline that has Components with conditional outputs. + Some branches that were expected not to run would run anyway, even if they received no inputs. + Some branches instead would cause the Pipeline to get stuck waiting to run that branch, even if they received no inputs. + The behaviour would depend whether the Component not receiving the input has a optional input or not. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-connect-with-same-name-5ce470f7f0451362.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-connect-with-same-name-5ce470f7f0451362.yaml new file mode 100644 index 0000000000000000000000000000000000000000..529cd69a108be66d02e405caa3ad5f7db16a2d54 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-connect-with-same-name-5ce470f7f0451362.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix `Pipeline.connect()` so it connects sockets with same name if multiple sockets with compatible types are found. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-descriptor-__dict__-doesnt-apply-to-bf6d47872345ed24.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-descriptor-__dict__-doesnt-apply-to-bf6d47872345ed24.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7a3ff8d07a5a6bc39761bbec1d05562d84e85f09 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-descriptor-__dict__-doesnt-apply-to-bf6d47872345ed24.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Fixes the error `descriptor '__dict__' for 'ComponentClassX' objects doesn't apply to a 'ComponentClassX' object` when calling + `dir()` on a component instance. This fix should allow auto-completion in code editors. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-device-deserialization-st-embedder-c4efad96dd3869d5.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-device-deserialization-st-embedder-c4efad96dd3869d5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6bb0a4d2b90fb72edd332007eaa6539ed4f06e2e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-device-deserialization-st-embedder-c4efad96dd3869d5.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Updates the from_dict method of SentenceTransformersTextEmbedder, SentenceTransformersDocumentEmbedder, NamedEntityExtractor, SentenceTransformersDiversityRanker and LocalWhisperTranscriber to allow None as a valid value for device when deserializing from a YAML file. + This allows a deserialized pipeline to auto-determine what device to use using the ComponentDevice.resolve_device logic. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-cleaner-page-tag-15c66d6433b82b0a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-cleaner-page-tag-15c66d6433b82b0a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b25bbb662c98df849dd7ab999fdb3f06166316bd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-cleaner-page-tag-15c66d6433b82b0a.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix the DocumentCleaner removing the `\f` tag from content preventing from counting page number (by Splitter for example). diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-constructor-18b9e5dd9522a918.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-constructor-18b9e5dd9522a918.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0227063156e61823f6056826e3f381314acd4d28 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-constructor-18b9e5dd9522a918.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Remove `id` parameter from `Document` constructor as it was ignored and a new one was generated anyway. + This is a backwards incompatible change. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-flatten-metadata-ef61dbbae08b1db7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-flatten-metadata-ef61dbbae08b1db7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ad516ff400fde9ef02096c0899d02e9d9461930c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-flatten-metadata-ef61dbbae08b1db7.yaml @@ -0,0 +1,8 @@ +--- + +preview: + - | + Fix a failure that occurred when creating a document passing the 'meta' keyword + to the constructor. Raise a specific ValueError if the 'meta' keyword is passed + along with metadata as keyword arguments, the two options are mutually exclusive + now. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-init-09c1cbb14202be7d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-init-09c1cbb14202be7d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f1fc6a6cb208e97e9b423a8421c74eab25be362d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-init-09c1cbb14202be7d.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Make Document's constructor fail when is passed fields that are not present in the dataclass. An exception is made for "content_type" and "id_hash_keys": they are accepted in order to keep backward compatibility. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-store-in-test-3640b8b079ff4539.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-store-in-test-3640b8b079ff4539.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f0f9a65496979586d5e8a95b178bef15522dfc73 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-store-in-test-3640b8b079ff4539.yaml @@ -0,0 +1,9 @@ +--- + +fixes: + - | + The `test_comparison_in` test case in the base document store tests used to + always pass, no matter how the `in` filtering logic was implemented in + document stores. With the fix, the `in` logic is actually tested. Some tests + might start to fail for document stores that don't implement the `in` filter + correctly. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-documentjoiner-topk-173141a894e5c093.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-documentjoiner-topk-173141a894e5c093.yaml new file mode 100644 index 0000000000000000000000000000000000000000..665186022ab26dffcdea3321c7a291004188be3e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-documentjoiner-topk-173141a894e5c093.yaml @@ -0,0 +1,5 @@ +--- + +enhancements: + - | + The `DocumentJoiner` component's `run` method now accepts a `top_k` parameter, allowing users to specify the maximum number of documents to return at query time. This fixes issue #7702. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-embedders-docs-examples-72119352572012d7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-embedders-docs-examples-72119352572012d7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ed812f99c84da961d90773422267239d18839de2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-embedders-docs-examples-72119352572012d7.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Fix usage examples for OpenAIDocumentEmbedder and SentenceTransformersDocumentEmbedder. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-execution-order-1121cedd9c68c560.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-execution-order-1121cedd9c68c560.yaml new file mode 100644 index 0000000000000000000000000000000000000000..77dd7796796a3d5c508cf492115bac27e0a79543 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-execution-order-1121cedd9c68c560.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix bug in Pipeline.run() executing Components in a wrong and unexpected order diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-issue-#5485-efa4486a414ce584.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-issue-#5485-efa4486a414ce584.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cc91785920c44181f12fdd865ce6ea1d805d6e86 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-issue-#5485-efa4486a414ce584.yaml @@ -0,0 +1,2 @@ +fixes: + - fix issue 5485, TransformersImageToText.generate_captions accepts "str" diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-jinja-env-81c98225b22dc827.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-jinja-env-81c98225b22dc827.yaml new file mode 100644 index 0000000000000000000000000000000000000000..328fae81416907eb681c2f3971b30967fd034f78 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-jinja-env-81c98225b22dc827.yaml @@ -0,0 +1,14 @@ +--- +upgrade: + - | + `OutputAdapter` and `ConditionalRouter` can't return users inputs anymore. +security: + - | + Fix issue that could lead to remote code execution when using insecure Jinja template in the following Components: + + - `PromptBuilder` + - `ChatPromptBuilder` + - `OutputAdapter` + - `ConditionalRouter` + + The same issue has been fixed in the `PipelineTemplate` class too. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-join-docs-null-score-746c392a87adffcc.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-join-docs-null-score-746c392a87adffcc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..33d2e9311d4fdbd32e4a90efd15363a4bb9701b2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-join-docs-null-score-746c392a87adffcc.yaml @@ -0,0 +1,7 @@ +--- +fixes: + - | + When using `JoinDocuments` with `join_mode=concatenate` (default) and + passing duplicate documents, including some with a null score, this + node raised an exception. + Now this case is handled correctly and the documents are joined as expected. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-linkcontentfetcher-encoding-6c8df3c5b09fbc50.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-linkcontentfetcher-encoding-6c8df3c5b09fbc50.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3dbf59254bfdc2a3f8dc24f1b45420300c4e4c1b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-linkcontentfetcher-encoding-6c8df3c5b09fbc50.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Encoding of HTML files in LinkContentFetcher diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-logger-reserved-attributes-9e4d4920c1e41a62.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-logger-reserved-attributes-9e4d4920c1e41a62.yaml new file mode 100644 index 0000000000000000000000000000000000000000..841c6fe41233cde0ac94983ab2937c216803415f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-logger-reserved-attributes-9e4d4920c1e41a62.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Remove the usage of reserved keywords in the logger calls, causing a `KeyError` when setting the log level + to DEBUG. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-logs-containing-json-1393a00b4904f996.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-logs-containing-json-1393a00b4904f996.yaml new file mode 100644 index 0000000000000000000000000000000000000000..618dbc78e195c6031068f0dd62ca79d200bae44f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-logs-containing-json-1393a00b4904f996.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fixes logs containing JSON data getting lost due to string interpolation. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-metafieldranker-weight-in-run-66ce13191e596214.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-metafieldranker-weight-in-run-66ce13191e596214.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e590bcc4ae0752817ec050dbc5d640c2f9690583 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-metafieldranker-weight-in-run-66ce13191e596214.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix a bug in the `MetaFieldRanker` where the `weight` parameter passed to the `run` method was not being used. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-metafieldranker-weight-in-run-method-e4e11011a8b99c34.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-metafieldranker-weight-in-run-method-e4e11011a8b99c34.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca3b03a543c34d589fac175f6025fc7b5160bdd3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-metafieldranker-weight-in-run-method-e4e11011a8b99c34.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Fixed a bug in the `MetaFieldRanker`: when the `weight` parameter was set to 0 in the `run` method, + the component was incorrectly using the default `weight` parameter set in the `__init__` method. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-model_max_length-prompt_handler-7f34c40c62a8c55b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-model_max_length-prompt_handler-7f34c40c62a8c55b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d2fe468663855baa2158e45597ecca38ceceb8ca --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-model_max_length-prompt_handler-7f34c40c62a8c55b.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix model_max_length not being set in the Tokenizer in DefaultPromptHandler. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-openai-base-url-assignment-0570a494d88fe365.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-openai-base-url-assignment-0570a494d88fe365.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6959e7493720f6b3ee979cb46594e64795ecfae9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-openai-base-url-assignment-0570a494d88fe365.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Adds `api_base_url` attribute to `OpenAITExtEmbedder`. + Previously, it was used only for initialization and was not serialized. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-output-adapter-from_dict-custom-filters-none-70705cbb474fe982.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-output-adapter-from_dict-custom-filters-none-70705cbb474fe982.yaml new file mode 100644 index 0000000000000000000000000000000000000000..72759e9c69e964487119f2e3b7ef6fe99557a6f6 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-output-adapter-from_dict-custom-filters-none-70705cbb474fe982.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix Output Adapter from_dict method when custom_filters value is None. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pdfminer-converter-54e6d7e1a82d6e7b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pdfminer-converter-54e6d7e1a82d6e7b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..42aa1e70318c135bf966e0964a1a9550ea8c6f35 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pdfminer-converter-54e6d7e1a82d6e7b.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fixed the PdfMinerToDocument converter's outputs to be properly wired up to 'documents'. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pipeline-deserialization-a3909bb6b623c588.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pipeline-deserialization-a3909bb6b623c588.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b8f91d5e5b0b013c655573ea279a3c7d98e731d9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pipeline-deserialization-a3909bb6b623c588.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Prevent `Pipeline.from_dict` from modifying the dictionary parameter passed to it. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pipeline-run-loop-99f7ff9db16544d4.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pipeline-run-loop-99f7ff9db16544d4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..61ad81c7824ba24cbbb5b53befc3b26889837bef --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pipeline-run-loop-99f7ff9db16544d4.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix a bug when running a Pipeline that would cause it to get stuck in an infinite loop diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-reader-top-k-b4f7e29be5ba5ee1.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-reader-top-k-b4f7e29be5ba5ee1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eb017358e9dc974fbbc07fcbe9ac3045bf8eed2c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-reader-top-k-b4f7e29be5ba5ee1.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Update Reader documentation to explain that top_k+1 answers are returned if no_answer is enabled (default). diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-serialization-docrecallevaluator-91ad772ffed119ed.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-serialization-docrecallevaluator-91ad772ffed119ed.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c98eb79ccdae45dede94844a35e1ce83eb2f70ad --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-serialization-docrecallevaluator-91ad772ffed119ed.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Add `to_dict` method to `DocumentRecallEvaluator` to allow proper serialization of the component. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-stop-words-criteria-check-order-bug-4badfcc021dfc92a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-stop-words-criteria-check-order-bug-4badfcc021dfc92a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6f06db3c980f5004bbb995440f298975296df4ce --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-stop-words-criteria-check-order-bug-4badfcc021dfc92a.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix StopWordsCriteria not checking stop word tokens in a continuous and sequential order diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-text-splitter-65870db474338749.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-text-splitter-65870db474338749.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6633117e4a97282d2dffde5c77f538a12a42f70a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-text-splitter-65870db474338749.yaml @@ -0,0 +1,3 @@ +--- +preview: + - Fix TextDocumentSplitter failing when run with an empty list diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-variadics-not-running-222b01ae44a4a9fc.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-variadics-not-running-222b01ae44a4a9fc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d4f1bdfcf695f448b919c3c78a487143ace1e731 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-variadics-not-running-222b01ae44a4a9fc.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix `Pipeline` not running Components with Variadic input even if it received inputs only from a subset of its senders diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-version-47afaec913788a01.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-version-47afaec913788a01.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9e657c7a529a06c154ade025c20dcfc2f9c51af6 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-version-47afaec913788a01.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix Haystack imports failing when using local development environment that doesn't have `haystack-ai` installed. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/flexible-hf-api-token-env-vars-5fe383cdc1a9cc29.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/flexible-hf-api-token-env-vars-5fe383cdc1a9cc29.yaml new file mode 100644 index 0000000000000000000000000000000000000000..506fa0513f552e6491dcb78661c382cb5a4c1fcd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/flexible-hf-api-token-env-vars-5fe383cdc1a9cc29.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Enhanced flexibility in HuggingFace API environment variable names across all related components to support both 'HF_API_TOKEN' and 'HF_TOKEN', improving compatibility with the widely used HF environmental variable naming conventions. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/gptgenerator-api-key-b9a648301a67bb37.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/gptgenerator-api-key-b9a648301a67bb37.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1e7b085c18c7695b43cd0c7ed9b19414a653f45e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/gptgenerator-api-key-b9a648301a67bb37.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Better management of API key in GPT Generator. The API key is never serialized. + Make the `api_base_url` parameter really used (previously it was ignored). diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hf-models-from-dict-default-values-47c2c73136ea6643.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hf-models-from-dict-default-values-47c2c73136ea6643.yaml new file mode 100644 index 0000000000000000000000000000000000000000..71b09ebf7f0ebda4b273ef104d8d567019f216fc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hf-models-from-dict-default-values-47c2c73136ea6643.yaml @@ -0,0 +1,3 @@ +fixes: + - | + This updates the components, TransformersSimilarityRanker, SentenceTransformersDiversityRanker, SentenceTransformersTextEmbedder, SentenceTransformersDocumentEmbedder and LocalWhisperTranscriber from_dict methods to work when loading with init_parameters only containing required parameters. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hfapichatgenerator-51772e1f0d679b1c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hfapichatgenerator-51772e1f0d679b1c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cd32439c9ba5229212243a1b5eaf252650ac655f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hfapichatgenerator-51772e1f0d679b1c.yaml @@ -0,0 +1,14 @@ +--- +features: + - | + Introduce `HuggingFaceAPIChatGenerator`. + This text-generation component uses the ChatMessage format and supports different Hugging Face APIs: + - free Serverless Inference API + - paid Inference Endpoints + - self-hosted Text Generation Inference. + + This generator will replace the `HuggingFaceTGIChatGenerator` in the future. +deprecations: + - | + Deprecate `HuggingFaceTGIChatGenerator`. This component will be removed in Haystack 2.3.0. + Use `HuggingFaceAPIChatGenerator` instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hfapidocembedder-4c3970d002275edb.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hfapidocembedder-4c3970d002275edb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8a5db689796619555efbd11a9d46969e60373a99 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hfapidocembedder-4c3970d002275edb.yaml @@ -0,0 +1,13 @@ +--- +features: + - | + Introduce `HuggingFaceAPIDocumentEmbedder`. + This component can be used to compute Document embeddings using different Hugging Face APIs: + - free Serverless Inference API + - paid Inference Endpoints + - self-hosted Text Embeddings Inference. + This embedder will replace the `HuggingFaceTEIDocumentEmbedder` in the future. +deprecations: + - | + Deprecate `HuggingFaceTEIDocumentEmbedder`. This component will be removed in Haystack 2.3.0. + Use `HuggingFaceAPIDocumentEmbedder` instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hfapigenerator-3b1c353a4e8e4c55.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hfapigenerator-3b1c353a4e8e4c55.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7607bf379ace678c66bb6813e86b63a3e81f827b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hfapigenerator-3b1c353a4e8e4c55.yaml @@ -0,0 +1,13 @@ +--- +features: + - | + Introduce `HuggingFaceAPIGenerator`. This text-generation component supports different Hugging Face APIs: + - free Serverless Inference API + - paid Inference Endpoints + - self-hosted Text Generation Inference. + + This generator will replace the `HuggingFaceTGIGenerator` in the future. +deprecations: + - | + Deprecate `HuggingFaceTGIGenerator`. This component will be removed in Haystack 2.3.0. + Use `HuggingFaceAPIGenerator` instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/highlight-optional-conns-in-draw-cf107ee210b7b8e7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/highlight-optional-conns-in-draw-cf107ee210b7b8e7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8ce9133fe286b44b071c6805d47e81ff544d941b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/highlight-optional-conns-in-draw-cf107ee210b7b8e7.yaml @@ -0,0 +1,3 @@ +--- +enhancements: + - Highlight optional connections in the `Pipeline.draw()` output. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/htmlconverter-allow-extractor-customizability-730ae129db17327a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/htmlconverter-allow-extractor-customizability-730ae129db17327a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a77b947505b7557a364a8c5bee8936b1b4bf100e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/htmlconverter-allow-extractor-customizability-730ae129db17327a.yaml @@ -0,0 +1,7 @@ +--- +enhancements: + - | + The `HTMLToDocument` converter now allows choosing the boilerpy3 extractor + to extract the content from the HTML document. + The default extractor has been changed to `DefaultExtractor`, which is better + for generic use cases than the previous default (`ArticleExtractor`). diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hybrid_search_faq_pipeline.py-815df846dca7e872.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hybrid_search_faq_pipeline.py-815df846dca7e872.yaml new file mode 100644 index 0000000000000000000000000000000000000000..660f7d692b3e9010cbe42d7f1ac0bc6ef17d9e35 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hybrid_search_faq_pipeline.py-815df846dca7e872.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Added documents_store.update_embeddings call to pipeline examples so that embeddings are calculated for newly added documents. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/implemeting-eval-results-API-25b2f8707495bea0.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/implemeting-eval-results-API-25b2f8707495bea0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2cec7bbd617b32f79278ffcd6c6a3624940aaacb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/implemeting-eval-results-API-25b2f8707495bea0.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Added a new EvaluationRunResult dataclass that wraps the results of an evaluation pipeline, + allowing for its transformation and visualization. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-link-content-fetcher-512d039e3c7684f1.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-link-content-fetcher-512d039e3c7684f1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..afb84eae28f9b02f9e10131a2a4704da01b3d93e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-link-content-fetcher-512d039e3c7684f1.yaml @@ -0,0 +1,8 @@ +--- +enhancements: + - | + Several minor enhancements for LinkContentFetcher: + - Dynamic content handler resolution + - Custom User-Agent header (optional, minimize blocking) + - PDF support + - Register new content handlers diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-streaming-callbacks-openai-b6c0b108f2de4142.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-streaming-callbacks-openai-b6c0b108f2de4142.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3df9559f64976022901f54ce419688cdbbbbf846 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-streaming-callbacks-openai-b6c0b108f2de4142.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + The `streaming_callback` parameter can be passed to OpenAIGenerator and OpenAIChatGenerator during pipeline run. This prevents the need to recreate pipelines for streaming callbacks. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-type-serialization-support-18822a5b978b1e77.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-type-serialization-support-18822a5b978b1e77.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b2c96fe48867bdec7106d87069da2685ba7576ce --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-type-serialization-support-18822a5b978b1e77.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Improves/fixes type serialization of PEP 585 types (e.g. list[Document], and their nested version). This improvement enables better serialization of generics and nested types and improves/fixes matching of list[X] and List[X] types in component connections after serialization. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/in-memory-docstore-memory-share-82b75d018b3545fc.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/in-memory-docstore-memory-share-82b75d018b3545fc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d60997a41c95b509e2da7bbcf588f6e64d8b29be --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/in-memory-docstore-memory-share-82b75d018b3545fc.yaml @@ -0,0 +1,19 @@ +--- +features: + - | + Add memory sharing between different instances of InMemoryDocumentStore. + Setting the same `index` argument as another instance will make sure that the memory is shared. + e.g. + ```python + index = "my_personal_index" + document_store_1 = InMemoryDocumentStore(index=index) + document_store_2 = InMemoryDocumentStore(index=index) + + assert document_store_1.count_documents() == 0 + assert document_store_2.count_documents() == 0 + + document_store_1.write_documents([Document(content="Hello world")]) + + assert document_store_1.count_documents() == 1 + assert document_store_2.count_documents() == 1 + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/inmemory-return-written-documents-488b7f90df84bc59.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/inmemory-return-written-documents-488b7f90df84bc59.yaml new file mode 100644 index 0000000000000000000000000000000000000000..632f2b6fb66c11e9c130b5921f3dc8d2cfe70818 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/inmemory-return-written-documents-488b7f90df84bc59.yaml @@ -0,0 +1,2 @@ +preview: + - Make `InMemoryDocumentStore.write_documents()` return the number of docs actually written diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/internal-logging-changes-a96533da55e309c3.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/internal-logging-changes-a96533da55e309c3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2bcf0d6626b3799c72a294230ab19c255efc0c3e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/internal-logging-changes-a96533da55e309c3.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Added a new `Logger` implementation which eases and enforces logging via key-word arguments. + This is an internal change only. The behavior of instances created via `logging.getLogger` is not affected. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/introduce-answer-joiner-component-885dd7846776f5cb.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/introduce-answer-joiner-component-885dd7846776f5cb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e1773183d3dc8597db0bf0310f2a602453479104 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/introduce-answer-joiner-component-885dd7846776f5cb.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Introduced a new AnswerJoiner component that allows joining multiple lists of Answers into a single list using + the Concatenate join mode. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/introduce-jsonschema-validator-65debc51a3b64975.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/introduce-jsonschema-validator-65debc51a3b64975.yaml new file mode 100644 index 0000000000000000000000000000000000000000..915b24bcdf16a7d5d361a23f99d1239087479ea5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/introduce-jsonschema-validator-65debc51a3b64975.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Introduced JsonSchemaValidator to validate the JSON content of ChatMessage against a provided JSON schema. Valid messages are emitted through the 'validated' output, while messages failing validation are sent via the 'validation_error' output, along with useful error details for troubleshooting. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/language-router-logging-6afed7b6b8a7ae78.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/language-router-logging-6afed7b6b8a7ae78.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bf1815d659db5b500ccfae508b757bff5799f7af --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/language-router-logging-6afed7b6b8a7ae78.yaml @@ -0,0 +1,12 @@ +--- +security: + - | + Remove the text value from a warning log in the `TextLanguageRouter` to avoid logging sensitive information. + The text can be still be shown by switching to the `debug` log level. + + ```python + import logging + + logging.basicConfig(format="%(levelname)s - %(name)s - %(message)s", level=logging.WARNING) + logging.getLogger("haystack").setLevel(logging.DEBUG) + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/lazy-import-v2-82902270867d9899.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/lazy-import-v2-82902270867d9899.yaml new file mode 100644 index 0000000000000000000000000000000000000000..36543095ebc7cbe60ab892f346460fa700fb1611 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/lazy-import-v2-82902270867d9899.yaml @@ -0,0 +1,2 @@ +preview: + - copy lazy_imports.py to preview diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/link-content-include-snippet-if-blocked-53b0e3108f010315.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/link-content-include-snippet-if-blocked-53b0e3108f010315.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b8291f1c3529b98b44f2bac28419c164918761a4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/link-content-include-snippet-if-blocked-53b0e3108f010315.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + If LinkContentFetcher encounters a block or receives any response code other than HTTPStatus.OK, return the search + engine snippet as content, if it's available. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/load-tokenizer-if-not-load-by-transformers-5841cdc9ff69bcc2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/load-tokenizer-if-not-load-by-transformers-5841cdc9ff69bcc2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3904010f980cc84517cc2d9afc8b28c02f7a35d8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/load-tokenizer-if-not-load-by-transformers-5841cdc9ff69bcc2.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Allow loading Tokenizers for prompt models not natively supported by transformers by setting `trust_remote_code` to `True`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/log-trace-correlation-78bcf418718b24b4.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/log-trace-correlation-78bcf418718b24b4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d2d327dbbd8c0138644c043929317d2b614d3b2a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/log-trace-correlation-78bcf418718b24b4.yaml @@ -0,0 +1,17 @@ +--- +enhancements: + - | + If using JSON logging in conjunction with tracing, Haystack will automatically add correlation IDs to the logs. + This is done by getting the necessary information from the current span and adding it to the log record. + You can customize this by overriding the `get_correlation_data_for_logs` of your tracer's span: + + ```python + from haystack.tracing import Span + + class OpenTelemetrySpan(Span): + ... + + def get_correlation_data_for_logs(self) -> Dict[str, Any]: + span_context = ... + return {"trace_id": span_context.trace_id, "span_id": span_context.span_id} + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/make-urlcachechecker-generic-e159d40bbd943081.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/make-urlcachechecker-generic-e159d40bbd943081.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7395748dd5f1f4fbee897b919c1eff5bc89c9a57 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/make-urlcachechecker-generic-e159d40bbd943081.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Improve the URLCacheChecker so that it can work with any type of data in the DocumentStore, not just URL caching. + Rename the component to CacheChecker. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/max-retries-for-AzureOpenAIGenerator-0f1a1807dd2af041.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/max-retries-for-AzureOpenAIGenerator-0f1a1807dd2af041.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7a00710c33512d749f9075b135b5434e437cc2f0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/max-retries-for-AzureOpenAIGenerator-0f1a1807dd2af041.yaml @@ -0,0 +1,9 @@ +--- +enhancements: + - | + Add max_retries to AzureOpenAIGenerator. + AzureOpenAIGenerator can now be initialised by setting max_retries. + If not set, it is inferred from the `OPENAI_MAX_RETRIES` + environment variable or set to 5. + The timeout for AzureOpenAIGenerator, if not set, it is inferred + from the `OPENAI_TIMEOUT` environment variable or set to 30. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/memory-embedding-retrieval-06f384baa04a63f7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/memory-embedding-retrieval-06f384baa04a63f7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1d5b374c75a8ed7f3cf9bd333fa476bf68ae13c5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/memory-embedding-retrieval-06f384baa04a63f7.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Add `embedding_retrieval` method to `MemoryDocumentStore`, + which allows to retrieve the relevant Documents, given a query embedding. + It will be called by the `MemoryEmbeddingRetriever`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/memory-embedding-retriever-dde22dedc83d1603.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/memory-embedding-retriever-dde22dedc83d1603.yaml new file mode 100644 index 0000000000000000000000000000000000000000..946dc4fda79b30996fa66099a0a014c9e63cba9d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/memory-embedding-retriever-dde22dedc83d1603.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Rename `MemoryRetriever` to `MemoryBM25Retriever` + Add `MemoryEmbeddingRetriever`, which takes as input a query embedding and + retrieves the most relevant Documents from a `MemoryDocumentStore`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/merge-pipeline-definitions-1da80e9803e2a8bb.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/merge-pipeline-definitions-1da80e9803e2a8bb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..094562e8f7974d6f1c9aa30c8598ea099df6ea84 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/merge-pipeline-definitions-1da80e9803e2a8bb.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Merge `Pipeline`s definitions into a single `Pipeline` class. + The class in the `haystack.pipeline` package has been deleted and only `haystack.core.pipeline` exists now. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/meta-in-bytestream-a29816c919c0be5a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/meta-in-bytestream-a29816c919c0be5a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e116c73fbc381e7c01940fdc8f13fdd50d54143e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/meta-in-bytestream-a29816c919c0be5a.yaml @@ -0,0 +1,3 @@ +--- +enhancements: + - Add meta parameter to `ByteStream.from_file_path()` and `ByteStream.from_string()`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/metafieldranker_sort-order_refactor-2000d89dc40dc15a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/metafieldranker_sort-order_refactor-2000d89dc40dc15a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..18a792c2323414a40201ee9bebdfddaf1f5c1876 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/metafieldranker_sort-order_refactor-2000d89dc40dc15a.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Prevent the `MetaFieldRanker` from throwing an error if one or more of the documents doesn't contain the specific meta data field. Now those documents will be ignored for ranking purposes and placed at the end of the ranked list so we don't completely throw them away. + Adding a sort_order that can have values of descending or ascending. + Added more runtime parameters. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/metaranker-missing-meta-options-1a969008d632a523.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/metaranker-missing-meta-options-1a969008d632a523.yaml new file mode 100644 index 0000000000000000000000000000000000000000..46cb0c82abb3f717118fbc09eb7125772894c57b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/metaranker-missing-meta-options-1a969008d632a523.yaml @@ -0,0 +1,7 @@ +--- +features: + - | + Add a new `missing_meta` param to `MetaFieldRanker`, which determines what to do with + documents that lack the ranked meta field. Supported values are `"bottom"` (which + puts documents with missing meta at the bottom of the sorted list), `"top"` (which puts them + at the top), and `"drop"` (which removes them from the results entirely). diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/migrate-gpt-generator-for-chat-generator-b1edb394f3d6c9ef.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/migrate-gpt-generator-for-chat-generator-b1edb394f3d6c9ef.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2e781c8302d3cc7997b8b1cb698eccedb193f553 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/migrate-gpt-generator-for-chat-generator-b1edb394f3d6c9ef.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adds GPTChatGenerator, a chat-based OpenAI LLM component, ChatMessage(s) are used for input and output diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/migrate-remote-whisper-transcriber-to-openai-sdk-980ae6f54ddfd7df.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/migrate-remote-whisper-transcriber-to-openai-sdk-980ae6f54ddfd7df.yaml new file mode 100644 index 0000000000000000000000000000000000000000..98e61e5f4986279c989ffb07c892f554948c35f8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/migrate-remote-whisper-transcriber-to-openai-sdk-980ae6f54ddfd7df.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Migrate RemoteWhisperTranscriber to OpenAI SDK. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/move-classifiers-943d9d52b4bfc49f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/move-classifiers-943d9d52b4bfc49f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ae1e2b1ca158270c7dca84295ee399cec1a84a59 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/move-classifiers-943d9d52b4bfc49f.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Move Text Language Classifier and Document Language Classifier to the + classifiers package. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/move-documentjoiner-to-joiners-7fe188d18d65ffcd.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/move-documentjoiner-to-joiners-7fe188d18d65ffcd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..59948c915fb5d71eda128e03e0d75137cc39321b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/move-documentjoiner-to-joiners-7fe188d18d65ffcd.yaml @@ -0,0 +1,10 @@ +--- +upgrade: + - | + Change any occurrence of: + from haystack.components.routers.document_joiner import DocumentJoiner + to: + from haystack.components.joiners.document_joiner import DocumentJoiner +enhancements: + - | + Create a new package called `joiners` and move `DocumentJoiner` there for clarity. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/multiplexer-a7b1259bd20c144c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/multiplexer-a7b1259bd20c144c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2ef1fbaa4246b3c51bf125ff32e4f6352c8b4ffa --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/multiplexer-a7b1259bd20c144c.yaml @@ -0,0 +1,3 @@ +features: + - | + Add `Multiplexer`. For an example of its usage, see https://github.com/deepset-ai/haystack/pull/6420. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/openai-text-embedder-8f06cf0bf29e6752.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/openai-text-embedder-8f06cf0bf29e6752.yaml new file mode 100644 index 0000000000000000000000000000000000000000..35ade4a2b8b37e9ac592affdb327ed31edae212e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/openai-text-embedder-8f06cf0bf29e6752.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Add OpenAI Text Embedder. + It is a component that uses OpenAI models to embed strings into vectors. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/openapi-connector-auth-enhancement-a78e0666d3cf6353.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/openapi-connector-auth-enhancement-a78e0666d3cf6353.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8575bc14f9161694d43275a6e72beb3b947cee9c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/openapi-connector-auth-enhancement-a78e0666d3cf6353.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Enhanced the OpenAPIServiceConnector to support dynamic authentication handling. With this update, service credentials are now dynamically provided at each run invocation, eliminating the need for pre-configuring a known set of service authentications. This flexibility allows for the introduction of new services on-the-fly, each with its unique authentication, streamlining the integration process. This modification not only simplifies the initial setup of the OpenAPIServiceConnector but also ensures a more transparent and straightforward authentication process for each interaction with different OpenAPI services. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/opentelemetry-tracer-33d44eb125a3145b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/opentelemetry-tracer-33d44eb125a3145b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..aa8a08040128fa89148b4b0d4b6a6f65922aef5f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/opentelemetry-tracer-33d44eb125a3145b.yaml @@ -0,0 +1,39 @@ +--- +features: + - | + Added out-of-the-box support for the OpenTelemetry Tracer. This allows you to instrument pipeline and component + runs using OpenTelemetry and send traces to your preferred backend. + + To use the OpenTelemetry Tracer you need to have the `opentelemetry-sdk` package installed in your environment. + To instruct Haystack to use the OpenTelemetry Tracer, you have multiple options: + + * Run your Haystack application using the `opentelemetry-instrument` command line tool as described in the + [OpenTelemetry documentation](https://opentelemetry.io/docs/languages/python/automatic/#configuring-the-agent). + This behavior can be disabled by setting the `HAYSTACK_AUTO_TRACE_ENABLED_ENV_VAR` environment variable to `false`. + * Configure the tracer manually in your code using the `opentelemetry` package: + ```python + from opentelemetry import trace + from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter + from opentelemetry.sdk.trace import TracerProvider + from opentelemetry.sdk.trace.export import BatchSpanProcessor + + # Service name is required for most backends + resource = Resource(attributes={ + SERVICE_NAME: "haystack" + }) + + traceProvider = TracerProvider(resource=resource) + processor = BatchSpanProcessor(OTLPSpanExporter(endpoint="http://localhost:4318/v1/traces")) + traceProvider.add_span_processor(processor) + trace.set_tracer_provider(traceProvider) + + # Auto-configuration + import haystack.tracing + haystack.tracing.auto_enable_tracing() + + # Or explicitly + from haystack.tracing import OpenTelemetryTracer + + tracer = traceProvider.get_tracer("my_application") + tracing.enable_tracing(OpenTelemetryTracer(tracer)) + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pin-numpy-2304f88504d5041a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pin-numpy-2304f88504d5041a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..00a876e0906e4a263ed653e74fbc3866d2b7ba23 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pin-numpy-2304f88504d5041a.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Pin numpy<2 to avoid breaking changes that cause several core integrations to fail. + Pin tenacity too (8.4.0 is broken). diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pin-structlog-39d991a70590dd6e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pin-structlog-39d991a70590dd6e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f633b3860808199212a58762e61a3235203fe36b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pin-structlog-39d991a70590dd6e.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Pins structlog to <= 24.2.0 to avoid some unit test failures. This is a temporary fix until we can upgrade tests to a newer versions of structlog. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pin-typing-extensions-c4026f59603445b7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pin-typing-extensions-c4026f59603445b7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..88e3ddeae2913f59b9af0a390e6d136db8b3693f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pin-typing-extensions-c4026f59603445b7.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Pin the `typing-extensions` package to versions >= 4.7 to avoid + [incompatibilities with the `openai` package](https://community.openai.com/t/error-while-importing-openai-from-open-import-openai/578166/26). diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipe-draw-transparent-bg-2e0c8ff586f8e70c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipe-draw-transparent-bg-2e0c8ff586f8e70c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4a831edb3895fe0be27d831df60e765d315cc17b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipe-draw-transparent-bg-2e0c8ff586f8e70c.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Restore transparent background for images generated with Pipeline.draw and Pipeline.show diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-deserialization-callbacks-0642248725918684.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-deserialization-callbacks-0642248725918684.yaml new file mode 100644 index 0000000000000000000000000000000000000000..68d1368750cb8566beb800cc79f9411deb97ea32 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-deserialization-callbacks-0642248725918684.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Add support for callbacks during pipeline deserialization. Currently supports a pre-init hook for components that can be used to inspect and modify the initialization parameters + before the invocation of the component's `__init__` method. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-intermediate-outputs-7cb8e71f79532ec1.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-intermediate-outputs-7cb8e71f79532ec1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..38a0a9ab8fba7891f016ec7425d8e6ebef0b2a39 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-intermediate-outputs-7cb8e71f79532ec1.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + `pipeline.run` accepts a set of component names whose intermediate outputs are returned in the final + pipeline output dictionary. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-io-connected-sockets-db862d045944f788.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-io-connected-sockets-db862d045944f788.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1ccfa63324b753df820149eabfa83445c5ddbdcb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-io-connected-sockets-db862d045944f788.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + `Pipeline.inputs` and `Pipeline.outputs` can optionally include components input/output sockets that are connected. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-run-fix-extra-outputs-a6c750a91faaa8fd.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-run-fix-extra-outputs-a6c750a91faaa8fd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..00d23f64ef55171956b2d2e9646400a0fbe73d28 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-run-fix-extra-outputs-a6c750a91faaa8fd.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + The `include_outputs_from` parameter in `Pipeline.run` correctly returns outputs of components with multiple outputs. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-same-input-ref-different-components-68d74cb17b35f8db.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-same-input-ref-different-components-68d74cb17b35f8db.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fbb7301fb25401077841392e8ecda4a555c1c9cd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-same-input-ref-different-components-68d74cb17b35f8db.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Previously, when using the same input reference in different components, the Pipeline run logic had an + unexpected behavior. This has been fixed by deepcopying the inputs before passing them to the components. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/preprocessor-2-0-9828d930562fa3f5.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/preprocessor-2-0-9828d930562fa3f5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bb58645d6d6fc0921a36451d1e31bae7365eda9a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/preprocessor-2-0-9828d930562fa3f5.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add the `TextDocumentSplitter` component for Haystack 2.0 that splits a Document with long text into multiple Documents with shorter texts. Thereby the texts match the maximum length that the language models in Embedders or other components can process. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/preview-extra-6dfdca55d17cbc7f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/preview-extra-6dfdca55d17cbc7f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..223e2cbef37c807f1d4f24d2f005c1d6475a5dc8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/preview-extra-6dfdca55d17cbc7f.yaml @@ -0,0 +1,4 @@ +preview: + - | + Create a dedicated dependency list for the preview package, `farm-haystack[preview]`. + Using `haystack-ai` is still the recommended way to test Haystack 2.0. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/prompt-builder-default-value-95383dd6d17a05d5.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/prompt-builder-default-value-95383dd6d17a05d5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b6f70c74648befeee31c3100e2169c745fc69659 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/prompt-builder-default-value-95383dd6d17a05d5.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Fix `PromptBuilder` missing input default values. + These missing default value was causing the PromptBuilder to never run if certain inputs are not received. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pypdf-page-breaks-b6842d93f4c69185.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pypdf-page-breaks-b6842d93f4c69185.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b57856dbbf462a5f75b6a7cc3cbb1e5e018ecad7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pypdf-page-breaks-b6842d93f4c69185.yaml @@ -0,0 +1,7 @@ +--- +upgrade: + - | + Upgraded the default converter in PyPDFToDocument to insert page breaks "\f" + between each extracted page. + This allows for downstream components and applications to better be able to + keep track of the original PDF page a portion of text comes from. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pypdf-rm-deprecated-params-6c4c51489305bb85.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pypdf-rm-deprecated-params-6c4c51489305bb85.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dcd6978e8edc690bc698849d04d4eb6b9872d2ef --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pypdf-rm-deprecated-params-6c4c51489305bb85.yaml @@ -0,0 +1,10 @@ +--- +upgrade: + - | + The deprecated `converter_name` parameter has been removed from `PyPDFToDocument`. + + To specify a custom converter for `PyPDFToDocument`, use the `converter` initialization parameter and + pass an instance of a class that implements the `PyPDFConverter` protocol. + + The `PyPDFConverter` protocol defines the methods `convert`, `to_dict` and `from_dict`. + A default implementation of `PyPDFConverter` is provided in the `DefaultConverter` class. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pypdf-serde-fixes-revert-22fcdad91951d3c2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pypdf-serde-fixes-revert-22fcdad91951d3c2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f087b7ae564d2dc404460d56f281b5fe3bae25b3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pypdf-serde-fixes-revert-22fcdad91951d3c2.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Revert change to PyPDFConverter that broke the deserialization of pre 2.6.0 YAMLs. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/python-3.11-3.12-857850f74f2e1ceb.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/python-3.11-3.12-857850f74f2e1ceb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2f9207f8ce88644038cf1f32ea061a7fd0f09694 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/python-3.11-3.12-857850f74f2e1ceb.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Document Python 3.11 and 3.12 support in project configuration. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/ranker-add-batching-during-inference-f077411ec389a63b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/ranker-add-batching-during-inference-f077411ec389a63b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..24e8191ac68762f365cd7d63019dcb6fb8e0bd18 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/ranker-add-batching-during-inference-f077411ec389a63b.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + We added batching during inference time to the TransformerSimilarityRanker to help prevent OOMs when ranking large amounts of Documents. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/reader-crash-no-docs-53085ce48baaae81.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/reader-crash-no-docs-53085ce48baaae81.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cf0cd02a89c21040bd4da7ce7b47162cebf03480 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/reader-crash-no-docs-53085ce48baaae81.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Return an empty list of answers when `ExtractiveReader` receives an empty list of documents instead of raising an exception. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/recall-evaluator-5595470406e93ad2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/recall-evaluator-5595470406e93ad2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..128b13e95dabcb0b0efeb71a115db7e2c24c7dd2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/recall-evaluator-5595470406e93ad2.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Add `DocumentRecallEvaluator`, a Component that can be used to calculate the Recall single-hit or multi-hit + metric given a list of questions, a list of expected documents for each question and the list of predicted + documents for each question. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-documentjoiner-992e662bee8ca219.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-documentjoiner-992e662bee8ca219.yaml new file mode 100644 index 0000000000000000000000000000000000000000..de31f8feadca42d7d08dda3b2da4fce18c6874b6 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-documentjoiner-992e662bee8ca219.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Refactor DocumentJoiner to use enum pattern for the 'join_mode' parameter instead of bare string. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-generator-public-interface-b588e9f23778e0ee.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-generator-public-interface-b588e9f23778e0ee.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c0cab7eed5ad6c7fa2e23b481fe6c5bfd095046e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-generator-public-interface-b588e9f23778e0ee.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Improve the public interface of the Generators: + - make `generation_kwargs` a dictionary + - rename `pipeline_kwargs` (in `HuggingFaceLocalGenerator`) to `huggingface_pipeline_kwargs` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-web-retriever-a0604ead72b84fdc.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-web-retriever-a0604ead72b84fdc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c2eaf51200271239b3f00a8bbb3c04e90829e8ef --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-web-retriever-a0604ead72b84fdc.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Refactor and simplify WebRetriever to use LinkContentFetcher component diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor_deserialize_document_store_in_init_parameters-b7f05173f0c56452.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor_deserialize_document_store_in_init_parameters-b7f05173f0c56452.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8186a6f6027c3cea57d3ed047d1788b6dc8261af --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor_deserialize_document_store_in_init_parameters-b7f05173f0c56452.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Refactor deserialize_document_store_in_init_parameters so that new function name + indicates that the operation occurs in place, with no return value. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/release-note-42273d88ce3e2b2e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/release-note-42273d88ce3e2b2e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..094246c604241600f4408dc0a5427d074c4c043e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/release-note-42273d88ce3e2b2e.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Add `precision` parameter to Sentence Transformers Embedders, which allows quantized + embeddings. Especially useful for reducing the size of the embeddings of a corpus for semantic search, among other tasks. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-api-key-from-serialization-2474a1539b86e233.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-api-key-from-serialization-2474a1539b86e233.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e1a879816eab75496f9e31efcad31f40cd9a3803 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-api-key-from-serialization-2474a1539b86e233.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Remove "api_key" from serialization of AzureOCRDocumentConverter and SerperDevWebSearch. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-base-test-component-ee1986a2bbbace46.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-base-test-component-ee1986a2bbbace46.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3932d0aed0ae701b38213650d7ca43ac81e29846 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-base-test-component-ee1986a2bbbace46.yaml @@ -0,0 +1,3 @@ +--- +preview: + - Remove `BaseTestComponent` class used to test `Component`s diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-deprecated-param-from-pipeline-6b05ce1ff1f7fdec.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-deprecated-param-from-pipeline-6b05ce1ff1f7fdec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..783382cb8407e68b5e3a5468de2c3e3150b1e8cc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-deprecated-param-from-pipeline-6b05ce1ff1f7fdec.yaml @@ -0,0 +1,6 @@ +--- +upgrade: + - | + Removed `Pipeline` init argument `max_loops_allowed`. Use `max_runs_per_component` instead. + - | + Removed `PipelineMaxLoops` exception. Use `PipelineMaxComponentRuns` instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-deprecated-sentence-window-retrieval-376f1fc000c9fa88.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-deprecated-sentence-window-retrieval-376f1fc000c9fa88.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8fee636eb3f6cc204afdcb81a98222aec2579b76 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-deprecated-sentence-window-retrieval-376f1fc000c9fa88.yaml @@ -0,0 +1,4 @@ +--- +upgrade: + - | + Removing deprecated `SentenceWindowRetrieval`, replaced by `SentenceWindowRetriever` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-document-store-aware-mixin-8eef714844ee04f2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-document-store-aware-mixin-8eef714844ee04f2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..01ca9ccce357b9f4556f4c46d693fcb242d35041 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-document-store-aware-mixin-8eef714844ee04f2.yaml @@ -0,0 +1,3 @@ +--- +preview: + - Remove `DocumentStoreAwareMixin` as it's not necessary anymore diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-htmltodocument-deprecated-init-params-2f81cf6a3b13710d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-htmltodocument-deprecated-init-params-2f81cf6a3b13710d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fa65cf17ecdcecc74301eabde7e0dec22f7b1fac --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-htmltodocument-deprecated-init-params-2f81cf6a3b13710d.yaml @@ -0,0 +1,4 @@ +--- +upgrade: + - | + Removed deprecated init parameters `extractor_type` and `try_others` from `HTMLToDocument`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-query-param-MetaFieldRanker-56883ab0377b7605.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-query-param-MetaFieldRanker-56883ab0377b7605.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e6ad905b4ca943554e54dddb0862c1196cb0fb0a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-query-param-MetaFieldRanker-56883ab0377b7605.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Removes the unused query parameter from the run method of MetaFieldRanker. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-serialization-from-telemetry-a054f7f26f277d2b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-serialization-from-telemetry-a054f7f26f277d2b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..82962d877d3dc8ea31a95019a866655231a0480c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-serialization-from-telemetry-a054f7f26f277d2b.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Fix telemetry code that could cause a ValueError by trying to serialize a pipeline. + Telemetry code does not serialize pipelines anymore. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-support-to-connect-component-to-self-6eedfb287f2a2a02.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-support-to-connect-component-to-self-6eedfb287f2a2a02.yaml new file mode 100644 index 0000000000000000000000000000000000000000..18792c2d19ccbaec8da2724ee200fd2ebf93217d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-support-to-connect-component-to-self-6eedfb287f2a2a02.yaml @@ -0,0 +1,5 @@ +--- +upgrade: + - | + `Pipeline.connect()` will now raise a `PipelineConnectError` if `sender` and `receiver` are the same Component. + We do not support this use case anymore. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-template-vars-invocation-kwargs-060f186fd1250fe4.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-template-vars-invocation-kwargs-060f186fd1250fe4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..43dec0f76517502970587f3e927c5e85ed99c4b3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-template-vars-invocation-kwargs-060f186fd1250fe4.yaml @@ -0,0 +1,11 @@ +--- +upgrade: + - | + This update impacts only those who have created custom invocation layers by subclassing PromptModelInvocationLayer. + Previously, the invoke() method in your custom layer received all prompt template parameters (like query, + documents, etc.) as keyword arguments. With this change, these parameters will no longer be passed in as keyword + arguments. If you've implemented such a custom layer, you'll need to potentially update your code to accommodate + this change. +enhancements: + - | + Remove template variables from invocation layer kwargs diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-confidence-score-3ba604b8f9bd0454.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-confidence-score-3ba604b8f9bd0454.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4b449fad3c70250e9105ae35a1b2152779b69656 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-confidence-score-3ba604b8f9bd0454.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Renamed the confidence_threshold parameter of the ExtractiveReader to score_threshold as ExtractedAnswers have a score and this is what the threshold is for. + For consistency, the term confidence is not mentioned anymore in favor of score. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-file-extension-router-9125028ec2c55e98.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-file-extension-router-9125028ec2c55e98.yaml new file mode 100644 index 0000000000000000000000000000000000000000..76f9cf840fbc8960e2751ce2b7e084b7331884c3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-file-extension-router-9125028ec2c55e98.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Enhanced file routing capabilities with the introduction of `ByteStream` handling, and + improved clarity by renaming the router to `FileTypeRouter`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-memory-doc-store-2a9960d11d2aa492.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-memory-doc-store-2a9960d11d2aa492.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5672821554dc3954f8b02360b928d8e41a4b1c51 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-memory-doc-store-2a9960d11d2aa492.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Rename `MemoryDocumentStore` to `InMemoryDocumentStore` + Rename `MemoryBM25Retriever` to `InMemoryBM25Retriever` + Rename `MemoryEmbeddingRetriever` to `InMemoryEmbeddingRetriever` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-model-param--transcribers-71dbe7cfb86950e0.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-model-param--transcribers-71dbe7cfb86950e0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e120da5c2a60c08953d69c522a3f1cd4b90cda95 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-model-param--transcribers-71dbe7cfb86950e0.yaml @@ -0,0 +1,5 @@ +--- +upgrade: + - | + Rename the transcriber parameters `model_name` and `model_name_or_path` to `model`. This change affects both + `LocalWhisperTranscriber` and `RemoteWhisperTranscriber` classes. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-model-param-embedders-7cc87a768554724d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-model-param-embedders-7cc87a768554724d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5a25873213e0d4fcb413c86c19ec4e1fb9a7f47 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-model-param-embedders-7cc87a768554724d.yaml @@ -0,0 +1,3 @@ +--- +upgrade: + - Rename the embedder parameters `model_name` and `model_name_or_path` to `model`. This change affects all Embedder classes. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-model-param-rankers-be3d6163597e0a9b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-model-param-rankers-be3d6163597e0a9b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..afc85b5fd9c0c2595cf818301ed272bb90b209d2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-model-param-rankers-be3d6163597e0a9b.yaml @@ -0,0 +1,3 @@ +--- +upgrade: + - Rename `model_name_or_path` to `model` in `TransformersSimilarityRanker`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-reader-input-af739955bf4f71b5.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-reader-input-af739955bf4f71b5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eec29c3e1b2e24d729127d6cc28b7ee33b062e12 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-reader-input-af739955bf4f71b5.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Renamed ExtractiveReader's input from `document` to `documents` to match its type List[Document]. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-streaming-callback-f4e6653c0aac8765.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-streaming-callback-f4e6653c0aac8765.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ccba3395291faf07c2c32a49d86c9e370fd822cd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-streaming-callback-f4e6653c0aac8765.yaml @@ -0,0 +1,7 @@ +--- +upgrade: +enhancements: + - | + The default in `default_streaming_callback` was confusing, this function was the go-to-helper + one would use to quickly print the generated tokens as they come, but it was not used by default. + The function was then renamed to `print_streaming_chunk.` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-text-document-splitter-1e9fcd292c4591dd.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-text-document-splitter-1e9fcd292c4591dd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..363da072d4915c9671a4e7375ccead8e626ed127 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-text-document-splitter-1e9fcd292c4591dd.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + rename `TextDocumentSplitter` to `DocumentSplitter`, to allow a better + distinction between Components that operate on text and those that operate + on Documents. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename_similarity_ranker-d755c2cd00449ecc.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename_similarity_ranker-d755c2cd00449ecc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a899742830e4121d5a02e6254bf643666e2adb53 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename_similarity_ranker-d755c2cd00449ecc.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Rename `SimilarityRanker` to `TransformersSimilarityRanker`, + as there will be more similarity rankers in the future. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/renamed-model_name-or-model_name_or_path-to-model-184490cbb66c4d7c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/renamed-model_name-or-model_name_or_path-to-model-184490cbb66c4d7c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..992bffaf81e3412de0e022dc04f722eb3cbb9791 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/renamed-model_name-or-model_name_or_path-to-model-184490cbb66c4d7c.yaml @@ -0,0 +1,3 @@ +--- +upgrade: + - Rename the generator parameters `model_name` and `model_name_or_path` to `model`. This change affects all Generator classes. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/retries-and-timeout-for-AzureOpenAIDocumentEmbedder-006fd84204942e43.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/retries-and-timeout-for-AzureOpenAIDocumentEmbedder-006fd84204942e43.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a4687dcbbb9c57ff210156c0466b2ad1b8e798c0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/retries-and-timeout-for-AzureOpenAIDocumentEmbedder-006fd84204942e43.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Add `max_retries`, `timeout` parameters to the `AzureOpenAIDocumentEmbedder` initialization. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rework-document-writer-4958db2024070f6f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rework-document-writer-4958db2024070f6f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ce10a4b9fb3c57b624f78fd357d3752eea91b701 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rework-document-writer-4958db2024070f6f.yaml @@ -0,0 +1,4 @@ +--- +features: + - Rework `DocumentWriter` to remove `DocumentStoreAwareMixin`. + Now we require a generic `DocumentStore` when initialisating the writer. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rm-deprecated-tei-embedders-cfcd660c906ba69e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rm-deprecated-tei-embedders-cfcd660c906ba69e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7cdc857950e91e388f430bbbc78c24fbd021fbf0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rm-deprecated-tei-embedders-cfcd660c906ba69e.yaml @@ -0,0 +1,5 @@ +--- +upgrade: + - | + Deprecated `HuggingFaceTEITextEmbedder` and `HuggingFaceTEIDocumentEmbedder` have been removed. + Use `HuggingFaceAPITextEmbedder` and `HuggingFaceAPIDocumentEmbedder` instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rm-deprecated-tgi-generators-6086bbb36417c0d8.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rm-deprecated-tgi-generators-6086bbb36417c0d8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a635630e67e32d95c4b540551668d9bf4ae306a4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rm-deprecated-tgi-generators-6086bbb36417c0d8.yaml @@ -0,0 +1,5 @@ +--- +upgrade: + - | + Deprecated `HuggingFaceTGIGenerator` and `HuggingFaceTGIChatGenerator` have been removed. + Use `HuggingFaceAPIGenerator` and `HuggingFaceAPIChatGenerator` instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rm-docstore-decorator-d8d2ebfdf1d9702e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rm-docstore-decorator-d8d2ebfdf1d9702e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b35d3b376d0173105c9f79c852ef4408e3ccd3e7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rm-docstore-decorator-d8d2ebfdf1d9702e.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Improve the deserialization logic for components that use a Document Store. + Remove the @document_store decorator and the registry of Document Stores. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rm-serialize-callback-handler-5c104eafc6673932.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rm-serialize-callback-handler-5c104eafc6673932.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d830c014b800eda1dd354161fcb8c61b9d483b5a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rm-serialize-callback-handler-5c104eafc6673932.yaml @@ -0,0 +1,8 @@ +--- +upgrade: + - | + The `serialize_callback_handler` and `deserialize_callback_handler` utility functions have been removed. + Use `serialize_callable` and `deserialize_callable` instead. + + For more information on `serialize_callable` and `deserialize_callable`, see the API reference: + https://docs.haystack.deepset.ai/reference/utils-api#module-callable_serialization diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sas-evaluator-6970865787557e83.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sas-evaluator-6970865787557e83.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d7aa24c734b8596f27b2fab7cb0d8e8e2f113a4f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sas-evaluator-6970865787557e83.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add SASEvaluator, it can be used to calculate Semantic Answer Similarity of generated answers from an LLM diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sas-evaluator-7858ea6c38f80bc7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sas-evaluator-7858ea6c38f80bc7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7447437d89754553cc1879511a8a8bf90cb860b3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sas-evaluator-7858ea6c38f80bc7.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add `SASEvaluator`, this Component can be used to calculate the Semantic Answer Similarity of answers returned by LLMs. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/scale-score-false-h2-3c8e4e7e543e8cce.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/scale-score-false-h2-3c8e4e7e543e8cce.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1b79085958ddc79dec10248f02968d664ebd3a8e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/scale-score-false-h2-3c8e4e7e543e8cce.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Change the default value of `scale_score` to False for Retrievers. + Users can still explicitly set `scale_score` to True to get relevance + scores in the range [0, 1]. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/secret-handling-for-components-d576a28135a224db.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/secret-handling-for-components-d576a28135a224db.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0548d9d269f15b394fc1e62725fa7f1bc858ea38 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/secret-handling-for-components-d576a28135a224db.yaml @@ -0,0 +1,40 @@ +--- +features: + - | + Expose a `Secret` type to provide consistent API for any component that requires secrets for authentication. + Currently supports string tokens and environment variables. Token-based secrets are automatically + prevented from being serialized to disk (to prevent accidental leakage of secrets). + ```python + @component + class MyComponent: + def __init__(self, api_key: Optional[Secret] = None, **kwargs): + self.api_key = api_key + self.backend = None + + def warm_up(self): + # Call resolve_value to yield a single result. The semantics of the result is policy-dependent. + # Currently, all supported policies will return a single string token. + self.backend = SomeBackend(api_key=self.api_key.resolve_value() if self.api_key else None, ...) + + def to_dict(self): + # Serialize the policy like any other (custom) data. If the policy is token-based, it will + # raise an error. + return default_to_dict(self, api_key=self.api_key.to_dict() if self.api_key else None, ...) + + @classmethod + def from_dict(cls, data): + # Deserialize the policy data before passing it to the generic from_dict function. + api_key_data = data["init_parameters"]["api_key"] + api_key = Secret.from_dict(api_key_data) if api_key_data is not None else None + data["init_parameters"]["api_key"] = api_key + return default_from_dict(cls, data) + + # No authentication. + component = MyComponent(api_key=None) + # Token based authentication + component = MyComponent(api_key=Secret.from_token("sk-randomAPIkeyasdsa32ekasd32e")) + component.to_dict() # Error! Can't serialize authentication tokens + # Environment variable based authentication + component = MyComponent(api_key=Secret.from_env("OPENAI_API_KEY")) + component.to_dict() # This is fine + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-transformers-doc-embedder-prefix-suffix-442412c553135406.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-transformers-doc-embedder-prefix-suffix-442412c553135406.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5f88f83f1ce83c7780e088cea2f51b006fb5f61 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-transformers-doc-embedder-prefix-suffix-442412c553135406.yaml @@ -0,0 +1,7 @@ +--- +preview: + - | + Add `prefix` and `suffix` attributes to `SentenceTransformersDocumentEmbedder`. + They can be used to add a prefix and suffix to the Document text before + embedding it. This is necessary to take full advantage of modern embedding + models, such as E5. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-transformers-embedders-new-devices-mgmt-07cb59c6b4a13280.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-transformers-embedders-new-devices-mgmt-07cb59c6b4a13280.yaml new file mode 100644 index 0000000000000000000000000000000000000000..19a8223a5f7d12f77f4c2aeb809b2295242e01b2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-transformers-embedders-new-devices-mgmt-07cb59c6b4a13280.yaml @@ -0,0 +1,20 @@ +--- +upgrade: + - | + Adopt the new framework-agnostic device management in Sentence Transformers Embedders. + + Before this change: + ```python + from haystack.components.embedders import SentenceTransformersTextEmbedder + embedder = SentenceTransformersTextEmbedder(device="cuda:0") + ``` + + After this change: + ```python + from haystack.utils.device import ComponentDevice, Device + from haystack.components.embedders import SentenceTransformersTextEmbedder + device = ComponentDevice.from_single(Device.gpu(id=0)) + # or + # device = ComponentDevice.from_str("cuda:0") + embedder = SentenceTransformersTextEmbedder(device=device) + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-transformers-embedding-backend-69bd9410ede08c8f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-transformers-embedding-backend-69bd9410ede08c8f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b5e647fa7ea29a7d1614a491345eddc647be581d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-transformers-embedding-backend-69bd9410ede08c8f.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Add Sentence Transformers Embedding Backend. + It will be used by Embedder components and is responsible for computing embeddings. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-window-retriever-output-docs-d3de2ac4328488f1.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-window-retriever-output-docs-d3de2ac4328488f1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7e86f75ecb1e763802d2f23f9318d5e0a63c9c42 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-window-retriever-output-docs-d3de2ac4328488f1.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + The SentenceWindowRetriever has now an extra output key containing all the documents belonging to the context window. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/separate-classifiers-from-routers-96a37c76820385d6.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/separate-classifiers-from-routers-96a37c76820385d6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e785ff96004c2fef0e8bfe0a307bdbb1710e9058 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/separate-classifiers-from-routers-96a37c76820385d6.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Remove routing functionality from DocumentLanguageClassifier and rename TextLanguageClassifer to TextLanguageRouter. + Classifiers in Haystack 2.x change metadata values but do not route inputs to multiple outputs. The latter is reserved for routers. + Use DocumentLanguageClassifier in combination with MetaDataRouter to classify and route documents in indexing pipelines. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/serialize-torch-dtype-57c6c94f6114fc00.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/serialize-torch-dtype-57c6c94f6114fc00.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ba54d199dcfae77f947fe8c990a744ece8f85a82 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/serialize-torch-dtype-57c6c94f6114fc00.yaml @@ -0,0 +1,6 @@ +--- +fixes: + - | + Correctly handle the serialization and deserialization of torch.dtype. + This concerns the following components: + ExtractiveReader, HuggingFaceLocalGenerator, and TransformersSimilarityRanker. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/set-input-type-328589ee51ffa21b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/set-input-type-328589ee51ffa21b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dfb95d711948edc70064d179e8d6e3f658084e08 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/set-input-type-328589ee51ffa21b.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add `component.set_input_type()` function to set a Component input name, type and default value. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/simplify-textfiletodocument-c9d2fb7ed2c848ed.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/simplify-textfiletodocument-c9d2fb7ed2c848ed.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a533f6e8ae1e12300daeb30ba43bb3b676c5c6bc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/simplify-textfiletodocument-c9d2fb7ed2c848ed.yaml @@ -0,0 +1,3 @@ +preview: + - Remove most parameters from TextFileToDocument to make it match all other converters. + - Add support for ByteStreams diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/simplify-whisper-installation-1e347e2527cbf913.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/simplify-whisper-installation-1e347e2527cbf913.yaml new file mode 100644 index 0000000000000000000000000000000000000000..93b7ecb772231f90d1eb33c6bd11ece6a121e264 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/simplify-whisper-installation-1e347e2527cbf913.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Upgraded openai-whisper to version 20231106 and simplified installation through re-introduced audio extra. + The latest openai-whisper version unpins its tiktoken dependency, which resolved a version conflict with Haystack's dependencies. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-meta-in-azureconverter-ce1cc196a9b161f3.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-meta-in-azureconverter-ce1cc196a9b161f3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ccc96750020f20df2a685aaa2e3f6ca2907146a2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-meta-in-azureconverter-ce1cc196a9b161f3.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Adds support for single metadata dictionary input in `AzureOCRDocumentConverter`. In this way, additional metadata can be added to all files processed by this component even when the length of the list of sources is unknown. + diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-meta-in-htm2document-199ea44a4ae5c02b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-meta-in-htm2document-199ea44a4ae5c02b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c4067ec60b27e27d684e12d4b2146aa38fca311a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-meta-in-htm2document-199ea44a4ae5c02b.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Adds support for single metadata dictionary input in `HTMLToDocument`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-meta-in-markdown2document-082bae7b20bd605d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-meta-in-markdown2document-082bae7b20bd605d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e692cce4297ddd792dcc50d69e2aff5f4c624ffd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-meta-in-markdown2document-082bae7b20bd605d.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Adds support for single metadata dictionary input in `MarkdownToDocument``. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-meta-in-pypdf2document-99e15f1cb9f65892.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-meta-in-pypdf2document-99e15f1cb9f65892.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ee7397321b7220b6158db3e5d428d2a8b3fa44fa --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-meta-in-pypdf2document-99e15f1cb9f65892.yaml @@ -0,0 +1,5 @@ + +--- +enhancements: + - | + Adds support for single metadata dictionary input in `PyPDFToDocument`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sparse-emb-eq-773ef04ae3ed83ea.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sparse-emb-eq-773ef04ae3ed83ea.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4074680bcf45b29116be22306effdee12d2cf84d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sparse-emb-eq-773ef04ae3ed83ea.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Add an `__eq__` method to `SparseEmbedding` class to compare two `SparseEmbedding` objects. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sparse-embedding-dataclass-d75ae1ee6d75e646.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sparse-embedding-dataclass-d75ae1ee6d75e646.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bd20c43899e36f8bd4f9f73c595888f5d5807bee --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sparse-embedding-dataclass-d75ae1ee6d75e646.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Make SparseEmbedding a dataclass, this makes it easier to use the class with Pydantic diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/split-by-token-b9a4f954d4077ecc.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/split-by-token-b9a4f954d4077ecc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..643793b7bc5d9b0fcf3e2d9d2d1045603ff1ff86 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/split-by-token-b9a4f954d4077ecc.yaml @@ -0,0 +1,2 @@ +features: + - Add `split_length` by token in PreProcessor diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/split-dynamic-prompt-builder-798e5a74caf7a2e8.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/split-dynamic-prompt-builder-798e5a74caf7a2e8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eaf57ba3fce7512891143a13c34d3159532b4149 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/split-dynamic-prompt-builder-798e5a74caf7a2e8.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Split DynamicPromptBuilder into DynamicPromptBuilder and DynamicChatPromptBuilder diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/statistical-evaluator-d65b80e3ac24778a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/statistical-evaluator-d65b80e3ac24778a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7da31e250e77256d166859439438c79b83606188 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/statistical-evaluator-d65b80e3ac24778a.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add `StatisticalEvaluator`, this Component can be used to calculate the different statistic metrics from answers returned by LLMs. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/stopwords-hf-generator-dab4b5827bae1492.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/stopwords-hf-generator-dab4b5827bae1492.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5ee9e9a0f87d9ab90765d76aab1765ace68749fc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/stopwords-hf-generator-dab4b5827bae1492.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Allow specifying stopwords to stop text generation for `HuggingFaceLocalGenerator`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/store-factory-91e7da46aeb7ff21.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/store-factory-91e7da46aeb7ff21.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7fc978a83f59df646a45d035ce47e852e4ad245c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/store-factory-91e7da46aeb7ff21.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add utility function `store_class` factory to create `Store`s for testing purposes. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/stores-serialisation-a09398d158b01ae6.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/stores-serialisation-a09398d158b01ae6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2dc9f1e000b052263d071befc73faa76ab16720c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/stores-serialisation-a09398d158b01ae6.yaml @@ -0,0 +1,4 @@ +--- +preview: + - Add `from_dict` and `to_dict` methods to `Store` `Protocol` + - Add default `from_dict` and `to_dict` implementations to classes decorated with `@store` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/structured-logging-2d6cef3fee2b4f0e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/structured-logging-2d6cef3fee2b4f0e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..583dea24778ca37cd85aa28b789ecaf93972644b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/structured-logging-2d6cef3fee2b4f0e.yaml @@ -0,0 +1,18 @@ +--- +features: + - | + Haystack now supports structured logging out-of-the box. + Logging can be separated into 3 categories: + - If [`structlog`](https://www.structlog.org/en/stable/) is not installed, Haystack will + use the standard Python logging library with whatever configuration is present. + - If `structlog` is installed, Haystack will log through [`structlog`](https://www.structlog.org/en/stable/) using + structlog's console renderer. + To disable structlog, set the environment variable `HAYSTACK_LOGGING_IGNORE_STRUCTLOG_ENV_VAR` to `true`. + - To log in JSON, install [`structlog`](https://www.structlog.org/en/stable/) and + - set the environment variable `HAYSTACK_LOGGING_JSON` to `true` or + - enable JSON logging from Python + ```python + import haystack.logging + + haystack.logging.configure_logging(use_json=True) + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/support-ChatMessage-in-AnswerBuilder-d7958a72d3786f08.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/support-ChatMessage-in-AnswerBuilder-d7958a72d3786f08.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eb3ddfd3ddd6ab0a51b8034153504afd8be7e732 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/support-ChatMessage-in-AnswerBuilder-d7958a72d3786f08.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + AnswerBuilder can now accept ChatMessages as input in addition to strings. When using ChatMessages, metadata will be automatically added to the answer. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/support-dates-in-filters-2.0-15785cc3776d2210.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/support-dates-in-filters-2.0-15785cc3776d2210.yaml new file mode 100644 index 0000000000000000000000000000000000000000..99c84a4c13838e4564ef3f079bc26024ba796de4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/support-dates-in-filters-2.0-15785cc3776d2210.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add support for dates in filters. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/support-gpt-3.5-turbo-instruct-79236835a8be143c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/support-gpt-3.5-turbo-instruct-79236835a8be143c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..48dede7f00e088e62cb7502996633531fb49c714 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/support-gpt-3.5-turbo-instruct-79236835a8be143c.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Support OpenAI's new `gpt-3.5-turbo-instruct` model diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/support-gpt-4-1106-preview-ce8e551b11d96471.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/support-gpt-4-1106-preview-ce8e551b11d96471.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8180ab3a52615f657746e5d6c63624117e2ef589 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/support-gpt-4-1106-preview-ce8e551b11d96471.yaml @@ -0,0 +1,2 @@ +enhancements: + - Add new token limit for gpt-4-1106-preview model diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/tgi-chat-missing-decorator-799b2a133ee4708c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/tgi-chat-missing-decorator-799b2a133ee4708c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5437a83b5d934eea043353733f570a629bf9fd45 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/tgi-chat-missing-decorator-799b2a133ee4708c.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Add the `@component` decorator to `HuggingFaceTGIChatGenerator`. + The lack of this decorator made it impossible to use the `HuggingFaceTGIChatGenerator` in a pipeline. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/timeout-and-retries-for-AzureOpenAITextEmbedder-b02b760e9d6f28aa.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/timeout-and-retries-for-AzureOpenAITextEmbedder-b02b760e9d6f28aa.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0f30a4738cddce63de24b37b8fbc78955d6db705 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/timeout-and-retries-for-AzureOpenAITextEmbedder-b02b760e9d6f28aa.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Add `max_retries` and `timeout` parameters to the AzureOpenAITextEmbedder initializations. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/tracing-with-concurrency-5daadfde0a36f94a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/tracing-with-concurrency-5daadfde0a36f94a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d319c98091ea198b7cb42be2ef02ef84cbcd94c4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/tracing-with-concurrency-5daadfde0a36f94a.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Each tracing span of a component run is now attached with the pipeline run span object. This allows users to trace + the execution of multiple pipeline runs concurrently. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/transformer-router-from-dict-fix-04cb41b38ca61043.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/transformer-router-from-dict-fix-04cb41b38ca61043.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9cd7d5ce6203f68e45c688e54600cfb2dbb52e82 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/transformer-router-from-dict-fix-04cb41b38ca61043.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix `TransformersZeroShotTextRouter` and `TransformersTextRouter` `from_dict` methods to work when `init_parameters` only contain required variables. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/transformers-4-35-2-1739bbaa8c6f0111.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/transformers-4-35-2-1739bbaa8c6f0111.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b3c9b169986f71d5d23781135daa84107321110a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/transformers-4-35-2-1739bbaa8c6f0111.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Upgrade Transformers to the latest version 4.35.2 + This version adds support for DistilWhisper, Fuyu, Kosmos-2, SeamlessM4T, Owl-v2. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/transformers-similarity-embed-meta-7f2b15988549f805.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/transformers-similarity-embed-meta-7f2b15988549f805.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4630bc2bdf73b4fed4a8caa50f5979eceea415c5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/transformers-similarity-embed-meta-7f2b15988549f805.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Add meta_fields_to_embed following the implementation in SentenceTransformersDocumentEmbedder to be able to + embed meta fields along with the content of the document. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/unsafe-behaviour-e8b41d957113e0c3.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/unsafe-behaviour-e8b41d957113e0c3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6242432e3134a734063b00d3ebcb17d772c898b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/unsafe-behaviour-e8b41d957113e0c3.yaml @@ -0,0 +1,8 @@ +--- +features: + - | + Add `unsafe` argument to enable behaviour that could lead to remote code execution in `ConditionalRouter` and `OutputAdapter`. + By default unsafe behaviour is not enabled, the user must set it explicitly to `True`. + This means that user types like `ChatMessage`, `Document`, and `Answer` can be used as output types when `unsafe` is `True`. + We recommend using `unsafe` behaviour only when the Jinja templates source is trusted. + For more info see the documentation for [`ConditionalRouter`](https://docs.haystack.deepset.ai/docs/conditionalrouter#unsafe-behaviour) and [`OutputAdapter`](https://docs.haystack.deepset.ai/docs/outputadapter#unsafe-behaviour) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-deepset-cloud-sdk-save-pipeline-config-ff820838846f5f38.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-deepset-cloud-sdk-save-pipeline-config-ff820838846f5f38.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a5ca3ac5e473480ecf0687d85e8c9b0999b40384 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-deepset-cloud-sdk-save-pipeline-config-ff820838846f5f38.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Update the deepset Cloud SDK to the new endpoint format for new saving pipeline configs. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-openai-chat-tools-3d3636b2ffea9736.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-openai-chat-tools-3d3636b2ffea9736.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4b30ee675e0207a5ade3701489c3de8dc34d8004 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-openai-chat-tools-3d3636b2ffea9736.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Update OpenAIChatGenerator to handle both tools and functions calling. OpenAIChatGenerator now supports both tools + and functions `generation_kwargs` parameters that enable function/tools invocation. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-searchapi-new-format-74d8794a8a6f5581.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-searchapi-new-format-74d8794a8a6f5581.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7c6a40d72cbbdc7d634c02f0298a1e59bb4eaabc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-searchapi-new-format-74d8794a8a6f5581.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Updated the SearchApiWebSearch component with new search format and allowed users to specify the search engine via the `engine` + parameter in `search_params`. The default search engine is Google, making it easier for users to tailor their web searches. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-secret-handling-in-components-925d4f3c3c9530db.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-secret-handling-in-components-925d4f3c3c9530db.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6e91c895264a450f6e8252288367705aab893f1a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-secret-handling-in-components-925d4f3c3c9530db.yaml @@ -0,0 +1,8 @@ +--- +upgrade: + - | + Update secret handling for components using the `Secret` type. The following components are affected: + `RemoteWhisperTranscriber`, `AzureOCRDocumentConverter`, `AzureOpenAIDocumentEmbedder`, `AzureOpenAITextEmbedder`, `HuggingFaceTEIDocumentEmbedder`, `HuggingFaceTEITextEmbedder`, `OpenAIDocumentEmbedder`, `SentenceTransformersDocumentEmbedder`, `SentenceTransformersTextEmbedder`, `AzureOpenAIGenerator`, `AzureOpenAIChatGenerator`, `HuggingFaceLocalChatGenerator`, `HuggingFaceTGIChatGenerator`, `OpenAIChatGenerator`, `HuggingFaceLocalGenerator`, `HuggingFaceTGIGenerator`, `OpenAIGenerator`, `TransformersSimilarityRanker`, `SearchApiWebSearch`, `SerperDevWebSearch` + + The default init parameters for `api_key`, `token`, `azure_ad_token` have been adjusted to use environment variables wherever possible. The `azure_ad_token_provider` parameter has been removed from Azure-based components. Components based on Hugging + Face are now required to either use a token or an environment variable if authentication is required - The on-disk local token file is no longer supported. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-supported-cohere-models-68f17fa70051fc90.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-supported-cohere-models-68f17fa70051fc90.yaml new file mode 100644 index 0000000000000000000000000000000000000000..19a1edc1c79f00e86f358072da48838cc3dfa929 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-supported-cohere-models-68f17fa70051fc90.yaml @@ -0,0 +1,7 @@ +--- +enhancements: + - | + Add alias names for Cohere embed models for an easier map between names +fixes: + - | + Remove unsupported `medium` and `finance-sentiment` models from supported Cohere embed model list diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/upgrade-hatch-uv-5e5cccdf7450d01f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/upgrade-hatch-uv-5e5cccdf7450d01f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a6a63d35ce9b751023c37fc5936159015cb03f38 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/upgrade-hatch-uv-5e5cccdf7450d01f.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Upgrade Hatch to 1.13.0 and adopt uv as installer, to speed up the CI. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/upgrade-openai-client-15fda68fc769f95b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/upgrade-openai-client-15fda68fc769f95b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..40b039a9ead91a723ad721f77affcfe77c20c8dc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/upgrade-openai-client-15fda68fc769f95b.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Upgrade to OpenAI client version 1.x diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/url-cache-checker-a0fb3d7ad0bdb8c2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/url-cache-checker-a0fb3d7ad0bdb8c2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d872c8b8015be2c7b35fd7d112207145ac3937e5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/url-cache-checker-a0fb3d7ad0bdb8c2.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Add `UrlCacheChecker` to support Web retrieval pipelines. + Check if documents coming from a given list of URLs are already present in the store and if so, returns them. + All URLs with no matching documents are returned on a separate connection. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/use-document-store-from-dict-db7975d0e0e5e451.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/use-document-store-from-dict-db7975d0e0e5e451.yaml new file mode 100644 index 0000000000000000000000000000000000000000..89563147f82f93958a69630c10b53f864a02b0fe --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/use-document-store-from-dict-db7975d0e0e5e451.yaml @@ -0,0 +1,7 @@ +--- +fixes: + - | + For components that support multiple Document Stores, prioritize using the specific `from_dict` class method + for deserialization when available. Otherwise, fall back to the generic `default_from_dict` method. + This impacts the following generic components: `CacheChecker`, `DocumentWriter`, `FilterRetriever`, and + `SentenceWindowRetriever`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/web-retriever-add-domain-scoping-6594425e0c0ace3c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/web-retriever-add-domain-scoping-6594425e0c0ace3c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..51b1b4ed4d207bc260ef6b712f3f0eeda2819553 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/web-retriever-add-domain-scoping-6594425e0c0ace3c.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Introduced `allowed_domains` parameter in `WebRetriever` for domain-specific searches, + thus enabling "talk to a website" and "talk to docs" scenarios. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/weights-normalize-docjoin-rrf-v2-9cad33012fe90a55.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/weights-normalize-docjoin-rrf-v2-9cad33012fe90a55.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e732906c98de31dc2842b71349adb6ac0b3f8f92 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/weights-normalize-docjoin-rrf-v2-9cad33012fe90a55.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Introduces weighted score normalization for the DocumentJoiner's reciprocal rank fusion, enhancing the relevance of document sorting by allowing customizable influence on the final scores diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/zero-shot-text-router-f5090589e652197c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/zero-shot-text-router-f5090589e652197c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..20c158e01e9244ea5d322ed13c8b112ef04dda87 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/zero-shot-text-router-f5090589e652197c.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add a Zero Shot Text Router that uses an NLI model from HF to classify texts based on a set of provided labels and routes them based on the label they were classified with.