HH/apps/ai_engine/models.py
2025-12-24 12:42:31 +03:00

115 lines
3.2 KiB
Python

"""
AI Engine models - AI sentiment analysis and NLP
This module implements AI capabilities:
- Sentiment analysis for text (complaints, comments, social posts)
- Generic sentiment result storage
- Stubbed AI service interface for future integration
"""
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from apps.core.models import TimeStampedModel, UUIDModel
class SentimentResult(UUIDModel, TimeStampedModel):
"""
AI Sentiment analysis result - linked to any text content.
Uses generic foreign key to link to:
- Complaints
- Survey responses (text answers)
- Social media mentions
- Call center notes
"""
# Related object (generic foreign key)
content_type = models.ForeignKey(
ContentType,
on_delete=models.CASCADE
)
object_id = models.UUIDField()
content_object = GenericForeignKey('content_type', 'object_id')
# Text analyzed
text = models.TextField(help_text="Text that was analyzed")
language = models.CharField(
max_length=5,
choices=[('en', 'English'), ('ar', 'Arabic')],
default='en'
)
# Sentiment result
sentiment = models.CharField(
max_length=20,
choices=[
('positive', 'Positive'),
('neutral', 'Neutral'),
('negative', 'Negative'),
],
db_index=True
)
# Sentiment score (-1 to 1, where -1 is very negative, 1 is very positive)
sentiment_score = models.DecimalField(
max_digits=5,
decimal_places=4,
help_text="Sentiment score from -1 (negative) to 1 (positive)"
)
# Confidence level (0 to 1)
confidence = models.DecimalField(
max_digits=5,
decimal_places=4,
help_text="Confidence level of the sentiment analysis"
)
# AI service information
ai_service = models.CharField(
max_length=100,
default='stub',
help_text="AI service used (e.g., 'openai', 'azure', 'aws', 'stub')"
)
ai_model = models.CharField(
max_length=100,
blank=True,
help_text="Specific AI model used"
)
# Processing metadata
processing_time_ms = models.IntegerField(
null=True,
blank=True,
help_text="Time taken to analyze (milliseconds)"
)
# Additional analysis (optional)
keywords = models.JSONField(
default=list,
blank=True,
help_text="Extracted keywords"
)
entities = models.JSONField(
default=list,
blank=True,
help_text="Extracted entities (people, places, etc.)"
)
emotions = models.JSONField(
default=dict,
blank=True,
help_text="Emotion scores (joy, anger, sadness, etc.)"
)
# Metadata
metadata = models.JSONField(default=dict, blank=True)
class Meta:
ordering = ['-created_at']
indexes = [
models.Index(fields=['sentiment', '-created_at']),
models.Index(fields=['content_type', 'object_id']),
]
def __str__(self):
return f"{self.sentiment} ({self.sentiment_score}) - {self.text[:50]}"