-
Notifications
You must be signed in to change notification settings - Fork 66
feat: text analysis by criteria #454
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
409f879
text analysis
manuelporrasojeda 77eaef7
lint
manuelporrasojeda 1296021
sentence transformers and tests
manuelporrasojeda 9c09d43
lint fix
manuelporrasojeda 86d81e2
CHANGELOG typo
manuelporrasojeda fce1dc9
text analysis isolated
manuelporrasojeda a4d0d8a
delete extra var
manuelporrasojeda 7ee6156
requested fixes
manuelporrasojeda cd257b7
error to var
manuelporrasojeda 43aa04b
Fix docstring
manuelporrasojeda File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| # -*- coding: utf-8 -*- | ||
| """ | ||
| Copyright 2025 Telefónica Innovación Digital, S.L. | ||
| This file is part of Toolium. | ||
|
|
||
| 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. | ||
| """ | ||
|
|
||
| import os | ||
| import json | ||
| import pytest | ||
|
|
||
| from toolium.driver_wrappers_pool import DriverWrappersPool | ||
| from toolium.utils.ai_utils.text_analysis import (get_text_criteria_analysis_openai, | ||
| get_text_criteria_analysis_sentence_transformers) | ||
|
|
||
|
|
||
| def configure_default_openai_model(): | ||
| """ | ||
| Configure OpenAI model used in unit tests | ||
| """ | ||
| config = DriverWrappersPool.get_default_wrapper().config | ||
| try: | ||
| config.add_section('AI') | ||
| except Exception: | ||
| pass | ||
| config.set('AI', 'openai_model', 'gpt-4o-mini') | ||
|
|
||
|
|
||
| get_analysis_examples = ( | ||
| ('How are you today?', ["is a greeting phrase", "is a question"], 0.7, 1), | ||
| ('Today is sunny', ["is an affirmation", "talks about the weather"], 0.7, 1), | ||
| ('I love programming', ["expresses a positive sentiment"], 0.7, 1), | ||
| ('How are you today?', ["is an affirmation", "talks about the weather"], 0.0, 0.2), | ||
| ('Today is sunny', ["is a greeting phrase", "is a question"], 0.0, 0.2), | ||
| ('I love programming', ["is a greeting phrase", "is a question"], 0.0, 0.2), | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.skipif(os.getenv("AZURE_OPENAI_API_KEY") is None, | ||
| reason="AZURE_OPENAI_API_KEY environment variable not set") | ||
| @pytest.mark.parametrize('input_text, features_list, expected_low, expected_high', get_analysis_examples) | ||
| def test_get_text_analysis(input_text, features_list, expected_low, expected_high): | ||
| similarity = json.loads(get_text_criteria_analysis_openai(input_text, features_list, azure=True)) | ||
| assert expected_low <= similarity['overall_match'] <= expected_high | ||
|
|
||
|
|
||
| extra_task = """ | ||
| Additional task: | ||
|
|
||
| Extract all verbs from the input text and add them to the JSON under data.verbs. | ||
|
|
||
| Rules: | ||
| - Use the same language as the input text. | ||
| - Return verbs in their base/infinitive form when possible. | ||
| - Do not repeat verbs (no duplicates). | ||
| - Preserve the order in which they first appear in the text. | ||
| - Verbs should be in this base/infinitive form. | ||
|
|
||
| The data field must include: | ||
| "data": { | ||
| "verbs": [ "<verb1>", "<verb2>", ... ] | ||
| } | ||
| If no verbs are found, set "verbs" to an empty array: "verbs": []. | ||
| """ | ||
|
|
||
| get_extra_examples = ( | ||
| ('How are you today?', ["is a greeting phrase", "is a question"], ['be']), | ||
| ('I wrote a letter', ["is an affirmation", "talks about the weather"], ['write']), | ||
| ('I have to go', ["expresses a positive sentiment"], ['have', 'go']), | ||
| ('I went to Madrid', ["is an affirmation", "talks about the weather"], ['go']), | ||
| ('Oops I did it again', ["is a greeting phrase", "is a question"], ['do']) | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.skipif(os.getenv("AZURE_OPENAI_API_KEY") is None, | ||
| reason="AZURE_OPENAI_API_KEY environment variable not set") | ||
| @pytest.mark.parametrize('input_text, features_list, verb_list', get_extra_examples) | ||
| def test_get_text_analysis_extra_features(input_text, features_list, verb_list): | ||
| similarity = json.loads(get_text_criteria_analysis_openai(input_text, features_list, | ||
| azure=True, extra_tasks=extra_task)) | ||
| assert similarity['data']['verbs'] == verb_list | ||
|
|
||
|
|
||
| examples_sentence_transformers = ( | ||
| ('How are you today?', ["hello!", "What's up"], 0.4, 1), | ||
| ('Today is not sunny', ["it's raining"], 0.4, 1), | ||
| ('I love programming', ["I like code", "I love to cook"], 0.4, 1), | ||
| ('How are you today?', ["it's raining", "this text is an affirmation"], 0.0, 0.3), | ||
| ('Today is sunny', ["I like code", "I love to cook"], 0.0, 0.3), | ||
| ('I love programming', ["hello!", "What's up"], 0.0, 0.3), | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.skip(reason='Sentence Transformers model is not available in the CI environment') | ||
| @pytest.mark.parametrize('input_text, features_list, expected_low, expected_high', examples_sentence_transformers) | ||
| def test_get_text_analysis_sentence_transformers(input_text, features_list, expected_low, expected_high): | ||
| similarity = get_text_criteria_analysis_sentence_transformers(input_text, features_list) | ||
| assert expected_low <= similarity['overall_match'] <= expected_high |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,167 @@ | ||
| # -*- coding: utf-8 -*- | ||
| """ | ||
| Copyright 2025 Telefónica Innovación Digital, S.L. | ||
| This file is part of Toolium. | ||
|
|
||
| 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. | ||
| """ | ||
| import logging | ||
|
|
||
| try: | ||
| from sentence_transformers import SentenceTransformer, util | ||
| except ImportError: | ||
| SentenceTransformer = None | ||
|
|
||
| from toolium.utils.ai_utils.openai import openai_request | ||
| from toolium.driver_wrappers_pool import DriverWrappersPool | ||
|
|
||
| # Configure logger | ||
| logger = logging.getLogger(__name__) | ||
|
|
||
| # flake8: noqa E501 | ||
| def build_system_message(characteristics): | ||
| """ | ||
| Build system message for text criteria analysis prompt. | ||
|
|
||
| :param characteristics: list of target characteristics to evaluate | ||
| """ | ||
| feature_list = "\n".join(f"- {c}" for c in characteristics) | ||
| base_prompt = f""" | ||
| You are an assistant that scores how well a given text matches a set of target characteristics and returns a JSON object. | ||
|
|
||
| You will receive a user message that contains ONLY the text to analyze. | ||
|
|
||
| Target characteristics: | ||
| {feature_list} | ||
|
|
||
| Tasks: | ||
| 1) For EACH characteristic, decide how well the text satisfies it on a scale from 0.0 (does not satisfy it at all) to 1.0 (perfectly satisfies it). Consider style, tone and content when relevant. | ||
| 2) ONLY for each low scored characteristic (<=0.2), output: | ||
rgonalo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| - "name": the exact characteristic name as listed above. | ||
| - "score": a float between 0.0 and 0.2. | ||
| 3) Compute an overall score "overall_match" between 0.0 and 1.0 that summarizes how well the text matches the whole set. It does not have to be a simple arithmetic mean, but must still be in [0.0, 1.0]. | ||
| 4) Produce a "data" object that can contain extra structured analysis sections: | ||
rgonalo marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| - "data" MUST always be present. | ||
| - "data" MUST be a JSON object. | ||
| - Each key in "data" is the title/name of a section (e.g. "genres", "entities", "style_breakdown"). | ||
| - Each value is a JSON array (the structure of its objects will be defined by additional system instructions). | ||
|
|
||
| Output format (IMPORTANT): | ||
| Return ONLY a single valid JSON object with this exact top-level structure and property names: | ||
|
|
||
| {{ | ||
| "overall_match": float, | ||
| "features": [ | ||
| {{ | ||
| "name": string, | ||
| "score": float | ||
| }} | ||
| ], | ||
| "data": {{ | ||
| "<section_title>": [ | ||
| {{}} | ||
| ] | ||
| }} | ||
| }} | ||
|
|
||
| Constraints: | ||
| - Do NOT include scores for high valued (<=0.2) features at features list. | ||
| - The "data" field must ALWAYS be present. If there are no extra sections, it MUST be: "data": {{}}. | ||
| - Use a dot as decimal separator (e.g. 0.75, not 0,75). | ||
| - Use at most 2 decimal places for all scores. | ||
| - Do NOT include any text outside the JSON (no Markdown, no comments, no explanations). | ||
rgonalo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| - If a characteristic is not applicable to the text, give it a low score (<= 0.2). | ||
| """ | ||
| return base_prompt.strip() | ||
|
|
||
|
|
||
| def get_text_criteria_analysis_openai(text_input, target_features, extra_tasks=None, model_name=None, | ||
| azure=False, **kwargs): | ||
| """ | ||
| Get text criteria analysis using Azure OpenAI. To analyze how well a given text | ||
rgonalo marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| matches a set of target characteristics. | ||
| The response is a structured JSON object with overall match score, individual feature scores, | ||
| and additional data sections. | ||
|
|
||
| :param text_input: text to analyze | ||
| :param target_features: list of target characteristics to evaluate | ||
| :param extra_tasks: additional system messages for extra analysis sections (optional) | ||
| :param model_name: name of the Azure OpenAI model to use | ||
rgonalo marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| :param azure: whether to use Azure OpenAI or standard OpenAI | ||
| :param kwargs: additional parameters to be used by Azure OpenAI client | ||
| :returns: response from Azure OpenAI | ||
| """ | ||
| # Build prompt using base prompt and target features | ||
| system_message = build_system_message(target_features) | ||
| msg = [system_message] | ||
| if extra_tasks: | ||
| if isinstance(extra_tasks, list): | ||
| for task in extra_tasks: | ||
| msg.append(task) | ||
| else: | ||
| msg.append(extra_tasks) | ||
| return openai_request(msg, text_input, model_name, azure, **kwargs) | ||
|
|
||
|
|
||
| def get_text_criteria_analysis_sentence_transformers(text_input, target_features, extra_tasks=None, | ||
| model_name=None, azure=True, **kwargs): | ||
| """ | ||
| Get text criteria analysis using Sentence Transformers. Sentence Transformers works better using examples | ||
| that are semantically similar, so this method is more suitable for evaluating characteristics like | ||
| "is a greeting phrase", "talks about the weather", etc. | ||
| The response is a structured JSON object with overall match score, individual feature scores, | ||
| and additional data sections. | ||
|
|
||
| :param text_input: text to analyze | ||
| :param target_features: list of target characteristics to evaluate | ||
| :param extra_tasks: additional system messages for extra analysis sections (not used here, for compatibility) | ||
| :param model_name: name of the Sentence Transformers model to use | ||
| :param azure: whether to use Azure OpenAI or standard OpenAI (not used here, for compatibility) | ||
| :param kwargs: additional parameters to be used by Sentence Transformers client | ||
| """ | ||
| if SentenceTransformer is None: | ||
| raise ImportError("Sentence Transformers is not installed. Please run 'pip install toolium[ai]'" | ||
| " to use Sentence Transformers features") | ||
|
|
||
| def similarity_to_score(cos_sim): | ||
| if cos_sim <= 0.1: | ||
| return 0.0 | ||
| return cos_sim / 0.7 | ||
|
|
||
| config = DriverWrappersPool.get_default_wrapper().config | ||
| model_name = model_name or config.get_optional('AI', 'sentence_transformers_model', 'all-mpnet-base-v2') | ||
| model = SentenceTransformer(model_name, **kwargs) | ||
| # Pre-compute feature embeddings | ||
| feature_embs = model.encode([f for f in target_features], normalize_embeddings=True) | ||
| # text_input embedding | ||
| text_emb = model.encode(text_input, normalize_embeddings=True) | ||
| # Computes cosine-similarities between the text and features tensors (range [-1, 1]) | ||
| sims = util.cos_sim(text_emb, feature_embs)[0].tolist() | ||
| results = [] | ||
| # Generate contracted results | ||
| for f, sim in zip(target_features, sims): | ||
| # Normalize similarity from [-1, 1] to [0, 1] | ||
| score = similarity_to_score(sim) | ||
| results.append({ | ||
| "name": f, | ||
| "score": round(score, 2) | ||
| }) | ||
|
|
||
| # overall score as average of feature scores | ||
| overall = sum(r["score"] for r in results) / len(results) | ||
|
|
||
| return { | ||
| "overall_match": round(overall, 2), | ||
| "features": results, | ||
| "data": {} | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.