diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..6edb9c6 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +__pycache__ +*.pyc +.git +.env +*.egg-info +.venv +venv +benchmark_notebooks +docs +test_*.py +*.ipynb +*.json +!app/** +!inference/** +!data/** +!requirements.txt diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..47712dd --- /dev/null +++ b/.env.example @@ -0,0 +1,18 @@ +# --------------------------------------------------------------- +# Classifier Service — Environment Variables +# --------------------------------------------------------------- +# +# 1. Copy this file: cp .env.example .env +# 2. Fill in the values below. +# 3. NEVER commit the .env file — it contains secrets. +# --------------------------------------------------------------- + +# REQUIRED — HuggingFace access token for the NER model. +# Request access to tabiya/roberta-base-job-ner, then create a +# read token at https://huggingface.co/settings/tokens +HF_TOKEN= + +# OPTIONAL — MongoDB connection (only needed for the change-stream-worker). +# Leave blank if you only need the classify API. +# APPLICATION_MONGODB_URI=mongodb+srv://:@.mongodb.net/?retryWrites=true&w=majority +# APPLICATION_DATABASE_NAME=horizon-scraper-dev diff --git a/DATA_LICENSE b/DATA_LICENSE deleted file mode 100644 index 4ea99c2..0000000 --- a/DATA_LICENSE +++ /dev/null @@ -1,395 +0,0 @@ -Attribution 4.0 International - -======================================================================= - -Creative Commons Corporation ("Creative Commons") is not a law firm and -does not provide legal services or legal advice. Distribution of -Creative Commons public licenses does not create a lawyer-client or -other relationship. Creative Commons makes its licenses and related -information available on an "as-is" basis. Creative Commons gives no -warranties regarding its licenses, any material licensed under their -terms and conditions, or any related information. Creative Commons -disclaims all liability for damages resulting from their use to the -fullest extent possible. - -Using Creative Commons Public Licenses - -Creative Commons public licenses provide a standard set of terms and -conditions that creators and other rights holders may use to share -original works of authorship and other material subject to copyright -and certain other rights specified in the public license below. The -following considerations are for informational purposes only, are not -exhaustive, and do not form part of our licenses. - - Considerations for licensors: Our public licenses are - intended for use by those authorized to give the public - permission to use material in ways otherwise restricted by - copyright and certain other rights. Our licenses are - irrevocable. Licensors should read and understand the terms - and conditions of the license they choose before applying it. - Licensors should also secure all rights necessary before - applying our licenses so that the public can reuse the - material as expected. Licensors should clearly mark any - material not subject to the license. This includes other CC- - licensed material, or material used under an exception or - limitation to copyright. More considerations for licensors: - wiki.creativecommons.org/Considerations_for_licensors - - Considerations for the public: By using one of our public - licenses, a licensor grants the public permission to use the - licensed material under specified terms and conditions. If - the licensor's permission is not necessary for any reason--for - example, because of any applicable exception or limitation to - copyright--then that use is not regulated by the license. Our - licenses grant only permissions under copyright and certain - other rights that a licensor has authority to grant. Use of - the licensed material may still be restricted for other - reasons, including because others have copyright or other - rights in the material. A licensor may make special requests, - such as asking that all changes be marked or described. - Although not required by our licenses, you are encouraged to - respect those requests where reasonable. More considerations - for the public: - wiki.creativecommons.org/Considerations_for_licensees - -======================================================================= - -Creative Commons Attribution 4.0 International Public License - -By exercising the Licensed Rights (defined below), You accept and agree -to be bound by the terms and conditions of this Creative Commons -Attribution 4.0 International Public License ("Public License"). To the -extent this Public License may be interpreted as a contract, You are -granted the Licensed Rights in consideration of Your acceptance of -these terms and conditions, and the Licensor grants You such rights in -consideration of benefits the Licensor receives from making the -Licensed Material available under these terms and conditions. - - -Section 1 -- Definitions. - - a. Adapted Material means material subject to Copyright and Similar - Rights that is derived from or based upon the Licensed Material - and in which the Licensed Material is translated, altered, - arranged, transformed, or otherwise modified in a manner requiring - permission under the Copyright and Similar Rights held by the - Licensor. For purposes of this Public License, where the Licensed - Material is a musical work, performance, or sound recording, - Adapted Material is always produced where the Licensed Material is - synched in timed relation with a moving image. - - b. Adapter's License means the license You apply to Your Copyright - and Similar Rights in Your contributions to Adapted Material in - accordance with the terms and conditions of this Public License. - - c. Copyright and Similar Rights means copyright and/or similar rights - closely related to copyright including, without limitation, - performance, broadcast, sound recording, and Sui Generis Database - Rights, without regard to how the rights are labeled or - categorized. For purposes of this Public License, the rights - specified in Section 2(b)(1)-(2) are not Copyright and Similar - Rights. - - d. Effective Technological Measures means those measures that, in the - absence of proper authority, may not be circumvented under laws - fulfilling obligations under Article 11 of the WIPO Copyright - Treaty adopted on December 20, 1996, and/or similar international - agreements. - - e. Exceptions and Limitations means fair use, fair dealing, and/or - any other exception or limitation to Copyright and Similar Rights - that applies to Your use of the Licensed Material. - - f. Licensed Material means the artistic or literary work, database, - or other material to which the Licensor applied this Public - License. - - g. Licensed Rights means the rights granted to You subject to the - terms and conditions of this Public License, which are limited to - all Copyright and Similar Rights that apply to Your use of the - Licensed Material and that the Licensor has authority to license. - - h. Licensor means the individual(s) or entity(ies) granting rights - under this Public License. - - i. Share means to provide material to the public by any means or - process that requires permission under the Licensed Rights, such - as reproduction, public display, public performance, distribution, - dissemination, communication, or importation, and to make material - available to the public including in ways that members of the - public may access the material from a place and at a time - individually chosen by them. - - j. Sui Generis Database Rights means rights other than copyright - resulting from Directive 96/9/EC of the European Parliament and of - the Council of 11 March 1996 on the legal protection of databases, - as amended and/or succeeded, as well as other essentially - equivalent rights anywhere in the world. - - k. You means the individual or entity exercising the Licensed Rights - under this Public License. Your has a corresponding meaning. - - -Section 2 -- Scope. - - a. License grant. - - 1. Subject to the terms and conditions of this Public License, - the Licensor hereby grants You a worldwide, royalty-free, - non-sublicensable, non-exclusive, irrevocable license to - exercise the Licensed Rights in the Licensed Material to: - - a. reproduce and Share the Licensed Material, in whole or - in part; and - - b. produce, reproduce, and Share Adapted Material. - - 2. Exceptions and Limitations. For the avoidance of doubt, where - Exceptions and Limitations apply to Your use, this Public - License does not apply, and You do not need to comply with - its terms and conditions. - - 3. Term. The term of this Public License is specified in Section - 6(a). - - 4. Media and formats; technical modifications allowed. The - Licensor authorizes You to exercise the Licensed Rights in - all media and formats whether now known or hereafter created, - and to make technical modifications necessary to do so. The - Licensor waives and/or agrees not to assert any right or - authority to forbid You from making technical modifications - necessary to exercise the Licensed Rights, including - technical modifications necessary to circumvent Effective - Technological Measures. For purposes of this Public License, - simply making modifications authorized by this Section 2(a) - (4) never produces Adapted Material. - - 5. Downstream recipients. - - a. Offer from the Licensor -- Licensed Material. Every - recipient of the Licensed Material automatically - receives an offer from the Licensor to exercise the - Licensed Rights under the terms and conditions of this - Public License. - - b. No downstream restrictions. You may not offer or impose - any additional or different terms or conditions on, or - apply any Effective Technological Measures to, the - Licensed Material if doing so restricts exercise of the - Licensed Rights by any recipient of the Licensed - Material. - - 6. No endorsement. Nothing in this Public License constitutes or - may be construed as permission to assert or imply that You - are, or that Your use of the Licensed Material is, connected - with, or sponsored, endorsed, or granted official status by, - the Licensor or others designated to receive attribution as - provided in Section 3(a)(1)(A)(i). - - b. Other rights. - - 1. Moral rights, such as the right of integrity, are not - licensed under this Public License, nor are publicity, - privacy, and/or other similar personality rights; however, to - the extent possible, the Licensor waives and/or agrees not to - assert any such rights held by the Licensor to the limited - extent necessary to allow You to exercise the Licensed - Rights, but not otherwise. - - 2. Patent and trademark rights are not licensed under this - Public License. - - 3. To the extent possible, the Licensor waives any right to - collect royalties from You for the exercise of the Licensed - Rights, whether directly or through a collecting society - under any voluntary or waivable statutory or compulsory - licensing scheme. In all other cases the Licensor expressly - reserves any right to collect such royalties. - - -Section 3 -- License Conditions. - -Your exercise of the Licensed Rights is expressly made subject to the -following conditions. - - a. Attribution. - - 1. If You Share the Licensed Material (including in modified - form), You must: - - a. retain the following if it is supplied by the Licensor - with the Licensed Material: - - i. identification of the creator(s) of the Licensed - Material and any others designated to receive - attribution, in any reasonable manner requested by - the Licensor (including by pseudonym if - designated); - - ii. a copyright notice; - - iii. a notice that refers to this Public License; - - iv. a notice that refers to the disclaimer of - warranties; - - v. a URI or hyperlink to the Licensed Material to the - extent reasonably practicable; - - b. indicate if You modified the Licensed Material and - retain an indication of any previous modifications; and - - c. indicate the Licensed Material is licensed under this - Public License, and include the text of, or the URI or - hyperlink to, this Public License. - - 2. You may satisfy the conditions in Section 3(a)(1) in any - reasonable manner based on the medium, means, and context in - which You Share the Licensed Material. For example, it may be - reasonable to satisfy the conditions by providing a URI or - hyperlink to a resource that includes the required - information. - - 3. If requested by the Licensor, You must remove any of the - information required by Section 3(a)(1)(A) to the extent - reasonably practicable. - - 4. If You Share Adapted Material You produce, the Adapter's - License You apply must not prevent recipients of the Adapted - Material from complying with this Public License. - - -Section 4 -- Sui Generis Database Rights. - -Where the Licensed Rights include Sui Generis Database Rights that -apply to Your use of the Licensed Material: - - a. for the avoidance of doubt, Section 2(a)(1) grants You the right - to extract, reuse, reproduce, and Share all or a substantial - portion of the contents of the database; - - b. if You include all or a substantial portion of the database - contents in a database in which You have Sui Generis Database - Rights, then the database in which You have Sui Generis Database - Rights (but not its individual contents) is Adapted Material; and - - c. You must comply with the conditions in Section 3(a) if You Share - all or a substantial portion of the contents of the database. - -For the avoidance of doubt, this Section 4 supplements and does not -replace Your obligations under this Public License where the Licensed -Rights include other Copyright and Similar Rights. - - -Section 5 -- Disclaimer of Warranties and Limitation of Liability. - - a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE - EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS - AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF - ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, - IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, - WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR - PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, - ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT - KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT - ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. - - b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE - TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, - NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, - INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, - COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR - USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN - ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR - DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR - IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. - - c. The disclaimer of warranties and limitation of liability provided - above shall be interpreted in a manner that, to the extent - possible, most closely approximates an absolute disclaimer and - waiver of all liability. - - -Section 6 -- Term and Termination. - - a. This Public License applies for the term of the Copyright and - Similar Rights licensed here. However, if You fail to comply with - this Public License, then Your rights under this Public License - terminate automatically. - - b. Where Your right to use the Licensed Material has terminated under - Section 6(a), it reinstates: - - 1. automatically as of the date the violation is cured, provided - it is cured within 30 days of Your discovery of the - violation; or - - 2. upon express reinstatement by the Licensor. - - For the avoidance of doubt, this Section 6(b) does not affect any - right the Licensor may have to seek remedies for Your violations - of this Public License. - - c. For the avoidance of doubt, the Licensor may also offer the - Licensed Material under separate terms or conditions or stop - distributing the Licensed Material at any time; however, doing so - will not terminate this Public License. - - d. Sections 1, 5, 6, 7, and 8 survive termination of this Public - License. - - -Section 7 -- Other Terms and Conditions. - - a. The Licensor shall not be bound by any additional or different - terms or conditions communicated by You unless expressly agreed. - - b. Any arrangements, understandings, or agreements regarding the - Licensed Material not stated herein are separate from and - independent of the terms and conditions of this Public License. - - -Section 8 -- Interpretation. - - a. For the avoidance of doubt, this Public License does not, and - shall not be interpreted to, reduce, limit, restrict, or impose - conditions on any use of the Licensed Material that could lawfully - be made without permission under this Public License. - - b. To the extent possible, if any provision of this Public License is - deemed unenforceable, it shall be automatically reformed to the - minimum extent necessary to make it enforceable. If the provision - cannot be reformed, it shall be severed from this Public License - without affecting the enforceability of the remaining terms and - conditions. - - c. No term or condition of this Public License will be waived and no - failure to comply consented to unless expressly agreed to by the - Licensor. - - d. Nothing in this Public License constitutes or may be interpreted - as a limitation upon, or waiver of, any privileges and immunities - that apply to the Licensor or You, including from the legal - processes of any jurisdiction or authority. - - -======================================================================= - -Creative Commons is not a party to its public -licenses. Notwithstanding, Creative Commons may elect to apply one of -its public licenses to material it publishes and in those instances -will be considered the “Licensor.” The text of the Creative Commons -public licenses is dedicated to the public domain under the CC0 Public -Domain Dedication. Except for the limited purpose of indicating that -material is shared under a Creative Commons public license or as -otherwise permitted by the Creative Commons policies published at -creativecommons.org/policies, Creative Commons does not authorize the -use of the trademark "Creative Commons" or any other trademark or logo -of Creative Commons without its prior written consent including, -without limitation, in connection with any unauthorized modifications -to any of its public licenses or any other arrangements, -understandings, or agreements concerning use of licensed material. For -the avoidance of doubt, this paragraph does not form part of the -public licenses. - -Creative Commons may be contacted at creativecommons.org. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..b7a8892 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +FROM python:3.10-slim + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt && \ + python -c "import nltk; nltk.download('punkt', quiet=True); nltk.download('punkt_tab', quiet=True)" + +COPY . . + +EXPOSE 5001 5002 5003 + +CMD ["uvicorn", "app.server.classify_server:app", "--host", "0.0.0.0", "--port", "5001"] diff --git a/README.md b/README.md index 02f340e..d85ad77 100644 --- a/README.md +++ b/README.md @@ -1,196 +1,176 @@ # Tabiya Livelihoods Classifier -The Tabiya Livelihoods Classifier provides an easy-to-use implementation of the entity-linking paradigm to support job description heuristics. Using state-of-the-art transformer neural networks, this tool can extract five entity types: Occupation, Skill, Qualification, Experience, and Domain. For the Occupations and Skills, ESCO-related entries are retrieved. The procedure consists of two discrete steps: entity extraction and similarity vector search. +Extracts **occupations**, **skills**, **qualifications**, **experience**, and **domain** entities from job text and links them to the [ESCO taxonomy](https://esco.ec.europa.eu/). -## Table of Contents +--- -- **[Installation](#installation)** -- **[Use the model](inference/README.md)**: Instructions on how to use the inference pipeline. -- **[Job Analysis Application](app/README.md)**: A web application for analyzing job descriptions and extracting and linking relevant entities. -- **[Training](train/README.md)**: Details on how to train the model. -- **[Model's Architecture](#models-architecture)** -- **[Datasets](#datasets)** -- **[License](#license)** -- **[Bibliography](#bibliography)** +## Prerequisites -## Installation +- [Docker Desktop](https://www.docker.com/products/docker-desktop/) +- [Git](https://git-scm.com/) (v2.37+) with [Git LFS](https://git-lfs.com/) +- **HuggingFace Token** -### Prerequisites +--- -- A recent version of [git](https://git-scm.com/) (e.g. ^2.37 ) -- [Python 3.10 or higher](https://www.python.org/downloads/) -- [Poerty 1.8 or higher](https://python-poetry.org/) - > Note: to install Poetry consult the [Poetry documentation](https://python-poetry.org/docs/#installing-with-the-official-installer) - - > Note: Install poetry system-wide (not in a virtualenv). -- [Git LFS](https://git-lfs.github.com/) +## Setup -### Using Git LFS - -This repository uses Git LFS for handling large files. Before you can use this repository, you need to install and set up Git LFS on your local machine. -See https://git-lfs.com/ for installation instructions. +```bash +git lfs install +git clone https://github.com/tabiya-tech/tabiya-livelihoods-classifier.git +cd tabiya-livelihoods-classifier -After Git LFS is set up, follow these steps to clone the repository: +cp .env.example .env +# Edit .env and set: HF_TOKEN=hf_your_token_here -```shell -git clone https://github.com/tabiya-tech/tabiya-livelihoods-classifier.git +docker compose up -d ``` -If you already cloned the repository without Git LFS, run: +First startup takes several minutes (image build + ~500 MB model download). Monitor with `docker compose logs -f`. + +Once ready, verify: + +```bash +curl http://localhost:5001/v1/health +``` -```shell -git lfs pull +```json +{ + "status": "healthy", + "service": "classify-api", + "dependencies": { + "ner-api": "healthy", + "nel-api": "healthy" + } +} ``` -### Install the dependencies +--- -#### Set up virtualenv -In the **root directory** of the backend project (so, the same directory as this README file), run the following commands: +## Usage -```shell -# create a virtual environment -python3 -m venv venv +### Classify a job -# activate the virtual environment -source venv/bin/activate +```bash +curl -X POST http://localhost:5001/v1/classify \ + -H "Content-Type: application/json" \ + -d '{ + "title": "Head Chef", + "description": "We are looking for an experienced Head Chef to plan menus, manage kitchen staff, and ensure food quality." + }' ``` -```shell -# Use the version of the dependencies specified in the lock file -poetry lock --no-update -# Install missing and remove unreferenced packages -poetry install --sync +You can also pass a single `"text"` field instead of `title` + `description`. + +### Options + +| Option | Default | Description | +|--------|---------|-------------| +| `top_k` | 5 | ESCO matches per entity | +| `min_similarity` | 0.0 | Minimum cosine similarity (0.0–1.0) | +| `extract_entities` | all | Filter entity types, e.g. `["occupation", "skill"]` | + +### Batch + +```bash +curl -X POST http://localhost:5001/v1/classify/batch \ + -H "Content-Type: application/json" \ + -d '{ + "jobs": [ + {"job_id": "001", "title": "Nurse", "description": "Provide patient care."}, + {"job_id": "002", "text": "Electrician. Install and maintain electrical systems."} + ] + }' ``` -> Note: -> Install the dependencies for the training using: -> ```shell -> # Use the version of the dependencies specified in the lock file -> poetry lock --no-update -> # Install missing and remove unreferenced packages -> poetry install --sync --with train -> ``` - -> Note: -> Before running any tasks, activate the virtual -> environment so that the installed dependencies are available: -> ```shell -> # activate the virtual environment -> source venv/bin/activate -> ``` -> To deactivate the virtual environment, run: -> ```shell -> # deactivate the virtual environment -> deactivate -> ``` - -Activate Python and download the NLTK punctuation package to use the sentence tokenizer. You only need to download `punkt` once. - -```shell -python < +Interactive docs at `http://localhost:5001/docs`. + +--- + +## Manual setup (without Docker) + +Requires **Python 3.10+** and [Poetry](https://python-poetry.org/). + +```bash +python3 -m venv venv && source venv/bin/activate +poetry install --sync +python -c "import nltk; nltk.download('punkt'); nltk.download('punkt_tab')" +export HF_TOKEN=hf_your_token_here ``` -> ATTENTION: The .env file should be kept secure and not shared with others as it contains sensitive information. -> It should not be committed to the repository. - -- **[Use the model](inference/README.md)**: Instructions on how to use the inference tool. -- **[Use the API](app/README.md)**: Instructions on how to use the API. -- **[Training](train/README.md)**: Details on how to train the model. - -## Model's Architecture - -![Model Architecture](./pics/entity_linker.png) - -## License - -The code and model weights are licensed under the MIT License. See the [LICENSE](./LICENSE) file for details. - -The [datasets](#Datasets) are licensed under the Creative Commons Attribution 4.0 International (CC BY 4.0). See the [DATA_LICENSE](./DATA_LICENSE) file for details. - -## Datasets - -### Occupations -- **Location**: [inference/files/occupations_augmented.csv](inference/files/occupations_augmented.csv) -- **Source**: [ESCO dataset - v1.1.1](https://esco.ec.europa.eu/en/use-esco/download) -- **Description**: ESCO (European Skills, Competences, Qualifications and Occupations) is the European multilingual classification of Skills, Competences, and Occupations. This dataset includes information relevant to the occupations. -- **License**: Creative Commons Attribution 4.0 International see [DATA_LICENSE](./DATA_LICENSE) for details. -- **Modifications**: The columns retained are `alt_label`, `preferred_label`, `esco_code`, and `uuid`. Each alternative label has been separated into individual rows. - -### Skills -- **Location**: [inference/files/skills.csv](inference/files/skills.csv) -- **Source**: [ESCO dataset - v1.1.1](https://esco.ec.europa.eu/en/use-esco/download) -- **Description**: ESCO (European Skills, Competences, Qualifications and Occupations) is the European multilingual classification of Skills, Competences and Occupations. This dataset includes information relevant to the skills. -- **License**: Creative Commons Attribution 4.0 International see [Data License](./DATA_LICENSE) for details. -- **Modifications**: The columns retained are `preferred_label` and `uuid`. - -### Qualifications -- **Location**: [inference/files/qualifications.csv](inference/files/qualifications.csv) -- **Source**: [Official European Union EQF comparison website](https://europass.europa.eu/en/compare-qualifications) -- **Description**: This dataset contains EQF (European Qualifications Framework) relevant information extracted from the official EQF comparison website. It includes data strings, country information, and EQF levels. Non-English text was ignored. -- **License**: Please refer to the original source for [license information](https://europass.europa.eu/en/node/2161). -- **Modifications**: Non-English text was removed, and the remaining information was formatted into a structured database. - -### Hahu Test -- **Location**: [inference/files/eval/redacted_hahu_test_with_id.csv](inference/files/eval/redacted_hahu_test_with_id.csv) -- **Source**: [hahu_test](https://huggingface.co/datasets/tabiya/hahu_test) -- **Description**: This dataset consists of 542 entries chosen at random from the 11 general classification system of the Ethiopian hahu jobs platform. 50 entries were selected from each class to create the final dataset. -- **License**: Creative Commons Attribution 4.0 International see [Data License](./DATA_LICENSE) for details. -- **Modifications**: No modifications were made to the selected entries. - -### House and Tech -- **Location**: - - [inference/files/eval/house_test_annotations.csv](inference/files/eval/house_test_annotations.csv) - - [inference/files/eval/house_validation_annotations.csv](inference/files/eval/house_validation_annotations.csv) - - [inference/files/eval/tech_test_annotations.csv](inference/files/eval/tech_test_annotations.csv) - - [inference/files/eval/tech_validation_annotations.csv](inference/files/eval/tech_validation_annotations.csv) -- **Source**: Provided by [Decorte et al.](https://arxiv.org/abs/2209.05987) -- **Description**: The dataset includes the HOUSE and TECH extensions of the SkillSpan Dataset. In the original work by Decorte et al., the test and development entities of the SkillSpan Dataset were annotated into the ESCO model. -- **License**: MIT, Please refer to the original source. -- **Modifications**: The datasets were used as provided without further modifications. - -### Qualification Mapping -- **Location**: [inference/files/eval/qualification_mapping.csv](inference/files/eval/qualification_mapping.csv) -- **Source**: Extended from the [Green Benchmark](https://github.com/acp19tag/skill-extraction-dataset) Qualifications -- **Description**: This dataset maps the Green Benchmark Qualifications to the appropriate EQF levels. Two annotators tagged the qualifications, resulting in a Cohen's Kappa agreement of 0.45, indicating moderate agreement. -- **License**: Creative Commons Attribution 4.0 International see [Data License](./DATA_LICENSE) for details. -- **Modifications**: Extended the dataset to include EQF level mappings, and the annotations were verified by two annotators. - -### Access and Usage - -To use these datasets, ensure you comply with the original dataset's license and terms of use. Any modifications made should be documented and attributed appropriately in your project. - -For datasets requiring access tokens, such as those from HuggingFace 🤗, please contact the maintainers to obtain a read access token. - -## Bibliography - -A list on interesting and relevant material for reading: -* **GPT NER** [GPT-NER: Named Entity Recognition via Large Language Models](https://arxiv.org/pdf/2304.10428) (Shuhe Wang) -* **Skill Extraction with LLMs** [Rethinking Skill Extraction in the Job Market Domain using Large Language Models](https://arxiv.org/pdf/2402.03832) (Mike Zhang) -* **NER annotation with LLM** [LLMs Accelerate Annotation for Medical Information Extraction](https://proceedings.mlr.press/v225/goel23a) -* **Skills Entity Linking** Zhang, Mike, Rob van der Goot, and Barbara Plank. "Entity Linking in the Job Market Domain." arXiv preprint arXiv:2401.17979 (2024). -* **Skills-ML** is an open-source Python library for developing and analyzing skills and competencies from unstructured text. (link: http://dataatwork.org/skills-ml/) -* **SkillSpan**: Hard and Soft Skill Extraction from English Job Postings https://arxiv.org/abs/2204.12811 (Mike Zhang) -* **work2vec**: Using the full text of data from 200 million online job postings, we train and evaluate a natural language processing (NLP) model to learn the language of jobs. We analyze how jobs have changed in the past decade, and show how different words in the posting denote different occupations. We use this approach to create novel indexes of jobs, such as work-from-home ability. In ongoing work, we quantify the return to various skills. - - https://digitaleconomy.stanford.edu/research/job2vec/ - https://digitaleconomy.stanford.edu/people/sarah-h-bana/ -* **Data Science and ESCO** Insights into how ESCO is leveraging data-science techniques. https://esco.ec.europa.eu/en/about-esco/data-science-and-esco -* **Machine Learning Assisted Mapping of Multilingual Occupational Data to ESCO**: A report that discusses the multilingual mapping -approach that the ESCO team established to support the maintenance of ESCO. https://esco.ec.europa.eu/en/about-esco/publications/publication/machine-learning-assisted-mapping-multilingual-occupational -* **ESCO Publications**: Artificial intelligence & machine learning. https://esco.ec.europa.eu/en/about-esco/publications?f%5B0%5D=theme%3A109860&page=0 +Start each in a separate terminal: + +```bash +uvicorn app.server.ner_server:app --host 0.0.0.0 --port 5002 +uvicorn app.server.nel_server:app --host 0.0.0.0 --port 5003 +uvicorn app.server.classify_server:app --host 0.0.0.0 --port 5001 +``` + +--- + +## Stopping + +```bash +docker compose down +``` diff --git a/app/repository.py b/app/repository.py new file mode 100644 index 0000000..fc603b5 --- /dev/null +++ b/app/repository.py @@ -0,0 +1,224 @@ +""" +Repository layer — abstracts database access so the classifier +never imports MongoDB (or any other DB) directly. + +Usage: + repo = MongoJobRepository(mongo_uri, db_name) + job = await repo.get_job("abc123") + + # For testing without a database: + repo = InMemoryJobRepository() +""" + +from abc import ABC, abstractmethod +from typing import Dict, List, Optional +from datetime import datetime, timezone +import logging +import os + +from dotenv import load_dotenv + +from util.job_text import build_input_text, compute_hash + +load_dotenv() + +logger = logging.getLogger("repository") + + +# ─── Abstract Interface ─────────────────────────────────────────── + +class JobRepository(ABC): + """ + Interface that the classifier depends on. + Swap implementations to change databases without touching classifier code. + """ + + @abstractmethod + async def get_job(self, fingerprint: str) -> Optional[Dict]: + """Fetch a raw job by its fingerprint.""" + ... + + @abstractmethod + async def get_unclassified_jobs(self, limit: int = 100, platform: Optional[str] = None) -> List[Dict]: + """Fetch raw jobs that haven't been classified yet, optionally filtered by platform.""" + ... + + @abstractmethod + async def save_classification(self, result: Dict) -> None: + """Upsert a classified-jobs document.""" + ... + + @abstractmethod + async def get_classification(self, fingerprint: str) -> Optional[Dict]: + """Fetch a classification by job fingerprint.""" + ... + + @abstractmethod + async def is_already_classified(self, fingerprint: str, input_text_hash: str) -> bool: + """Check if a job has already been classified with the same text.""" + ... + + @abstractmethod + async def get_all_classified_jobs(self, limit: int = 500, platform: Optional[str] = None) -> List[Dict]: + """Fetch classified jobs, optionally filtered by source platform.""" + ... + + @abstractmethod + async def close(self) -> None: + """Clean up connections.""" + ... + + +# ─── MongoDB Implementation ─────────────────────────────────────── + +class MongoJobRepository(JobRepository): + """ + MongoDB-specific implementation. This is the only place that + imports motor/pymongo. Replace this class to swap databases. + """ + + def __init__(self, mongo_uri: Optional[str] = None, db_name: Optional[str] = None): + from motor.motor_asyncio import AsyncIOMotorClient + + # Also load .env from the scraper directory if classifier .env doesn't have MongoDB config + scraper_env = os.path.join(os.path.dirname(__file__), "..", "..", "job_scraper", ".env") + if os.path.exists(scraper_env): + load_dotenv(scraper_env, override=False) + + uri = mongo_uri or os.getenv("APPLICATION_MONGODB_URI") or os.getenv("MONGODB_URI", "mongodb://localhost:27017") + name = db_name or os.getenv("APPLICATION_DATABASE_NAME", "horizon-scraper-dev") + + self.client = AsyncIOMotorClient(uri) + self.db = self.client[name] + self.raw_jobs = self.db["raw-jobs"] + self.classified_jobs = self.db["classified-jobs"] + + async def get_job(self, fingerprint: str) -> Optional[Dict]: + return await self.raw_jobs.find_one({"job_fingerprint": fingerprint}) + + async def get_unclassified_jobs(self, limit: int = 100, platform: Optional[str] = None) -> List[Dict]: + match_stage: Dict = {"classification": {"$size": 0}} + if platform: + match_stage["sources.platform"] = platform + + pipeline = [ + { + "$lookup": { + "from": "classified-jobs", + "localField": "job_fingerprint", + "foreignField": "job_fingerprint", + "as": "classification", + } + }, + {"$match": match_stage}, + {"$project": {"classification": 0}}, + {"$sort": {"created_at": -1}}, + {"$limit": limit}, + ] + cursor = self.raw_jobs.aggregate(pipeline) + return await cursor.to_list(length=limit) + + async def save_classification(self, result: Dict) -> None: + now = datetime.now(timezone.utc) + result["updated_at"] = now + set_doc = {k: v for k, v in result.items() if k != "created_at"} + + await self.classified_jobs.update_one( + {"job_fingerprint": result["job_fingerprint"]}, + {"$set": set_doc, "$setOnInsert": {"created_at": now}}, + upsert=True, + ) + + async def get_classification(self, fingerprint: str) -> Optional[Dict]: + return await self.classified_jobs.find_one({"job_fingerprint": fingerprint}) + + async def is_already_classified(self, fingerprint: str, input_text_hash: str) -> bool: + doc = await self.classified_jobs.find_one({ + "job_fingerprint": fingerprint, + "$or": [ + {"input_text_hash": input_text_hash}, + {"metadata.input_text_hash": input_text_hash}, + ], + }) + return doc is not None + + async def get_all_classified_jobs(self, limit: int = 500, platform: Optional[str] = None) -> List[Dict]: + """Fetch classified jobs, optionally filtered by source platform.""" + query: Dict = {} + if platform: + query["source_fields.source_platform"] = platform + cursor = self.classified_jobs.find(query).sort("classified_at", -1).limit(limit) + return await cursor.to_list(length=limit) + + async def watch_raw_jobs(self): + """Yield full documents from the raw-jobs change stream (MongoDB-specific).""" + pipeline = [ + {"$match": {"operationType": {"$in": ["insert", "replace", "update"]}}} + ] + async with self.raw_jobs.watch(pipeline, full_document="updateLookup") as stream: + async for change in stream: + doc = change.get("fullDocument") + if doc: + yield doc + + async def close(self) -> None: + self.client.close() + + +# ─── In-Memory Implementation (for testing) ─────────────────────── + +class InMemoryJobRepository(JobRepository): + """ + Stores everything in Python dicts. No database needed. + Useful for unit tests and local development without credentials. + """ + + def __init__(self): + self.raw_jobs: Dict[str, Dict] = {} + self.classifications: Dict[str, Dict] = {} + + async def get_job(self, fingerprint: str) -> Optional[Dict]: + return self.raw_jobs.get(fingerprint) + + async def get_unclassified_jobs(self, limit: int = 100) -> List[Dict]: + unclassified = [ + job for fp, job in self.raw_jobs.items() + if fp not in self.classifications + ] + return unclassified[:limit] + + async def save_classification(self, result: Dict) -> None: + now = datetime.now(timezone.utc) + result.setdefault("created_at", now) + result["updated_at"] = now + self.classifications[result["job_fingerprint"]] = result + + async def get_classification(self, fingerprint: str) -> Optional[Dict]: + return self.classifications.get(fingerprint) + + async def is_already_classified(self, fingerprint: str, input_text_hash: str) -> bool: + doc = self.classifications.get(fingerprint) + if not doc: + return False + return doc.get("input_text_hash") == input_text_hash + + async def get_all_classified_jobs(self, limit: int = 500, platform: Optional[str] = None) -> List[Dict]: + results = list(self.classifications.values()) + if platform: + results = [r for r in results if r.get("source_fields", {}).get("source_platform") == platform] + return results[:limit] + + def add_raw_job(self, job: Dict) -> None: + """Helper to seed test data.""" + self.raw_jobs[job["job_fingerprint"]] = job + + async def close(self) -> None: + pass + + +# ─── Helper ─────────────────────────────────────────────────────── + +def compute_input_text_hash(title: str, description: str) -> str: + """Compute SHA256 of the classifier input text for deduplication.""" + text = build_input_text({"title": title, "description": description}) + return compute_hash(text or "") diff --git a/app/server/classify_server.py b/app/server/classify_server.py new file mode 100644 index 0000000..9431119 --- /dev/null +++ b/app/server/classify_server.py @@ -0,0 +1,389 @@ +""" +Classify API Server — POST /v1/classify + batch endpoints +Orchestrator that calls NER API then NEL API and merges the results. +This is the primary endpoint for the scraper pipeline. + +Endpoints: + POST /v1/classify — classify a single job + POST /v1/classify/batch — submit a batch of jobs + GET /v1/batch//status — poll batch progress + GET /v1/batch//results — retrieve batch results + +Requires ner_server.py (port 5002) and nel_server.py (port 5003) to be running. + +Run: uvicorn app.server.classify_server:app --host 0.0.0.0 --port 5001 +""" + +import sys +import os +import time +import uuid +import logging +from contextlib import asynccontextmanager +from typing import Optional, Any + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) + +from fastapi import FastAPI, Request, HTTPException, BackgroundTasks +from pydantic import BaseModel, Field +import httpx + +from app.server.common import setup_logging, add_common_middleware +from util.job_text import build_input_text, compute_hash + +setup_logging() +log = logging.getLogger("classify-api") + +NER_API_URL = os.getenv("NER_API_URL", "http://localhost:5002") +NEL_API_URL = os.getenv("NEL_API_URL", "http://localhost:5003") +CLASSIFIER_VERSION = "1.0.0" + +MAX_TEXT_LENGTH = int(os.getenv("MAX_TEXT_LENGTH", "50000")) +MAX_BATCH_SIZE = int(os.getenv("MAX_BATCH_SIZE", "500")) + +_batches: dict[str, dict] = {} +_http_client: Optional[httpx.AsyncClient] = None + + +@asynccontextmanager +async def lifespan(app: FastAPI): + global _http_client + _http_client = httpx.AsyncClient(timeout=30.0) + log.info(f"Classify API starting...") + log.info(f" NER API: {NER_API_URL}") + log.info(f" NEL API: {NEL_API_URL}") + log.info(f" Max text length: {MAX_TEXT_LENGTH}") + log.info(f" Max batch size: {MAX_BATCH_SIZE}") + yield + await _http_client.aclose() + + +app = FastAPI( + title="Classify API", + version=CLASSIFIER_VERSION, + lifespan=lifespan, +) + +add_common_middleware(app) + + +# --------------------------------------------------------------------------- +# Request / Response models +# --------------------------------------------------------------------------- + +class ClassifyOptions(BaseModel): + extract_entities: Optional[list[str]] = None + top_k: int = Field(default=5, ge=1) + min_similarity: float = Field(default=0.0, ge=0.0, le=1.0) + + +class ClassifyRequest(BaseModel): + text: Optional[str] = None + title: Optional[str] = None + description: Optional[str] = None + options: Optional[ClassifyOptions] = None + + +class BatchJob(BaseModel): + job_id: Optional[str] = None + text: Optional[str] = None + title: Optional[str] = None + description: Optional[str] = None + + +class BatchRequest(BaseModel): + jobs: list[BatchJob] = Field(..., min_length=1) + options: Optional[ClassifyOptions] = None + + +# --------------------------------------------------------------------------- +# Core classification logic +# --------------------------------------------------------------------------- + +async def _classify_text(input_text: str, options: Optional[ClassifyOptions] = None, request_id: str = "") -> dict: + """ + Core classification logic — calls NER then NEL and merges results. + Uses async httpx for non-blocking downstream calls. + """ + options = options or ClassifyOptions() + entity_types = options.extract_entities + top_k = options.top_k + min_similarity = options.min_similarity + + start = time.time() + headers = {"X-Request-ID": request_id} if request_id else {} + + ner_payload: dict[str, Any] = {"text": input_text} + if entity_types: + ner_payload["entity_types"] = entity_types + + ner_resp = await _http_client.post(f"{NER_API_URL}/v1/ner", json=ner_payload, headers=headers) + ner_resp.raise_for_status() + ner_data = ner_resp.json() + ner_entities = ner_data.get("entities", []) + + linkable_types = {"occupation", "skill", "qualification"} + nel_input = [ + {"text": e["surface_form"], "entity_type": e["entity_type"]} + for e in ner_entities + if e["entity_type"] in linkable_types + ] + + linked_map = {} + nel_metadata = {} + if nel_input: + nel_resp = await _http_client.post( + f"{NEL_API_URL}/v1/nel", + json={"entities": nel_input, "options": {"top_k": top_k, "min_similarity": min_similarity}}, + headers=headers, + ) + nel_resp.raise_for_status() + nel_data = nel_resp.json() + nel_metadata = nel_data.get("metadata", {}) + + for item in nel_data.get("linked_entities", []): + key = (item["input_text"], item["entity_type"]) + linked_map[key] = item["matches"] + + merged_entities = [] + entity_counts: dict[str, int] = {} + + for entity in ner_entities: + etype = entity["entity_type"] + entity_counts[etype] = entity_counts.get(etype, 0) + 1 + + merged: dict[str, Any] = { + "entity_type": etype, + "surface_form": entity["surface_form"], + "span": entity["span"], + } + + key = (entity["surface_form"], etype) + if key in linked_map: + merged["linked_entities"] = linked_map[key] + + merged_entities.append(merged) + + processing_time = round((time.time() - start) * 1000, 1) + input_text_hash = compute_hash(input_text) + + return { + "classification": { + "entities": merged_entities, + "entity_counts": entity_counts, + }, + "metadata": { + "classifier_version": CLASSIFIER_VERSION, + "model_name": ner_data.get("metadata", {}).get("model_name", "unknown"), + "linker_model": nel_metadata.get("linker_model", "unknown"), + "processing_time_ms": processing_time, + "input_text_hash": input_text_hash, + }, + } + + +# --------------------------------------------------------------------------- +# Single classify endpoint +# --------------------------------------------------------------------------- + +@app.post("/v1/classify") +async def classify(body: ClassifyRequest, request: Request): + rid = request.state.request_id + data = body.model_dump() + + input_text = build_input_text(data, allow_text_field=True) + if not input_text: + raise HTTPException(status_code=400, detail="Provide 'text' or 'title'+'description'") + + if len(input_text) > MAX_TEXT_LENGTH: + raise HTTPException( + status_code=413, + detail=f"Text exceeds maximum length ({MAX_TEXT_LENGTH} chars)", + ) + + log.info(f"[{rid}] Classify request: {len(input_text)} chars") + + try: + result = await _classify_text(input_text, body.options, request_id=rid) + except httpx.HTTPStatusError as e: + log.error(f"[{rid}] Downstream error: {e}") + raise HTTPException(status_code=502, detail=f"Downstream API error: {e}") + + entity_count = sum(result["classification"]["entity_counts"].values()) + log.info(f"[{rid}] Classify done: {entity_count} entities in {result['metadata']['processing_time_ms']}ms") + return result + + +# --------------------------------------------------------------------------- +# Batch endpoints +# --------------------------------------------------------------------------- + +async def _process_batch(batch_id: str, jobs: list[dict], options: Optional[ClassifyOptions]): + """Background task: classify each job and update batch state.""" + batch = _batches[batch_id] + + for i, job in enumerate(jobs): + input_text = build_input_text(job, allow_text_field=True) + job_id = job.get("job_id", f"job_{i}") + + if not input_text: + batch["results"].append({ + "job_id": job_id, + "status": "error", + "error": "No classifiable text found", + }) + elif len(input_text) > MAX_TEXT_LENGTH: + batch["results"].append({ + "job_id": job_id, + "status": "error", + "error": f"Text exceeds {MAX_TEXT_LENGTH} char limit", + }) + else: + try: + result = await _classify_text(input_text, options, request_id=f"batch-{batch_id}-{i}") + batch["results"].append({ + "job_id": job_id, + "status": "completed", + **result, + }) + except Exception as e: + log.error(f"[batch-{batch_id}] Job {job_id} failed: {e}") + batch["results"].append({ + "job_id": job_id, + "status": "error", + "error": str(e), + }) + + batch["completed"] = i + 1 + + batch["status"] = "completed" + batch["finished_at"] = time.time() + elapsed = round((batch["finished_at"] - batch["started_at"]) * 1000) + batch["total_processing_time_ms"] = elapsed + log.info(f"[batch-{batch_id}] Completed: {batch['total']} jobs in {elapsed}ms") + + +@app.post("/v1/classify/batch", status_code=202) +async def submit_batch(body: BatchRequest, request: Request, background_tasks: BackgroundTasks): + rid = request.state.request_id + + if len(body.jobs) > MAX_BATCH_SIZE: + raise HTTPException( + status_code=413, + detail=f"Batch too large ({len(body.jobs)} jobs). Maximum is {MAX_BATCH_SIZE}.", + ) + + batch_id = str(uuid.uuid4())[:12] + + _batches[batch_id] = { + "status": "processing", + "total": len(body.jobs), + "completed": 0, + "results": [], + "started_at": time.time(), + "finished_at": None, + "total_processing_time_ms": None, + } + + log.info(f"[{rid}] Batch {batch_id} submitted: {len(body.jobs)} jobs") + + jobs_as_dicts = [j.model_dump() for j in body.jobs] + background_tasks.add_task(_process_batch, batch_id, jobs_as_dicts, body.options) + + return { + "batch_id": batch_id, + "status": "processing", + "total_jobs": len(body.jobs), + "poll_url": f"/v1/batch/{batch_id}/status", + "results_url": f"/v1/batch/{batch_id}/results", + } + + +@app.get("/v1/batch/{batch_id}/status") +async def batch_status(batch_id: str): + batch = _batches.get(batch_id) + if not batch: + raise HTTPException(status_code=404, detail=f"Batch '{batch_id}' not found") + + resp = { + "batch_id": batch_id, + "status": batch["status"], + "total": batch["total"], + "completed": batch["completed"], + "progress_pct": round(batch["completed"] / batch["total"] * 100, 1), + } + if batch["total_processing_time_ms"] is not None: + resp["total_processing_time_ms"] = batch["total_processing_time_ms"] + + return resp + + +@app.get("/v1/batch/{batch_id}/results") +async def batch_results(batch_id: str): + batch = _batches.get(batch_id) + if not batch: + raise HTTPException(status_code=404, detail=f"Batch '{batch_id}' not found") + + if batch["status"] != "completed": + return JSONResponse( + status_code=202, + content={ + "error": "Batch still processing", + "status": batch["status"], + "completed": batch["completed"], + "total": batch["total"], + }, + ) + + return { + "batch_id": batch_id, + "status": "completed", + "total": batch["total"], + "total_processing_time_ms": batch["total_processing_time_ms"], + "results": batch["results"], + } + + +# --------------------------------------------------------------------------- +# Health & version +# --------------------------------------------------------------------------- + +@app.get("/v1/health") +async def health(): + ner_ok = False + nel_ok = False + + try: + r = await _http_client.get(f"{NER_API_URL}/v1/health", timeout=5.0) + ner_ok = r.status_code == 200 + except httpx.HTTPError: + pass + + try: + r = await _http_client.get(f"{NEL_API_URL}/v1/health", timeout=5.0) + nel_ok = r.status_code == 200 + except httpx.HTTPError: + pass + + status = "healthy" if (ner_ok and nel_ok) else "degraded" + return { + "status": status, + "service": "classify-api", + "dependencies": { + "ner-api": "healthy" if ner_ok else "unavailable", + "nel-api": "healthy" if nel_ok else "unavailable", + }, + } + + +@app.get("/v1/version") +async def version(): + return { + "service": "classify-api", + "version": CLASSIFIER_VERSION, + } + + +if __name__ == "__main__": + import uvicorn + uvicorn.run("app.server.classify_server:app", host="0.0.0.0", port=5001, log_level="info") diff --git a/app/server/common.py b/app/server/common.py new file mode 100644 index 0000000..1fd4c3d --- /dev/null +++ b/app/server/common.py @@ -0,0 +1,47 @@ +""" +Shared FastAPI boilerplate — CORS, request-ID middleware, exception +handler, and logging setup used by all API servers. +""" + +import uuid +import logging + +from fastapi import FastAPI, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware + +LOG_FORMAT = "%(asctime)s [%(levelname)s] [%(name)s] %(message)s" + + +def setup_logging() -> None: + logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) + + +def add_common_middleware(app: FastAPI) -> None: + """Attach CORS, request-ID tracking, and the global exception handler.""" + app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) + + @app.middleware("http") + async def request_id_middleware(request: Request, call_next): + request.state.request_id = request.headers.get( + "X-Request-ID", str(uuid.uuid4())[:8] + ) + response = await call_next(request) + response.headers["X-Request-ID"] = request.state.request_id + return response + + @app.exception_handler(Exception) + async def unhandled_exception_handler(request: Request, exc: Exception): + rid = getattr(request.state, "request_id", "?") + log = logging.getLogger(app.title) + log.exception("[%s] Unhandled error: %s", rid, exc) + return JSONResponse( + status_code=500, + content={"error": "Internal server error", "request_id": rid}, + ) diff --git a/app/server/matching.py b/app/server/matching.py index 185d047..0583ee2 100644 --- a/app/server/matching.py +++ b/app/server/matching.py @@ -1,23 +1,24 @@ -# %% -print() -# %% import sys import os + +PATH = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))) + import pandas as pd -from flask import Flask, request, jsonify, render_template -from flask_cors import CORS +from fastapi import FastAPI, Form, Request +from fastapi.responses import HTMLResponse, JSONResponse +from fastapi.staticfiles import StaticFiles +from fastapi.templating import Jinja2Templates from inference.linker import EntityLinker +from app.server.common import add_common_middleware -# Add the parent and the current directory to the path -PATH = os.path.dirname(os.path.abspath(__file__)) -sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))) -sys.path.append(os.path.abspath(os.path.dirname(__file__))) +app = FastAPI(title="Job Matching UI") + +add_common_middleware(app) -app = Flask(__name__) -CORS(app, resources={r"/*": {"origins": "*"}}) -cors = CORS(app, resources={r"/*": {"origins": "*"}}) +app.mount("/static", StaticFiles(directory=os.path.join(PATH, "static")), name="static") +templates = Jinja2Templates(directory=os.path.join(PATH, "templates")) -# Load occupations data try: dict_occupations = pd.read_csv(os.path.abspath(os.path.join(os.path.dirname(__file__), "occupations_en.csv")), sep=",", header=0) except FileNotFoundError: @@ -25,24 +26,20 @@ sys.exit(1) custom_pipeline = EntityLinker(entity_model='tabiya/bert-base-job-extract', similarity_model='all-MiniLM-L6-v2', output_format='all', k=10) -# preferredLabel -# code -# %% -@app.route('/', methods=['GET']) -def index(): - return render_template('client.html') +@app.get("/", response_class=HTMLResponse) +async def index(request: Request): + return templates.TemplateResponse("client.html", {"request": request}) -@app.route("/match", methods=["POST"]) -def match(): - job_descr = request.form.get("job_descr") +@app.post("/match") +async def match(job_descr: str = Form(...)): if not job_descr: - return jsonify({"error": "job_descr is required"}), 400 + return JSONResponse(content={"error": "job_descr is required"}, status_code=400) extracted = custom_pipeline(job_descr) if not extracted: - return jsonify({"error": "No entities extracted"}), 400 + return JSONResponse(content={"error": "No entities extracted"}, status_code=400) for elem in extracted: if elem['type'] == "Occupation": @@ -55,19 +52,17 @@ def match(): new_list.append({'code': occupation.esco_code, 'uri': conceptUri, 'label': preferredLabel}) elem['retrieved'] = new_list elif elem['type'] == "Skill": - # get the list of skills from the list of retrieved objects new_list = [retrieved.skills for retrieved in elem['retrieved']] elem['retrieved'] = new_list elif elem['type'] == "Qualification": - # get the list of qualifications from the list of retrieved objects new_list = [f"{retrieved.qualification}: EQF level {int(retrieved.eqf_level)}" for retrieved in elem['retrieved']] - # remove duplicates new_list = list(dict.fromkeys(new_list)) elem['retrieved'] = new_list else: elem['retrieved'] = ["Type not recognized"] - - return jsonify(extracted) + + return extracted if __name__ == "__main__": - app.run(host="0.0.0.0", port=5001, debug=True) \ No newline at end of file + import uvicorn + uvicorn.run("app.server.matching:app", host="0.0.0.0", port=5001, log_level="info") diff --git a/app/server/nel_server.py b/app/server/nel_server.py new file mode 100644 index 0000000..e6efd8f --- /dev/null +++ b/app/server/nel_server.py @@ -0,0 +1,168 @@ +""" +NEL API Server — POST /v1/nel +Links entity text to ESCO taxonomy entries using embedding similarity. +Does NOT require NER — accepts pre-extracted entities from any source. +This is the endpoint Compass would call directly for skill-to-ESCO linking. + +Run: uvicorn app.server.nel_server:app --host 0.0.0.0 --port 5003 +""" + +import sys +import os +import time +import logging +from contextlib import asynccontextmanager + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) + +from fastapi import FastAPI, Request, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, Field +from typing import Optional, Any + +from app.server.common import setup_logging, add_common_middleware + +setup_logging() +log = logging.getLogger("nel-api") + +MAX_ENTITIES_PER_REQUEST = int(os.getenv("MAX_ENTITIES_PER_REQUEST", "200")) +MAX_TOP_K = int(os.getenv("MAX_TOP_K", "50")) + +nel_linker = None +_linker_load_error: Optional[str] = None + + +def _load_linker(): + global nel_linker, _linker_load_error + if nel_linker is None and _linker_load_error is None: + try: + from inference.nel import NELLinker + model_name = os.getenv("LINKER_MODEL", "all-MiniLM-L6-v2") + nel_linker = NELLinker(similarity_model=model_name) + except Exception as e: + _linker_load_error = str(e) + log.error(f"Failed to load NEL linker: {e}") + + +@asynccontextmanager +async def lifespan(app: FastAPI): + log.info("Loading NEL linker on startup...") + _load_linker() + if nel_linker: + log.info("NEL linker loaded.") + else: + log.error(f"NEL linker failed to load: {_linker_load_error}") + log.info("Starting server anyway (will return 503 on requests)...") + yield + + +app = FastAPI( + title="NEL API", + version="1.0.0", + lifespan=lifespan, +) + +add_common_middleware(app) + + +# --------------------------------------------------------------------------- +# Request / Response models +# --------------------------------------------------------------------------- + +class EntityInput(BaseModel): + text: str = Field(..., min_length=1) + entity_type: str = Field(..., min_length=1) + + +class NELOptions(BaseModel): + top_k: int = Field(default=5, ge=1) + min_similarity: float = Field(default=0.0, ge=0.0, le=1.0) + + +class NELRequest(BaseModel): + entities: list[EntityInput] = Field(..., min_length=1) + options: Optional[NELOptions] = None + + +class NELResponse(BaseModel): + linked_entities: list[dict[str, Any]] + metadata: dict[str, Any] + + +# --------------------------------------------------------------------------- +# Endpoints +# --------------------------------------------------------------------------- + +@app.post("/v1/nel", response_model=NELResponse) +async def link_entities(body: NELRequest, request: Request): + rid = request.state.request_id + + if len(body.entities) > MAX_ENTITIES_PER_REQUEST: + raise HTTPException( + status_code=413, + detail=f"Too many entities ({len(body.entities)}). Maximum is {MAX_ENTITIES_PER_REQUEST}.", + ) + + options = body.options or NELOptions() + top_k = min(options.top_k, MAX_TOP_K) + min_similarity = options.min_similarity + + if nel_linker is None: + raise HTTPException(status_code=503, detail=_linker_load_error or "NEL linker not loaded") + + entity_dicts = [e.model_dump() for e in body.entities] + + log.info(f"[{rid}] NEL request: {len(entity_dicts)} entities, top_k={top_k}") + start = time.time() + + try: + results = nel_linker.link(entity_dicts, top_k=top_k, min_similarity=min_similarity) + except Exception as e: + log.error(f"[{rid}] NEL linking failed: {e}") + raise HTTPException(status_code=500, detail=f"Entity linking failed: {e}") + + processing_time = round((time.time() - start) * 1000, 1) + log.info(f"[{rid}] NEL done: {len(results)} linked in {processing_time}ms") + + return NELResponse( + linked_entities=results, + metadata={ + "linker_model": nel_linker.similarity_model_name, + "taxonomy": "esco", + "processing_time_ms": processing_time, + }, + ) + + +@app.get("/v1/health") +async def health(): + linker_ok = nel_linker is not None + status = "healthy" if linker_ok else "unavailable" + resp = { + "status": status, + "service": "nel-api", + "model_loaded": linker_ok, + } + if linker_ok: + resp["linker_model"] = nel_linker.similarity_model_name + if _linker_load_error: + resp["error"] = _linker_load_error + + if not linker_ok: + return JSONResponse(content=resp, status_code=503) + return resp + + +@app.get("/v1/version") +async def version(): + return { + "service": "nel-api", + "version": "1.0.0", + "linker_model": os.getenv("LINKER_MODEL", "all-MiniLM-L6-v2"), + "taxonomy": "esco", + } + + +if __name__ == "__main__": + import uvicorn + uvicorn.run("app.server.nel_server:app", host="0.0.0.0", port=5003, log_level="info") diff --git a/app/server/ner_server.py b/app/server/ner_server.py new file mode 100644 index 0000000..1cb8b3e --- /dev/null +++ b/app/server/ner_server.py @@ -0,0 +1,171 @@ +""" +NER API Server — POST /v1/ner +Extracts entity spans from job-related text. +Does NOT perform entity linking (that's the NEL API). + +Run: uvicorn app.server.ner_server:app --host 0.0.0.0 --port 5002 +""" + +import sys +import os +import time +import logging +from contextlib import asynccontextmanager + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) + +from fastapi import FastAPI, Request, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, Field +from typing import Optional + +from app.server.common import setup_logging, add_common_middleware + +setup_logging() +log = logging.getLogger("ner-api") + +MAX_TEXT_LENGTH = int(os.getenv("MAX_TEXT_LENGTH", "50000")) + +ner_model = None +_model_load_error: Optional[str] = None + + +def _load_model(): + global ner_model, _model_load_error + if ner_model is None and _model_load_error is None: + try: + from inference.ner import NERModel + model_name = os.getenv("NER_MODEL", "tabiya/roberta-base-job-ner") + ner_model = NERModel(model_name=model_name) + except Exception as e: + _model_load_error = str(e) + log.error(f"Failed to load NER model: {e}") + + +@asynccontextmanager +async def lifespan(app: FastAPI): + log.info("Loading NER model on startup...") + _load_model() + if ner_model: + log.info("NER model loaded.") + else: + log.error(f"NER model failed to load: {_model_load_error}") + log.info("Starting server anyway (will return 503 on requests)...") + yield + + +app = FastAPI( + title="NER API", + version="1.0.0", + lifespan=lifespan, +) + +add_common_middleware(app) + + +# --------------------------------------------------------------------------- +# Request / Response models +# --------------------------------------------------------------------------- + +class NERRequest(BaseModel): + text: str = Field(..., min_length=1) + entity_types: Optional[list[str]] = None + + +class SpanOut(BaseModel): + start: int + end: int + + +class EntityOut(BaseModel): + entity_type: str + surface_form: str + span: SpanOut + + +class NERMetadata(BaseModel): + model_name: str + entity_count: int + processing_time_ms: float + + +class NERResponse(BaseModel): + entities: list[EntityOut] + metadata: NERMetadata + + +# --------------------------------------------------------------------------- +# Endpoints +# --------------------------------------------------------------------------- + +@app.post("/v1/ner", response_model=NERResponse) +async def extract_entities(body: NERRequest, request: Request): + rid = request.state.request_id + + if len(body.text) > MAX_TEXT_LENGTH: + raise HTTPException( + status_code=413, + detail=f"Text exceeds maximum length ({MAX_TEXT_LENGTH} chars)", + ) + + if ner_model is None: + raise HTTPException(status_code=503, detail=_model_load_error or "NER model not loaded") + + log.info(f"[{rid}] NER request: {len(body.text)} chars") + start = time.time() + + try: + entities = ner_model.extract(body.text) + except Exception as e: + log.error(f"[{rid}] NER inference failed: {e}") + raise HTTPException(status_code=500, detail=f"Model inference failed: {e}") + + processing_time = round((time.time() - start) * 1000, 1) + + if body.entity_types: + allowed = {t.lower() for t in body.entity_types} + entities = [e for e in entities if e["entity_type"] in allowed] + + log.info(f"[{rid}] NER done: {len(entities)} entities in {processing_time}ms") + + return NERResponse( + entities=entities, + metadata=NERMetadata( + model_name=ner_model.model_name, + entity_count=len(entities), + processing_time_ms=processing_time, + ), + ) + + +@app.get("/v1/health") +async def health(): + model_ok = ner_model is not None + status = "healthy" if model_ok else "unavailable" + resp = { + "status": status, + "service": "ner-api", + "model_loaded": model_ok, + } + if model_ok: + resp["model_name"] = ner_model.model_name + if _model_load_error: + resp["error"] = _model_load_error + + if not model_ok: + return JSONResponse(content=resp, status_code=503) + return resp + + +@app.get("/v1/version") +async def version(): + return { + "service": "ner-api", + "version": "1.0.0", + "model": os.getenv("NER_MODEL", "tabiya/roberta-base-job-ner"), + } + + +if __name__ == "__main__": + import uvicorn + uvicorn.run("app.server.ner_server:app", host="0.0.0.0", port=5002, log_level="info") diff --git a/app/server/templates/client.html b/app/server/templates/client.html index f393eb9..faf2224 100644 --- a/app/server/templates/client.html +++ b/app/server/templates/client.html @@ -1,10 +1,10 @@ - + - - + +