-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
168 lines (143 loc) · 6.98 KB
/
main.py
File metadata and controls
168 lines (143 loc) · 6.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# Proyecto: Content Processor
# Script: Script principal
# Autor: Eduardo Llaguno Velasco
# Versión: 4.82
# Fecha: 2024-10-09
import asyncio
import argparse
import logging
import traceback
import json
import sys
from pathlib import Path
# Añadir el directorio src al Python path
src_path = Path(__file__).parent / 'src'
sys.path.append(str(src_path))
from src.utils.architecture_utils import setup_environment, is_arm_architecture
from src.utils.nextcloud_utils import scan_nextcloud_files, create_directory_structure
from src.utils.logging_utils import setup_logging, get_logger
from src.utils.config_utils import load_config
from src.utils.lock_utils import acquire_lock, release_lock, is_process_running
def get_parser():
parser = argparse.ArgumentParser(
description="Procesador de contenido de Nextcloud",
epilog="Para más información, consulte la documentación del proyecto.",
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument("--analyze", action="store_true", help="Ejecutar análisis de documentos")
parser.add_argument("--analyze-mpp", action="store_true", help="Ejecutar análisis de archivos MPP")
parser.add_argument("--transcribe", action="store_true", help="Ejecutar transcripción de audio")
parser.add_argument("--ocr", action="store_true", help="Ejecutar procesamiento OCR")
parser.add_argument("--generate-article", action="store_true", help="Generar artículo de WordPress")
parser.add_argument("--generate-news", action="store_true", help="Generar noticias de WordPress")
parser.add_argument("--tema", type=str, help="Tema específico para el artículo (solo con --generate-article)")
parser.add_argument("--sitio", type=str, choices=["pruebas", "sesolibre"], default="pruebas",
help="Sitio WordPress de destino (pruebas o sesolibre)")
parser.add_argument("--prompt", type=str, default="default",
help="Tipo de prompt para el análisis de documentos")
return parser
async def run_process(process_name, function_name, *args, **kwargs):
logger = get_logger(__name__)
if is_process_running(process_name):
logger.warning(f"Ya se está ejecutando un proceso de {process_name}. Saltando...")
return None
lock = acquire_lock(process_name)
if lock is None:
logger.error(f"No se pudo adquirir el bloqueo para {process_name}. Saltando...")
return None
try:
module_mapping = {
"analyze_documents": ("document_analyzer", "run"),
"run_mpp_analysis": ("mpp_analyzer", "run_mpp_analysis"),
"transcribe_audio": ("audio_transcriber", "run"),
"transcribe_audio_vosk": ("audio_transcriber_vosk", "run"),
"transcribe_audio_whispercpp": ("audio_transcriber_whispercpp", "run"),
"process_ocr": ("ocr_processor", "run"),
"generate_article": ("wordpress_article_generator", "run"),
"generate_news": ("wordpress_news_generator", "run")
}
module_name, real_function_name = module_mapping.get(function_name, (None, None))
if not module_name or not real_function_name:
raise ValueError(f"Función desconocida: {function_name}")
logger.info(f"Intentando ejecutar {function_name} desde el módulo {module_name}")
module = __import__(f"src.{module_name}", fromlist=[real_function_name])
function = getattr(module, real_function_name)
#logger.info(f"Ejecutando {function_name} con argumentos: {args}, {kwargs}")
if asyncio.iscoroutinefunction(function):
result = await function(*args, **kwargs)
else:
result = function(*args, **kwargs)
logger.info(f"Resultado de {function_name}: {result}")
return result
except Exception as e:
logger.error(f"Error durante {process_name}: {str(e)}")
logger.error(traceback.format_exc())
finally:
release_lock(process_name)
async def main():
setup_logging()
logger = get_logger(__name__)
parser = get_parser()
args = parser.parse_args()
try:
CONFIG = load_config()
create_directory_structure(CONFIG)
except Exception as e:
logger.error(f"Error al cargar la configuración o crear la estructura de directorios: {str(e)}")
return
env_config = setup_environment()
modified_paths = set()
processes = [
("analyze_mpp", "run_mpp_analysis", args.analyze_mpp, {}),
("ocr", "process_ocr", args.ocr, {}),
("generate_article", "generate_article", args.generate_article, {"tema": args.tema, "sitio": args.sitio}),
("generate_news", "generate_news", args.generate_news, {})
]
for process_name, function_name, should_run, extra_args in processes:
if should_run:
if process_name == "generate_article":
result = await run_process(process_name, function_name, **extra_args)
else:
result = await run_process(process_name, function_name, CONFIG, **extra_args)
if result:
modified_paths.update(result)
if args.analyze:
result = await run_process("analyze", "analyze_documents", CONFIG, prompt_type=args.prompt)
if result:
modified_paths.update(result)
if args.transcribe:
transcribe_engine = CONFIG['transcribe'].get('engine', 'auto')
is_arm = is_arm_architecture()
logger.info(f"Motor de transcripción seleccionado: {transcribe_engine}")
logger.info(f"¿Es arquitectura ARM?: {is_arm}")
if transcribe_engine == 'auto':
if CONFIG.get('use_whispercpp', False):
transcribe_function = "transcribe_audio_whispercpp"
elif is_arm or CONFIG.get('use_vosk', False):
transcribe_function = "transcribe_audio_vosk"
else:
transcribe_function = "transcribe_audio"
elif transcribe_engine == 'whisper':
transcribe_function = "transcribe_audio"
elif transcribe_engine == 'whispercpp':
transcribe_function = "transcribe_audio_whispercpp"
elif transcribe_engine == 'vosk':
transcribe_function = "transcribe_audio_vosk"
else:
logger.error(f"Motor de transcripción desconocido: {transcribe_engine}")
return
logger.info(f"Usando función de transcripción: {transcribe_function}")
transcribe_result = await run_process("transcribe", transcribe_function, CONFIG)
logger.info(f"Resultado de la transcripción: {transcribe_result}")
if transcribe_result:
modified_paths.update(transcribe_result)
if modified_paths:
try:
scan_nextcloud_files(CONFIG, modified_paths)
except Exception as e:
logger.error(f"Error scanning Nextcloud files: {str(e)}")
logger.error(traceback.format_exc())
else:
logger.info("No se detectaron cambios en los archivos de Nextcloud.")
if __name__ == "__main__":
asyncio.run(main())