A privacy-sovereign middleware for forensic emotional inference and affective computing.
Project description
๐ Affective-Bridge
A Privacy-Sovereign Adapter for Forensic Emotional Inference.
Affective-Bridge is a lightweight, high-performance middleware designed to translate unstructured human text into structured, high-dimensional psychological coordinates.
Built for Affective Computing, context-aware systems, and behavioral analytics, it acts as the analytical layer between raw LLM outputs and deterministic application logic.
Key Features
- Forensic Subtext Extraction: Identifies the overt "Alibi", linguistic "Glitches", and the suppressed "Silent Narrative" in user input.
- Dimensional Affect Mapping: Calculates Valence (-1.0 to 1.0), Arousal (0.0 to 1.0), and psychological Dissonance.
- Provider Agnostic: Strategy-based architecture supporting local inference via Ollama (Zero-Persistence) and easily extensible to cloud providers.
- Strict Schema Enforcement: Utilizes Pydantic V2 for guaranteed JSON validation.
- Async-First: Built on
asyncioandhttpxfor low-latency, concurrent processing.
Architecture
The bridge utilizes Schema-Driven Reasoning (SDR) to bypass the limitations of standard sentiment analysis. Unlike traditional black-box models, Affective-Bridge employs a single-pass, reasoning-first extraction pipeline:
- Internal Monologue: The engine performs a brief, binary psychological evaluation to determine the "Null Hypothesis" (congruence) before committing to a dissonance state.
- Dual-State Mapping: By explicitly parsing the Alibi (overt claim) and the Glitch (linguistic tell), the library maps latent tension into deterministic metrics.
- Few-Shot Calibration: Utilizing specialized emotional archetypes, the engine maintains a consistent mathematical scale for Valence and Arousal, preventing coordinate drift and ensuring stable, repeatable results.
This architecture eliminates the need for complex multi-agent overhead, providing high-fidelity emotional subtext detection with minimal latency.
๐ Project Structure
affective-bridge/
โโโ affective_bridge/
โ โโโ __init__.py
โ โโโ providers/
โ โ โโโ __init__.py
โ โ โโโ base.py # The Strategy Interface
โ โ โโโ ollama_provider.py # Local LLM integration
โ โโโ exceptions.py # Custom exceptions
โ โโโ prompts.py # The Forensic System Prompt
โ โโโ schemas.py # The Pydantic output models
โโโ evals/
โ โโโ baseline_evaluation_matrix.csv
โ โโโ example_eval_run.csv
โ โโโ prompt_calibration_matrix.ipynb
โโโ tests/
โ โโโ test_dissonance.py
โ โโโ test_providers.py
โ โโโ test_schemas.py
โโโ examples/
โ โโโ basic_usage.py
โโโ pyproject.toml # Project configuration
โโโ README.md # Project documentation
โโโ LICENSE # Apache License 2.0
โโโ requirements-dev.txt # Python dependencies
Installation
You can install affective-bridge directly from PyPI:
pip install affective-bridge
Quick Start
Prerequisites
- Python 3.10+
- Ollama installed locally.
- A local copy of a model, for example Llama 3:
ollama pull llama3
Basic Usage
import asyncio
from affective_bridge.providers.ollama_provider import OllamaProvider
from affective_bridge.prompts import SYSTEM_PROMPT
from affective_bridge.schemas import ForensicAnalysis
async def main():
# Initialize with local privacy-first provider
provider = OllamaProvider(model="llama3")
text = "I'm fine. Everything is going exactly according to plan."
# Get the structured analysis directly from the provider.
analysis: ForensicAnalysis = await provider.get_analysis(text, SYSTEM_PROMPT)
print(f"Alibi: {analysis.alibi}")
print(f"Silent Narrative: {analysis.silent_narrative}")
print(f"Dissonance Score: {analysis.dissonance}") # e.g., 0.82
if __name__ == "__main__":
asyncio.run(main())
Development Setup
For development, it's recommended to set up an editable install. This allows you to run examples and tests against your local source code.
First, clone the repository and navigate into the project directory:
git clone https://github.com/AetherMarina/affective-bridge.git
cd affective-bridge
Create and activate a virtual environment:
python -m venv venv
source venv/bin/activate
Install the project in editable mode + Install development dependencies:
pip install -r requirements-dev.txt
This command installs all dependencies from pyproject.toml and makes the affective_bridge package available in your environment.
Extending the Bridge: Custom Providers
Affective-Bridge is designed to be provider-agnostic. You can easily add support for any LLM backend (e.g., Anthropic, Gemini, Groq, or a custom internal API) by creating a new provider class that implements the LLMProvider interface.
The Contract
Your custom provider must inherit from LLMProvider and implement the get_completion async method. The base class automatically provides the get_analysis wrapper, which handles the JSON parsing and Pydantic validation for you.
The core interface is defined in affective_bridge/providers/base.py.
Example: Creating a Dummy Provider
Here is a minimal example of a provider that returns a hardcoded JSON response to demonstrate the required structure:
1. Create the file: affective_bridge/providers/dummy_provider.py
import json
from .base import LLMProvider
class DummyProvider(LLMProvider):
"""A simple provider for testing that returns a fixed JSON response."""
async def get_completion(self, prompt: str, system_prompt: str) -> str:
# In a real provider, you would make an HTTP/API call here.
# For this example, we return a valid, hardcoded JSON string.
dummy_response = {
"psychological_evaluation": "The user claims the project is on track, but the repeated use of passive voice indicates emotional distancing. This linguistic glitch reveals underlying frustration with team performance, creating measurable dissonance.",
"alibi": "User claims the project is on track.",
"glitch": "Repeatedly uses passive voice ('milestones were met').",
"silent_narrative": "Underlying frustration with team performance.",
"silent_valence": -0.3,
"silent_arousal": 0.5,
"alibi_valence": 0.2,
"alibi_arousal": 0.1
}
return json.dumps(dummy_response)
- Use the new provider: You can now import and use DummyProvider just like any other provider.
from affective_bridge.providers.dummy_provider import DummyProvider
provider = DummyProvider()
analysis = await provider.get_analysis("Any text here", "Any prompt here")
print(analysis.silent_narrative)
๐งช Evaluation & Calibration
Because affective extraction relies on probabilistic models, Affective-Bridge ships with a deterministic evaluation suite located in the evals/ directory.
This suite contains a Golden Dataset (baseline_evaluation_matrix.csv) consisting of 15 highly complex psychological edge cases (including toxic positivity, passive-aggression, and burden minimization) calibrated against Llama 3 8B.
If you modify the SYSTEM_PROMPT or swap the backend to a different provider (like Claude or GPT-4), you can use the included evaluation scripts to generate an example_eval_run.csv. The suite will output a color-coded Pandas heatmap comparing your new run against the baseline, instantly highlighting any regressions in the model's ability to detect psychological dissonance.
โ ๏ธ Limitations & Disclaimer
Affective-Bridge is an experimental utility that interfaces with probabilistic Large Language Models (LLMs). Users must be aware of the following inherent limitations:
- Non-Deterministic Outputs: LLMs are not deterministic. While this library enforces a strict output schema, the underlying qualitative analysis (like the "Silent Narrative") is subjective and can contain inaccuracies or hallucinations.
- Not a Clinical or Diagnostic Tool (No Profiling): The dimensional mapping is an abstraction based on the Circumplex Model of Affect, intended solely for research, creative, and experimental applications. It is not a valid psychological metric. This tool must never be used for mental health diagnostics, employee monitoring, or automated decision-making. Furthermore, using this library to profile individuals or infer real-world traits, intentions, or mental states is strictly discouraged and may violate applicable data protection and AI regulations.
- Use at Your Own Risk: This open-source library is provided "as is," without warranty of any kind. Developers are responsible for implementing their own safety fallbacks and ethical reviews when using this data to drive application logic.
โ๏ธ Authorship Disclaimer
Affective-Bridge is an independent, personal project developed by Marina Kaliฤanin. It is not an official product of, nor is it endorsed by, any past or current employers. The architecture, logic, and implementation were created outside of professional work hours using personal resources.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file affective_bridge-0.1.0.tar.gz.
File metadata
- Download URL: affective_bridge-0.1.0.tar.gz
- Upload date:
- Size: 19.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3fbfd36c18a0aeb5e0d700c706fab86d19103f55539253e10678049cecac2a4f
|
|
| MD5 |
9f077a80481e6c080cc729d4f5f3141e
|
|
| BLAKE2b-256 |
f57be39e11d9b09653682d2024d03bd416d7282a9a69c8ede17e4ed3a3837f92
|
Provenance
The following attestation bundles were made for affective_bridge-0.1.0.tar.gz:
Publisher:
release.yml on AetherMarina/affective-bridge
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
affective_bridge-0.1.0.tar.gz -
Subject digest:
3fbfd36c18a0aeb5e0d700c706fab86d19103f55539253e10678049cecac2a4f - Sigstore transparency entry: 1383755476
- Sigstore integration time:
-
Permalink:
AetherMarina/affective-bridge@4ed16e9829eba19cbb8c47b6590df9b73ad62885 -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/AetherMarina
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@4ed16e9829eba19cbb8c47b6590df9b73ad62885 -
Trigger Event:
release
-
Statement type:
File details
Details for the file affective_bridge-0.1.0-py3-none-any.whl.
File metadata
- Download URL: affective_bridge-0.1.0-py3-none-any.whl
- Upload date:
- Size: 16.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3b643f83f62a223084d2226e3f000d874604017acde4a5ec1272bee5e08885ef
|
|
| MD5 |
f32f4ffe932361e5f14ab504b09e0c4a
|
|
| BLAKE2b-256 |
89a5bb57647298a114bbcf2ba05d147ab47ea116515e0e0f652722fa13eed127
|
Provenance
The following attestation bundles were made for affective_bridge-0.1.0-py3-none-any.whl:
Publisher:
release.yml on AetherMarina/affective-bridge
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
affective_bridge-0.1.0-py3-none-any.whl -
Subject digest:
3b643f83f62a223084d2226e3f000d874604017acde4a5ec1272bee5e08885ef - Sigstore transparency entry: 1383755527
- Sigstore integration time:
-
Permalink:
AetherMarina/affective-bridge@4ed16e9829eba19cbb8c47b6590df9b73ad62885 -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/AetherMarina
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@4ed16e9829eba19cbb8c47b6590df9b73ad62885 -
Trigger Event:
release
-
Statement type: