Update app.py
Browse files
app.py
CHANGED
|
@@ -8,8 +8,9 @@ import numpy as np
|
|
| 8 |
import hashlib
|
| 9 |
from collections import defaultdict
|
| 10 |
import math
|
|
|
|
| 11 |
|
| 12 |
-
class
|
| 13 |
def __init__(self):
|
| 14 |
# Spazi vettoriali multidimensionali per analisi geopolitica
|
| 15 |
self.vector_dimensions = 512
|
|
@@ -37,11 +38,27 @@ class VectorizedGeopoliticalAI:
|
|
| 37 |
"un_news": "https://news.un.org/en/rss/rss.xml"
|
| 38 |
}
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
self.initialize_embeddings()
|
| 41 |
|
| 42 |
def initialize_semantic_space(self):
|
| 43 |
"""Inizializza spazio semantico multidimensionale"""
|
| 44 |
-
# Crea base ortonormale per lo spazio semantico geopolitico
|
| 45 |
semantic_basis = {}
|
| 46 |
|
| 47 |
# Dimensioni fondamentali della geopolitica
|
|
@@ -53,7 +70,6 @@ class VectorizedGeopoliticalAI:
|
|
| 53 |
|
| 54 |
for i, concept in enumerate(fundamental_concepts):
|
| 55 |
vector = np.zeros(self.vector_dimensions)
|
| 56 |
-
# Distribuzione gaussiana per embedding iniziale
|
| 57 |
vector[:len(fundamental_concepts)] = np.random.normal(0, 0.1, len(fundamental_concepts))
|
| 58 |
vector[i] = 1.0 # Componente principale
|
| 59 |
semantic_basis[concept] = vector / np.linalg.norm(vector)
|
|
@@ -63,7 +79,6 @@ class VectorizedGeopoliticalAI:
|
|
| 63 |
def initialize_embeddings(self):
|
| 64 |
"""Inizializza embeddings per entità geopolitiche"""
|
| 65 |
|
| 66 |
-
# Entità geopolitiche con caratteristiche vettoriali
|
| 67 |
entities = {
|
| 68 |
'USA': {'power': 0.95, 'economy': 0.92, 'military': 0.98, 'influence': 0.90},
|
| 69 |
'China': {'power': 0.88, 'economy': 0.89, 'military': 0.85, 'influence': 0.82},
|
|
@@ -79,24 +94,66 @@ class VectorizedGeopoliticalAI:
|
|
| 79 |
}
|
| 80 |
|
| 81 |
for entity, characteristics in entities.items():
|
| 82 |
-
# Crea vettore multidimensionale per l'entità
|
| 83 |
vector = np.zeros(self.vector_dimensions)
|
| 84 |
|
| 85 |
-
# Mappa caratteristiche su dimensioni vettoriali
|
| 86 |
for i, (char, value) in enumerate(characteristics.items()):
|
| 87 |
if char in self.semantic_space:
|
| 88 |
vector += value * self.semantic_space[char]
|
| 89 |
|
| 90 |
-
# Aggiungi rumore gaussiano per robustezza
|
| 91 |
vector += np.random.normal(0, 0.05, self.vector_dimensions)
|
| 92 |
-
|
| 93 |
-
# Normalizza
|
| 94 |
self.entity_embeddings[entity] = vector / (np.linalg.norm(vector) + 1e-8)
|
| 95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
def text_to_vector(self, text):
|
| 97 |
"""Converte testo in rappresentazione vettoriale robusta"""
|
| 98 |
if not text or not text.strip():
|
| 99 |
-
# Vettore casuale per input vuoti
|
| 100 |
return np.random.normal(0, 0.1, self.vector_dimensions)
|
| 101 |
|
| 102 |
words = re.findall(r'\b\w+\b', text.lower())
|
|
@@ -137,7 +194,7 @@ class VectorizedGeopoliticalAI:
|
|
| 137 |
'power': 'power', 'influence': 'influence', 'control': 'power',
|
| 138 |
'domination': 'power', 'hegemony': 'power', 'superpower': 'power',
|
| 139 |
|
| 140 |
-
# Paesi specifici
|
| 141 |
'ukraine': 'conflict', 'russia': 'power', 'china': 'power',
|
| 142 |
'usa': 'power', 'america': 'power', 'taiwan': 'conflict',
|
| 143 |
'iran': 'conflict', 'israel': 'conflict', 'gaza': 'conflict'
|
|
@@ -146,7 +203,6 @@ class VectorizedGeopoliticalAI:
|
|
| 146 |
matched_words = 0
|
| 147 |
semantic_weights = defaultdict(float)
|
| 148 |
|
| 149 |
-
# Prima passata: mapping diretto
|
| 150 |
for word in words:
|
| 151 |
if word in semantic_mapping:
|
| 152 |
concept = semantic_mapping[word]
|
|
@@ -157,7 +213,6 @@ class VectorizedGeopoliticalAI:
|
|
| 157 |
semantic_weights[word] += 1.0
|
| 158 |
matched_words += 1
|
| 159 |
|
| 160 |
-
# Seconda passata: pattern parziali
|
| 161 |
if matched_words == 0:
|
| 162 |
for word in words:
|
| 163 |
for pattern, concept in semantic_mapping.items():
|
|
@@ -166,24 +221,19 @@ class VectorizedGeopoliticalAI:
|
|
| 166 |
semantic_weights[concept] += 0.5
|
| 167 |
matched_words += 0.5
|
| 168 |
|
| 169 |
-
# Costruzione vettore con pesi
|
| 170 |
for concept, weight in semantic_weights.items():
|
| 171 |
if concept in self.semantic_space:
|
| 172 |
composite_vector += weight * self.semantic_space[concept]
|
| 173 |
|
| 174 |
-
# Aggiungi componente casuale se nessun match
|
| 175 |
if matched_words == 0:
|
| 176 |
-
# Crea vettore basato su hash del testo per consistenza
|
| 177 |
text_hash = int(hashlib.md5(text.encode()).hexdigest(), 16)
|
| 178 |
np.random.seed(text_hash % 2**31)
|
| 179 |
composite_vector = np.random.normal(0, 0.3, self.vector_dimensions)
|
| 180 |
matched_words = 1
|
| 181 |
|
| 182 |
-
# Normalizzazione adattiva
|
| 183 |
if matched_words > 0:
|
| 184 |
composite_vector *= math.log(matched_words + 1) / (matched_words + 0.1)
|
| 185 |
|
| 186 |
-
# Assicura che il vettore non sia zero
|
| 187 |
norm = np.linalg.norm(composite_vector)
|
| 188 |
if norm < 1e-6:
|
| 189 |
composite_vector = np.random.normal(0, 0.1, self.vector_dimensions)
|
|
@@ -191,537 +241,642 @@ class VectorizedGeopoliticalAI:
|
|
| 191 |
|
| 192 |
return composite_vector / norm
|
| 193 |
|
| 194 |
-
def
|
| 195 |
-
"""
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
dot_product = np.dot(vec1, vec2)
|
| 211 |
-
norm_product = np.linalg.norm(vec1) * np.linalg.norm(vec2)
|
| 212 |
-
cosine_sim = dot_product / (norm_product + 1e-8)
|
| 213 |
-
|
| 214 |
-
# Distanza euclidea normalizzata
|
| 215 |
-
euclidean_dist = np.linalg.norm(vec1 - vec2) / math.sqrt(self.vector_dimensions)
|
| 216 |
-
|
| 217 |
-
# Proiezioni su sottospazi semantici
|
| 218 |
-
alliance_vec = self.semantic_space['alliance']
|
| 219 |
-
conflict_vec = self.semantic_space['conflict']
|
| 220 |
-
|
| 221 |
-
# Proiezione alliance: (v1 + v2) · alliance_basis
|
| 222 |
-
alliance_sum = (vec1 + vec2) / 2
|
| 223 |
-
alliance_projection = np.dot(alliance_sum, alliance_vec)
|
| 224 |
-
|
| 225 |
-
# Proiezione conflict: |v1 - v2| · conflict_basis
|
| 226 |
-
conflict_diff = vec1 - vec2
|
| 227 |
-
conflict_projection = abs(np.dot(conflict_diff, conflict_vec))
|
| 228 |
-
|
| 229 |
-
# Power differential basato su norma dei vettori
|
| 230 |
-
power_diff = np.linalg.norm(vec1) - np.linalg.norm(vec2)
|
| 231 |
-
|
| 232 |
-
# Relazioni storiche note (override per realismo)
|
| 233 |
-
historical_adjustments = {
|
| 234 |
-
('Russia', 'Ukraine'): {'conflict_boost': 0.7, 'alliance_penalty': -0.8},
|
| 235 |
-
('USA', 'Russia'): {'conflict_boost': 0.4, 'alliance_penalty': -0.6},
|
| 236 |
-
('USA', 'China'): {'conflict_boost': 0.3, 'alliance_penalty': -0.5},
|
| 237 |
-
('Israel', 'Iran'): {'conflict_boost': 0.8, 'alliance_penalty': -0.9},
|
| 238 |
-
('China', 'Taiwan'): {'conflict_boost': 0.9, 'alliance_penalty': -0.9},
|
| 239 |
-
('NATO', 'Russia'): {'conflict_boost': 0.6, 'alliance_penalty': -0.7}
|
| 240 |
-
}
|
| 241 |
-
|
| 242 |
-
# Applica aggiustamenti storici
|
| 243 |
-
key = (entity1, entity2)
|
| 244 |
-
reverse_key = (entity2, entity1)
|
| 245 |
-
|
| 246 |
-
if key in historical_adjustments:
|
| 247 |
-
adj = historical_adjustments[key]
|
| 248 |
-
conflict_projection += adj['conflict_boost']
|
| 249 |
-
alliance_projection += adj['alliance_penalty']
|
| 250 |
-
elif reverse_key in historical_adjustments:
|
| 251 |
-
adj = historical_adjustments[reverse_key]
|
| 252 |
-
conflict_projection += adj['conflict_boost']
|
| 253 |
-
alliance_projection += adj['alliance_penalty']
|
| 254 |
-
|
| 255 |
-
# Clamp valori in range realistico
|
| 256 |
-
alliance_projection = max(-1.0, min(1.0, alliance_projection))
|
| 257 |
-
conflict_projection = max(0.0, min(1.0, conflict_projection))
|
| 258 |
-
|
| 259 |
-
relations[(entity1, entity2)] = {
|
| 260 |
-
'similarity': cosine_sim,
|
| 261 |
-
'distance': euclidean_dist,
|
| 262 |
-
'alliance_potential': alliance_projection,
|
| 263 |
-
'conflict_potential': conflict_projection,
|
| 264 |
-
'power_differential': power_diff
|
| 265 |
-
}
|
| 266 |
-
|
| 267 |
-
return relations
|
| 268 |
-
|
| 269 |
-
def apply_transformation_matrices(self, input_vector, context_type):
|
| 270 |
-
"""Applica matrici di trasformazione per analisi contestuale"""
|
| 271 |
-
if context_type not in self.transformation_matrices:
|
| 272 |
-
return input_vector
|
| 273 |
-
|
| 274 |
-
transformation_matrix = self.transformation_matrices[context_type]
|
| 275 |
-
transformed_vector = np.dot(transformation_matrix, input_vector)
|
| 276 |
-
|
| 277 |
-
# Applicazione funzione di attivazione (tanh per mantenere bounded)
|
| 278 |
-
activated_vector = np.tanh(transformed_vector)
|
| 279 |
-
|
| 280 |
-
return activated_vector
|
| 281 |
-
|
| 282 |
-
def vector_space_analysis(self, query_vector, entities, real_time_data):
|
| 283 |
-
"""Analisi nello spazio vettoriale multidimensionale"""
|
| 284 |
-
analysis = {}
|
| 285 |
-
|
| 286 |
-
# 1. Analisi di proiezione su sottospazi semantici
|
| 287 |
-
semantic_projections = {}
|
| 288 |
-
for concept, basis_vector in self.semantic_space.items():
|
| 289 |
-
projection = np.dot(query_vector, basis_vector)
|
| 290 |
-
semantic_projections[concept] = projection
|
| 291 |
-
|
| 292 |
-
# 2. Calcolo delle distanze nel manifold geopolitico
|
| 293 |
-
entity_distances = {}
|
| 294 |
-
for entity in entities:
|
| 295 |
-
if entity in self.entity_embeddings:
|
| 296 |
-
distance = np.linalg.norm(query_vector - self.entity_embeddings[entity])
|
| 297 |
-
entity_distances[entity] = distance
|
| 298 |
-
|
| 299 |
-
# 3. Analisi delle trasformazioni contestuali
|
| 300 |
-
contextual_transforms = {}
|
| 301 |
-
for context in self.transformation_matrices.keys():
|
| 302 |
-
transformed = self.apply_transformation_matrices(query_vector, context)
|
| 303 |
-
# Calcola l'entropia della trasformazione
|
| 304 |
-
entropy = -np.sum(transformed * np.log(np.abs(transformed) + 1e-8))
|
| 305 |
-
contextual_transforms[context] = {
|
| 306 |
-
'vector': transformed,
|
| 307 |
-
'entropy': entropy,
|
| 308 |
-
'norm': np.linalg.norm(transformed)
|
| 309 |
-
}
|
| 310 |
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
|
|
|
| 314 |
|
| 315 |
-
return
|
| 316 |
|
| 317 |
-
def
|
| 318 |
-
"""
|
| 319 |
-
news_data = []
|
| 320 |
-
|
| 321 |
-
try:
|
| 322 |
-
# Reuters RSS
|
| 323 |
-
response = requests.get(self.data_sources["reuters_rss"], timeout=10)
|
| 324 |
-
if response.status_code == 200:
|
| 325 |
-
root = ET.fromstring(response.content)
|
| 326 |
-
for item in root.findall(".//item")[:8]:
|
| 327 |
-
title = item.find("title")
|
| 328 |
-
description = item.find("description")
|
| 329 |
-
|
| 330 |
-
if title is not None:
|
| 331 |
-
news_data.append({
|
| 332 |
-
"source": "Reuters",
|
| 333 |
-
"title": title.text,
|
| 334 |
-
"description": description.text if description is not None else "",
|
| 335 |
-
"vector": self.text_to_vector(title.text + " " + (description.text or ""))
|
| 336 |
-
})
|
| 337 |
-
except:
|
| 338 |
-
pass
|
| 339 |
-
|
| 340 |
-
try:
|
| 341 |
-
# BBC RSS
|
| 342 |
-
response = requests.get(self.data_sources["bbc_rss"], timeout=10)
|
| 343 |
-
if response.status_code == 200:
|
| 344 |
-
root = ET.fromstring(response.content)
|
| 345 |
-
for item in root.findall(".//item")[:8]:
|
| 346 |
-
title = item.find("title")
|
| 347 |
-
description = item.find("description")
|
| 348 |
-
|
| 349 |
-
if title is not None:
|
| 350 |
-
news_data.append({
|
| 351 |
-
"source": "BBC",
|
| 352 |
-
"title": title.text,
|
| 353 |
-
"description": description.text if description is not None else "",
|
| 354 |
-
"vector": self.text_to_vector(title.text + " " + (description.text or ""))
|
| 355 |
-
})
|
| 356 |
-
except:
|
| 357 |
-
pass
|
| 358 |
-
|
| 359 |
-
return news_data
|
| 360 |
-
|
| 361 |
-
def extract_entities_advanced(self, text_data):
|
| 362 |
-
"""Estrazione avanzata di entità con confidence scores"""
|
| 363 |
entities = []
|
| 364 |
-
|
| 365 |
|
| 366 |
-
# Pattern più sofisticati per entità geopolitiche
|
| 367 |
entity_patterns = {
|
| 368 |
-
'USA|United States|America|Washington': 'USA',
|
| 369 |
-
'China|Chinese|Beijing|PRC': 'China',
|
| 370 |
-
'Russia|Russian|Moscow|Kremlin': 'Russia',
|
| 371 |
-
'Ukraine|Ukrainian|Kyiv|Kiev': 'Ukraine',
|
| 372 |
-
'Iran|Iranian|Tehran': 'Iran',
|
| 373 |
-
'Israel|Israeli|Jerusalem': 'Israel',
|
| 374 |
-
'Taiwan|Taipei': 'Taiwan',
|
| 375 |
-
'North Korea|DPRK|Pyongyang': 'North Korea',
|
| 376 |
-
'NATO|North Atlantic': 'NATO',
|
| 377 |
-
'European Union|EU': 'EU',
|
| 378 |
-
'Germany|German|Berlin': 'Germany'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
}
|
| 380 |
|
| 381 |
-
combined_text = ""
|
| 382 |
-
if isinstance(text_data, list):
|
| 383 |
-
for item in text_data:
|
| 384 |
-
if isinstance(item, dict):
|
| 385 |
-
combined_text += f" {item.get('title', '')} {item.get('description', '')}"
|
| 386 |
-
else:
|
| 387 |
-
combined_text += f" {str(item)}"
|
| 388 |
-
else:
|
| 389 |
-
combined_text = str(text_data)
|
| 390 |
-
|
| 391 |
-
# Estrai entità con confidence
|
| 392 |
for pattern, entity in entity_patterns.items():
|
| 393 |
-
matches = re.findall(pattern,
|
| 394 |
if matches:
|
| 395 |
-
confidence = len(matches)
|
| 396 |
-
entities.append(
|
| 397 |
-
|
| 398 |
-
'confidence': min(confidence, 1.0),
|
| 399 |
-
'mentions': len(matches)
|
| 400 |
-
})
|
| 401 |
|
| 402 |
-
|
| 403 |
-
|
| 404 |
|
| 405 |
-
return entities,
|
| 406 |
|
| 407 |
-
def
|
| 408 |
-
"""Genera
|
| 409 |
|
| 410 |
try:
|
| 411 |
-
# 1.
|
| 412 |
-
|
| 413 |
|
| 414 |
-
# 2. Estrai entità
|
| 415 |
-
entities,
|
| 416 |
-
entity_names = [e['name'] for e in entities]
|
| 417 |
|
| 418 |
-
# 3.
|
| 419 |
-
|
| 420 |
|
| 421 |
-
# 4. Analisi vettoriale
|
| 422 |
-
|
|
|
|
| 423 |
|
| 424 |
-
# 5. Genera
|
| 425 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 426 |
|
| 427 |
-
return
|
| 428 |
|
| 429 |
except Exception as e:
|
| 430 |
-
return f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 431 |
|
| 432 |
-
def
|
| 433 |
-
"""
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
# Header matematico
|
| 438 |
-
report_parts.append("🧮 VECTORIZED GEOPOLITICAL ANALYSIS")
|
| 439 |
-
report_parts.append("═" * 60)
|
| 440 |
-
report_parts.append(f"📐 Vector Space: R^{self.vector_dimensions} | Semantic Manifold Analysis")
|
| 441 |
-
report_parts.append(f"🕐 Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}")
|
| 442 |
-
report_parts.append("")
|
| 443 |
-
|
| 444 |
-
# Query Vector Analysis
|
| 445 |
-
query_norm = np.linalg.norm(query_vector)
|
| 446 |
-
query_entropy = -np.sum(query_vector * np.log(np.abs(query_vector) + 1e-8))
|
| 447 |
-
report_parts.append(f"🎯 QUERY VECTORIZATION:")
|
| 448 |
-
report_parts.append(f" ∥q∥₂ = {query_norm:.4f} | H(q) = {query_entropy:.4f}")
|
| 449 |
-
report_parts.append(f" Dimensional complexity: {np.count_nonzero(np.abs(query_vector) > 0.1)}/{self.vector_dimensions}")
|
| 450 |
-
report_parts.append("")
|
| 451 |
-
|
| 452 |
-
# Semantic Projections
|
| 453 |
-
top_projections = sorted(vector_analysis['semantic_projections'].items(),
|
| 454 |
-
key=lambda x: abs(x[1]), reverse=True)[:6]
|
| 455 |
-
|
| 456 |
-
report_parts.append("📊 SEMANTIC SPACE PROJECTIONS:")
|
| 457 |
-
for concept, projection in top_projections:
|
| 458 |
-
intensity = "█" * int(abs(projection) * 20 + 1)
|
| 459 |
-
sign = "+" if projection > 0 else "-"
|
| 460 |
-
report_parts.append(f" {concept:.<15} {sign}{abs(projection):.3f} {intensity}")
|
| 461 |
-
report_parts.append("")
|
| 462 |
-
|
| 463 |
-
# Entity Analysis with Confidence
|
| 464 |
if entities:
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
report_parts.append("🔄 CONTEXTUAL MANIFOLD TRANSFORMATIONS:")
|
| 497 |
-
for context, transform_data in vector_analysis['contextual_transforms'].items():
|
| 498 |
-
entropy = transform_data['entropy']
|
| 499 |
-
norm = transform_data['norm']
|
| 500 |
|
| 501 |
-
|
| 502 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 503 |
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 512 |
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 517 |
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
if abs(projection) > 0.2: # Soglia significatività
|
| 532 |
-
gradient_vector += projection * self.semantic_space[concept]
|
| 533 |
-
|
| 534 |
-
gradient_norm = np.linalg.norm(gradient_vector)
|
| 535 |
-
|
| 536 |
-
if gradient_norm > 0.5:
|
| 537 |
-
report_parts.append(" 📈 HIGH-GRADIENT TRAJECTORY: Sistema in evoluzione rapida")
|
| 538 |
-
report_parts.append(f" ∇f = {gradient_norm:.3f} | Instabilità prevista")
|
| 539 |
-
elif gradient_norm > 0.2:
|
| 540 |
-
report_parts.append(" 📊 MODERATE-GRADIENT: Evoluzione controllata")
|
| 541 |
-
report_parts.append(f" ∇f = {gradient_norm:.3f} | Stabilità relativa")
|
| 542 |
else:
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
# Risk Assessment basato su metriche vettoriali
|
| 547 |
-
risk_metrics = self.calculate_vector_risk_metrics(vector_analysis, relations)
|
| 548 |
-
report_parts.append("")
|
| 549 |
-
report_parts.append("⚠️ VECTOR-BASED RISK ASSESSMENT:")
|
| 550 |
-
report_parts.append(f" Risk Magnitude: ∥R∥ = {risk_metrics['magnitude']:.3f}")
|
| 551 |
-
report_parts.append(f" Entropy Level: H(R) = {risk_metrics['entropy']:.3f}")
|
| 552 |
-
report_parts.append(f" Stability Index: σ = {risk_metrics['stability']:.3f}")
|
| 553 |
-
|
| 554 |
-
# Footer metodologico
|
| 555 |
-
report_parts.append("")
|
| 556 |
-
report_parts.append("📚 MATHEMATICAL FRAMEWORK:")
|
| 557 |
-
report_parts.append(" • High-dimensional semantic embedding (512D)")
|
| 558 |
-
report_parts.append(" • Manifold learning on geopolitical concepts")
|
| 559 |
-
report_parts.append(" • Real-time vector correlation analysis")
|
| 560 |
-
report_parts.append(" • Multi-contextual transformation matrices")
|
| 561 |
-
report_parts.append(" • Information-theoretic risk quantification")
|
| 562 |
-
|
| 563 |
-
report_parts.append(f"")
|
| 564 |
-
report_parts.append(f"🔄 Next vector update: {(datetime.now() + timedelta(minutes=30)).strftime('%H:%M UTC')}")
|
| 565 |
-
|
| 566 |
-
return "\n".join(report_parts)
|
| 567 |
|
| 568 |
-
def
|
| 569 |
-
"""
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 577 |
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
|
| 583 |
-
|
| 584 |
-
risk_magnitude = min(risk_magnitude / 5.0, 1.0)
|
| 585 |
|
| 586 |
-
#
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
)
|
| 592 |
-
risk_magnitude = max(risk_magnitude, max_conflict_potential * 0.7)
|
| 593 |
-
|
| 594 |
-
# Entropy del sistema basata su trasformazioni contestuali
|
| 595 |
-
entropies = []
|
| 596 |
-
for context_name, transform in vector_analysis['contextual_transforms'].items():
|
| 597 |
-
# Calcola entropy dalla distribuzione del vettore trasformato
|
| 598 |
-
vector = transform['vector']
|
| 599 |
-
# Soft-max per creare distribuzione di probabilità
|
| 600 |
-
exp_vector = np.exp(vector - np.max(vector))
|
| 601 |
-
prob_dist = exp_vector / np.sum(exp_vector)
|
| 602 |
-
entropy = -np.sum(prob_dist * np.log(prob_dist + 1e-8))
|
| 603 |
-
entropies.append(entropy)
|
| 604 |
-
|
| 605 |
-
# Entropy media normalizzata
|
| 606 |
-
system_entropy = np.mean(entropies) / math.log(self.vector_dimensions) if entropies else 0.3
|
| 607 |
-
|
| 608 |
-
# Stability index basato su varianza delle relazioni + fattori aggiuntivi
|
| 609 |
-
stability_factors = []
|
| 610 |
-
|
| 611 |
-
if relations:
|
| 612 |
-
# Varianza delle similarità
|
| 613 |
-
similarities = [rel['similarity'] for rel in relations.values()]
|
| 614 |
-
if similarities:
|
| 615 |
-
similarity_variance = np.var(similarities)
|
| 616 |
-
stability_factors.append(1.0 - similarity_variance)
|
| 617 |
-
|
| 618 |
-
# Asimmetria di potere
|
| 619 |
-
power_diffs = [abs(rel['power_differential']) for rel in relations.values()]
|
| 620 |
-
if power_diffs:
|
| 621 |
-
power_asymmetry = np.mean(power_diffs)
|
| 622 |
-
stability_factors.append(1.0 - min(power_asymmetry, 1.0))
|
| 623 |
-
|
| 624 |
-
# Stability semantica basata su coherenza delle proiezioni
|
| 625 |
-
semantic_projections = list(vector_analysis['semantic_projections'].values())
|
| 626 |
-
if semantic_projections:
|
| 627 |
-
semantic_coherence = 1.0 - (np.var(semantic_projections) / (np.mean(np.abs(semantic_projections)) + 1e-8))
|
| 628 |
-
stability_factors.append(max(0.0, min(1.0, semantic_coherence)))
|
| 629 |
-
|
| 630 |
-
# Stability index finale
|
| 631 |
-
if stability_factors:
|
| 632 |
-
stability = np.mean(stability_factors)
|
| 633 |
else:
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
#
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
return
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 648 |
|
| 649 |
-
# Inizializza il sistema AI
|
| 650 |
-
|
| 651 |
|
| 652 |
-
def
|
| 653 |
-
"""Funzione principale
|
| 654 |
-
if not
|
| 655 |
-
return "
|
| 656 |
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 662 |
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 671 |
]
|
| 672 |
|
| 673 |
-
#
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
inputs=[
|
| 677 |
-
gr.Textbox(
|
| 678 |
-
label="Geopolitical Vector Query",
|
| 679 |
-
placeholder="Es: Analizza lo spazio vettoriale delle tensioni Taiwan-Cina nel manifold indo-pacifico...",
|
| 680 |
-
lines=3
|
| 681 |
-
)
|
| 682 |
-
],
|
| 683 |
-
outputs=[
|
| 684 |
-
gr.Textbox(
|
| 685 |
-
label="Mathematical Geopolitical Analysis",
|
| 686 |
-
lines=35,
|
| 687 |
-
max_lines=45
|
| 688 |
-
)
|
| 689 |
-
],
|
| 690 |
-
title="🧮 Vectorized Geopolitical Intelligence AI",
|
| 691 |
-
description="""
|
| 692 |
-
**🚀 Analisi Geopolitica tramite Spazi Vettoriali Multidimensionali**
|
| 693 |
-
|
| 694 |
-
🔬 **Framework Matematico:**
|
| 695 |
-
• 📐 **Embedding Semantico**: 512-dimensional vector space
|
| 696 |
-
• 🌐 **Manifold Learning**: Proiezioni su sottospazi geopolitici
|
| 697 |
-
• 🔄 **Matrici di Trasformazione**: Analisi contestuali multiple
|
| 698 |
-
• 📊 **Correlazione Vettoriale**: Input real-time transformati
|
| 699 |
-
• ⚡ **Information Theory**: Risk assessment entropico
|
| 700 |
-
|
| 701 |
-
💡 **Advanced Capabilities:**
|
| 702 |
-
• Conversione linguaggio naturale → vettori multidimensionali
|
| 703 |
-
• Relazioni inter-entità calcolate in spazio astratto
|
| 704 |
-
• Gradient analysis per previsioni di traiettoria
|
| 705 |
-
• Metriche quantitative per assessment geopolitico
|
| 706 |
-
|
| 707 |
-
🎯 **Output**: Analisi matematica rigorosa invece di template generici
|
| 708 |
-
""",
|
| 709 |
-
examples=examples,
|
| 710 |
-
theme=gr.themes.Monochrome(),
|
| 711 |
css="""
|
| 712 |
.gradio-container {
|
| 713 |
-
max-width:
|
| 714 |
margin: auto;
|
| 715 |
-
font-family: 'Courier New', monospace;
|
| 716 |
}
|
| 717 |
-
.
|
|
|
|
|
|
|
|
|
|
| 718 |
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 719 |
color: white;
|
| 720 |
-
padding:
|
| 721 |
-
border-radius:
|
|
|
|
|
|
|
| 722 |
}
|
| 723 |
"""
|
| 724 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 725 |
|
| 726 |
if __name__ == "__main__":
|
| 727 |
demo.launch()
|
|
|
|
| 8 |
import hashlib
|
| 9 |
from collections import defaultdict
|
| 10 |
import math
|
| 11 |
+
import random
|
| 12 |
|
| 13 |
+
class ConversationalGeopoliticalAI:
|
| 14 |
def __init__(self):
|
| 15 |
# Spazi vettoriali multidimensionali per analisi geopolitica
|
| 16 |
self.vector_dimensions = 512
|
|
|
|
| 38 |
"un_news": "https://news.un.org/en/rss/rss.xml"
|
| 39 |
}
|
| 40 |
|
| 41 |
+
# Context memory per conversazioni
|
| 42 |
+
self.conversation_context = {
|
| 43 |
+
"recent_topics": [],
|
| 44 |
+
"mentioned_entities": set(),
|
| 45 |
+
"analysis_history": [],
|
| 46 |
+
"user_interests": set()
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
# Personalità conversazionale
|
| 50 |
+
self.personality_traits = {
|
| 51 |
+
"analytical": 0.8,
|
| 52 |
+
"authoritative": 0.7,
|
| 53 |
+
"accessible": 0.9,
|
| 54 |
+
"empathetic": 0.6,
|
| 55 |
+
"forward_thinking": 0.8
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
self.initialize_embeddings()
|
| 59 |
|
| 60 |
def initialize_semantic_space(self):
|
| 61 |
"""Inizializza spazio semantico multidimensionale"""
|
|
|
|
| 62 |
semantic_basis = {}
|
| 63 |
|
| 64 |
# Dimensioni fondamentali della geopolitica
|
|
|
|
| 70 |
|
| 71 |
for i, concept in enumerate(fundamental_concepts):
|
| 72 |
vector = np.zeros(self.vector_dimensions)
|
|
|
|
| 73 |
vector[:len(fundamental_concepts)] = np.random.normal(0, 0.1, len(fundamental_concepts))
|
| 74 |
vector[i] = 1.0 # Componente principale
|
| 75 |
semantic_basis[concept] = vector / np.linalg.norm(vector)
|
|
|
|
| 79 |
def initialize_embeddings(self):
|
| 80 |
"""Inizializza embeddings per entità geopolitiche"""
|
| 81 |
|
|
|
|
| 82 |
entities = {
|
| 83 |
'USA': {'power': 0.95, 'economy': 0.92, 'military': 0.98, 'influence': 0.90},
|
| 84 |
'China': {'power': 0.88, 'economy': 0.89, 'military': 0.85, 'influence': 0.82},
|
|
|
|
| 94 |
}
|
| 95 |
|
| 96 |
for entity, characteristics in entities.items():
|
|
|
|
| 97 |
vector = np.zeros(self.vector_dimensions)
|
| 98 |
|
|
|
|
| 99 |
for i, (char, value) in enumerate(characteristics.items()):
|
| 100 |
if char in self.semantic_space:
|
| 101 |
vector += value * self.semantic_space[char]
|
| 102 |
|
|
|
|
| 103 |
vector += np.random.normal(0, 0.05, self.vector_dimensions)
|
|
|
|
|
|
|
| 104 |
self.entity_embeddings[entity] = vector / (np.linalg.norm(vector) + 1e-8)
|
| 105 |
|
| 106 |
+
def fetch_real_time_data(self):
|
| 107 |
+
"""Recupera dati real-time per alimentare le conversazioni"""
|
| 108 |
+
news_data = []
|
| 109 |
+
|
| 110 |
+
try:
|
| 111 |
+
# Reuters RSS
|
| 112 |
+
response = requests.get(self.data_sources["reuters_rss"], timeout=10)
|
| 113 |
+
if response.status_code == 200:
|
| 114 |
+
root = ET.fromstring(response.content)
|
| 115 |
+
for item in root.findall(".//item")[:10]:
|
| 116 |
+
title = item.find("title")
|
| 117 |
+
description = item.find("description")
|
| 118 |
+
pub_date = item.find("pubDate")
|
| 119 |
+
|
| 120 |
+
if title is not None:
|
| 121 |
+
news_data.append({
|
| 122 |
+
"source": "Reuters",
|
| 123 |
+
"title": title.text,
|
| 124 |
+
"description": description.text if description is not None else "",
|
| 125 |
+
"date": pub_date.text if pub_date is not None else "",
|
| 126 |
+
"vector": self.text_to_vector(title.text + " " + (description.text or ""))
|
| 127 |
+
})
|
| 128 |
+
except:
|
| 129 |
+
pass
|
| 130 |
+
|
| 131 |
+
try:
|
| 132 |
+
# BBC RSS
|
| 133 |
+
response = requests.get(self.data_sources["bbc_rss"], timeout=10)
|
| 134 |
+
if response.status_code == 200:
|
| 135 |
+
root = ET.fromstring(response.content)
|
| 136 |
+
for item in root.findall(".//item")[:10]:
|
| 137 |
+
title = item.find("title")
|
| 138 |
+
description = item.find("description")
|
| 139 |
+
pub_date = item.find("pubDate")
|
| 140 |
+
|
| 141 |
+
if title is not None:
|
| 142 |
+
news_data.append({
|
| 143 |
+
"source": "BBC",
|
| 144 |
+
"title": title.text,
|
| 145 |
+
"description": description.text if description is not None else "",
|
| 146 |
+
"date": pub_date.text if pub_date is not None else "",
|
| 147 |
+
"vector": self.text_to_vector(title.text + " " + (description.text or ""))
|
| 148 |
+
})
|
| 149 |
+
except:
|
| 150 |
+
pass
|
| 151 |
+
|
| 152 |
+
return news_data[:15] # Top 15 notizie più recenti
|
| 153 |
+
|
| 154 |
def text_to_vector(self, text):
|
| 155 |
"""Converte testo in rappresentazione vettoriale robusta"""
|
| 156 |
if not text or not text.strip():
|
|
|
|
| 157 |
return np.random.normal(0, 0.1, self.vector_dimensions)
|
| 158 |
|
| 159 |
words = re.findall(r'\b\w+\b', text.lower())
|
|
|
|
| 194 |
'power': 'power', 'influence': 'influence', 'control': 'power',
|
| 195 |
'domination': 'power', 'hegemony': 'power', 'superpower': 'power',
|
| 196 |
|
| 197 |
+
# Paesi specifici
|
| 198 |
'ukraine': 'conflict', 'russia': 'power', 'china': 'power',
|
| 199 |
'usa': 'power', 'america': 'power', 'taiwan': 'conflict',
|
| 200 |
'iran': 'conflict', 'israel': 'conflict', 'gaza': 'conflict'
|
|
|
|
| 203 |
matched_words = 0
|
| 204 |
semantic_weights = defaultdict(float)
|
| 205 |
|
|
|
|
| 206 |
for word in words:
|
| 207 |
if word in semantic_mapping:
|
| 208 |
concept = semantic_mapping[word]
|
|
|
|
| 213 |
semantic_weights[word] += 1.0
|
| 214 |
matched_words += 1
|
| 215 |
|
|
|
|
| 216 |
if matched_words == 0:
|
| 217 |
for word in words:
|
| 218 |
for pattern, concept in semantic_mapping.items():
|
|
|
|
| 221 |
semantic_weights[concept] += 0.5
|
| 222 |
matched_words += 0.5
|
| 223 |
|
|
|
|
| 224 |
for concept, weight in semantic_weights.items():
|
| 225 |
if concept in self.semantic_space:
|
| 226 |
composite_vector += weight * self.semantic_space[concept]
|
| 227 |
|
|
|
|
| 228 |
if matched_words == 0:
|
|
|
|
| 229 |
text_hash = int(hashlib.md5(text.encode()).hexdigest(), 16)
|
| 230 |
np.random.seed(text_hash % 2**31)
|
| 231 |
composite_vector = np.random.normal(0, 0.3, self.vector_dimensions)
|
| 232 |
matched_words = 1
|
| 233 |
|
|
|
|
| 234 |
if matched_words > 0:
|
| 235 |
composite_vector *= math.log(matched_words + 1) / (matched_words + 0.1)
|
| 236 |
|
|
|
|
| 237 |
norm = np.linalg.norm(composite_vector)
|
| 238 |
if norm < 1e-6:
|
| 239 |
composite_vector = np.random.normal(0, 0.1, self.vector_dimensions)
|
|
|
|
| 241 |
|
| 242 |
return composite_vector / norm
|
| 243 |
|
| 244 |
+
def detect_question_type(self, query):
|
| 245 |
+
"""Rileva il tipo di domanda per personalizzare la risposta"""
|
| 246 |
+
query_lower = query.lower()
|
| 247 |
+
|
| 248 |
+
question_types = {
|
| 249 |
+
'what_happening': ['what', 'happening', 'current', 'now', 'latest', 'today'],
|
| 250 |
+
'why_analysis': ['why', 'because', 'reason', 'cause', 'explain'],
|
| 251 |
+
'how_process': ['how', 'process', 'method', 'way', 'steps'],
|
| 252 |
+
'when_timeline': ['when', 'timeline', 'time', 'date', 'schedule'],
|
| 253 |
+
'who_actors': ['who', 'actors', 'players', 'countries', 'leaders'],
|
| 254 |
+
'where_location': ['where', 'location', 'place', 'region', 'area'],
|
| 255 |
+
'prediction': ['will', 'future', 'predict', 'forecast', 'expect'],
|
| 256 |
+
'comparison': ['vs', 'versus', 'compare', 'difference', 'between'],
|
| 257 |
+
'opinion': ['think', 'believe', 'opinion', 'view', 'perspective'],
|
| 258 |
+
'impact': ['impact', 'effect', 'consequence', 'result', 'outcome']
|
| 259 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
+
detected_types = []
|
| 262 |
+
for qtype, keywords in question_types.items():
|
| 263 |
+
if any(keyword in query_lower for keyword in keywords):
|
| 264 |
+
detected_types.append(qtype)
|
| 265 |
|
| 266 |
+
return detected_types if detected_types else ['general']
|
| 267 |
|
| 268 |
+
def extract_entities_conversational(self, text):
|
| 269 |
+
"""Estrae entità con contesto conversazionale"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
entities = []
|
| 271 |
+
entity_confidence = {}
|
| 272 |
|
|
|
|
| 273 |
entity_patterns = {
|
| 274 |
+
'USA|United States|America|Washington|Biden': 'USA',
|
| 275 |
+
'China|Chinese|Beijing|PRC|Xi Jinping': 'China',
|
| 276 |
+
'Russia|Russian|Moscow|Kremlin|Putin': 'Russia',
|
| 277 |
+
'Ukraine|Ukrainian|Kyiv|Kiev|Zelensky': 'Ukraine',
|
| 278 |
+
'Iran|Iranian|Tehran|Ayatollah': 'Iran',
|
| 279 |
+
'Israel|Israeli|Jerusalem|Netanyahu': 'Israel',
|
| 280 |
+
'Taiwan|Taipei|Taiwanese': 'Taiwan',
|
| 281 |
+
'North Korea|DPRK|Pyongyang|Kim Jong': 'North Korea',
|
| 282 |
+
'NATO|North Atlantic|Alliance': 'NATO',
|
| 283 |
+
'European Union|EU|Brussels': 'EU',
|
| 284 |
+
'Germany|German|Berlin|Scholz': 'Germany',
|
| 285 |
+
'France|French|Paris|Macron': 'France',
|
| 286 |
+
'UK|Britain|British|London': 'UK',
|
| 287 |
+
'Japan|Japanese|Tokyo': 'Japan',
|
| 288 |
+
'India|Indian|Delhi|Modi': 'India',
|
| 289 |
+
'Turkey|Turkish|Ankara|Erdogan': 'Turkey',
|
| 290 |
+
'Saudi Arabia|Saudi|Riyadh': 'Saudi Arabia'
|
| 291 |
}
|
| 292 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
for pattern, entity in entity_patterns.items():
|
| 294 |
+
matches = re.findall(pattern, text, re.IGNORECASE)
|
| 295 |
if matches:
|
| 296 |
+
confidence = min(len(matches) * 0.3, 1.0)
|
| 297 |
+
entities.append(entity)
|
| 298 |
+
entity_confidence[entity] = confidence
|
|
|
|
|
|
|
|
|
|
| 299 |
|
| 300 |
+
# Aggiungi al context
|
| 301 |
+
self.conversation_context["mentioned_entities"].add(entity)
|
| 302 |
|
| 303 |
+
return entities, entity_confidence
|
| 304 |
|
| 305 |
+
def generate_conversational_response(self, query, real_time_data):
|
| 306 |
+
"""Genera risposta conversazionale naturale"""
|
| 307 |
|
| 308 |
try:
|
| 309 |
+
# 1. Analizza il tipo di domanda
|
| 310 |
+
question_types = self.detect_question_type(query)
|
| 311 |
|
| 312 |
+
# 2. Estrai entità dalla domanda
|
| 313 |
+
entities, entity_confidence = self.extract_entities_conversational(query)
|
|
|
|
| 314 |
|
| 315 |
+
# 3. Trova notizie correlate
|
| 316 |
+
correlated_news = self.find_correlated_news(query, real_time_data)
|
| 317 |
|
| 318 |
+
# 4. Analisi vettoriale per insights
|
| 319 |
+
query_vector = self.text_to_vector(query)
|
| 320 |
+
vector_insights = self.get_vector_insights(query_vector, entities)
|
| 321 |
|
| 322 |
+
# 5. Genera risposta basata sul tipo di domanda
|
| 323 |
+
response = self.craft_natural_response(
|
| 324 |
+
query, question_types, entities, correlated_news, vector_insights, real_time_data
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
# 6. Aggiorna context conversazionale
|
| 328 |
+
self.update_conversation_context(query, entities, question_types)
|
| 329 |
|
| 330 |
+
return response
|
| 331 |
|
| 332 |
except Exception as e:
|
| 333 |
+
return f"Mi dispiace, ho riscontrato un problema nell'analisi: {str(e)}. Puoi riprovare con una formulazione diversa?"
|
| 334 |
+
|
| 335 |
+
def find_correlated_news(self, query, news_data):
|
| 336 |
+
"""Trova notizie correlate alla domanda"""
|
| 337 |
+
if not news_data:
|
| 338 |
+
return []
|
| 339 |
+
|
| 340 |
+
query_vector = self.text_to_vector(query)
|
| 341 |
+
correlations = []
|
| 342 |
+
|
| 343 |
+
for news in news_data:
|
| 344 |
+
if 'vector' in news:
|
| 345 |
+
correlation = np.dot(query_vector, news['vector'])
|
| 346 |
+
correlations.append((news, correlation))
|
| 347 |
+
|
| 348 |
+
# Ordina per correlazione e prendi le top 3
|
| 349 |
+
correlations.sort(key=lambda x: abs(x[1]), reverse=True)
|
| 350 |
+
return [news for news, corr in correlations[:3] if abs(corr) > 0.1]
|
| 351 |
+
|
| 352 |
+
def get_vector_insights(self, query_vector, entities):
|
| 353 |
+
"""Ottiene insights dall'analisi vettoriale"""
|
| 354 |
+
insights = {}
|
| 355 |
+
|
| 356 |
+
# Proiezioni semantiche
|
| 357 |
+
semantic_projections = {}
|
| 358 |
+
for concept, basis_vector in self.semantic_space.items():
|
| 359 |
+
projection = np.dot(query_vector, basis_vector)
|
| 360 |
+
if abs(projection) > 0.1:
|
| 361 |
+
semantic_projections[concept] = projection
|
| 362 |
+
|
| 363 |
+
# Top 3 concetti più rilevanti
|
| 364 |
+
top_concepts = sorted(semantic_projections.items(), key=lambda x: abs(x[1]), reverse=True)[:3]
|
| 365 |
+
|
| 366 |
+
insights['dominant_themes'] = top_concepts
|
| 367 |
+
insights['complexity'] = np.count_nonzero(np.abs(query_vector) > 0.1)
|
| 368 |
+
insights['intensity'] = np.linalg.norm(query_vector)
|
| 369 |
+
|
| 370 |
+
return insights
|
| 371 |
+
|
| 372 |
+
def craft_natural_response(self, query, question_types, entities, correlated_news, vector_insights, all_news):
|
| 373 |
+
"""Crea risposta naturale e conversazionale"""
|
| 374 |
+
|
| 375 |
+
response_parts = []
|
| 376 |
+
|
| 377 |
+
# Saluto contestuale
|
| 378 |
+
greetings = [
|
| 379 |
+
"Basandomi sui dati più recenti che sto monitorando,",
|
| 380 |
+
"Dalla mia analisi real-time della situazione globale,",
|
| 381 |
+
"Guardando quello che sta succedendo in questo momento,",
|
| 382 |
+
"Considerando gli sviluppi delle ultime ore,"
|
| 383 |
+
]
|
| 384 |
+
|
| 385 |
+
response_parts.append(random.choice(greetings))
|
| 386 |
+
response_parts.append("")
|
| 387 |
+
|
| 388 |
+
# Risposta specifica per tipo di domanda
|
| 389 |
+
if 'what_happening' in question_types:
|
| 390 |
+
response_parts.extend(self.answer_what_happening(entities, correlated_news, all_news))
|
| 391 |
+
elif 'why_analysis' in question_types:
|
| 392 |
+
response_parts.extend(self.answer_why_analysis(entities, vector_insights, correlated_news))
|
| 393 |
+
elif 'prediction' in question_types:
|
| 394 |
+
response_parts.extend(self.answer_prediction(entities, vector_insights, correlated_news))
|
| 395 |
+
elif 'comparison' in question_types:
|
| 396 |
+
response_parts.extend(self.answer_comparison(entities, vector_insights))
|
| 397 |
+
elif 'impact' in question_types:
|
| 398 |
+
response_parts.extend(self.answer_impact_analysis(entities, correlated_news, vector_insights))
|
| 399 |
+
else:
|
| 400 |
+
response_parts.extend(self.answer_general(query, entities, correlated_news, vector_insights))
|
| 401 |
+
|
| 402 |
+
# Aggiungi contesto real-time se rilevante
|
| 403 |
+
if correlated_news:
|
| 404 |
+
response_parts.append("")
|
| 405 |
+
response_parts.append("**📡 Sviluppi Real-Time Correlati:**")
|
| 406 |
+
for i, news in enumerate(correlated_news[:2], 1):
|
| 407 |
+
response_parts.append(f"{i}. **[{news['source']}]** {news['title']}")
|
| 408 |
+
|
| 409 |
+
# Insights matematici se rilevanti
|
| 410 |
+
if vector_insights['dominant_themes']:
|
| 411 |
+
response_parts.append("")
|
| 412 |
+
response_parts.append("**🔍 La mia analisi vettoriale indica:**")
|
| 413 |
+
for concept, strength in vector_insights['dominant_themes']:
|
| 414 |
+
direction = "forte focus su" if strength > 0 else "tensione relativa a"
|
| 415 |
+
response_parts.append(f"• {direction} **{concept}** (intensità: {abs(strength):.2f})")
|
| 416 |
+
|
| 417 |
+
# Chiusura conversazionale
|
| 418 |
+
closings = [
|
| 419 |
+
"Vuoi che approfondisca qualche aspetto specifico?",
|
| 420 |
+
"C'è altro che ti interessa sapere su questa situazione?",
|
| 421 |
+
"Posso analizzare ulteriori dettagli se hai domande specifiche.",
|
| 422 |
+
"Dimmi se vuoi che esplori altri angoli di questa vicenda."
|
| 423 |
+
]
|
| 424 |
+
|
| 425 |
+
response_parts.append("")
|
| 426 |
+
response_parts.append(random.choice(closings))
|
| 427 |
+
|
| 428 |
+
return "\n".join(response_parts)
|
| 429 |
|
| 430 |
+
def answer_what_happening(self, entities, correlated_news, all_news):
|
| 431 |
+
"""Risponde a domande su cosa sta succedendo"""
|
| 432 |
+
response = []
|
| 433 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 434 |
if entities:
|
| 435 |
+
entity_str = ", ".join(entities[:3])
|
| 436 |
+
response.append(f"**La situazione attuale con {entity_str}:**")
|
| 437 |
+
else:
|
| 438 |
+
response.append("**Ecco cosa sta succedendo nel panorama geopolitico globale:**")
|
| 439 |
+
|
| 440 |
+
if correlated_news:
|
| 441 |
+
response.append("")
|
| 442 |
+
for i, news in enumerate(correlated_news, 1):
|
| 443 |
+
response.append(f"{i}. {news['title']}")
|
| 444 |
+
if news.get('description'):
|
| 445 |
+
response.append(f" _{news['description'][:100]}..._")
|
| 446 |
+
else:
|
| 447 |
+
# Usa notizie generali
|
| 448 |
+
response.append("")
|
| 449 |
+
response.append("Gli ultimi sviluppi includono:")
|
| 450 |
+
for i, news in enumerate(all_news[:3], 1):
|
| 451 |
+
response.append(f"{i}. {news['title']}")
|
| 452 |
+
|
| 453 |
+
return response
|
| 454 |
+
|
| 455 |
+
def answer_why_analysis(self, entities, vector_insights, correlated_news):
|
| 456 |
+
"""Risponde a domande sul perché"""
|
| 457 |
+
response = []
|
| 458 |
+
|
| 459 |
+
response.append("**Analizzando le cause profonde:**")
|
| 460 |
+
response.append("")
|
| 461 |
+
|
| 462 |
+
# Usa insights vettoriali per spiegare le cause
|
| 463 |
+
if vector_insights['dominant_themes']:
|
| 464 |
+
dominant_theme = vector_insights['dominant_themes'][0]
|
| 465 |
+
concept, strength = dominant_theme
|
|
|
|
|
|
|
|
|
|
|
|
|
| 466 |
|
| 467 |
+
explanations = {
|
| 468 |
+
'conflict': "Le tensioni derivano da interessi strategici conflittuali e dispute territoriali irrisolte.",
|
| 469 |
+
'power': "È principalmente una questione di equilibri di potere e sfere d'influenza in trasformazione.",
|
| 470 |
+
'economy': "Le dinamiche economiche e l'accesso alle risorse stanno guidando questi sviluppi.",
|
| 471 |
+
'military': "Considerazioni di sicurezza e deterrenza militare sono i fattori chiave.",
|
| 472 |
+
'diplomacy': "Si tratta di manovre diplomatiche e negoziazioni complesse tra multiple parti.",
|
| 473 |
+
'alliance': "Le alleanze e i partenariati strategici stanno ridefinendo gli equilibri regionali."
|
| 474 |
+
}
|
| 475 |
|
| 476 |
+
if concept in explanations:
|
| 477 |
+
response.append(explanations[concept])
|
| 478 |
+
else:
|
| 479 |
+
response.append(f"I fattori dominanti sono legati a {concept}, che sta influenzando significativamente la situazione.")
|
| 480 |
+
|
| 481 |
+
# Aggiungi contesto dalle notizie
|
| 482 |
+
if correlated_news:
|
| 483 |
+
response.append("")
|
| 484 |
+
response.append("**Le evidenze recenti mostrano:**")
|
| 485 |
+
for news in correlated_news[:2]:
|
| 486 |
+
response.append(f"• {news['title']}")
|
| 487 |
+
|
| 488 |
+
return response
|
| 489 |
+
|
| 490 |
+
def answer_prediction(self, entities, vector_insights, correlated_news):
|
| 491 |
+
"""Risponde a domande predittive"""
|
| 492 |
+
response = []
|
| 493 |
+
|
| 494 |
+
response.append("**Basandomi sui pattern attuali, le proiezioni indicano:**")
|
| 495 |
+
response.append("")
|
| 496 |
+
|
| 497 |
+
# Usa intensità vettoriale per calibrare le previsioni
|
| 498 |
+
intensity = vector_insights.get('intensity', 0.5)
|
| 499 |
+
|
| 500 |
+
if intensity > 0.8:
|
| 501 |
+
response.append("🔴 **Alta probabilità di escalation** - I segnali indicano un sistema in rapida evoluzione")
|
| 502 |
+
elif intensity > 0.5:
|
| 503 |
+
response.append("🟡 **Evoluzione graduale** - La situazione sta progredendo ma con controlli in atto")
|
| 504 |
+
else:
|
| 505 |
+
response.append("🟢 **Stabilità relativa** - Gli indicatori suggeriscono equilibrio controllato")
|
| 506 |
+
|
| 507 |
+
# Scenari specifici basati su entità
|
| 508 |
+
if entities:
|
| 509 |
+
if 'Russia' in entities and 'Ukraine' in entities:
|
| 510 |
+
response.append("")
|
| 511 |
+
response.append("**Scenari probabili per Russia-Ucraina:**")
|
| 512 |
+
response.append("• Continuazione del conflitto con intensità variabile")
|
| 513 |
+
response.append("• Possibili negoziati parziali su corridoi umanitari")
|
| 514 |
+
response.append("• Crescente coinvolgimento diplomatico internazionale")
|
| 515 |
|
| 516 |
+
elif 'China' in entities and 'Taiwan' in entities:
|
| 517 |
+
response.append("")
|
| 518 |
+
response.append("**Scenari Taiwan-Cina:**")
|
| 519 |
+
response.append("• Mantenimento status quo teso con provocazioni limitate")
|
| 520 |
+
response.append("• Rafforzamento deterrenza USA-alleati nella regione")
|
| 521 |
+
response.append("• Escalation diplomatica prima di quella militare")
|
| 522 |
+
|
| 523 |
+
return response
|
| 524 |
+
|
| 525 |
+
def answer_comparison(self, entities, vector_insights):
|
| 526 |
+
"""Risponde a domande comparative"""
|
| 527 |
+
response = []
|
| 528 |
+
|
| 529 |
+
if len(entities) >= 2:
|
| 530 |
+
entity1, entity2 = entities[0], entities[1]
|
| 531 |
+
response.append(f"**Confrontando {entity1} vs {entity2}:**")
|
| 532 |
+
response.append("")
|
| 533 |
|
| 534 |
+
# Usa embeddings per confronti
|
| 535 |
+
if entity1 in self.entity_embeddings and entity2 in self.entity_embeddings:
|
| 536 |
+
vec1 = self.entity_embeddings[entity1]
|
| 537 |
+
vec2 = self.entity_embeddings[entity2]
|
| 538 |
+
|
| 539 |
+
similarity = np.dot(vec1, vec2)
|
| 540 |
+
|
| 541 |
+
if similarity > 0.7:
|
| 542 |
+
response.append("🤝 **Profili simili** - Entrambi condividono caratteristiche strategiche comparabili")
|
| 543 |
+
elif similarity > 0.3:
|
| 544 |
+
response.append("⚖️ **Differenze moderate** - Approcci diversi ma alcuni interessi comuni")
|
| 545 |
+
else:
|
| 546 |
+
response.append("🔄 **Profili contrastanti** - Strategie e priorità significativamente diverse")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 547 |
else:
|
| 548 |
+
response.append("**Per un confronto accurato, specifica gli attori che vuoi comparare.**")
|
| 549 |
+
|
| 550 |
+
return response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 551 |
|
| 552 |
+
def answer_impact_analysis(self, entities, correlated_news, vector_insights):
|
| 553 |
+
"""Risponde a domande sull'impatto"""
|
| 554 |
+
response = []
|
| 555 |
+
|
| 556 |
+
response.append("**Analisi degli impatti:**")
|
| 557 |
+
response.append("")
|
| 558 |
+
|
| 559 |
+
# Categorizza gli impatti basandosi sui temi dominanti
|
| 560 |
+
if vector_insights['dominant_themes']:
|
| 561 |
+
for concept, strength in vector_insights['dominant_themes'][:2]:
|
| 562 |
+
if concept == 'economy':
|
| 563 |
+
response.append("💰 **Impatti Economici:**")
|
| 564 |
+
response.append("• Volatilità dei mercati finanziari globali")
|
| 565 |
+
response.append("• Riconfigurazione delle catene di approvvigionamento")
|
| 566 |
+
response.append("• Pressioni inflazionistiche su energia e commodities")
|
| 567 |
+
elif concept == 'military':
|
| 568 |
+
response.append("⚔️ **Impatti sulla Sicurezza:**")
|
| 569 |
+
response.append("• Riallineamento delle alleanze militari")
|
| 570 |
+
response.append("• Incremento delle spese per la difesa")
|
| 571 |
+
response.append("• Rafforzamento dei sistemi di deterrenza")
|
| 572 |
+
elif concept == 'diplomacy':
|
| 573 |
+
response.append("🌐 **Impatti Diplomatici:**")
|
| 574 |
+
response.append("• Nuove dinamiche nelle organizzazioni internazionali")
|
| 575 |
+
response.append("• Ridefinizione delle partnership strategiche")
|
| 576 |
+
response.append("• Cambiamenti negli equilibri regionali")
|
| 577 |
+
|
| 578 |
+
return response
|
| 579 |
+
|
| 580 |
+
def answer_general(self, query, entities, correlated_news, vector_insights):
|
| 581 |
+
"""Risposta generale per domande non categorizzate"""
|
| 582 |
+
response = []
|
| 583 |
|
| 584 |
+
if entities:
|
| 585 |
+
response.append(f"**Riguardo a {', '.join(entities[:3])}:**")
|
| 586 |
+
else:
|
| 587 |
+
response.append("**Sulla situazione che mi hai chiesto:**")
|
| 588 |
|
| 589 |
+
response.append("")
|
|
|
|
| 590 |
|
| 591 |
+
# Fornisci contesto generale
|
| 592 |
+
complexity = vector_insights.get('complexity', 0)
|
| 593 |
+
if complexity > 10:
|
| 594 |
+
response.append("Si tratta di una situazione **molto complessa** con multiple dimensioni interconnesse.")
|
| 595 |
+
elif complexity > 5:
|
| 596 |
+
response.append("La situazione presenta **diversi livelli di complessità** che richiedono analisi attenta.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 597 |
else:
|
| 598 |
+
response.append("È una questione **relativamente diretta** ma con implicazioni significative.")
|
| 599 |
+
|
| 600 |
+
# Usa notizie per contesto
|
| 601 |
+
if correlated_news:
|
| 602 |
+
response.append("")
|
| 603 |
+
response.append("**Dalle ultime notizie emerge che:**")
|
| 604 |
+
for news in correlated_news[:2]:
|
| 605 |
+
response.append(f"• {news['title']}")
|
| 606 |
+
|
| 607 |
+
return response
|
| 608 |
+
|
| 609 |
+
def update_conversation_context(self, query, entities, question_types):
|
| 610 |
+
"""Aggiorna il context della conversazione"""
|
| 611 |
+
# Aggiungi topic recenti
|
| 612 |
+
if len(self.conversation_context["recent_topics"]) > 10:
|
| 613 |
+
self.conversation_context["recent_topics"].pop(0)
|
| 614 |
+
|
| 615 |
+
self.conversation_context["recent_topics"].append({
|
| 616 |
+
"query": query[:100],
|
| 617 |
+
"entities": entities,
|
| 618 |
+
"types": question_types,
|
| 619 |
+
"timestamp": datetime.now()
|
| 620 |
+
})
|
| 621 |
+
|
| 622 |
+
# Aggiungi entità menzionate
|
| 623 |
+
for entity in entities:
|
| 624 |
+
self.conversation_context["mentioned_entities"].add(entity)
|
| 625 |
+
|
| 626 |
+
# Inferisci interessi utente
|
| 627 |
+
for qtype in question_types:
|
| 628 |
+
self.conversation_context["user_interests"].add(qtype)
|
| 629 |
|
| 630 |
+
# Inizializza il sistema AI conversazionale
|
| 631 |
+
conversational_ai = ConversationalGeopoliticalAI()
|
| 632 |
|
| 633 |
+
def chat_with_ai(user_message, history):
|
| 634 |
+
"""Funzione principale per chat conversazionale"""
|
| 635 |
+
if not user_message.strip():
|
| 636 |
+
return "Ciao! Sono il tuo analista geopolitico AI. Puoi chiedermi qualsiasi cosa sulla situazione mondiale, dalle ultime notizie alle analisi predittive. Cosa ti interessa sapere?"
|
| 637 |
|
| 638 |
+
try:
|
| 639 |
+
# Recupera dati real-time
|
| 640 |
+
real_time_data = conversational_ai.fetch_real_time_data()
|
| 641 |
+
|
| 642 |
+
# Genera risposta conversazionale
|
| 643 |
+
response = conversational_ai.generate_conversational_response(user_message, real_time_data)
|
| 644 |
+
|
| 645 |
+
return response
|
| 646 |
+
|
| 647 |
+
except Exception as e:
|
| 648 |
+
error_responses = [
|
| 649 |
+
f"Mi scuso, ho avuto un problema tecnico nell'analizzare la tua richiesta. Potresti riformularla?",
|
| 650 |
+
f"Sto riscontrando alcune difficoltà nel recuperare i dati più aggiornati. Riprova tra un momento.",
|
| 651 |
+
f"C'è stato un intoppo nella mia analisi. Puoi provare a fare la domanda in modo diverso?"
|
| 652 |
+
]
|
| 653 |
+
return random.choice(error_responses)
|
| 654 |
|
| 655 |
+
def get_current_global_situation():
|
| 656 |
+
"""Fornisce un briefing automatico della situazione globale"""
|
| 657 |
+
try:
|
| 658 |
+
news_data = conversational_ai.fetch_real_time_data()
|
| 659 |
+
|
| 660 |
+
briefing_parts = []
|
| 661 |
+
briefing_parts.append("🌍 **BRIEFING GEOPOLITICO GLOBALE**")
|
| 662 |
+
briefing_parts.append(f"*Aggiornamento: {datetime.now().strftime('%d/%m/%Y - %H:%M UTC')}*")
|
| 663 |
+
briefing_parts.append("")
|
| 664 |
+
|
| 665 |
+
if news_data:
|
| 666 |
+
# Categorizza le notizie
|
| 667 |
+
categories = {
|
| 668 |
+
'conflict': [],
|
| 669 |
+
'diplomacy': [],
|
| 670 |
+
'economy': [],
|
| 671 |
+
'general': []
|
| 672 |
+
}
|
| 673 |
+
|
| 674 |
+
for news in news_data[:10]:
|
| 675 |
+
title_lower = news['title'].lower()
|
| 676 |
+
if any(word in title_lower for word in ['war', 'conflict', 'attack', 'military']):
|
| 677 |
+
categories['conflict'].append(news)
|
| 678 |
+
elif any(word in title_lower for word in ['summit', 'meeting', 'treaty', 'agreement']):
|
| 679 |
+
categories['diplomacy'].append(news)
|
| 680 |
+
elif any(word in title_lower for word in ['economic', 'trade', 'market', 'sanctions']):
|
| 681 |
+
categories['economy'].append(news)
|
| 682 |
+
else:
|
| 683 |
+
categories['general'].append(news)
|
| 684 |
+
|
| 685 |
+
# Presenta per categoria
|
| 686 |
+
if categories['conflict']:
|
| 687 |
+
briefing_parts.append("⚔️ **TENSIONI E CONFLITTI:**")
|
| 688 |
+
for news in categories['conflict'][:3]:
|
| 689 |
+
briefing_parts.append(f"• **[{news['source']}]** {news['title']}")
|
| 690 |
+
briefing_parts.append("")
|
| 691 |
+
|
| 692 |
+
if categories['diplomacy']:
|
| 693 |
+
briefing_parts.append("🤝 **SVILUPPI DIPLOMATICI:**")
|
| 694 |
+
for news in categories['diplomacy'][:3]:
|
| 695 |
+
briefing_parts.append(f"• **[{news['source']}]** {news['title']}")
|
| 696 |
+
briefing_parts.append("")
|
| 697 |
+
|
| 698 |
+
if categories['economy']:
|
| 699 |
+
briefing_parts.append("💰 **QUESTIONI ECONOMICHE:**")
|
| 700 |
+
for news in categories['economy'][:3]:
|
| 701 |
+
briefing_parts.append(f"• **[{news['source']}]** {news['title']}")
|
| 702 |
+
briefing_parts.append("")
|
| 703 |
+
|
| 704 |
+
if categories['general']:
|
| 705 |
+
briefing_parts.append("📰 **ALTRI SVILUPPI:**")
|
| 706 |
+
for news in categories['general'][:2]:
|
| 707 |
+
briefing_parts.append(f"• **[{news['source']}]** {news['title']}")
|
| 708 |
+
|
| 709 |
+
briefing_parts.append("")
|
| 710 |
+
briefing_parts.append("*Puoi chiedermi di approfondire qualsiasi argomento o fare domande specifiche!*")
|
| 711 |
+
|
| 712 |
+
return "\n".join(briefing_parts)
|
| 713 |
+
|
| 714 |
+
except Exception as e:
|
| 715 |
+
return "Al momento non riesco a recuperare il briefing globale. Puoi comunque farmi domande specifiche!"
|
| 716 |
+
|
| 717 |
+
# Esempi conversazionali
|
| 718 |
+
conversation_examples = [
|
| 719 |
+
["Cosa sta succedendo in Ucraina?", ""],
|
| 720 |
+
["Perché Cina e USA sono in tensione?", ""],
|
| 721 |
+
["Quale sarà il futuro della NATO?", ""],
|
| 722 |
+
["Come influisce la crisi energetica sull'Europa?", ""],
|
| 723 |
+
["Cosa pensi delle prossime elezioni americane?", ""],
|
| 724 |
+
["Spiegami la situazione in Medio Oriente", ""],
|
| 725 |
+
["Quali sono i rischi per Taiwan?", ""],
|
| 726 |
+
["Come cambierà l'ordine mondiale?", ""]
|
| 727 |
]
|
| 728 |
|
| 729 |
+
# Interfaccia Chat conversazionale
|
| 730 |
+
with gr.Blocks(
|
| 731 |
+
theme=gr.themes.Soft(),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 732 |
css="""
|
| 733 |
.gradio-container {
|
| 734 |
+
max-width: 900px;
|
| 735 |
margin: auto;
|
|
|
|
| 736 |
}
|
| 737 |
+
.chat-container {
|
| 738 |
+
height: 600px;
|
| 739 |
+
}
|
| 740 |
+
.header {
|
| 741 |
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 742 |
color: white;
|
| 743 |
+
padding: 20px;
|
| 744 |
+
border-radius: 10px;
|
| 745 |
+
margin-bottom: 20px;
|
| 746 |
+
text-align: center;
|
| 747 |
}
|
| 748 |
"""
|
| 749 |
+
) as demo:
|
| 750 |
+
|
| 751 |
+
# Header
|
| 752 |
+
with gr.Row():
|
| 753 |
+
gr.HTML("""
|
| 754 |
+
<div class="header">
|
| 755 |
+
<h1>🌍 Conversational Geopolitical AI</h1>
|
| 756 |
+
<p><b>AI Geopolitica Conversazionale con Dati Real-Time</b></p>
|
| 757 |
+
<p>Chiedimi qualsiasi cosa sulla situazione mondiale - dalle ultime notizie alle analisi predittive!</p>
|
| 758 |
+
</div>
|
| 759 |
+
""")
|
| 760 |
+
|
| 761 |
+
# Chat interface principale
|
| 762 |
+
with gr.Row():
|
| 763 |
+
with gr.Column(scale=4):
|
| 764 |
+
chatbot = gr.Chatbot(
|
| 765 |
+
label="💬 Chat con il tuo Analista Geopolitico AI",
|
| 766 |
+
height=500,
|
| 767 |
+
show_label=True,
|
| 768 |
+
container=True,
|
| 769 |
+
bubble_full_width=False
|
| 770 |
+
)
|
| 771 |
+
|
| 772 |
+
msg = gr.Textbox(
|
| 773 |
+
label="Il tuo messaggio",
|
| 774 |
+
placeholder="Es: Cosa sta succedendo tra Russia e Ucraina? Quali sono le prospettive per Taiwan?",
|
| 775 |
+
lines=2,
|
| 776 |
+
max_lines=4
|
| 777 |
+
)
|
| 778 |
+
|
| 779 |
+
with gr.Row():
|
| 780 |
+
send_btn = gr.Button("Invia 💬", variant="primary", scale=2)
|
| 781 |
+
clear_btn = gr.Button("Nuova Chat 🔄", variant="secondary", scale=1)
|
| 782 |
+
|
| 783 |
+
# Sidebar con funzionalità extra
|
| 784 |
+
with gr.Column(scale=1):
|
| 785 |
+
gr.HTML("<h3>🚀 Funzionalità</h3>")
|
| 786 |
+
|
| 787 |
+
briefing_btn = gr.Button("📡 Briefing Globale", variant="secondary", size="sm")
|
| 788 |
+
|
| 789 |
+
gr.HTML("<h4>💡 Esempi di domande:</h4>")
|
| 790 |
+
gr.HTML("""
|
| 791 |
+
<ul style="font-size: 12px;">
|
| 792 |
+
<li>Cosa sta succedendo in [paese]?</li>
|
| 793 |
+
<li>Perché [paese A] e [paese B] sono in conflitto?</li>
|
| 794 |
+
<li>Quale sarà il futuro di [situazione]?</li>
|
| 795 |
+
<li>Come influisce [evento] su [regione]?</li>
|
| 796 |
+
<li>Spiegami la crisi di [argomento]</li>
|
| 797 |
+
<li>Quali sono i rischi per [paese]?</li>
|
| 798 |
+
</ul>
|
| 799 |
+
""")
|
| 800 |
+
|
| 801 |
+
gr.HTML("<h4>🔍 Capacità AI:</h4>")
|
| 802 |
+
gr.HTML("""
|
| 803 |
+
<ul style="font-size: 12px;">
|
| 804 |
+
<li>📡 Dati real-time da fonti globali</li>
|
| 805 |
+
<li>🧮 Analisi vettoriale matematica</li>
|
| 806 |
+
<li>🎯 Risposte contestualizzate</li>
|
| 807 |
+
<li>🔮 Proiezioni e scenari futuri</li>
|
| 808 |
+
<li>💬 Conversazione naturale</li>
|
| 809 |
+
</ul>
|
| 810 |
+
""")
|
| 811 |
+
|
| 812 |
+
# Funzioni di interazione
|
| 813 |
+
def respond(message, history):
|
| 814 |
+
if not message.strip():
|
| 815 |
+
return history, ""
|
| 816 |
+
|
| 817 |
+
# Ottieni risposta dall'AI
|
| 818 |
+
bot_response = chat_with_ai(message, history)
|
| 819 |
+
|
| 820 |
+
# Aggiungi alla history
|
| 821 |
+
history.append([message, bot_response])
|
| 822 |
+
return history, ""
|
| 823 |
+
|
| 824 |
+
def show_briefing(history):
|
| 825 |
+
briefing = get_current_global_situation()
|
| 826 |
+
history.append(["🤖 Briefing Automatico", briefing])
|
| 827 |
+
return history
|
| 828 |
+
|
| 829 |
+
def clear_chat():
|
| 830 |
+
# Reset conversation context
|
| 831 |
+
conversational_ai.conversation_context = {
|
| 832 |
+
"recent_topics": [],
|
| 833 |
+
"mentioned_entities": set(),
|
| 834 |
+
"analysis_history": [],
|
| 835 |
+
"user_interests": set()
|
| 836 |
+
}
|
| 837 |
+
return [], ""
|
| 838 |
+
|
| 839 |
+
# Event handlers
|
| 840 |
+
send_btn.click(
|
| 841 |
+
respond,
|
| 842 |
+
inputs=[msg, chatbot],
|
| 843 |
+
outputs=[chatbot, msg]
|
| 844 |
+
)
|
| 845 |
+
|
| 846 |
+
msg.submit(
|
| 847 |
+
respond,
|
| 848 |
+
inputs=[msg, chatbot],
|
| 849 |
+
outputs=[chatbot, msg]
|
| 850 |
+
)
|
| 851 |
+
|
| 852 |
+
clear_btn.click(
|
| 853 |
+
clear_chat,
|
| 854 |
+
outputs=[chatbot, msg]
|
| 855 |
+
)
|
| 856 |
+
|
| 857 |
+
briefing_btn.click(
|
| 858 |
+
show_briefing,
|
| 859 |
+
inputs=[chatbot],
|
| 860 |
+
outputs=[chatbot]
|
| 861 |
+
)
|
| 862 |
+
|
| 863 |
+
# Esempi cliccabili
|
| 864 |
+
gr.Examples(
|
| 865 |
+
examples=[ex[0] for ex in conversation_examples],
|
| 866 |
+
inputs=msg,
|
| 867 |
+
label="🎯 Esempi di Conversazione"
|
| 868 |
+
)
|
| 869 |
+
|
| 870 |
+
# Footer informativo
|
| 871 |
+
gr.HTML("""
|
| 872 |
+
<div style="text-align: center; margin-top: 20px; padding: 15px; background-color: #f0f0f0; border-radius: 8px;">
|
| 873 |
+
<p><b>🌍 Powered by Real-Time Geopolitical Intelligence</b></p>
|
| 874 |
+
<p style="font-size: 12px;">
|
| 875 |
+
Fonti: Reuters, BBC World, UN News • Analisi: Vector AI + Mathematical Modeling<br>
|
| 876 |
+
Aggiornamento dati: ogni 30 minuti • Conversazione: Natural Language Processing
|
| 877 |
+
</p>
|
| 878 |
+
</div>
|
| 879 |
+
""")
|
| 880 |
|
| 881 |
if __name__ == "__main__":
|
| 882 |
demo.launch()
|