{
"tool_response": {
"filePath": "\/var\/www\/migration\/content-pipeline\/src\/web_generate.py",
"oldString": "# Change to pipeline directory and add to path\nPIPELINE_PATH = \"\/var\/www\/scripts\/pipeline\"\nsys.path.insert(0, PIPELINE_PATH)",
"newString": "# Add current directory to path (portable)\nimport os\nPIPELINE_PATH = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, PIPELINE_PATH)",
"originalFile": "#!\/usr\/bin\/env python3\n\"\"\"\nWeb Content Generation Interface for KI-System\nCalled from PHP with command and parameters.\n\nUsage:\n python web_generate.py generate <order_id> [model] [collection] [limit]\n python web_generate.py critique <version_id> [model]\n python web_generate.py revise <version_id> [model]\n\"\"\"\n\nimport json\nimport sys\nfrom datetime import datetime\n\nimport mysql.connector\n\n# Change to pipeline directory and add to path\nPIPELINE_PATH = \"\/var\/www\/scripts\/pipeline\"\nsys.path.insert(0, PIPELINE_PATH)\n\nfrom config import DB_CONFIG\nfrom generate import generate_content, revise_content, run_critique_round\n\n# Max log lines to keep\nMAX_LOG_LINES = 50\n\n\ndef log_step(order_id: int, message: str, step: str | None = None) -> None:\n \"\"\"Append a log line and optionally update current step.\"\"\"\n timestamp = datetime.now().strftime(\"%H:%M:%S\")\n log_line = f\"[{timestamp}] {message}\"\n\n try:\n conn = mysql.connector.connect(**DB_CONFIG)\n cursor = conn.cursor()\n # Get current log\n cursor.execute(\"SELECT generation_log FROM content_orders WHERE id = %s\", (order_id,))\n row = cursor.fetchone()\n current_log = row[0] if row and row[0] else \"\"\n\n # Append new line, keep last N lines\n lines = current_log.split(\"\\n\") if current_log else []\n lines.append(log_line)\n if len(lines) > MAX_LOG_LINES:\n lines = lines[-MAX_LOG_LINES:]\n new_log = \"\\n\".join(lines)\n\n # Update DB\n if step:\n cursor.execute(\n \"UPDATE content_orders SET generation_log = %s, generation_step = %s, updated_at = NOW() WHERE id = %s\",\n (new_log, step, order_id),\n )\n else:\n cursor.execute(\n \"UPDATE content_orders SET generation_log = %s, updated_at = NOW() WHERE id = %s\",\n (new_log, order_id),\n )\n conn.commit()\n cursor.close()\n conn.close()\n except Exception as e:\n print(f\"Log update failed: {e}\", file=sys.stderr)\n\n\ndef update_generation_status(order_id: int, status: str, error: str | None = None) -> None:\n \"\"\"Update generation_status in content_orders table.\"\"\"\n try:\n conn = mysql.connector.connect(**DB_CONFIG)\n cursor = conn.cursor()\n if status == \"generating\":\n cursor.execute(\n \"UPDATE content_orders SET generation_status = %s, generation_started_at = NOW(), generation_log = NULL, updated_at = NOW() WHERE id = %s\",\n (status, order_id),\n )\n elif error:\n cursor.execute(\n \"UPDATE content_orders SET generation_status = %s, generation_error = %s, updated_at = NOW() WHERE id = %s\",\n (status, error, order_id),\n )\n else:\n cursor.execute(\n \"UPDATE content_orders SET generation_status = %s, generation_error = NULL, updated_at = NOW() WHERE id = %s\",\n (status, order_id),\n )\n conn.commit()\n cursor.close()\n conn.close()\n except Exception as e:\n print(f\"DB update failed: {e}\", file=sys.stderr)\n\n\ndef log_critique_step(order_id: int, message: str, step: str | None = None) -> None:\n \"\"\"Append a log line for critique and optionally update current step.\"\"\"\n timestamp = datetime.now().strftime(\"%H:%M:%S\")\n log_line = f\"[{timestamp}] {message}\"\n\n try:\n conn = mysql.connector.connect(**DB_CONFIG)\n cursor = conn.cursor()\n cursor.execute(\"SELECT critique_log FROM content_orders WHERE id = %s\", (order_id,))\n row = cursor.fetchone()\n current_log = row[0] if row and row[0] else \"\"\n\n lines = current_log.split(\"\\n\") if current_log else []\n lines.append(log_line)\n if len(lines) > MAX_LOG_LINES:\n lines = lines[-MAX_LOG_LINES:]\n new_log = \"\\n\".join(lines)\n\n if step:\n cursor.execute(\n \"UPDATE content_orders SET critique_log = %s, critique_step = %s, updated_at = NOW() WHERE id = %s\",\n (new_log, step, order_id),\n )\n else:\n cursor.execute(\n \"UPDATE content_orders SET critique_log = %s, updated_at = NOW() WHERE id = %s\",\n (new_log, order_id),\n )\n conn.commit()\n cursor.close()\n conn.close()\n except Exception as e:\n print(f\"Critique log update failed: {e}\", file=sys.stderr)\n\n\ndef update_critique_status(order_id: int, status: str, error: str | None = None) -> None:\n \"\"\"Update critique_status in content_orders table.\"\"\"\n try:\n conn = mysql.connector.connect(**DB_CONFIG)\n cursor = conn.cursor()\n if status == \"critiquing\":\n cursor.execute(\n \"UPDATE content_orders SET critique_status = %s, critique_started_at = NOW(), critique_log = NULL, updated_at = NOW() WHERE id = %s\",\n (status, order_id),\n )\n elif error:\n cursor.execute(\n \"UPDATE content_orders SET critique_status = %s, critique_error = %s, updated_at = NOW() WHERE id = %s\",\n (status, error, order_id),\n )\n else:\n cursor.execute(\n \"UPDATE content_orders SET critique_status = %s, critique_error = NULL, updated_at = NOW() WHERE id = %s\",\n (status, order_id),\n )\n conn.commit()\n cursor.close()\n conn.close()\n except Exception as e:\n print(f\"Critique DB update failed: {e}\", file=sys.stderr)\n\n\ndef main():\n \"\"\"Route CLI commands to content generation functions.\"\"\"\n if len(sys.argv) < 3:\n print(json.dumps({\"error\": \"Usage: web_generate.py <command> <id> [options]\"}))\n return\n\n command = sys.argv[1]\n entity_id = int(sys.argv[2])\n\n try:\n if command == \"generate\":\n model = sys.argv[3] if len(sys.argv) > 3 else \"anthropic\"\n collection = sys.argv[4] if len(sys.argv) > 4 else \"documents\"\n limit = int(sys.argv[5]) if len(sys.argv) > 5 else 5\n\n # Update status to generating\n update_generation_status(entity_id, \"generating\")\n\n # Log start\n model_display = model.replace(\"ollama:\", \"Ollama: \") if model.startswith(\"ollama:\") else f\"Claude ({model})\"\n log_step(entity_id, \"Starte Content-Generierung...\", \"init\")\n log_step(entity_id, f\"Modell: {model_display}\")\n log_step(entity_id, f\"Collection: {collection}, Kontext-Limit: {limit}\")\n\n # Log RAG search\n log_step(entity_id, \"Suche relevante Dokumente (RAG)...\", \"rag\")\n\n # Run generation with intermediate logging\n result = generate_content(order_id=entity_id, model=model, collection=collection, context_limit=limit)\n\n # Log result\n if result.get(\"error\"):\n log_step(entity_id, f\"Fehler: {result['error']}\", \"error\")\n update_generation_status(entity_id, \"failed\", result[\"error\"])\n else:\n sources = result.get(\"sources\", [])\n log_step(entity_id, f\"{len(sources)} Quellen gefunden\", \"sources\")\n for src in sources[:3]:\n log_step(entity_id, f\" - {src.get('source', 'Unbekannt')} ({int(src.get('score', 0) * 100)}%)\")\n\n log_step(entity_id, \"Generiere Content mit KI...\", \"llm\")\n log_step(entity_id, \"Content erfolgreich generiert!\", \"done\")\n log_step(entity_id, f\"Version {result.get('version_number', '?')} erstellt\")\n update_generation_status(entity_id, \"completed\")\n\n elif command == \"critique\":\n model = sys.argv[3] if len(sys.argv) > 3 else \"anthropic\"\n # order_id is passed as 5th argument for logging\n order_id = int(sys.argv[4]) if len(sys.argv) > 4 else None\n\n if order_id:\n # Async mode with live logging\n update_critique_status(order_id, \"critiquing\")\n log_critique_step(order_id, \"Starte Kritik-Runde...\", \"init\")\n model_display = (\n model.replace(\"ollama:\", \"Ollama: \") if model.startswith(\"ollama:\") else f\"Claude ({model})\"\n )\n log_critique_step(order_id, f\"Modell: {model_display}\")\n\n # Get critics list (filtered by selected_critics from order)\n log_critique_step(order_id, \"Lade Kritiker...\", \"critics\")\n\n try:\n from db import db\n\n db.connect()\n # Get selected_critics from order\n cursor = db.execute(\n \"SELECT selected_critics, quality_check FROM content_orders WHERE id = %s\", (order_id,)\n )\n order_row = cursor.fetchone()\n cursor.close()\n\n if not order_row or not order_row.get(\"quality_check\", False):\n log_critique_step(order_id, \"Qualitätsprüfung deaktiviert\", \"skipped\")\n db.disconnect()\n result = {\"success\": True, \"skipped\": True, \"message\": \"Qualitätsprüfung deaktiviert\"}\n print(json.dumps(result, ensure_ascii=False))\n return\n\n # Parse selected_critics\n selected_raw = order_row.get(\"selected_critics\")\n if selected_raw:\n import json as json_module\n\n selected_ids = (\n json_module.loads(selected_raw) if isinstance(selected_raw, str) else selected_raw\n )\n else:\n selected_ids = []\n\n # Get critics - filter by selected_critics if specified\n if selected_ids:\n placeholders = \", \".join([\"%s\"] * len(selec... [TRUNCATED-bd86d8e5b1f98dfc]",
"structuredPatch": [
{
"oldStart": 15,
"oldLines": 8,
"newStart": 15,
"newLines": 9,
"lines": [
" ",
" import mysql.connector",
" ",
"-# Change to pipeline directory and add to path",
"-PIPELINE_PATH = \"\/var\/www\/scripts\/pipeline\"",
"+# Add current directory to path (portable)",
"+import os",
"+PIPELINE_PATH = os.path.dirname(os.path.abspath(__file__))",
" sys.path.insert(0, PIPELINE_PATH)",
" ",
" from config import DB_CONFIG"
]
}
],
"userModified": false,
"replaceAll": false
}
}