Repository: Knowledgator/GLiClass Branch: main Commit: 6ccf83fe5130 Files: 35 Total size: 364.2 KB Directory structure: gitextract_2n3b6llp/ ├── .github/ │ └── workflows/ │ ├── release.yaml │ └── tests.yml ├── .gitignore ├── LICENSE ├── README.md ├── demo.py ├── gliclass/ │ ├── __init__.py │ ├── config.py │ ├── data_processing.py │ ├── layers.py │ ├── loss_functions.py │ ├── model.py │ ├── ops.py │ ├── pipeline.py │ ├── poolings.py │ ├── scorers.py │ ├── serve/ │ │ ├── __init__.py │ │ ├── __main__.py │ │ ├── client.py │ │ ├── config.py │ │ ├── memory.py │ │ └── server.py │ ├── training.py │ └── utils.py ├── notebooks/ │ └── finetuning.ipynb ├── pyproject.toml ├── serve_configs/ │ └── serve_config.yaml ├── test_gliclass.py ├── tests/ │ ├── test_data_processing.py │ ├── test_loss_functions.py │ ├── test_poolings.py │ ├── test_scorers.py │ └── test_utils.py ├── train.py └── train_rl.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/release.yaml ================================================ name: Release GLiClass to PyPI on: push: tags: - 'v*' # Trigger on version tags (e.g., v1.0.0, v2.1.3) concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: build: name: Build distribution 📦 runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 with: persist-credentials: false - name: Set up Python uses: actions/setup-python@v6 with: python-version: "3.x" - name: Install pypa/build run: >- python3 -m pip install build --user - name: Build a binary wheel and a source tarball run: python3 -m build - name: Store the distribution packages uses: actions/upload-artifact@v5 with: name: python-package-distributions path: dist/ publish-to-pypi: name: >- Publish Python 🐍 distribution 📦 to PyPI if: startsWith(github.ref, 'refs/tags/') # only publish to PyPI on tag pushes needs: - build runs-on: ubuntu-latest environment: name: pypi url: https://pypi.org/project/gliclass/ # Replace with your PyPI project name permissions: id-token: write # IMPORTANT: mandatory for trusted publishing steps: - name: Checkout code uses: actions/checkout@v6 with: fetch-depth: 0 # Fetch all history to check branches - name: Verify tag is on main branch run: | if ! git branch -r --contains ${{ github.ref_name }} | grep -q 'origin/main'; then echo "Error: Tag ${{ github.ref_name }} is not on the main branch" exit 1 fi echo "✓ Tag ${{ github.ref_name }} is on main branch" - name: Download all the dists uses: actions/download-artifact@v6 with: name: python-package-distributions path: dist/ - name: Publish distribution 📦 to PyPI uses: pypa/gh-action-pypi-publish@release/v1 ================================================ FILE: .github/workflows/tests.yml ================================================ name: Tests on: push: branches: - main pull_request: branches: - main workflow_dispatch: concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: test: name: pytest (Python ${{ matrix.python-version }}) runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ["3.10", "3.11", "3.12"] steps: - name: Check out repository uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Cache pip uses: actions/cache@v4 with: path: ~/.cache/pip key: ${{ runner.os }}-py${{ matrix.python-version }}-pip-${{ hashFiles('pyproject.toml') }} restore-keys: | ${{ runner.os }}-py${{ matrix.python-version }}-pip- - name: Install dependencies run: | python -m pip install --upgrade pip pip install -e . pip install pytest pytest-asyncio - name: Run pytest run: pytest -v --tb=short lint: name: ruff runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.12" - name: Install ruff run: pip install ruff - name: ruff check run: ruff check gliclass - name: ruff format --check run: ruff format --check gliclass ================================================ FILE: .gitignore ================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so #custom models/ wandb/ gradio_cached_examples/ test.ipynb demo1.py .gradio/ uv.lock # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ .ruff_cache/ cover/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder .pybuilder/ target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv # For a library or package, you might want to ignore these files since the code is # intended to run in multiple environments; otherwise, check them in: # .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # poetry # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. # This is especially recommended for binary packages to ensure reproducibility, and is more # commonly ignored for libraries. # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control #poetry.lock # pdm # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. #pdm.lock # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it # in version control. # https://pdm.fming.dev/latest/usage/project/#working-with-version-control .pdm.toml .pdm-python .pdm-build/ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # pytype static type analyzer .pytype/ # Cython debug symbols cython_debug/ # PyCharm # JetBrains specific template is maintained in a separate JetBrains.gitignore that can # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. #.idea/ ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # ⭐ GLiClass: Generalist and Lightweight Model for Sequence Classification **GLiClass** is an efficient, zero-shot sequence classification model inspired by the [GLiNER](https://github.com/urchade/GLiNER/tree/main) framework. It achieves comparable performance to traditional cross-encoder models while being significantly more computationally efficient, offering classification results approximately **10 times faster** by performing classification in a single forward pass.

📄 Blog   •   📢 Discord   •   📺 Demo   •   🤗 Available models   •  

