# Inteligencia-Territorial-DH (`navalos/inteligencia-territorial-dh`) Actor

- **URL**: https://apify.com/navalos/inteligencia-territorial-dh.md
- **Developed by:** [Nahuel Avalos](https://apify.com/navalos) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 92.3% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/store.md#pay-per-usage

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## 🌃 Data Horizon — Inteligencia Territorial Nocturna (CABA)

Plataforma integral de analítica geoespacial y predicción de riesgo delictivo nocturno en la Ciudad Autónoma de Buenos Aires (CABA), desarrollada mediante la integración de **datos abiertos de delitos (GCBA)** e **imágenes satelitales de luminosidad nocturna (NASA Black Marble)**.

El sistema combina un motor de procesamiento e inferencia en la nube sobre **Apify**, automatización de flujos con **Make**, y una aplicación web interactiva construida en **Streamlit** para visualización ejecutiva y toma de decisiones preventivas.

***

### 🏗️ Arquitectura de la Solución

El proyecto implementa los dos productos requeridos en un flujo unificado:

1. **Producto 1 — Analytics (`ETL + EDA`):** Extracción, limpieza, cruce espacial por grilla territorial de **1.600 celdas** de CABA y análisis exploratorio de distribución delictiva y niveles de luminosidad.
2. **Producto 2 — Inference (`RandomForest`):** Servicio predictivo que evalúa el nivel de riesgo nocturno (`Bajo`, `Medio`, `Alto`) y su porcentaje de confianza combinando ubicación geográfica, luminosidad satelital, día de la semana y franja horaria.
3. **Dashboard Interactivo (`Data Horizon`):** Interfaz web desplegada en Streamlit Community Cloud con mapa interactivo de CABA, consulta por clic directo sobre celdas, simulación temporal (día y hora) y vista ejecutiva de indicadores macro.

#### Estructura del Repositorio

```text
├── actor_apify/
│   ├── .actor/                 # Esquemas de configuración, entrada y salida de Apify
│   ├── my_actor/               # Código fuente del Actor (main.py), grilla y modelo JSON
│   ├── Dockerfile              # Definición del contenedor del servicio
│   └── requirements.txt        # Dependencias del Actor
├── colabs/
│   ├── analytics.ipynb         # Notebook de ETL, cruce geoespacial y EDA
│   └── training.ipynb          # Notebook de entrenamiento, validación y exportación del modelo
├── dashboard/
│   └── app.py                  # Aplicación web interactiva en Streamlit
├── data/
│   ├── raw/                    # Datasets originales sin procesar
│   └── processed/              # Dataset maestro consolidado (dataset_inteligencia_territorial.csv)
├── requirements.txt            # Dependencias del Dashboard web
└── README.md
```

***

### ⚙️ Parámetros de Entrada del Servicio (`Input`)

El Actor de Apify admite ejecución mediante parámetro `operation` (`analytics` o `inference`), soportando tanto **Consulta Individual** como **Consulta por Lotes (`bulk_items`)**:

| Parámetro | Tipo | Requerido | Valor por defecto | Descripción |
| :--- | :--- | :--- | :--- | :--- |
| `operation` | `string` | No | `"inference"` | Operación a ejecutar: `"analytics"` (ETL + EDA) o `"inference"` (predicción ML). |
| `zona_id` | `string` | No\* | `"-34.5880_-58.4160"` | Identificador de la celda geográfica (`latitud_longitud`) en CABA. |
| `dia_semana` | `string` | No | `"Viernes"` | Día de la semana a evaluar (`Lunes` a `Domingo`). |
| `franja_horaria` | `integer` | No | `21` | Hora del día en formato 24 hs (`0` a `23`). |
| `bulk_items` | `array` | No | `[]` | Lista de objetos JSON para evaluación masiva. Tiene prioridad sobre los campos individuales. |

*\*Si se consulta una coordenada fuera de las celdas activas del dataset maestro, el motor aplica valores de referencia promedio de CABA e informa `zona_valida_en_dataset: false`.*

***

### 🚀 Ejemplos de Uso (API POST)

#### 1. Consulta Individual (`inference`)

```json
{
  "operation": "inference",
  "zona_id": "-34.5880_-58.4160",
  "dia_semana": "Sabado",
  "franja_horaria": 2
}
```

#### 2. Consulta por Lotes (`bulk_items`)

```json
{
  "operation": "inference",
  "bulk_items": [
    {
      "zona_id": "-34.5880_-58.4160",
      "dia_semana": "Viernes",
      "franja_horaria": 21
    },
    {
      "zona_id": "-34.6037_-58.3816",
      "dia_semana": "Sabado",
      "franja_horaria": 3
    }
  ]
}
```

***

### 📤 Formato de Salida (`Output Dataset`)

Por cada consulta procesada, el servicio devuelve un objeto JSON estructurado con la predicción del modelo y los indicadores territoriales asociados:

```json
[
  {
    "zona_id": "-34.5880_-58.4160",
    "latitud": -34.5880,
    "longitud": -58.4160,
    "zona_valida_en_dataset": true,
    "dia_semana": "Sabado",
    "franja_horaria": 2,
    "nivel_incidencia_estimado": "Alto",
    "confianza_modelo": 0.914,
    "modelo_utilizado": "RandomForest",
    "luminosidad_promedio": 78.45,
    "clasificacion_luminosidad": "Media",
    "delitos_nocturnos_historicos": 42
  }
]
```

#### Descripción de campos de salida

- **`latitud` / `longitud`:** Coordenadas del centroide de la celda para renderizado cartográfico.
- **`zona_valida_en_dataset`:** Indica si la celda cuenta con relevamiento directo en la grilla de CABA (`true`) o utiliza respaldo estadístico (`false`).
- **`nivel_incidencia_estimado`:** Categoría de riesgo estimada (`Bajo`, `Medio`, `Alto`) combinando el modelo `RandomForest` con el ajuste temporal por franja horaria y fin de semana.
- **`confianza_modelo` / `modelo_utilizado`:** Probabilidad asociada a la clase predicha e identificador del modelo entrenado.
- **`luminosidad_promedio` / `clasificacion_luminosidad`:** Índice de radiancia nocturna (nW) y su categorización (`Baja`, `Media`, `Alta`).
- **`delitos_nocturnos_historicos`:** Conteo histórico de delitos nocturnos registrados en la celda.

# Actor input Schema

## `operation` (type: `string`):

Seleccioná el producto o etapa del pipeline: 'etl', 'eda' o 'inference'.

## `raw_records` (type: `array`):

Lista de registros crudos provenientes de delitos_2024.csv (enviados por Make desde Drive/raw).

## `clean_records` (type: `array`):

Lista de celdas limpias generadas por el ETL (enviadas por Make desde Drive/limpio).

## `eda_tabla` (type: `string`):

Qué resumen devolver en modo EDA: 'all', 'incidencia' (csv_1), 'top_zonas' (csv_2) o 'luminosidad' (csv_3).

## `zona_id` (type: `string`):

Identificador latitud_longitud de la celda geográfica en CABA.

## `dia_semana` (type: `string`):

Día a evaluar.

## `franja_horaria` (type: `integer`):

Hora del día (0 a 23).

## `bulk_items` (type: `array`):

Lista de consultas para predicción masiva.

## Actor input object example

```json
{
  "operation": "inference",
  "raw_records": [],
  "clean_records": [],
  "eda_tabla": "all",
  "zona_id": "-34.5375_-58.4595",
  "dia_semana": "Viernes",
  "franja_horaria": 21,
  "bulk_items": []
}
```

# Actor output Schema

## `dataset` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("navalos/inteligencia-territorial-dh").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("navalos/inteligencia-territorial-dh").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call navalos/inteligencia-territorial-dh --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,navalos/inteligencia-territorial-dh"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/zxHfIFAWY427PGfe7/builds/I7eFhNAbqBpLan6QN/openapi.json
