""" NLP Processor Tools | AgenThink SME Credit Intelligence System Responsibility: Provides NLP capabilities to Data Swarm agents: - Sentiment analysis (Arabic + English) - Adverse media detection - Theme/topic extraction - Named entity recognition (company names, amounts) Uses OpenAI GPT-4.1-mini for LLM-powered analysis (configurable). """ import logging import os from typing import List logger = logging.getLogger(__name__) class NLPProcessor: """NLP utility for sentiment, adverse media, and theme extraction.""" ADVERSE_KEYWORDS = [ "fraud", "lawsuit", "bankruptcy", "insolvency", "default", "scandal", "investigation", "regulatory action", "fine", "penalty", "closure", "liquidation", "arrest", "corruption", "money laundering", "AML", "إفلاس", "احتيال", "تصفية", "غرامة", "تحقيق", # Arabic equivalents ] def __init__(self, model: str = "gpt-4.1-mini"): self.model = model self._client = self._init_openai() def sentiment(self, text: str) -> float: """ Returns sentiment score: 0.0 (very negative) to 1.0 (very positive). Uses LLM for Arabic/English bilingual analysis. """ if not text or not text.strip(): return 0.5 try: prompt = ( "Analyse the sentiment of the following text about a business. " "Return ONLY a single float between 0.0 (very negative) and 1.0 (very positive). " "No explanation.\n\nText:\n" + text[:1000] ) response = self._client.chat.completions.create( model=self.model, messages=[{"role": "user", "content": prompt}], max_tokens=10, temperature=0, ) score_str = response.choices[0].message.content.strip() return max(0.0, min(1.0, float(score_str))) except Exception as e: logger.debug(f"[NLP] Sentiment analysis failed: {e}. Returning neutral 0.5.") return 0.5 def detect_adverse_media(self, text: str) -> bool: """Returns True if adverse media keywords are detected.""" if not text: return False text_lower = text.lower() return any(kw.lower() in text_lower for kw in self.ADVERSE_KEYWORDS) def extract_themes(self, text: str) -> List[str]: """Extract top business themes from text using LLM.""" if not text or not text.strip(): return [] try: prompt = ( "Extract the top 5 business themes from the following text. " "Return as a JSON array of short strings (max 3 words each). " "No explanation.\n\nText:\n" + text[:1500] ) response = self._client.chat.completions.create( model=self.model, messages=[{"role": "user", "content": prompt}], max_tokens=100, temperature=0, ) import json raw = response.choices[0].message.content.strip() themes = json.loads(raw) return themes[:5] if isinstance(themes, list) else [] except Exception as e: logger.debug(f"[NLP] Theme extraction failed: {e}. Returning empty list.") return [] def _init_openai(self): try: import openai return openai.OpenAI() except ImportError: logger.warning("[NLP] openai library not installed. NLP features degraded.") return _MockOpenAIClient() class _MockOpenAIClient: """Mock OpenAI client for testing without API access.""" class chat: class completions: @staticmethod def create(**kwargs): class MockResponse: class choices: class message: content = "0.5" choices = [type("c", (), {"message": message})()] return MockResponse()