### 🚀 Quick Start Install GLiClass easily using pip: ```bash pip install gliclass ``` #### Install from Source Clone and install directly from GitHub: ```bash git clone https://github.com/Knowledgator/GLiClass cd GLiClass python -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate pip install -r requirements.txt pip install . ``` Verify your installation: ```python import gliclass print(gliclass.__version__) ``` ### 🧑‍💻 Usage Example ```python from gliclass import GLiClassModel, ZeroShotClassificationPipeline from transformers import AutoTokenizer model = GLiClassModel.from_pretrained("knowledgator/gliclass-small-v1.0") tokenizer = AutoTokenizer.from_pretrained("knowledgator/gliclass-small-v1.0") pipeline = ZeroShotClassificationPipeline( model, tokenizer, classification_type='multi-label', device='cuda:0' ) text = "One day I will see the world!" labels = ["travel", "dreams", "sport", "science", "politics"] results = pipeline(text, labels, threshold=0.5)[0] for result in results: print(f"{result['label']} => {result['score']:.3f}") ``` ### 🔥 New Features #### Hierarchical Labels GLiClass now supports hierarchical label structures using dot notation: ```python hierarchical_labels = { "sentiment": ["positive", "negative", "neutral"], "topic": ["product", "service", "shipping"] } text = "The product quality is amazing but delivery was slow" results = pipeline(text, hierarchical_labels, threshold=0.5)[0] for result in results: print(f"{result['label']} => {result['score']:.3f}") # Output: # sentiment.positive => 0.892 # topic.product => 0.921 # topic.shipping => 0.763 ``` Get hierarchical output matching your input structure: ```python results = pipeline(text, hierarchical_labels, return_hierarchical=True)[0] print(results) # Output: # { # "sentiment": {"positive": 0.892, "negative": 0.051, "neutral": 0.124}, # "topic": {"product": 0.921, "service": 0.153, "shipping": 0.763} # } ``` #### Few-Shot Examples Improve classification accuracy with in-context examples using the `<>` token: ```python examples = [ { "text": "Love this item, great quality!", "labels": ["positive", "product"] }, { "text": "Customer support was unhelpful", "labels": ["negative", "service"] } ] text = "Fast delivery and the item works perfectly!" labels = ["positive", "negative", "product", "service", "shipping"] results = pipeline(text, labels, examples=examples, threshold=0.5)[0] for result in results: print(f"{result['label']} => {result['score']:.3f}") ``` #### Task Description Prompts Add custom prompts to guide the classification task: ```python text = "The battery life on this phone is incredible" labels = ["positive", "negative", "neutral"] results = pipeline( text, labels, prompt="Classify the sentiment of this product review:", threshold=0.5 )[0] ``` Use per-text prompts for batch processing: ```python texts = ["Review about electronics", "Review about clothing"] prompts = [ "Analyze this electronics review:", "Analyze this clothing review:" ] results = pipeline(texts, labels, prompt=prompts) ``` #### Long Document Classification Process long documents with automatic text chunking: ```python from gliclass import ZeroShotClassificationWithChunkingPipeline chunking_pipeline = ZeroShotClassificationWithChunkingPipeline( model, tokenizer, text_chunk_size=8192, text_chunk_overlap=256, labels_chunk_size=8 ) long_document = "..." # Very long text labels = ["category1", "category2", "category3"] results = chunking_pipeline(long_document, labels, threshold=0.5) ``` ### 🌟 Retrieval-Augmented Classification (RAC) With new models trained with retrieval-agumented classification, such as [this model](https://huggingface.co/knowledgator/gliclass-base-v2.0-rac-init) you can specify examples to improve classification accuracy: ```python example = { "text": "A new machine learning platform automates complex data workflows but faces integration issues.", "all_labels": ["AI", "automation", "data_analysis", "usability", "integration"], "true_labels": ["AI", "integration", "automation"] } text = "The new AI-powered tool streamlines data analysis but has limited integration capabilities." labels = ["AI", "automation", "data_analysis", "usability", "integration"] results = pipeline(text, labels, threshold=0.1, rac_examples=[example])[0] for predict in results: print(f"{predict['label']} => {predict['score']:.3f}") ``` ### 🚀 Production Serving Deploy GLiClass with Ray Serve for production workloads with dynamic batching and memory-aware processing. #### Installation ```bash pip install gliclass[serve] ``` #### Quick Start ```bash # Default model python -m gliclass.serve # Specify model and port python -m gliclass.serve --model knowledgator/gliclass-edge-v3.0 --port 8000 # With config file python -m gliclass.serve --config serve_configs/serve_config.yaml ``` #### Python Client ```python from gliclass.serve import GLiClassClient client = GLiClassClient(url="http://localhost:8000/gliclass") result = client.classify( text="This is a great product!", labels=["positive", "negative", "neutral"], threshold=0.3, ) print(result) # [{"label": "positive", "score": 0.95}, ...] ``` #### HTTP API The HTTP endpoint processes one text per request. ```bash curl -X POST http://localhost:8000/gliclass \ -H "Content-Type: application/json" \ -d '{ "texts": "This is a great product!", "labels": ["positive", "negative", "neutral"], "threshold": 0.3 }' # Response: [{"label": "positive", "score": 0.95}, ...] ``` **Note:** For batch processing multiple texts, use the `ZeroShotClassificationPipeline` directly instead of the serving API. See `serve_configs/serve_config.yaml` for full configuration options. ### 🎯 Key Use Cases - **Sentiment Analysis:** Rapidly classify texts as positive, negative, or neutral. - **Document Classification:** Efficiently organize and categorize large document collections. - **Search Results Re-ranking:** Improve relevance and precision by reranking search outputs. - **News Categorization:** Automatically tag and organize news articles into predefined categories. - **Fact Checking:** Quickly validate and categorize statements based on factual accuracy. ### 🛠️ How to Train Prepare your training data as follows: ```json [ {"text": "Sample text.", "all_labels": ["sports", "science", "business"], "true_labels": ["sports"]}, ... ] ``` Optionally, specify confidence scores explicitly: ```json [ {"text": "Sample text.", "all_labels": ["sports", "science"], "true_labels": {"sports": 0.9}}, ... ] ``` Please, refer to the `train.py` script to set up your training from scratch or fine-tune existing models. ### ⚙️ Advanced Configuration #### Architecture Types GLiClass supports multiple architecture types: - **uni-encoder**: Single encoder for both text and labels (default, most efficient) - **bi-encoder**: Separate encoders for text and labels - **bi-encoder-fused**: Bi-encoder with label embeddings fused into text encoding - **encoder-decoder**: Encoder-decoder architecture for sequence-to-sequence tasks ```python from gliclass import GLiClassBiEncoder # Load a bi-encoder model model = GLiClassBiEncoder.from_pretrained("knowledgator/gliclass-biencoder-v1.0") ``` #### Pooling Strategies Configure how token embeddings are pooled: - `first`: First token (CLS token) - `avg`: Average pooling - `max`: Max pooling - `last`: Last token - `sum`: Sum pooling - `rms`: Root mean square pooling - `abs_max`: Max of absolute values - `abs_avg`: Average of absolute values ```python from gliclass import GLiClassModelConfig config = GLiClassModelConfig( pooling_strategy='avg', class_token_pooling='average' # or 'first' ) ``` #### Scoring Mechanisms Choose different scoring mechanisms for classification: - `simple`: Dot product (fastest) - `weighted-dot`: Weighted dot product with learned projections - `mlp`: Multi-layer perceptron scorer - `hopfield`: Hopfield network-based scorer ```python config = GLiClassModelConfig( scorer_type='mlp' ) ``` --- ### Flash Attention Backends GLiClass supports optional flash attention backends for faster inference. #### Install ```bash pip install flashdeberta # DeBERTa v2 pip install turbot5 # T5 / mT5 ``` --- #### FlashDeBERTa (DeBERTa v2) Enable via environment variable: ```bash export USE_FLASHDEBERTA=1 ``` If `flashdeberta` is installed, DeBERTa v2 models will use `FlashDebertaV2Model`. Otherwise, GLiClass falls back to `DebertaV2Model`. --- #### TurboT5 (T5 / mT5) Enable via environment variable: ```bash export TURBOT5_ATTN_TYPE=triton-basic ``` If `turbot5` is installed, T5 / mT5 models will use `FlashT5EncoderModel`. Otherwise, GLiClass falls back to `T5EncoderModel`. Notes: * Flash backends are **optional** * Enabled automatically when available * No code changes required Want it even tighter (single block), or is this the sweet spot? ## 📚 Citations If you find GLiClass useful in your research or project, please cite our papers: ```bibtex @misc{stepanov2025gliclassgeneralistlightweightmodel, title={GLiClass: Generalist Lightweight Model for Sequence Classification Tasks}, author={Ihor Stepanov and Mykhailo Shtopko and Dmytro Vodianytskyi and Oleksandr Lukashov and Alexander Yavorskyi and Mykyta Yaroshenko}, year={2025}, eprint={2508.07662}, archivePrefix={arXiv}, primaryClass={cs.LG}, url={https://arxiv.org/abs/2508.07662}, } ``` ================================================ FILE: demo.py ================================================ """ GLiClass Enhanced Demo with Advanced Features Features: - Task description prompts - Hierarchical label inputs (JSON format) - Few-shot examples - Hierarchical output structure - Label descriptions """ import json from typing import Dict, List, Any, Union, Optional import gradio as gr import torch from transformers import AutoTokenizer from gliclass import GLiClassModel, ZeroShotClassificationPipeline # Initialize model and pipeline device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') model_path = "knowledgator/gliclass-small-v1.0" model = GLiClassModel.from_pretrained(model_path) tokenizer = AutoTokenizer.from_pretrained(model_path) pipeline = ZeroShotClassificationPipeline( model, tokenizer, classification_type='multi-label', device=device ) # ============== Example Texts ============== TEXT_PRODUCT_REVIEW = """ I recently purchased the Sony WH-1000XM4 Wireless Noise-Canceling Headphones from Amazon and I must say, I'm thoroughly impressed. The package arrived in New York within 2 days, thanks to Amazon Prime's expedited shipping. The headphones themselves are remarkable. The noise-canceling feature works like a charm in the bustling city environment, and the 30-hour battery life means I don't have to charge them every day. Connecting them to my Samsung Galaxy S21 was a breeze, and the sound quality is second to none. I also appreciated the customer service from Amazon when I had a question about the warranty. They responded within an hour and provided all the information I needed. However, the headphones did not come with a hard case, which was listed in the product description. I contacted Amazon, and they offered a 10% discount on my next purchase as an apology. Overall, I'd give these headphones a 4.5/5 rating and highly recommend them to anyone looking for top-notch quality in both product and service. """ TEXT_TECH_COMPANIES = """ Apple Inc. is an American multinational technology company headquartered in Cupertino, California. Apple is the world's largest technology company by revenue, with US$394.3 billion in 2022 revenue. As of March 2023, Apple is the world's biggest company by market capitalization. Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975 to develop and sell BASIC interpreters for the Altair 8800. During his career at Microsoft, Gates held the positions of chairman, chief executive officer, president and chief software architect. Apple was founded as Apple Computer Company on April 1, 1976, by Steve Wozniak, Steve Jobs (1955–2011) and Ronald Wayne to develop and sell Wozniak's Apple I personal computer. """ TEXT_SCIENTIFIC = """ Several studies have reported its pharmacological activities, including anti-inflammatory, antimicrobial, and antitumoral effects. The effect of E-anethole was studied in the osteosarcoma MG-63 cell line, and the antiproliferative activity was evaluated by an MTT assay. It showed a GI50 value of 60.25 μM with apoptosis induction through the mitochondrial-mediated pathway. Additionally, it induced cell cycle arrest at the G0/G1 phase, up-regulated the expression of p53, caspase-3, and caspase-9, and down-regulated Bcl-xL expression. """ TEXT_RESTAURANT_REVIEW = """ We visited La Maison last Friday for our anniversary dinner. The ambiance was absolutely stunning - dim lighting, soft jazz music, and elegant table settings. Our waiter, Marcus, was incredibly attentive without being intrusive. For appetizers, we had the truffle bruschetta and the soup of the day. Both were divine! The main courses - filet mignon for me and lobster risotto for my wife - were cooked to perfection. The only downside was the wait time for our desserts, which took about 25 minutes. However, the chocolate soufflé was worth the wait! Price was on the higher side ($180 for two), but the quality justified the cost. Will definitely return! """ TEXT_NEWS_POLITICS = """ The Senate passed a landmark bipartisan infrastructure bill late Thursday night, allocating $1.2 trillion for roads, bridges, broadband internet, and clean energy initiatives. The vote was 69-30, with 19 Republican senators joining all Democrats in support. President Biden called the passage "a historic investment in America's future" and urged the House to act quickly. However, progressive Democrats have signaled they won't vote for the infrastructure bill unless it's paired with a larger social spending package. Senate Minority Leader criticized portions of the bill related to climate spending, calling them "unnecessary green new deal provisions," while environmental groups praised the clean energy investments as "a step in the right direction, but not nearly enough." """ TEXT_SPORTS = """ In a thrilling overtime finish, the Lakers defeated the Celtics 118-112 in Game 7 of the NBA Finals. LeBron James delivered a historic performance with 42 points, 16 rebounds, and 10 assists, securing his fifth championship ring and fourth Finals MVP award. The game was tied at 102 with 30 seconds remaining in regulation when Marcus Smart hit a contested three-pointer. However, James answered with a driving layup at the buzzer to force overtime. In the extra period, the Lakers outscored Boston 16-10, with Anthony Davis contributing two crucial blocks in the final minute. "This is what you dream about as a kid," James said in the post-game interview. "Playing against the Celtics, Game 7, everything on the line." """ TEXT_MOVIE_REVIEW = """ Christopher Nolan's "Oppenheimer" is a masterwork of biographical cinema that demands to be seen on the largest screen possible. Cillian Murphy delivers a career-defining performance as J. Robert Oppenheimer, capturing both the brilliance and moral anguish of the father of the atomic bomb. The film's nonlinear structure, weaving between the Manhattan Project, the 1954 security hearing, and the 1959 Lewis Strauss confirmation hearing, could have been confusing. Instead, Nolan crafts a compelling narrative that builds to a devastating emotional climax. At three hours, some viewers may find the pacing challenging, particularly in the courtroom sequences. However, the technical achievements - Ludwig Göransson's haunting score, Hoyte van Hoytema's IMAX cinematography - make this an unmissable theatrical experience. Rating: 9/10 """ TEXT_TECH_STARTUP = """ San Francisco-based AI startup Anthropic announced today it has raised $450 million in Series C funding, valuing the company at $5 billion. The round was led by Spark Capital, with participation from Google and existing investors. Founded in 2021 by former OpenAI researchers Dario and Daniela Amodei, Anthropic has positioned itself as a leader in AI safety research. The company's Claude assistant has gained significant market share in the enterprise segment. "This funding will accelerate our research into interpretable and steerable AI systems," said CEO Dario Amodei. "We believe safety and capability go hand in hand." The company plans to double its research team and expand internationally, with offices planned in London and Tokyo. """ TEXT_HEALTH_WELLNESS = """ A new study published in the Journal of the American Medical Association suggests that intermittent fasting may offer significant benefits beyond weight loss. Researchers followed 500 participants over two years and found improvements in cardiovascular health markers, insulin sensitivity, and cognitive function. Participants who followed a 16:8 fasting protocol (eating within an 8-hour window) showed a 15% reduction in LDL cholesterol and a 20% improvement in fasting glucose levels compared to the control group. However, experts caution that intermittent fasting isn't suitable for everyone. "Pregnant women, people with a history of eating disorders, and those with certain medical conditions should consult their doctor first," said Dr. Sarah Chen, the study's lead author. "It's not a magic solution, but for many people, it can be a sustainable approach to improving metabolic health." """ TEXT_TRAVEL = """ Hidden among the limestone karsts of Ha Long Bay, Cat Ba Island offers travelers an authentic Vietnamese experience away from the tourist crowds. We spent five days exploring this gem and discovered why it's becoming a favorite among backpackers and adventure seekers. The island's national park features challenging hikes through tropical rainforest, with the trek to the peak of Ngu Lam offering panoramic views of the bay. We also kayaked through hidden lagoons and explored caves that few tourists ever see. Accommodation ranges from basic hostels ($8/night) to comfortable eco-resorts ($60/night). The seafood is incredibly fresh - we had the best grilled squid of our lives at a family-run restaurant in Cat Ba Town for just $5. Pro tip: rent a motorbike to explore the quieter beaches on the island's east side. """ TEXT_COOKING_RECIPE = """ This Thai green curry comes together in just 30 minutes and tastes better than takeout. The secret is making your own curry paste - it takes an extra 10 minutes but the flavor difference is remarkable. For the paste, blend together: 10 green chilies, 4 garlic cloves, 2 shallots, 1 stalk lemongrass, 1 inch galangal, handful of cilantro stems, 1 tsp cumin, 1 tsp coriander, zest of 1 lime, and 2 tbsp fish sauce. Heat coconut oil in a wok, fry the paste for 2 minutes until fragrant. Add chicken (or tofu), cook until browned. Pour in coconut milk, add bamboo shoots, Thai eggplant, and basil. Simmer for 15 minutes. Season with palm sugar and more fish sauce to taste. Serve over jasmine rice with extra chilies on the side. This recipe serves 4 and can be made ahead - the flavors actually improve overnight. """ TEXT_FINANCIAL_ADVICE = """ With inflation running at 4.2% and the Fed signaling more rate hikes, many investors are wondering how to position their portfolios. Here's what our analysis suggests for Q4 2024. Fixed income is finally attractive again. With 10-year Treasury yields above 4.5%, bonds offer meaningful real returns for the first time in years. We recommend increasing allocation to investment-grade corporate bonds and TIPS for inflation protection. For equities, we're cautiously optimistic on value stocks, particularly in the energy and financial sectors. Tech valuations remain stretched despite recent pullbacks. International developed markets, especially Japan and Europe, offer better risk-reward at current levels. Remember: past performance doesn't guarantee future results. This is general information, not personalized advice. Consult a financial advisor before making investment decisions. """ TEXT_ENVIRONMENTAL = """ The Great Barrier Reef experienced its sixth mass bleaching event in a decade this summer, with aerial surveys showing 91% of reefs affected. Scientists warn that without dramatic action on climate change, the world's largest coral ecosystem may not survive beyond 2050. "We're witnessing the collapse of one of Earth's most biodiverse ecosystems in real time," said Dr. Terry Hughes of James Cook University. Water temperatures reached 2°C above the February average, causing corals to expel the symbiotic algae that give them color and nutrients. Some researchers are experimenting with heat-resistant coral varieties and cloud-brightening technology to shade reefs. However, most scientists agree these are stopgap measures. "The only real solution is rapid decarbonization," Hughes said. "Everything else is just buying time." """ TEXT_EDUCATION = """ The debate over standardized testing in American schools has intensified following a new report showing significant post-pandemic learning gaps. The National Assessment of Educational Progress found that fourth-grade math scores dropped to levels not seen since 2005. Proponents of testing argue that standardized assessments are essential for identifying struggling students and holding schools accountable. "Without data, we're flying blind," said Education Secretary Miguel Cardona. "Tests help us direct resources where they're needed most." Critics counter that high-stakes testing narrows the curriculum and increases student stress without improving outcomes. "We're testing kids more than ever, but educational outcomes aren't improving," said education researcher Dr. Pasi Sahlberg. "Countries like Finland, which use minimal standardized testing, consistently outperform the US." """ TEXT_FASHION = """ Milan Fashion Week wrapped up yesterday with several surprising trends that will likely dominate fall/winter 2025. After years of quiet luxury and minimalism, designers are embracing bold maximalism - think dramatic volumes, clashing prints, and unapologetic color. Prada's collection featured oversized coats with exaggerated shoulders paired with flowing silk pants, while Gucci returned to its pattern-mixing roots under new creative direction. Versace went full baroque with gold-embroidered gowns that would feel at home in a Renaissance painting. Sustainability remained a talking point, with Stella McCartney showcasing a collection made entirely from recycled ocean plastic. However, critics noted that the industry still has far to go. "One sustainable collection doesn't offset the environmental impact of fast fashion," noted fashion journalist Vanessa Friedman. "The industry needs systemic change, not just good PR." """ TEXT_LEGAL_CASE = """ The Supreme Court agreed Monday to hear a case that could reshape the boundaries of free speech on social media platforms. The case, NetChoice v. Paxton, challenges Texas and Florida laws that prohibit large social media companies from removing certain political content. Tech companies argue that the First Amendment protects their right to moderate content as they see fit, similar to how newspapers decide what to publish. "Forcing platforms to host speech they find objectionable is compelled speech, which the Constitution forbids," said NetChoice counsel Paul Clement. Texas and Florida counter that social media platforms function as common carriers or public utilities and should be subject to similar non-discrimination requirements. "These companies have become the modern public square," said Texas Attorney General Ken Paxton. "They shouldn't be able to silence voices based on political viewpoint." """ TEXT_GAMING = """ After three years in development hell, "Hollow Eclipse" has finally launched - and it's everything fans hoped for. This action RPG from indie studio Moonlight Games delivers a haunting 40-hour adventure that rivals titles from studios with ten times the budget. The combat system strikes a perfect balance between accessibility and depth. Basic attacks and dodges are simple to execute, but mastering the "shadow merge" mechanic - which lets you temporarily possess enemies - adds layers of strategy. Boss fights are challenging without feeling unfair, though the final boss may take even experienced players dozens of attempts. Where the game truly shines is its atmosphere. The decaying gothic city of Velmoor is rendered in stunning hand-drawn art, and the ambient soundtrack creates constant unease. The story tackles themes of grief and memory with surprising emotional maturity. Minor technical issues (occasional frame drops, one softlock) can't diminish this achievement. Score: 9.5/10 """ TEXT_REAL_ESTATE = """ The housing market is sending mixed signals as we enter 2025. Existing home sales fell for the third consecutive month, down 4.1% in November, yet prices continue to climb in most metropolitan areas. The median home price hit $416,000, up 3.8% year-over-year. Low inventory remains the central issue. Many homeowners are reluctant to sell because they've locked in sub-3% mortgage rates and don't want to trade up to today's 7% rates. This "lock-in effect" has created a severe shortage of listings, particularly in the starter home category. "We're seeing bidding wars even in this high-rate environment because there's simply nothing to buy," said economist Lawrence Yun. First-time buyers are particularly squeezed, with affordability at its worst level since 1984. Some markets, including Austin and Phoenix, are showing price corrections, but coastal cities remain stubbornly expensive. """ TEXT_MENTAL_HEALTH = """ Workplace burnout has reached epidemic proportions, with a new Gallup survey finding that 76% of employees experience burnout at least sometimes. But recognizing burnout isn't always straightforward - it often manifests differently than simple exhaustion. The three hallmarks of burnout are: emotional exhaustion (feeling drained and unable to cope), depersonalization (becoming cynical and detached from work), and reduced personal accomplishment (feeling ineffective regardless of actual performance). Recovery requires more than a vacation. "You can't just rest your way out of burnout," says psychologist Dr. Christina Maslach, who pioneered burnout research. "You need to address the root causes - usually workload, lack of control, insufficient recognition, or values conflicts." Strategies include setting firm boundaries, delegating tasks, and having honest conversations with managers about sustainable workloads. In severe cases, professional support from a therapist can help. """ TEXT_ASTRONOMY = """ NASA's James Webb Space Telescope has detected what may be signs of biological activity in the atmosphere of K2-18b, an exoplanet 120 light-years away. The discovery has electrified the scientific community, though researchers caution against jumping to conclusions. The telescope's spectrometers identified dimethyl sulfide (DMS), a molecule produced almost exclusively by living organisms on Earth. Webb also confirmed the presence of methane and carbon dioxide, consistent with a water-rich atmosphere. "This is tantalizing, but not definitive proof of life," said lead researcher Dr. Nikku Madhusudhan. "DMS could potentially be produced by unknown geological processes. We need more observations." K2-18b is a "Hycean" world - a planet with a hydrogen-rich atmosphere and potentially a liquid water ocean beneath. If confirmed, this would be humanity's first detection of a potential biosignature beyond our solar system. """ def parse_labels_input(labels_input: str) -> Union[List[str], Dict[str, Any]]: """ Parse labels input - supports both comma-separated and JSON hierarchical format. Examples: - "positive, negative, neutral" -> ["positive", "negative", "neutral"] - '{"sentiment": ["positive", "negative"], "topic": ["food", "service"]}' -> dict """ labels_input = labels_input.strip() # Try parsing as JSON first (for hierarchical labels) if labels_input.startswith('{'): try: return json.loads(labels_input) except json.JSONDecodeError as e: raise ValueError(f"Invalid JSON format for hierarchical labels: {e}") # Otherwise, treat as comma-separated flat labels labels = [label.strip() for label in labels_input.split(',') if label.strip()] return labels def parse_examples_input(examples_input: str) -> Optional[List[Dict[str, Any]]]: """ Parse few-shot examples input (JSON format). Expected format: [ {"text": "Example text 1", "labels": ["label1", "label2"]}, {"text": "Example text 2", "labels": ["label3"]} ] """ if not examples_input or not examples_input.strip(): return None try: examples = json.loads(examples_input.strip()) if not isinstance(examples, list): raise ValueError("Examples must be a JSON array") for i, ex in enumerate(examples): if not isinstance(ex, dict): raise ValueError(f"Example {i+1} must be a JSON object") if 'text' not in ex: raise ValueError(f"Example {i+1} missing 'text' field") if 'labels' not in ex and 'true_labels' not in ex: raise ValueError(f"Example {i+1} missing 'labels' field") return examples except json.JSONDecodeError as e: raise ValueError(f"Invalid JSON format for examples: {e}") def format_output( results: Union[List[Dict], Dict], hierarchical: bool = False, output_format: str = "visual" ) -> Union[Dict[str, float], str]: """Format classification output for Gradio display.""" if output_format == "json": return format_as_json(results, hierarchical) if hierarchical and isinstance(results, dict): # Format hierarchical output as readable string return format_hierarchical_dict(results) if isinstance(results, list): return {result['label']: float(result['score']) for result in results} return results def format_as_json(results: Union[List[Dict], Dict], hierarchical: bool = False) -> str: """Format results as pretty-printed JSON string.""" if hierarchical and isinstance(results, dict): # Already in hierarchical dict format return json.dumps(results, indent=2, ensure_ascii=False) if isinstance(results, list): # Convert list of predictions to structured format output = { "predictions": [ {"label": r["label"], "score": round(r["score"], 4)} for r in results ], "scores": {r["label"]: round(r["score"], 4) for r in results} } return json.dumps(output, indent=2, ensure_ascii=False) return json.dumps(results, indent=2, ensure_ascii=False) def format_hierarchical_dict(d: Dict, indent: int = 0) -> str: """Format hierarchical dict for display with visual score bars.""" lines = [] prefix = " " * indent for key, value in d.items(): if isinstance(value, dict): lines.append(f"{prefix}**{key}**:") lines.append(format_hierarchical_dict(value, indent + 1)) else: score_bar = "█" * int(value * 20) + "░" * (20 - int(value * 20)) lines.append(f"{prefix}{key}: {score_bar} {value:.3f}") return "\n".join(lines) def classification( text: str, labels_input: str, threshold: float, multi_label: bool, prompt: str, examples_input: str, hierarchical_output: bool, output_format: str = "visual" ) -> Union[Dict[str, float], str]: """ Perform classification with all advanced features. """ try: # Parse labels (flat or hierarchical) labels = parse_labels_input(labels_input) # Parse few-shot examples examples = parse_examples_input(examples_input) if examples_input else None # Set classification type pipeline.pipe.classification_type = 'multi-label' if multi_label else 'single-label' # Prepare prompt task_prompt = prompt.strip() if prompt and prompt.strip() else None # Run classification results = pipeline( text, labels, threshold=threshold, examples=examples, prompt=task_prompt, return_hierarchical=hierarchical_output )[0] # Single text, get first result # Format output based on selected format if output_format == "json": return format_as_json(results, hierarchical_output) elif hierarchical_output: return format_hierarchical_dict(results) else: return {result['label']: float(result['score']) for result in results} except Exception as e: return f"Error: {str(e)}" # ============== Example Configurations ============== EXAMPLES = [ # Example 1: Basic flat labels with prompt [ TEXT_PRODUCT_REVIEW, "product review, electronics, positive feedback, negative feedback, customer service, shipping", 0.5, True, "Classify this customer review by topic and sentiment:", "", False, "visual" ], # Example 2: Hierarchical labels for restaurant review [ TEXT_RESTAURANT_REVIEW, '''{ "sentiment": ["positive", "negative", "mixed"], "aspects": ["food quality", "service", "ambiance", "price", "wait time"], "recommendation": ["would recommend", "would not recommend"] }''', 0.4, True, "Analyze this restaurant review:", "", True, "visual" ], # Example 3: News article with few-shot examples [ TEXT_NEWS_POLITICS, "politics, business, technology, sports, entertainment, science, health", 0.5, True, "Classify this news article by category:", '''[ {"text": "The Federal Reserve raised interest rates by 0.25% today, citing persistent inflation concerns.", "labels": ["politics", "business"]}, {"text": "Scientists discover high new high-temperature superconductor material that works at room temperature.", "labels": ["science", "technology"]} ]''', False, "visual" ], # Example 4: Scientific classification with hierarchical output [ TEXT_SCIENTIFIC, '''{ "domain": ["biology", "chemistry", "medicine", "physics"], "research_type": ["experimental", "theoretical", "review"], "application": ["therapeutic", "diagnostic", "basic research"] }''', 0.3, True, "Classify this scientific abstract:", "", True, "visual" ], # Example 5: Sports article - single label [ TEXT_SPORTS, "basketball, football, soccer, tennis, baseball, hockey, golf", 0.5, False, "What sport is this article about?", "", False, "visual" ], # Example 6: Movie review with detailed sentiment (JSON output) [ TEXT_MOVIE_REVIEW, '''{ "overall_sentiment": ["positive", "negative", "mixed"], "aspects_praised": ["acting", "direction", "cinematography", "music", "story", "pacing"], "aspects_criticized": ["acting", "direction", "cinematography", "music", "story", "pacing"], "recommendation": ["must watch", "worth watching", "skip it"] }''', 0.35, True, "Analyze this movie review in detail:", "", True, "json" ], # Example 7: Tech startup news [ TEXT_TECH_STARTUP, "funding announcement, product launch, acquisition, IPO, partnership, hiring, layoffs, legal", 0.4, True, "What type of tech news is this?", "", False, "visual" ], # Example 8: Health article with hierarchical categories [ TEXT_HEALTH_WELLNESS, '''{ "topic": ["nutrition", "exercise", "mental health", "sleep", "medical research"], "content_type": ["research findings", "practical advice", "expert opinion", "warning"], "audience": ["general public", "healthcare professionals", "patients"] }''', 0.4, True, "Categorize this health article:", "", True, "visual" ], # Example 9: Travel content (JSON output) [ TEXT_TRAVEL, "destination guide, hotel review, restaurant review, adventure travel, budget travel, luxury travel, travel tips", 0.4, True, "What type of travel content is this?", "", False, "json" ], # Example 10: Recipe classification [ TEXT_COOKING_RECIPE, '''{ "cuisine": ["Thai", "Italian", "Mexican", "Indian", "Chinese", "Japanese", "French", "American"], "difficulty": ["easy", "medium", "hard"], "meal_type": ["breakfast", "lunch", "dinner", "dessert", "snack"], "dietary": ["vegetarian friendly", "vegan friendly", "gluten free", "dairy free", "contains meat"] }''', 0.35, True, "Classify this recipe:", "", True, "visual" ], # Example 11: Financial content with examples [ TEXT_FINANCIAL_ADVICE, "investment advice, market analysis, personal finance, retirement planning, tax advice, economic news", 0.4, True, "Categorize this financial content:", '''[ {"text": "Here are 5 ways to maximize your 401k contributions before year end.", "labels": ["personal finance", "retirement planning", "tax advice"]}, {"text": "The S&P 500 rose 2% today following strong jobs report.", "labels": ["market analysis", "economic news"]} ]''', False, "visual" ], # Example 12: Environmental news (JSON output) [ TEXT_ENVIRONMENTAL, '''{ "topic": ["climate change", "biodiversity", "pollution", "conservation", "renewable energy"], "tone": ["alarming", "hopeful", "neutral", "urgent"], "focus": ["problem description", "solutions", "policy", "research findings"] }''', 0.35, True, "Analyze this environmental article:", "", True, "json" ], # Example 13: Education debate [ TEXT_EDUCATION, "education policy, standardized testing, curriculum, teacher issues, student welfare, technology in education, higher education", 0.4, True, "What education topics does this article cover?", "", False, "visual" ], # Example 14: Fashion news with hierarchy [ TEXT_FASHION, '''{ "content_type": ["trend report", "designer profile", "collection review", "industry news", "sustainability"], "season": ["spring/summer", "fall/winter"], "market_segment": ["luxury", "fast fashion", "sustainable fashion", "streetwear"] }''', 0.4, True, "Classify this fashion article:", "", True, "visual" ], # Example 15: Legal case (JSON output) [ TEXT_LEGAL_CASE, "constitutional law, criminal law, civil rights, corporate law, intellectual property, free speech, privacy", 0.4, True, "What areas of law does this case involve?", "", False, "json" ], # Example 16: Gaming review with detailed analysis [ TEXT_GAMING, '''{ "genre": ["action", "RPG", "adventure", "puzzle", "strategy", "simulation", "sports"], "platform_feel": ["indie", "AAA", "mid-tier"], "strengths": ["gameplay", "story", "graphics", "music", "replayability"], "weaknesses": ["bugs", "difficulty", "length", "graphics", "story"], "recommendation": ["must play", "worth playing", "wait for sale", "skip"] }''', 0.35, True, "Analyze this game review:", "", True, "visual" ], # Example 17: Real estate market analysis [ TEXT_REAL_ESTATE, "market analysis, buying advice, selling advice, investment, rental market, mortgage rates, housing policy", 0.4, True, "What real estate topics are covered?", "", False, "visual" ], # Example 18: Mental health with few-shot (JSON output) [ TEXT_MENTAL_HEALTH, '''{ "topic": ["burnout", "anxiety", "depression", "stress management", "work-life balance"], "content_type": ["educational", "self-help advice", "research summary", "personal story"], "actionability": ["provides concrete steps", "general awareness", "seeks professional help"] }''', 0.35, True, "Categorize this mental health content:", '''[ {"text": "Feeling overwhelmed? Try the 5-4-3-2-1 grounding technique: notice 5 things you see, 4 you hear...", "labels": ["topic.anxiety", "topic.stress management", "content_type.self-help advice", "actionability.provides concrete steps"]}, {"text": "A new study links social media use exceeding 3 hours daily with increased rates of depression in teens.", "labels": ["topic.depression", "content_type.research summary", "actionability.general awareness"]} ]''', True, "json" ], # Example 19: Astronomy discovery [ TEXT_ASTRONOMY, "exoplanets, astrobiology, cosmology, solar system, space exploration, telescopes, astrophysics", 0.4, True, "What astronomy topics are discussed?", "", False, "visual" ], # Example 20: Tech companies - single label [ TEXT_TECH_COMPANIES, "company profile, product announcement, financial report, industry analysis, biography, opinion piece", 0.5, False, "What is the primary type of this article?", "", False, "visual" ], ] # ============== Gradio Interface ============== with gr.Blocks( title="GLiClass Advanced Demo", theme=gr.themes.Soft( primary_hue="blue", secondary_hue="slate", ) ) as demo: gr.Markdown(""" # 🏷️ GLiClass Advanced Zero-Shot Classification Enhanced demo featuring **prompts**, **hierarchical labels**, **few-shot examples**, and **structured outputs**. """) with gr.Accordion("📖 How to Use This Demo", open=False): gr.Markdown(""" ## Features Overview ### 1. Task Description Prompts Add a natural language description of the classification task to guide the model. **Example:** `"Classify this customer review by sentiment and topic:"` --- ### 2. Hierarchical Labels (JSON Format) Structure your labels in categories for organized classification: ```json { "sentiment": ["positive", "negative", "neutral"], "topic": ["product", "service", "shipping"], "urgency": ["high", "medium", "low"] } ``` Or use simple comma-separated labels: `positive, negative, neutral` --- ### 3. Few-Shot Examples Provide examples to guide the model's understanding: ```json [ {"text": "Great product, love it!", "labels": ["positive", "product"]}, {"text": "Shipping was delayed by 2 weeks", "labels": ["negative", "shipping"]} ] ``` --- ### 4. Hierarchical Output When enabled with hierarchical labels, returns structured scores matching your input format. """) with gr.Accordion("💻 Code Example", open=False): gr.Code( '''from gliclass import GLiClassModel, ZeroShotClassificationPipeline from transformers import AutoTokenizer model = GLiClassModel.from_pretrained("knowledgator/gliclass-small-v1") tokenizer = AutoTokenizer.from_pretrained("knowledgator/gliclass-small-v1") pipeline = ZeroShotClassificationPipeline(model, tokenizer, classification_type='multi-label', device='cuda:0') # Basic usage text = "The product quality is amazing but delivery was slow" labels = ["positive", "negative", "product", "shipping"] results = pipeline(text, labels, threshold=0.5)[0] # With hierarchical labels hierarchical_labels = { "sentiment": ["positive", "negative", "neutral"], "topic": ["product", "service", "shipping"] } results = pipeline( text, hierarchical_labels, prompt="Classify this review:", return_hierarchical=True )[0] # With few-shot examples examples = [ {"text": "Love this item!", "labels": ["sentiment.positive", "topic.product"]}, {"text": "Terrible customer support", "labels": ["sentiment.negative", "topic.service"]} ] results = pipeline( text, hierarchical_labels, examples=examples, prompt="Classify customer feedback:" )[0] ''', language="python", ) with gr.Row(): with gr.Column(scale=2): input_text = gr.Textbox( value=EXAMPLES[0][0], label="📝 Text Input", placeholder="Enter the text you want to classify...", lines=8 ) prompt_input = gr.Textbox( value=EXAMPLES[0][4], label="💡 Task Description Prompt (Optional)", placeholder="E.g., 'Classify this customer review by sentiment and topic:'", lines=1 ) with gr.Column(scale=1): labels_input = gr.Textbox( value=EXAMPLES[0][1], label="🏷️ Labels (comma-separated or JSON)", placeholder='positive, negative\n\nOR\n\n{"category": ["label1", "label2"]}', lines=6 ) with gr.Row(): threshold = gr.Slider( 0, 1, value=0.5, step=0.01, label="Threshold", info="Confidence threshold for predictions" ) with gr.Row(): multi_label = gr.Checkbox( value=True, label="Multi-label", info="Allow multiple labels per text" ) hierarchical_output = gr.Checkbox( value=False, label="Hierarchical Output", info="Return structured output matching label hierarchy" ) with gr.Row(): output_format = gr.Radio( choices=["visual", "json"], value="visual", label="Output Format", info="Visual: charts/bars | JSON: raw data" ) with gr.Accordion("🎯 Few-Shot Examples (Optional)", open=False): examples_input = gr.Textbox( value="", label="Examples (JSON format)", placeholder='''[ {"text": "Example text 1", "labels": ["label1", "label2"]}, {"text": "Example text 2", "labels": ["label3"]} ]''', lines=5 ) gr.Markdown(""" *Provide labeled examples to guide the model. Each example needs a `text` field and a `labels` array.* """) submit_btn = gr.Button("🚀 Classify", variant="primary", size="lg") output = gr.Label(label="📊 Classification Results") output_text = gr.Textbox( label="📊 Hierarchical Results", visible=False, lines=10 ) output_json = gr.Code( label="📊 JSON Output", language="json", visible=False, lines=15 ) # Dynamic output visibility based on format and hierarchical toggle def update_output_visibility(hierarchical: bool, fmt: str): if fmt == "json": return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True) elif hierarchical: return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False) else: return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False) hierarchical_output.change( fn=update_output_visibility, inputs=[hierarchical_output, output_format], outputs=[output, output_text, output_json] ) output_format.change( fn=update_output_visibility, inputs=[hierarchical_output, output_format], outputs=[output, output_text, output_json] ) # Classification function wrapper for different outputs def classify_wrapper(text, labels, threshold, multi_label, prompt, examples, hierarchical, fmt): result = classification(text, labels, threshold, multi_label, prompt, examples, hierarchical, fmt) if fmt == "json": return None, None, result elif hierarchical or isinstance(result, str): return None, result, None else: return result, None, None # Event handlers submit_btn.click( fn=classify_wrapper, inputs=[input_text, labels_input, threshold, multi_label, prompt_input, examples_input, hierarchical_output, output_format], outputs=[output, output_text, output_json] ) input_text.submit( fn=classify_wrapper, inputs=[input_text, labels_input, threshold, multi_label, prompt_input, examples_input, hierarchical_output, output_format], outputs=[output, output_text, output_json] ) gr.Markdown("### 📚 Example Configurations") gr.Examples( examples=EXAMPLES, inputs=[input_text, labels_input, threshold, multi_label, prompt_input, examples_input, hierarchical_output, output_format], outputs=[output, output_text, output_json], fn=classify_wrapper, cache_examples=False, examples_per_page=5 ) gr.Markdown(""" --- ### 🔧 Tips for Best Results | Feature | Best Practice | |---------|---------------| | **Prompts** | Be specific about the task, e.g., "Classify by sentiment:" vs "Analyze:" | | **Labels** | Use descriptive labels; "customer service issue" > "service" | | **Hierarchical** | Group related labels under categories for organized results | | **Examples** | 2-3 diverse examples often improve accuracy significantly | | **Threshold** | Start at 0.5, lower for more predictions, raise for higher precision | """) if __name__ == "__main__": demo.queue() demo.launch(debug=True, share=True) ================================================ FILE: gliclass/__init__.py ================================================ from .model import GLiClassModel, GLiClassBiEncoder, GLiClassUniEncoder, GLiClassEncoderDecoderCLS from .config import GLiClassModelConfig from .pipeline import ( ZeroShotClassificationPipeline, BiEncoderZeroShotClassificationPipeline, ZeroShotClassificationWithChunkingPipeline, ) __version__ = "0.1.19" # Serve module (optional import) try: from . import serve except ImportError: serve = None ================================================ FILE: gliclass/config.py ================================================ from transformers import AutoConfig from transformers.utils import logging from transformers.models.auto import CONFIG_MAPPING from transformers.configuration_utils import PretrainedConfig from .utils import is_module_available IS_TURBOT5 = is_module_available("turbot5") if IS_TURBOT5: from turbot5.model.config import T5Config else: from transformers import T5Config logger = logging.get_logger(__name__) class GLiClassModelConfig(PretrainedConfig): model_type = "GLiClass" is_composition = True def __init__( self, encoder_config=None, encoder_model=None, label_model_config=None, label_model_name=None, class_token_index=-1, text_token_index=-1, example_token_index=-1, ignore_index=-100, hidden_size=None, projector_hidden_act="gelu", vocab_size=None, problem_type="single_label_classification", max_num_classes=25, use_lstm=False, initializer_range=0.03, scorer_type="simple", scorer_num_heads=16, scorer_mlp_hidden_size=1024, scorer_attn_dropout=0.1, pooling_strategy="first", class_token_pooling="first", focal_loss_alpha=0.5, focal_loss_gamma=2, focal_loss_reduction=None, logit_scale_init_value=2.6592, normalize_features=False, extract_text_features=False, max_labels_alloc: str = "dynamic", contrastive_loss_coef=0, architecture_type="uni-encoder", prompt_first=False, squeeze_layers=False, layer_wise=False, encoder_layer_id=-1, embed_class_token=True, dropout=0.1, use_segment_embeddings=False, **kwargs, ): if isinstance(encoder_config, dict): encoder_config["model_type"] = encoder_config.get("model_type", "deberta-v2") if encoder_config["model_type"] == "t5": encoder_config = T5Config(**encoder_config) elif encoder_config["model_type"] in CONFIG_MAPPING: encoder_config = CONFIG_MAPPING[encoder_config["model_type"]](**encoder_config) else: _name = encoder_model or kwargs.get("encoder_model_name") if _name: encoder_config = AutoConfig.from_pretrained(_name, trust_remote_code=True) else: encoder_config = PretrainedConfig(**encoder_config) elif encoder_config is None: encoder_config = CONFIG_MAPPING["deberta-v2"]() self.encoder_config = encoder_config self.encoder_model_name = encoder_model if label_model_name is not None: if isinstance(label_model_config, dict): label_model_config["model_type"] = label_model_config.get("model_type", "deberta-v2") label_model_config = CONFIG_MAPPING[label_model_config["model_type"]](**label_model_config) elif label_model_config is None: label_model_config = CONFIG_MAPPING["deberta-v2"]() self.label_model_config = label_model_config else: self.label_model_config = None self.label_model_name = label_model_name if hidden_size is None: self.hidden_size = self.encoder_config.hidden_size else: self.hidden_size = hidden_size if vocab_size is None: self.vocab_size = self.encoder_config.vocab_size else: self.vocab_size = vocab_size if class_token_index == -1: self.class_token_index = self.vocab_size else: self.class_token_index = class_token_index if text_token_index == -1: self.text_token_index = self.vocab_size + 1 else: self.text_token_index = text_token_index if example_token_index == -1: self.example_token_index = self.vocab_size + 2 else: self.example_token_index = example_token_index self.ignore_index = ignore_index self.projector_hidden_act = projector_hidden_act self.problem_type = problem_type self.max_num_classes = max_num_classes self.initializer_range = initializer_range self.scorer_type = scorer_type self.scorer_num_heads = scorer_num_heads self.scorer_mlp_hidden_size = scorer_mlp_hidden_size self.scorer_attn_dropout = scorer_attn_dropout self.pooling_strategy = pooling_strategy self.class_token_pooling = class_token_pooling self.use_lstm = use_lstm self.focal_loss_alpha = focal_loss_alpha self.focal_loss_gamma = focal_loss_gamma self.focal_loss_reduction = focal_loss_reduction self.contrastive_loss_coef = contrastive_loss_coef self.logit_scale_init_value = logit_scale_init_value self.normalize_features = normalize_features self.extract_text_features = extract_text_features self.max_labels_alloc = max_labels_alloc self.architecture_type = architecture_type self.prompt_first = prompt_first self.squeeze_layers = squeeze_layers self.layer_wise = layer_wise self.encoder_layer_id = encoder_layer_id self.embed_class_token = embed_class_token self.pad_token_id = self.encoder_config.pad_token_id self.dropout = dropout self.use_segment_embeddings = use_segment_embeddings super().__init__(**kwargs) ================================================ FILE: gliclass/data_processing.py ================================================ import copy import random from dataclasses import dataclass import torch from torch.utils.data import Dataset from torch.nn.utils.rnn import pad_sequence @dataclass class AugmentationConfig: """Configuration for data augmentation.""" enabled: bool = True # Probability for each augmentation type random_label_removal_prob: float = 0.15 random_label_addition_prob: float = 0.10 random_text_addition_prob: float = 0.05 random_add_description_prob: float = 0.25 random_add_synonyms_prob: float = 0.1 random_add_examples_prob: float = 0.25 max_num_examples: int = 5 class DataAugmenter: def __init__(self, config, examples, labels, label2description=None): self.config = config self.examples = examples self.labels = sorted(labels) self.max_examples = self.config.max_num_examples self.label2description = label2description or {} def remove_labels(self, true_labels, all_labels): if len(all_labels) <= 1: return true_labels, all_labels k = random.randint(1, len(all_labels)) all_labels = random.sample(all_labels, k=k) true_labels = [lbl for lbl in true_labels if lbl in all_labels] return true_labels, all_labels def add_random_labels(self, all_labels): if not self.labels: return all_labels num_add = len(all_labels) + 1 k = random.randint(1, min(num_add, len(self.labels))) add_labels = random.sample(self.labels, k=k) all_labels.extend(add_labels) return all_labels def add_random_text(self, text, all_labels): if not self.examples: return text example = random.sample(self.examples, k=1)[0] curr_labels = example["all_labels"] joint_labels = set(all_labels) & set(curr_labels) if len(joint_labels): return text else: if random.randint(0, 1): text = example["text"] + " " + text else: text = text + " " + example["text"] return text def add_random_synonyms(self, all_labels): """Replace some labels with their synonyms if available.""" if not self.label2description: return all_labels augmented_labels = [] for label in all_labels: if label in self.label2description: label_info = self.label2description[label] synonyms = label_info.get("synonyms", []) if synonyms and random.random() < 0.5: augmented_labels.append(random.choice(synonyms)) else: augmented_labels.append(label) else: augmented_labels.append(label) return augmented_labels def add_random_descriptions(self, item): """Add descriptions to labels in the text or metadata.""" if not self.label2description or not item["all_labels"]: return item max_labels = min(3, len(item["all_labels"])) labels_to_describe = random.sample(item["all_labels"], k=random.randint(1, max_labels)) descriptions = [] for label in labels_to_describe: if label in self.label2description: label_info = self.label2description[label] desc_list = label_info.get("descriptions", []) if desc_list: descriptions.append(f"{label}: {random.choice(desc_list)}") if descriptions: desc_text = " ".join(descriptions) if random.random() < 0.5: item["text"] = desc_text + " " + item["text"] else: item["text"] = item["text"] + " " + desc_text return item def add_random_examples(self, item): """Add example texts with similar labels.""" if not item["all_labels"]: return item candidate_examples = item.get("examples", []) item_label_set = set(item["all_labels"]) if not candidate_examples: for example in self.examples: example_label_set = set(example["true_labels"]) example_text = example["text"] overlap = item_label_set & example_label_set # Only consider examples with at least one overlapping label if overlap: candidate_examples.append({"text": example_text, "labels": list(example_label_set)}) if not candidate_examples: return item # Sort by overlap and select top examples random.shuffle(candidate_examples) top_candidates = candidate_examples[: self.max_examples] num_examples = random.randint(1, min(2, len(top_candidates))) selected_examples = random.sample(top_candidates, k=num_examples) item["examples"] = selected_examples return item def augment(self, item): if not self.config.enabled: return item text = copy.deepcopy(item["text"]) true_labels = copy.deepcopy(item["true_labels"]) all_labels = copy.deepcopy(item["all_labels"]) # Create augmented item aug_item = {"text": text, "true_labels": true_labels, "all_labels": all_labels} # Copy any additional fields for key in item: if key not in aug_item: aug_item[key] = copy.deepcopy(item[key]) if random.random() < self.config.random_label_removal_prob: aug_item["true_labels"], aug_item["all_labels"] = self.remove_labels( aug_item["true_labels"], aug_item["all_labels"] ) if random.random() < self.config.random_label_addition_prob: aug_item["all_labels"] = self.add_random_labels(aug_item["all_labels"]) if random.random() < self.config.random_text_addition_prob: aug_item["text"] = self.add_random_text(aug_item["text"], aug_item["all_labels"]) if random.random() < self.config.random_add_synonyms_prob: aug_item["all_labels"] = self.add_random_synonyms(aug_item["all_labels"]) if random.random() < self.config.random_add_description_prob: aug_item = self.add_random_descriptions(aug_item) if random.random() < self.config.random_add_examples_prob: aug_item = self.add_random_examples(aug_item) return aug_item class GLiClassDataset(Dataset): def __init__( self, examples, tokenizer, augment_config, label2description={}, max_length=512, problem_type="multi_label_classification", architecture_type="uni-encoder", add_description=True, prompt_first=False, get_negatives=False, max_labels=50, labels_tokenizer=None, shuffle_labels=True, ): self.tokenizer = tokenizer self.labels_tokenizer = labels_tokenizer self.label2description = label2description self.augment_config = augment_config self.max_length = max_length self._data = examples self.add_description = add_description self.problem_type = problem_type self.architecture_type = architecture_type self.prompt_first = prompt_first self.dataset_labels = self.collect_dataset_labels() self.get_negatives = get_negatives self.max_labels = max_labels self.shuffle_labels = shuffle_labels self.sep_token = "<>" self.label_token = "<