Skip to main content

Multipurpose python utils

Project description

JANIA LIB

Librería multipropósito en Python: utilidades para procesamiento de configuración, extracción de datos de PDF usando LLM y limpieza avanzada de JSON.

Instalación

Requiere Python 3.7 o superior.

pip install jania

O bien, clona el repositorio:

git clone https://github.com/julianin/JANIALIB.git
cd JANIALIB
pip install .

Dependencias

  • toml
  • PyYAML
  • python-dotenv
  • pdf2image
  • Pillow
  • openai (opcional, solo si usas funciones LLM)

Funcionalidades principales

1. Limpieza y formateo de JSON: cleanJSON

Función para extraer, limpiar y formatear el primer bloque JSON válido de un texto (útil para outputs de LLM o APIs poco estrictas).

Uso básico:

from jania import cleanJSON
json_str = cleanJSON(raw_text)

Parámetros:

  • text: (str) Texto de entrada donde buscar JSON.
  • indent: (int, opcional) Espacios de indentación para el JSON de salida. Default: 2.
  • debug: (bool, opcional) Si es True, también devuelve el fragmento corregido que se intentó parsear. Default: False.

Devuelve:

  • Un string con el JSON limpio y formateado, o None si no se encuentra JSON válido.

Ejemplo:

json_str = cleanJSON('output: {a:1, b:2, c:true}')
print(json_str)
# {
#   "a": 1,
#   "b": 2,
#   "c": true
# }

2. Gestión de configuración: env y env_config

Utilidades para leer configuración multi-formato y variables de entorno, con prioridad flexible.

env_config(filename)

Carga un archivo de configuración extra (acepta .py, .toml, .yaml/.yml, .json, .txt). El archivo se usará como fuente prioritaria tras el entorno.

Uso:

from jania import env, env_config
env_config('settings.toml')

Parámetro:

  • filename: Ruta al archivo de configuración.

env(key, fallback=None)

Busca el valor de una clave de configuración (str) siguiendo este orden:

  1. Variable de entorno
  2. Config cargado por env_config()
  3. config.py
  4. settings.toml
  5. settings.yaml
  6. fallback (valor por defecto)

Uso:

valor = env('API_KEY', fallback='1234')

Devuelve:

  • Valor de la clave (str) o fallback si no se encuentra.

3. Extracción y análisis de PDF con LLM: extractPDF

Convierte cada página de un PDF a imagen y consulta un modelo LLM Vision (por defecto: gpt-4-vision-preview) para analizarlo.

Uso típico:

from jania import extractPDF
with open('documento.pdf', 'rb') as f:
    respuesta = extractPDF(
        prompt='Resume el documento:',
        archivo=f,
        nombre_archivo='documento.pdf',
        model='gpt-4-vision-preview',  # opcional
        max_images=10,                 # opcional
        openai_api_key=None            # opcional
    )

Parámetros:

  • prompt: (str) Instrucción para el LLM.
  • archivo: (BinaryIO) Archivo PDF abierto en modo binario.
  • nombre_archivo: (str) Nombre del archivo (para almacenamiento temporal).
  • model: (str, opcional) Modelo de OpenAI Vision a usar. Default: "gpt-4-vision-preview".
  • max_images: (int, opcional) Número máximo de páginas/imágenes a procesar. Default: 10.
  • openai_api_key: (str, opcional) API Key de OpenAI. Si no se da, se busca en configuración/env.

Devuelve:

  • Diccionario con la respuesta del LLM bajo la clave respuesta_llm.

Notas:

  • Requiere la librería openai y una API Key válida.
  • Si no tienes la clave, colócala en una variable de entorno OPENAI_API_KEY o config compatible.

Ejemplo de uso general

from jania import env, env_config
from jania import cleanJSON
from jania import extractPDF

# Configuración
env_config('settings.toml')
clave = env('OPENAI_API_KEY')

# Limpieza de JSON
json_str = cleanJSON('Responde en json: {"x":1, "y":true, "z":null}')

# Análisis de PDF
with open('ejemplo.pdf', 'rb') as f:
    resultado = extractPDF('Describe cada página', f, 'ejemplo.pdf', openai_api_key=clave)
    print(resultado['respuesta_llm'])

Licencia

MIT

Autor

Julian Ania

NOTES

git tag -a v0.3.1 -m "Release v0.3.1"
git push origin  v0.3.1

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jania-0.3.4.tar.gz (5.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

jania-0.3.4-py3-none-any.whl (6.6 kB view details)

Uploaded Python 3

File details

Details for the file jania-0.3.4.tar.gz.

File metadata

  • Download URL: jania-0.3.4.tar.gz
  • Upload date:
  • Size: 5.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for jania-0.3.4.tar.gz
Algorithm Hash digest
SHA256 048e486c69c734dfafc3e8f89169abbae04a1d3979d2ac3afddb241675aa39c7
MD5 14496318b6f8ee45c1ea728481f938eb
BLAKE2b-256 5d334678266fc57b1dbe7fcd1a7aa6cfca818921f3c1af671d0fad1c681da000

See more details on using hashes here.

Provenance

The following attestation bundles were made for jania-0.3.4.tar.gz:

Publisher: publish.yml on julianin/JANIALIB

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file jania-0.3.4-py3-none-any.whl.

File metadata

  • Download URL: jania-0.3.4-py3-none-any.whl
  • Upload date:
  • Size: 6.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for jania-0.3.4-py3-none-any.whl
Algorithm Hash digest
SHA256 78249f6666ed3071decd0ad22786a3a7afd4be0d359a5d1d74c2712a7a300b4f
MD5 d54c3ec65df8d34a7680778a0fba8f17
BLAKE2b-256 e2c1d827947c4dd53b6d9b8fd6b92d698852937b22f968408d12c8aa53f2c2d1

See more details on using hashes here.

Provenance

The following attestation bundles were made for jania-0.3.4-py3-none-any.whl:

Publisher: publish.yml on julianin/JANIALIB

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page