61 lines
3.1 KiB
Python
61 lines
3.1 KiB
Python
#!/usr/bin/env python3
|
|
import json, re, subprocess
|
|
from pathlib import Path
|
|
import psycopg2
|
|
|
|
PASS = Path("/root/.pg-superuser-pass").read_text().strip()
|
|
GEMINI = Path("/root/.gemini-key").read_text().strip()
|
|
VPS = "root@193.233.210.184"
|
|
PACKET = json.loads(Path("/root/buryan-infra/ops/audit/arena_packet.json").read_text(encoding="utf-8"))
|
|
PROMPT = """Ты независимый аудитор Buryans Hub. Не выдумывай сервисы, метрики и владельцев.
|
|
Ниже evidence-пакет. Предложи 6 возможностей развития с максимальной пользой.
|
|
Для каждой: title, capability (key), hypothesis, impact 1-5, effort 1-5, risk 1-5,
|
|
first_step, evidence (конкретный факт/сервис из пакета). Верни ТОЛЬКО JSON:
|
|
{"opportunities":[...]}.
|
|
PACKET:
|
|
%s
|
|
""" % json.dumps(PACKET, ensure_ascii=False)[:9000]
|
|
|
|
def json_from_text(text):
|
|
t = str(text or "").strip()
|
|
t = re.sub(r"^```(?:json)?", "", t, flags=re.I).strip()
|
|
t = re.sub(r"```$", "", t).strip()
|
|
try:
|
|
return json.loads(t)
|
|
except Exception:
|
|
i, j = t.find("{"), t.rfind("}")
|
|
if i >= 0 and j > i:
|
|
return json.loads(t[i:j+1])
|
|
raise
|
|
|
|
def ask_gemini():
|
|
body = json.dumps({"contents": [{"parts": [{"text": PROMPT}]}],
|
|
"generationConfig": {"temperature": 0.3, "maxOutputTokens": 1400}})
|
|
subprocess.run(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", VPS,
|
|
"umask 077; cat > /tmp/.audit-gemini-key"], input=GEMINI, text=True, timeout=20, check=True)
|
|
remote = ("KEY=$(cat /tmp/.audit-gemini-key); "
|
|
"curl -sS --max-time 180 -X POST -H 'Content-Type: application/json' -d @- "
|
|
"'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$KEY'; "
|
|
"rm -f /tmp/.audit-gemini-key")
|
|
p = subprocess.run(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", VPS, remote],
|
|
input=body, text=True, capture_output=True, timeout=220)
|
|
if p.returncode != 0:
|
|
raise RuntimeError((p.stderr or "gemini ssh error")[:300])
|
|
d = json.loads(p.stdout)
|
|
raw = d.get("candidates", [{}])[0].get("content", {}).get("parts", [{}])[0].get("text") or "{}"
|
|
return json_from_text(raw).get("opportunities") or [], raw
|
|
|
|
conn = psycopg2.connect(host="192.168.1.151", dbname="rag", user="postgres", password=PASS, client_encoding="UTF8")
|
|
cur = conn.cursor()
|
|
cur.execute("select id from audit.arena_runs where status='packet' order by id desc limit 1")
|
|
run_id = cur.fetchone()[0]
|
|
cur.execute("select 1 from audit.arena_answers where arena_run_id=%s and voice='gemini-flash'", (run_id,))
|
|
if cur.fetchone():
|
|
print("gemini already exists"); raise SystemExit(0)
|
|
items, raw = ask_gemini()
|
|
cur.execute("insert into audit.arena_answers(arena_run_id,voice,model,role,answer,raw) values(%s,%s,%s,%s,%s,%s)",
|
|
(run_id, "gemini-flash", "gemini-2.5-flash", "Независимый аудитор, стратегия", json.dumps(items, ensure_ascii=False), raw[:30000]))
|
|
conn.commit()
|
|
print("gemini items", len(items))
|
|
cur.close(); conn.close()
|