|
|
import gradio as gr |
|
|
import requests |
|
|
import json |
|
|
from datetime import datetime, timedelta |
|
|
import re |
|
|
import xml.etree.ElementTree as ET |
|
|
import numpy as np |
|
|
import hashlib |
|
|
from collections import defaultdict |
|
|
import math |
|
|
|
|
|
class VectorizedGeopoliticalAI: |
|
|
def __init__(self): |
|
|
|
|
|
self.vector_dimensions = 512 |
|
|
self.semantic_space = self.initialize_semantic_space() |
|
|
|
|
|
|
|
|
self.transformation_matrices = { |
|
|
'power_dynamics': np.random.randn(self.vector_dimensions, self.vector_dimensions) * 0.1, |
|
|
'economic_influence': np.random.randn(self.vector_dimensions, self.vector_dimensions) * 0.1, |
|
|
'military_capability': np.random.randn(self.vector_dimensions, self.vector_dimensions) * 0.1, |
|
|
'diplomatic_relations': np.random.randn(self.vector_dimensions, self.vector_dimensions) * 0.1, |
|
|
'resource_control': np.random.randn(self.vector_dimensions, self.vector_dimensions) * 0.1, |
|
|
'information_warfare': np.random.randn(self.vector_dimensions, self.vector_dimensions) * 0.1 |
|
|
} |
|
|
|
|
|
|
|
|
self.entity_embeddings = {} |
|
|
self.relation_embeddings = {} |
|
|
self.temporal_embeddings = {} |
|
|
|
|
|
|
|
|
self.data_sources = { |
|
|
"reuters_rss": "https://feeds.reuters.com/reuters/worldNews", |
|
|
"bbc_rss": "https://feeds.bbci.co.uk/news/world/rss.xml", |
|
|
"un_news": "https://news.un.org/en/rss/rss.xml" |
|
|
} |
|
|
|
|
|
self.initialize_embeddings() |
|
|
|
|
|
def initialize_semantic_space(self): |
|
|
"""Inizializza spazio semantico multidimensionale""" |
|
|
|
|
|
semantic_basis = {} |
|
|
|
|
|
|
|
|
fundamental_concepts = [ |
|
|
'sovereignty', 'power', 'alliance', 'conflict', 'trade', 'territory', |
|
|
'resource', 'influence', 'security', 'diplomacy', 'ideology', 'culture', |
|
|
'economy', 'military', 'information', 'technology', 'energy', 'population' |
|
|
] |
|
|
|
|
|
for i, concept in enumerate(fundamental_concepts): |
|
|
vector = np.zeros(self.vector_dimensions) |
|
|
|
|
|
vector[:len(fundamental_concepts)] = np.random.normal(0, 0.1, len(fundamental_concepts)) |
|
|
vector[i] = 1.0 |
|
|
semantic_basis[concept] = vector / np.linalg.norm(vector) |
|
|
|
|
|
return semantic_basis |
|
|
|
|
|
def initialize_embeddings(self): |
|
|
"""Inizializza embeddings per entità geopolitiche""" |
|
|
|
|
|
|
|
|
entities = { |
|
|
'USA': {'power': 0.95, 'economy': 0.92, 'military': 0.98, 'influence': 0.90}, |
|
|
'China': {'power': 0.88, 'economy': 0.89, 'military': 0.85, 'influence': 0.82}, |
|
|
'Russia': {'power': 0.75, 'economy': 0.45, 'military': 0.88, 'influence': 0.70}, |
|
|
'Germany': {'power': 0.65, 'economy': 0.85, 'military': 0.55, 'influence': 0.72}, |
|
|
'Ukraine': {'power': 0.25, 'economy': 0.20, 'military': 0.45, 'influence': 0.35}, |
|
|
'Iran': {'power': 0.40, 'economy': 0.30, 'military': 0.60, 'influence': 0.45}, |
|
|
'Israel': {'power': 0.55, 'economy': 0.70, 'military': 0.80, 'influence': 0.60}, |
|
|
'Taiwan': {'power': 0.45, 'economy': 0.75, 'military': 0.50, 'influence': 0.40}, |
|
|
'North Korea': {'power': 0.20, 'economy': 0.10, 'military': 0.70, 'influence': 0.25}, |
|
|
'NATO': {'power': 0.95, 'economy': 0.88, 'military': 0.95, 'influence': 0.90}, |
|
|
'EU': {'power': 0.80, 'economy': 0.90, 'military': 0.60, 'influence': 0.85} |
|
|
} |
|
|
|
|
|
for entity, characteristics in entities.items(): |
|
|
|
|
|
vector = np.zeros(self.vector_dimensions) |
|
|
|
|
|
|
|
|
for i, (char, value) in enumerate(characteristics.items()): |
|
|
if char in self.semantic_space: |
|
|
vector += value * self.semantic_space[char] |
|
|
|
|
|
|
|
|
vector += np.random.normal(0, 0.05, self.vector_dimensions) |
|
|
|
|
|
|
|
|
self.entity_embeddings[entity] = vector / (np.linalg.norm(vector) + 1e-8) |
|
|
|
|
|
def text_to_vector(self, text): |
|
|
"""Converte testo in rappresentazione vettoriale robusta""" |
|
|
if not text or not text.strip(): |
|
|
|
|
|
return np.random.normal(0, 0.1, self.vector_dimensions) |
|
|
|
|
|
words = re.findall(r'\b\w+\b', text.lower()) |
|
|
composite_vector = np.zeros(self.vector_dimensions) |
|
|
|
|
|
|
|
|
semantic_mapping = { |
|
|
|
|
|
'war': 'conflict', 'guerra': 'conflict', 'fight': 'conflict', |
|
|
'conflict': 'conflict', 'crisis': 'conflict', 'tension': 'conflict', |
|
|
'attack': 'military', 'invasion': 'military', 'strike': 'military', |
|
|
|
|
|
|
|
|
'peace': 'diplomacy', 'pace': 'diplomacy', 'negotiation': 'diplomacy', |
|
|
'summit': 'diplomacy', 'agreement': 'diplomacy', 'treaty': 'diplomacy', |
|
|
'diplomatic': 'diplomacy', 'dialogue': 'diplomacy', |
|
|
|
|
|
|
|
|
'trade': 'economy', 'economic': 'economy', 'economy': 'economy', |
|
|
'sanctions': 'economy', 'embargo': 'economy', 'tariff': 'economy', |
|
|
'market': 'economy', 'investment': 'economy', 'gdp': 'economy', |
|
|
|
|
|
|
|
|
'military': 'military', 'defense': 'military', 'security': 'military', |
|
|
'nuclear': 'military', 'missile': 'military', 'weapon': 'military', |
|
|
'army': 'military', 'navy': 'military', 'airforce': 'military', |
|
|
|
|
|
|
|
|
'alliance': 'alliance', 'nato': 'alliance', 'partnership': 'alliance', |
|
|
'coalition': 'alliance', 'bloc': 'alliance', 'union': 'alliance', |
|
|
|
|
|
|
|
|
'oil': 'resource', 'gas': 'resource', 'energy': 'resource', |
|
|
'water': 'resource', 'mineral': 'resource', 'pipeline': 'resource', |
|
|
'territory': 'territory', 'border': 'territory', 'region': 'territory', |
|
|
|
|
|
|
|
|
'power': 'power', 'influence': 'influence', 'control': 'power', |
|
|
'domination': 'power', 'hegemony': 'power', 'superpower': 'power', |
|
|
|
|
|
|
|
|
'ukraine': 'conflict', 'russia': 'power', 'china': 'power', |
|
|
'usa': 'power', 'america': 'power', 'taiwan': 'conflict', |
|
|
'iran': 'conflict', 'israel': 'conflict', 'gaza': 'conflict' |
|
|
} |
|
|
|
|
|
matched_words = 0 |
|
|
semantic_weights = defaultdict(float) |
|
|
|
|
|
|
|
|
for word in words: |
|
|
if word in semantic_mapping: |
|
|
concept = semantic_mapping[word] |
|
|
if concept in self.semantic_space: |
|
|
semantic_weights[concept] += 1.0 |
|
|
matched_words += 1 |
|
|
elif word in self.semantic_space: |
|
|
semantic_weights[word] += 1.0 |
|
|
matched_words += 1 |
|
|
|
|
|
|
|
|
if matched_words == 0: |
|
|
for word in words: |
|
|
for pattern, concept in semantic_mapping.items(): |
|
|
if pattern in word or word in pattern: |
|
|
if concept in self.semantic_space: |
|
|
semantic_weights[concept] += 0.5 |
|
|
matched_words += 0.5 |
|
|
|
|
|
|
|
|
for concept, weight in semantic_weights.items(): |
|
|
if concept in self.semantic_space: |
|
|
composite_vector += weight * self.semantic_space[concept] |
|
|
|
|
|
|
|
|
if matched_words == 0: |
|
|
|
|
|
text_hash = int(hashlib.md5(text.encode()).hexdigest(), 16) |
|
|
np.random.seed(text_hash % 2**31) |
|
|
composite_vector = np.random.normal(0, 0.3, self.vector_dimensions) |
|
|
matched_words = 1 |
|
|
|
|
|
|
|
|
if matched_words > 0: |
|
|
composite_vector *= math.log(matched_words + 1) / (matched_words + 0.1) |
|
|
|
|
|
|
|
|
norm = np.linalg.norm(composite_vector) |
|
|
if norm < 1e-6: |
|
|
composite_vector = np.random.normal(0, 0.1, self.vector_dimensions) |
|
|
norm = np.linalg.norm(composite_vector) |
|
|
|
|
|
return composite_vector / norm |
|
|
|
|
|
def compute_entity_relations(self, entities): |
|
|
"""Calcola relazioni tra entità nello spazio vettoriale con valori realistici""" |
|
|
relations = {} |
|
|
|
|
|
for i, entity1 in enumerate(entities): |
|
|
if entity1 not in self.entity_embeddings: |
|
|
continue |
|
|
|
|
|
for j, entity2 in enumerate(entities[i+1:], i+1): |
|
|
if entity2 not in self.entity_embeddings: |
|
|
continue |
|
|
|
|
|
vec1 = self.entity_embeddings[entity1] |
|
|
vec2 = self.entity_embeddings[entity2] |
|
|
|
|
|
|
|
|
dot_product = np.dot(vec1, vec2) |
|
|
norm_product = np.linalg.norm(vec1) * np.linalg.norm(vec2) |
|
|
cosine_sim = dot_product / (norm_product + 1e-8) |
|
|
|
|
|
|
|
|
euclidean_dist = np.linalg.norm(vec1 - vec2) / math.sqrt(self.vector_dimensions) |
|
|
|
|
|
|
|
|
alliance_vec = self.semantic_space['alliance'] |
|
|
conflict_vec = self.semantic_space['conflict'] |
|
|
|
|
|
|
|
|
alliance_sum = (vec1 + vec2) / 2 |
|
|
alliance_projection = np.dot(alliance_sum, alliance_vec) |
|
|
|
|
|
|
|
|
conflict_diff = vec1 - vec2 |
|
|
conflict_projection = abs(np.dot(conflict_diff, conflict_vec)) |
|
|
|
|
|
|
|
|
power_diff = np.linalg.norm(vec1) - np.linalg.norm(vec2) |
|
|
|
|
|
|
|
|
historical_adjustments = { |
|
|
('Russia', 'Ukraine'): {'conflict_boost': 0.7, 'alliance_penalty': -0.8}, |
|
|
('USA', 'Russia'): {'conflict_boost': 0.4, 'alliance_penalty': -0.6}, |
|
|
('USA', 'China'): {'conflict_boost': 0.3, 'alliance_penalty': -0.5}, |
|
|
('Israel', 'Iran'): {'conflict_boost': 0.8, 'alliance_penalty': -0.9}, |
|
|
('China', 'Taiwan'): {'conflict_boost': 0.9, 'alliance_penalty': -0.9}, |
|
|
('NATO', 'Russia'): {'conflict_boost': 0.6, 'alliance_penalty': -0.7} |
|
|
} |
|
|
|
|
|
|
|
|
key = (entity1, entity2) |
|
|
reverse_key = (entity2, entity1) |
|
|
|
|
|
if key in historical_adjustments: |
|
|
adj = historical_adjustments[key] |
|
|
conflict_projection += adj['conflict_boost'] |
|
|
alliance_projection += adj['alliance_penalty'] |
|
|
elif reverse_key in historical_adjustments: |
|
|
adj = historical_adjustments[reverse_key] |
|
|
conflict_projection += adj['conflict_boost'] |
|
|
alliance_projection += adj['alliance_penalty'] |
|
|
|
|
|
|
|
|
alliance_projection = max(-1.0, min(1.0, alliance_projection)) |
|
|
conflict_projection = max(0.0, min(1.0, conflict_projection)) |
|
|
|
|
|
relations[(entity1, entity2)] = { |
|
|
'similarity': cosine_sim, |
|
|
'distance': euclidean_dist, |
|
|
'alliance_potential': alliance_projection, |
|
|
'conflict_potential': conflict_projection, |
|
|
'power_differential': power_diff |
|
|
} |
|
|
|
|
|
return relations |
|
|
|
|
|
def apply_transformation_matrices(self, input_vector, context_type): |
|
|
"""Applica matrici di trasformazione per analisi contestuale""" |
|
|
if context_type not in self.transformation_matrices: |
|
|
return input_vector |
|
|
|
|
|
transformation_matrix = self.transformation_matrices[context_type] |
|
|
transformed_vector = np.dot(transformation_matrix, input_vector) |
|
|
|
|
|
|
|
|
activated_vector = np.tanh(transformed_vector) |
|
|
|
|
|
return activated_vector |
|
|
|
|
|
def vector_space_analysis(self, query_vector, entities, real_time_data): |
|
|
"""Analisi nello spazio vettoriale multidimensionale""" |
|
|
analysis = {} |
|
|
|
|
|
|
|
|
semantic_projections = {} |
|
|
for concept, basis_vector in self.semantic_space.items(): |
|
|
projection = np.dot(query_vector, basis_vector) |
|
|
semantic_projections[concept] = projection |
|
|
|
|
|
|
|
|
entity_distances = {} |
|
|
for entity in entities: |
|
|
if entity in self.entity_embeddings: |
|
|
distance = np.linalg.norm(query_vector - self.entity_embeddings[entity]) |
|
|
entity_distances[entity] = distance |
|
|
|
|
|
|
|
|
contextual_transforms = {} |
|
|
for context in self.transformation_matrices.keys(): |
|
|
transformed = self.apply_transformation_matrices(query_vector, context) |
|
|
|
|
|
entropy = -np.sum(transformed * np.log(np.abs(transformed) + 1e-8)) |
|
|
contextual_transforms[context] = { |
|
|
'vector': transformed, |
|
|
'entropy': entropy, |
|
|
'norm': np.linalg.norm(transformed) |
|
|
} |
|
|
|
|
|
analysis['semantic_projections'] = semantic_projections |
|
|
analysis['entity_distances'] = entity_distances |
|
|
analysis['contextual_transforms'] = contextual_transforms |
|
|
|
|
|
return analysis |
|
|
|
|
|
def fetch_real_time_data(self): |
|
|
"""Recupera dati real-time per alimentare i vettori""" |
|
|
news_data = [] |
|
|
|
|
|
try: |
|
|
|
|
|
response = requests.get(self.data_sources["reuters_rss"], timeout=10) |
|
|
if response.status_code == 200: |
|
|
root = ET.fromstring(response.content) |
|
|
for item in root.findall(".//item")[:8]: |
|
|
title = item.find("title") |
|
|
description = item.find("description") |
|
|
|
|
|
if title is not None: |
|
|
news_data.append({ |
|
|
"source": "Reuters", |
|
|
"title": title.text, |
|
|
"description": description.text if description is not None else "", |
|
|
"vector": self.text_to_vector(title.text + " " + (description.text or "")) |
|
|
}) |
|
|
except: |
|
|
pass |
|
|
|
|
|
try: |
|
|
|
|
|
response = requests.get(self.data_sources["bbc_rss"], timeout=10) |
|
|
if response.status_code == 200: |
|
|
root = ET.fromstring(response.content) |
|
|
for item in root.findall(".//item")[:8]: |
|
|
title = item.find("title") |
|
|
description = item.find("description") |
|
|
|
|
|
if title is not None: |
|
|
news_data.append({ |
|
|
"source": "BBC", |
|
|
"title": title.text, |
|
|
"description": description.text if description is not None else "", |
|
|
"vector": self.text_to_vector(title.text + " " + (description.text or "")) |
|
|
}) |
|
|
except: |
|
|
pass |
|
|
|
|
|
return news_data |
|
|
|
|
|
def extract_entities_advanced(self, text_data): |
|
|
"""Estrazione avanzata di entità con confidence scores""" |
|
|
entities = [] |
|
|
entity_vectors = {} |
|
|
|
|
|
|
|
|
entity_patterns = { |
|
|
'USA|United States|America|Washington': 'USA', |
|
|
'China|Chinese|Beijing|PRC': 'China', |
|
|
'Russia|Russian|Moscow|Kremlin': 'Russia', |
|
|
'Ukraine|Ukrainian|Kyiv|Kiev': 'Ukraine', |
|
|
'Iran|Iranian|Tehran': 'Iran', |
|
|
'Israel|Israeli|Jerusalem': 'Israel', |
|
|
'Taiwan|Taipei': 'Taiwan', |
|
|
'North Korea|DPRK|Pyongyang': 'North Korea', |
|
|
'NATO|North Atlantic': 'NATO', |
|
|
'European Union|EU': 'EU', |
|
|
'Germany|German|Berlin': 'Germany' |
|
|
} |
|
|
|
|
|
combined_text = "" |
|
|
if isinstance(text_data, list): |
|
|
for item in text_data: |
|
|
if isinstance(item, dict): |
|
|
combined_text += f" {item.get('title', '')} {item.get('description', '')}" |
|
|
else: |
|
|
combined_text += f" {str(item)}" |
|
|
else: |
|
|
combined_text = str(text_data) |
|
|
|
|
|
|
|
|
for pattern, entity in entity_patterns.items(): |
|
|
matches = re.findall(pattern, combined_text, re.IGNORECASE) |
|
|
if matches: |
|
|
confidence = len(matches) / len(combined_text.split()) * 100 |
|
|
entities.append({ |
|
|
'name': entity, |
|
|
'confidence': min(confidence, 1.0), |
|
|
'mentions': len(matches) |
|
|
}) |
|
|
|
|
|
if entity in self.entity_embeddings: |
|
|
entity_vectors[entity] = self.entity_embeddings[entity] |
|
|
|
|
|
return entities, entity_vectors |
|
|
|
|
|
def generate_mathematical_analysis(self, query, real_time_data): |
|
|
"""Genera analisi matematica avanzata dai vettori""" |
|
|
|
|
|
try: |
|
|
|
|
|
query_vector = self.text_to_vector(query) |
|
|
|
|
|
|
|
|
entities, entity_vectors = self.extract_entities_advanced([{"title": query}] + real_time_data) |
|
|
entity_names = [e['name'] for e in entities] |
|
|
|
|
|
|
|
|
relations = self.compute_entity_relations(entity_names) |
|
|
|
|
|
|
|
|
vector_analysis = self.vector_space_analysis(query_vector, entity_names, real_time_data) |
|
|
|
|
|
|
|
|
report = self.generate_vector_report(query, query_vector, entities, relations, vector_analysis, real_time_data) |
|
|
|
|
|
return report |
|
|
|
|
|
except Exception as e: |
|
|
return f"❌ Errore nell'analisi vettoriale: {str(e)}" |
|
|
|
|
|
def generate_vector_report(self, query, query_vector, entities, relations, vector_analysis, real_time_data): |
|
|
"""Genera report basato su analisi vettoriale matematica""" |
|
|
|
|
|
report_parts = [] |
|
|
|
|
|
|
|
|
report_parts.append("🧮 VECTORIZED GEOPOLITICAL ANALYSIS") |
|
|
report_parts.append("═" * 60) |
|
|
report_parts.append(f"📐 Vector Space: R^{self.vector_dimensions} | Semantic Manifold Analysis") |
|
|
report_parts.append(f"🕐 Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}") |
|
|
report_parts.append("") |
|
|
|
|
|
|
|
|
query_norm = np.linalg.norm(query_vector) |
|
|
query_entropy = -np.sum(query_vector * np.log(np.abs(query_vector) + 1e-8)) |
|
|
report_parts.append(f"🎯 QUERY VECTORIZATION:") |
|
|
report_parts.append(f" ∥q∥₂ = {query_norm:.4f} | H(q) = {query_entropy:.4f}") |
|
|
report_parts.append(f" Dimensional complexity: {np.count_nonzero(np.abs(query_vector) > 0.1)}/{self.vector_dimensions}") |
|
|
report_parts.append("") |
|
|
|
|
|
|
|
|
top_projections = sorted(vector_analysis['semantic_projections'].items(), |
|
|
key=lambda x: abs(x[1]), reverse=True)[:6] |
|
|
|
|
|
report_parts.append("📊 SEMANTIC SPACE PROJECTIONS:") |
|
|
for concept, projection in top_projections: |
|
|
intensity = "█" * int(abs(projection) * 20 + 1) |
|
|
sign = "+" if projection > 0 else "-" |
|
|
report_parts.append(f" {concept:.<15} {sign}{abs(projection):.3f} {intensity}") |
|
|
report_parts.append("") |
|
|
|
|
|
|
|
|
if entities: |
|
|
report_parts.append("🎭 ENTITY DETECTION (CONFIDENCE-WEIGHTED):") |
|
|
sorted_entities = sorted(entities, key=lambda x: x['confidence'], reverse=True) |
|
|
for entity in sorted_entities[:8]: |
|
|
confidence_bar = "▓" * int(entity['confidence'] * 20) |
|
|
report_parts.append(f" {entity['name']:.<12} π={entity['confidence']:.3f} n={entity['mentions']} {confidence_bar}") |
|
|
report_parts.append("") |
|
|
|
|
|
|
|
|
if relations: |
|
|
report_parts.append("🔗 INTER-ENTITY VECTOR RELATIONS:") |
|
|
sorted_relations = sorted(relations.items(), key=lambda x: x[1]['similarity'], reverse=True) |
|
|
for (e1, e2), rel_data in sorted_relations[:5]: |
|
|
sim = rel_data['similarity'] |
|
|
conflict_pot = rel_data['conflict_potential'] |
|
|
alliance_pot = rel_data['alliance_potential'] |
|
|
|
|
|
|
|
|
if alliance_pot > 0.3 and sim > 0.5: |
|
|
relation_type = "🤝 ALLIANCE" |
|
|
elif conflict_pot > 0.4 and sim < 0.2: |
|
|
relation_type = "⚔️ ADVERSARIAL" |
|
|
elif abs(rel_data['power_differential']) > 0.3: |
|
|
relation_type = "⚖️ ASYMMETRIC" |
|
|
else: |
|
|
relation_type = "🔄 NEUTRAL" |
|
|
|
|
|
report_parts.append(f" {e1} ↔ {e2}") |
|
|
report_parts.append(f" {relation_type} | cos(θ)={sim:.3f} | ∆P={rel_data['power_differential']:.3f}") |
|
|
report_parts.append("") |
|
|
|
|
|
|
|
|
report_parts.append("🔄 CONTEXTUAL MANIFOLD TRANSFORMATIONS:") |
|
|
for context, transform_data in vector_analysis['contextual_transforms'].items(): |
|
|
entropy = transform_data['entropy'] |
|
|
norm = transform_data['norm'] |
|
|
|
|
|
|
|
|
divergence = np.linalg.norm(query_vector - transform_data['vector']) |
|
|
|
|
|
report_parts.append(f" {context.replace('_', ' ').title()}:") |
|
|
report_parts.append(f" H(T(q)) = {entropy:.3f} | ∥T(q)∥ = {norm:.3f} | D_KL = {divergence:.3f}") |
|
|
report_parts.append("") |
|
|
|
|
|
|
|
|
if real_time_data: |
|
|
report_parts.append("📡 REAL-TIME VECTOR CORRELATION:") |
|
|
correlations = [] |
|
|
|
|
|
for news in real_time_data[:5]: |
|
|
if 'vector' in news: |
|
|
correlation = np.dot(query_vector, news['vector']) |
|
|
correlations.append((news['title'][:50] + "...", correlation)) |
|
|
|
|
|
sorted_correlations = sorted(correlations, key=lambda x: abs(x[1]), reverse=True) |
|
|
for title, corr in sorted_correlations[:3]: |
|
|
corr_intensity = "●" * int(abs(corr) * 15 + 1) |
|
|
report_parts.append(f" ρ={corr:.3f} {corr_intensity}") |
|
|
report_parts.append(f" {title}") |
|
|
report_parts.append("") |
|
|
|
|
|
|
|
|
report_parts.append("🔮 MATHEMATICAL TRAJECTORY ANALYSIS:") |
|
|
|
|
|
|
|
|
gradient_vector = np.zeros(self.vector_dimensions) |
|
|
for concept, projection in vector_analysis['semantic_projections'].items(): |
|
|
if abs(projection) > 0.2: |
|
|
gradient_vector += projection * self.semantic_space[concept] |
|
|
|
|
|
gradient_norm = np.linalg.norm(gradient_vector) |
|
|
|
|
|
if gradient_norm > 0.5: |
|
|
report_parts.append(" 📈 HIGH-GRADIENT TRAJECTORY: Sistema in evoluzione rapida") |
|
|
report_parts.append(f" ∇f = {gradient_norm:.3f} | Instabilità prevista") |
|
|
elif gradient_norm > 0.2: |
|
|
report_parts.append(" 📊 MODERATE-GRADIENT: Evoluzione controllata") |
|
|
report_parts.append(f" ∇f = {gradient_norm:.3f} | Stabilità relativa") |
|
|
else: |
|
|
report_parts.append(" 📉 LOW-GRADIENT: Sistema in equilibrio") |
|
|
report_parts.append(f" ∇f = {gradient_norm:.3f} | Convergenza locale") |
|
|
|
|
|
|
|
|
risk_metrics = self.calculate_vector_risk_metrics(vector_analysis, relations) |
|
|
report_parts.append("") |
|
|
report_parts.append("⚠️ VECTOR-BASED RISK ASSESSMENT:") |
|
|
report_parts.append(f" Risk Magnitude: ∥R∥ = {risk_metrics['magnitude']:.3f}") |
|
|
report_parts.append(f" Entropy Level: H(R) = {risk_metrics['entropy']:.3f}") |
|
|
report_parts.append(f" Stability Index: σ = {risk_metrics['stability']:.3f}") |
|
|
|
|
|
|
|
|
report_parts.append("") |
|
|
report_parts.append("📚 MATHEMATICAL FRAMEWORK:") |
|
|
report_parts.append(" • High-dimensional semantic embedding (512D)") |
|
|
report_parts.append(" • Manifold learning on geopolitical concepts") |
|
|
report_parts.append(" • Real-time vector correlation analysis") |
|
|
report_parts.append(" • Multi-contextual transformation matrices") |
|
|
report_parts.append(" • Information-theoretic risk quantification") |
|
|
|
|
|
report_parts.append(f"") |
|
|
report_parts.append(f"🔄 Next vector update: {(datetime.now() + timedelta(minutes=30)).strftime('%H:%M UTC')}") |
|
|
|
|
|
return "\n".join(report_parts) |
|
|
|
|
|
def calculate_vector_risk_metrics(self, vector_analysis, relations): |
|
|
"""Calcola metriche di rischio basate su analisi vettoriale con valori realistici""" |
|
|
|
|
|
|
|
|
conflict_indicators = { |
|
|
'conflict': 3.0, |
|
|
'military': 2.5, |
|
|
'power': 1.5 |
|
|
} |
|
|
|
|
|
risk_magnitude = 0.0 |
|
|
for indicator, weight in conflict_indicators.items(): |
|
|
projection = abs(vector_analysis['semantic_projections'].get(indicator, 0)) |
|
|
risk_magnitude += projection * weight |
|
|
|
|
|
|
|
|
risk_magnitude = min(risk_magnitude / 5.0, 1.0) |
|
|
|
|
|
|
|
|
if relations: |
|
|
max_conflict_potential = max( |
|
|
(rel.get('conflict_potential', 0) for rel in relations.values()), |
|
|
default=0 |
|
|
) |
|
|
risk_magnitude = max(risk_magnitude, max_conflict_potential * 0.7) |
|
|
|
|
|
|
|
|
entropies = [] |
|
|
for context_name, transform in vector_analysis['contextual_transforms'].items(): |
|
|
|
|
|
vector = transform['vector'] |
|
|
|
|
|
exp_vector = np.exp(vector - np.max(vector)) |
|
|
prob_dist = exp_vector / np.sum(exp_vector) |
|
|
entropy = -np.sum(prob_dist * np.log(prob_dist + 1e-8)) |
|
|
entropies.append(entropy) |
|
|
|
|
|
|
|
|
system_entropy = np.mean(entropies) / math.log(self.vector_dimensions) if entropies else 0.3 |
|
|
|
|
|
|
|
|
stability_factors = [] |
|
|
|
|
|
if relations: |
|
|
|
|
|
similarities = [rel['similarity'] for rel in relations.values()] |
|
|
if similarities: |
|
|
similarity_variance = np.var(similarities) |
|
|
stability_factors.append(1.0 - similarity_variance) |
|
|
|
|
|
|
|
|
power_diffs = [abs(rel['power_differential']) for rel in relations.values()] |
|
|
if power_diffs: |
|
|
power_asymmetry = np.mean(power_diffs) |
|
|
stability_factors.append(1.0 - min(power_asymmetry, 1.0)) |
|
|
|
|
|
|
|
|
semantic_projections = list(vector_analysis['semantic_projections'].values()) |
|
|
if semantic_projections: |
|
|
semantic_coherence = 1.0 - (np.var(semantic_projections) / (np.mean(np.abs(semantic_projections)) + 1e-8)) |
|
|
stability_factors.append(max(0.0, min(1.0, semantic_coherence))) |
|
|
|
|
|
|
|
|
if stability_factors: |
|
|
stability = np.mean(stability_factors) |
|
|
else: |
|
|
stability = 0.5 |
|
|
|
|
|
|
|
|
|
|
|
active_transforms = sum(1 for t in vector_analysis['contextual_transforms'].values() |
|
|
if t['norm'] > 0.1) |
|
|
if active_transforms > 3: |
|
|
stability *= 0.85 |
|
|
|
|
|
return { |
|
|
'magnitude': max(0.0, min(1.0, risk_magnitude)), |
|
|
'entropy': max(0.0, min(1.0, system_entropy)), |
|
|
'stability': max(0.0, min(1.0, stability)) |
|
|
} |
|
|
|
|
|
|
|
|
ai_system = VectorizedGeopoliticalAI() |
|
|
|
|
|
def analyze_vectorized(user_query): |
|
|
"""Funzione principale con analisi vettoriale matematica""" |
|
|
if not user_query.strip(): |
|
|
return "❌ Inserisci una query per l'analisi vettoriale geopolitica." |
|
|
|
|
|
|
|
|
real_time_data = ai_system.fetch_real_time_data() |
|
|
|
|
|
|
|
|
return ai_system.generate_mathematical_analysis(user_query, real_time_data) |
|
|
|
|
|
|
|
|
examples = [ |
|
|
"Analizza la dinamica vettoriale del conflitto Russia-Ucraina", |
|
|
"Proiezione multidimensionale delle tensioni USA-Cina", |
|
|
"Manifold geopolitico della crisi energetica europea", |
|
|
"Trasformazioni contestuali delle alleanze NATO", |
|
|
"Correlazioni vettoriali nell'instabilità mediorientale", |
|
|
"Analisi del gradiente nelle relazioni Indo-Pacifiche" |
|
|
] |
|
|
|
|
|
|
|
|
demo = gr.Interface( |
|
|
fn=analyze_vectorized, |
|
|
inputs=[ |
|
|
gr.Textbox( |
|
|
label="Geopolitical Vector Query", |
|
|
placeholder="Es: Analizza lo spazio vettoriale delle tensioni Taiwan-Cina nel manifold indo-pacifico...", |
|
|
lines=3 |
|
|
) |
|
|
], |
|
|
outputs=[ |
|
|
gr.Textbox( |
|
|
label="Mathematical Geopolitical Analysis", |
|
|
lines=35, |
|
|
max_lines=45 |
|
|
) |
|
|
], |
|
|
title="🧮 Vectorized Geopolitical Intelligence AI", |
|
|
description=""" |
|
|
**🚀 Analisi Geopolitica tramite Spazi Vettoriali Multidimensionali** |
|
|
|
|
|
🔬 **Framework Matematico:** |
|
|
• 📐 **Embedding Semantico**: 512-dimensional vector space |
|
|
• 🌐 **Manifold Learning**: Proiezioni su sottospazi geopolitici |
|
|
• 🔄 **Matrici di Trasformazione**: Analisi contestuali multiple |
|
|
• 📊 **Correlazione Vettoriale**: Input real-time transformati |
|
|
• ⚡ **Information Theory**: Risk assessment entropico |
|
|
|
|
|
💡 **Advanced Capabilities:** |
|
|
• Conversione linguaggio naturale → vettori multidimensionali |
|
|
• Relazioni inter-entità calcolate in spazio astratto |
|
|
• Gradient analysis per previsioni di traiettoria |
|
|
• Metriche quantitative per assessment geopolitico |
|
|
|
|
|
🎯 **Output**: Analisi matematica rigorosa invece di template generici |
|
|
""", |
|
|
examples=examples, |
|
|
theme=gr.themes.Monochrome(), |
|
|
css=""" |
|
|
.gradio-container { |
|
|
max-width: 1100px; |
|
|
margin: auto; |
|
|
font-family: 'Courier New', monospace; |
|
|
} |
|
|
.description { |
|
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); |
|
|
color: white; |
|
|
padding: 25px; |
|
|
border-radius: 15px; |
|
|
} |
|
|
""" |
|
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
demo.launch() |