# Rada Gas (`taiel_ramos/rada-gas`) Actor

- **URL**: https://apify.com/taiel_ramos/rada-gas.md
- **Developed by:** [Taiel Ramos](https://apify.com/taiel_ramos) (community)
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% 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

## RADA-GAS — Pipeline de clasificación de gas

Clasificación de lecturas de sensores de gas para detección temprana de fugas, con un modelo ExtraTrees servido como Actor de Apify y orquestado desde Make.

### 1. Arquitectura y flujo

Trigger (Webhook) → Apify (Actor) → ETL → Preprocessing → Inferencia (ExtraTrees) → Destino (Drive / CSV)
| Etapa             | Qué pasa                                                   |
|-------------------|------------------------------------------------------------|
| **Trigger**       | Make recibe un POST con las lecturas de sensores           |
| **Apify**         | El Actor carga el modelo y clasifica cada lectura          |
| **ETL**           | Limpieza y validación de las 128 features                  |
| **Preprocessing** | Escalado y armado de la matriz de entrada                  |
| **Inferencia**    | ExtraTrees predice la clase de gas y la confianza          |
| **Destino**       | Dataset en Apify + `matriz_resultados.csv` en Google Drive |

### 2. Estructura del repositorio

rada-gas/

├── .actor/
│
│         ├── actor.json # Configuración del Actor
│         ├── input_schema.json # Contrato de entrada
│         └── output_schema.json # Contrato de salida
├── .dock/
│         └── MAKE.jpeg
│\
├── modelo_gas_extratrees.pkl # Modelo entrenado (ExtraTrees)
├── requirements.txt
├── main.py # Código del Actor\
├── flujo make.jpeg
├── Dockerfile
└── README.md

### 3. Actor de Apify

| Campo             | Valor                |
|-------------------|----------------------|
| **Código**        | `src/main.py`        |
| **Input**         | `input_schema.json`  |
| **Output**        | `output_schema.json` |
| **Cómo correrlo** | `apify run`          |

El Actor recibe un array de lecturas, carga el `.pkl`, predice y empuja los resultados al dataset. Además guarda `matriz_resultados.csv` en el key-value store.

### 4. Funciones de ETL, preprocessing y modelo

| Función        | Input            | Output          | Descripción                                     |
|----------------|------------------|-----------------|-------------------------------------------------|
| `extract()`    | JSON del webhook | Lecturas crudas | Valida cantidad y tipo de features              |
| `transform()`  | Lecturas crudas  | Matriz numérica | Convierte a `float`, descarta filas incompletas |
| `preprocess()` | Matriz numérica  | Matriz lista    | Escalado y orden de columnas de entrenamiento   |

**Modelo seleccionado**

- **Modelo:** ExtraTreesClassifier (scikit-learn)
- **¿Por qué?** Alta exactitud sobre datos tabulares de sensores, robusto al ruido y sin necesidad de escalado agresivo. Alternativas: RandomForest (más lento) y Gradient Boosting (más sensible a outliers).

### 5. Contrato del Actor

| Campo         | Dirección |  Tipo de dato       | Descripción                         |
|---------------|-----------|---------------------|-------------------------------------|
| `lecturas`    | input     | array\[array\[float]] | Una fila de 128 valores por lectura |
| `id_registro` | output    | integer             | Índice de la lectura                |
| `gas_codigo`  | output    | integer             | Código de gas (1 a 6)               |
| `gas_nombre`  | output    | string              | Nombre del gas detectado            |
| `confianza`   | output    | float               | Probabilidad de la clase predicha   |

### 6. Orquestación con Make

El escenario tiene seis módulos:

1. **Webhooks → Custom webhook**: recibe el POST con las lecturas.
2. **Webhooks → Webhook Response**: responde 202 con `{"status":"accepted"}` para no bloquear al cliente.
3. **Apify → Run an Actor**: ejecuta el Actor con *Run synchronously* en Yes.
4. **Apify → Get Dataset Items**: lee las predicciones con `{{3.defaultDatasetId}}`.
5. **Apify → Make an API Call**: `GET /v2/key-value-stores/{{3.defaultKeyValueStoreId}}/records/matriz_resultados.csv`.
6. **Google Drive → Upload a file**: sube `{{5.data}}` como `matriz_resultados.csv` a la carpeta destino.

### 7. Métricas

| Métrica                | Valor                                                                           |
|------------------------|---------------------------------------------------------------------------------|
| **Métrica de negocio** | Detección temprana de fugas: alerta antes de que la concentración sea peligrosa |
| **Métrica de modelo**  | Accuracy 0.93 · F1 macro 0.91 (conjunto de evaluación de 10k lecturas)          |

### 8. Costo computacional de una corrida

| Recurso                       | Valor                     |
|-------------------------------|---------------------------|
| **Tiempo por corrida**        | ~45 segundos              |
| **Memoria / CPU / GPU**       | 512 MB / 1 vCPU / sin GPU |
| **Costo en Apify**            | ~0.01 USD (≈ 1 CU)        |
| **Costo por 1.000 registros** | ~10 USD                   |

### 9. Cómo correr el proyecto

1. **Actor:** `cd .` y `apify run` (o desde Apify Console → **Start**).
2. **Entrenamiento:** abrir `notebooks/` en Google Colab o Jupyter.
3. **Datos de prueba:** ver `data/` con lecturas de ejemplo.
4. **Make:** importar el escenario, cargar el token de Apify y la carpeta de Drive.

### Input

````json
{
  "lecturas": [
    [0.02, 0.04, 0.11, "...128 valores..."]
  ]
}



# Actor input Schema

## `lecturas` (type: `array`):

Cada elemento es un vector de 128 valores (f0..f127).

## Actor input object example

```json
{
  "lecturas": []
}
````

# Actor output Schema

## `resultados` (type: `string`):

Clasificación de gas por lectura de sensores.

## `matriz` (type: `string`):

Archivo CSV con la distribución de predicciones.

# 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 = {
    "lecturas": []
};

// Run the Actor and wait for it to finish
const run = await client.actor("taiel_ramos/rada-gas").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 = { "lecturas": [] }

# Run the Actor and wait for it to finish
run = client.actor("taiel_ramos/rada-gas").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 '{
  "lecturas": []
}' |
apify call taiel_ramos/rada-gas --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,taiel_ramos/rada-gas"
        }
    }
}
```

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/RVGkMYCQ0ZJSdE3IW/builds/YSzLFdZ4birLh4Olw/openapi.json
