update front
This commit is contained in:
155
frontend/ui.py
155
frontend/ui.py
@@ -1,12 +1,14 @@
|
|||||||
import os
|
import os
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
import streamlit as st
|
import streamlit as st
|
||||||
|
import yaml
|
||||||
|
|
||||||
st.set_page_config(page_title="DevOps AI Assistant", page_icon="🚀")
|
st.set_page_config(page_title="DevOps AI Assistant", page_icon="🚀")
|
||||||
|
|
||||||
st.title("🤖 AI CI/CD Pipeline Generator")
|
st.title("DevOps AI Assistant")
|
||||||
st.markdown("Прототип сервиса для генерации и валидации конфигураций")
|
st.markdown("Веб-интерфейс для генерации и проверки CI/CD конфигураций.")
|
||||||
|
|
||||||
|
|
||||||
def _env(name: str, default: str) -> str:
|
def _env(name: str, default: str) -> str:
|
||||||
@@ -25,34 +27,133 @@ with st.sidebar:
|
|||||||
)
|
)
|
||||||
platform = st.radio("Платформа", ["PV DOT CI", "PV DOT CD", "DPM CI", "DPM CD"])
|
platform = st.radio("Платформа", ["PV DOT CI", "PV DOT CD", "DPM CI", "DPM CD"])
|
||||||
|
|
||||||
user_input = st.text_area(
|
if "history" not in st.session_state:
|
||||||
"Опишите пайплайн (например: 'Python app with pytest and docker build')", height=150
|
st.session_state.history = []
|
||||||
|
|
||||||
|
|
||||||
|
def _push_history(*, platform: str, model: str, prompt: str, status: str, config: str, error: str | None):
|
||||||
|
st.session_state.history.insert(
|
||||||
|
0,
|
||||||
|
{
|
||||||
|
"ts": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"),
|
||||||
|
"platform": platform,
|
||||||
|
"model": model,
|
||||||
|
"prompt": prompt,
|
||||||
|
"status": status,
|
||||||
|
"error": error,
|
||||||
|
"config": config,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
st.session_state.history = st.session_state.history[:50]
|
||||||
|
|
||||||
|
|
||||||
|
tab_overview, tab_generator, tab_validator, tab_history = st.tabs(
|
||||||
|
["Обзор", "Pipeline generator", "Проверка YAML", "История"]
|
||||||
)
|
)
|
||||||
|
|
||||||
if st.button("Сгенерировать конфигурацию", type="primary"):
|
with tab_overview:
|
||||||
if user_input:
|
st.subheader("Что умеет сервис")
|
||||||
with st.spinner("LLM думает..."):
|
st.markdown(
|
||||||
try:
|
"- **Pipeline generator**: генерирует YAML через backend (FastAPI → Ollama).\n"
|
||||||
res = requests.post(
|
"- **Проверка YAML**: локально проверяет синтаксис YAML, чтобы быстро править конфиг.\n"
|
||||||
api_url,
|
"- **История**: хранит последние результаты в рамках сессии браузера."
|
||||||
json={"description": user_input, "platform": platform, "model": model},
|
)
|
||||||
timeout=90,
|
st.divider()
|
||||||
)
|
st.caption(f"Backend URL: {api_url}")
|
||||||
res.raise_for_status()
|
|
||||||
data = res.json()
|
|
||||||
|
|
||||||
if data.get("status") == "ok":
|
with tab_generator:
|
||||||
st.success("✅ Конфигурация валидна!")
|
st.subheader("AI CI/CD Pipeline Generator")
|
||||||
st.code(data.get("config", ""), language="yaml")
|
user_input = st.text_area(
|
||||||
st.download_button(
|
"Опишите пайплайн (например: 'Python app with pytest and docker build')",
|
||||||
"Скачать .yml",
|
height=150,
|
||||||
data.get("config", ""),
|
key="generator_prompt",
|
||||||
file_name="pipeline.yml",
|
)
|
||||||
|
|
||||||
|
col_a, col_b = st.columns([1, 3])
|
||||||
|
with col_a:
|
||||||
|
generate_clicked = st.button("Сгенерировать конфигурацию", type="primary")
|
||||||
|
with col_b:
|
||||||
|
st.caption("Подсказка: чем конкретнее требования, тем валиднее YAML.")
|
||||||
|
|
||||||
|
if generate_clicked:
|
||||||
|
if user_input.strip():
|
||||||
|
with st.spinner("LLM думает..."):
|
||||||
|
try:
|
||||||
|
res = requests.post(
|
||||||
|
api_url,
|
||||||
|
json={"description": user_input, "platform": platform, "model": model},
|
||||||
|
timeout=90,
|
||||||
)
|
)
|
||||||
else:
|
res.raise_for_status()
|
||||||
st.error(f"❌ Ошибка валидации: {data.get('validation_error')}")
|
data = res.json()
|
||||||
st.code(data.get("config", ""), language="yaml")
|
|
||||||
|
status = data.get("status", "error")
|
||||||
|
config = data.get("config", "")
|
||||||
|
err = data.get("validation_error")
|
||||||
|
|
||||||
|
_push_history(
|
||||||
|
platform=platform,
|
||||||
|
model=model,
|
||||||
|
prompt=user_input,
|
||||||
|
status=status,
|
||||||
|
config=config,
|
||||||
|
error=err,
|
||||||
|
)
|
||||||
|
|
||||||
|
if status == "ok":
|
||||||
|
st.success("Конфигурация валидна.")
|
||||||
|
else:
|
||||||
|
st.error(f"Ошибка валидации: {err}")
|
||||||
|
|
||||||
|
st.code(config, language="yaml")
|
||||||
|
st.download_button("Скачать .yml", config, file_name="pipeline.yml")
|
||||||
|
except Exception as e:
|
||||||
|
st.error(f"Ошибка подключения к бекенду: {e}")
|
||||||
|
else:
|
||||||
|
st.warning("Пожалуйста, введите описание.")
|
||||||
|
|
||||||
|
with tab_validator:
|
||||||
|
st.subheader("Локальная проверка YAML")
|
||||||
|
yaml_text = st.text_area("Вставьте YAML для проверки", height=240, key="validator_yaml")
|
||||||
|
|
||||||
|
c1, c2 = st.columns([1, 1])
|
||||||
|
with c1:
|
||||||
|
validate_clicked = st.button("Проверить YAML")
|
||||||
|
with c2:
|
||||||
|
if st.button("Вставить последний результат", disabled=(len(st.session_state.history) == 0)):
|
||||||
|
st.session_state.validator_yaml = (st.session_state.history[0].get("config") or "")
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
if validate_clicked:
|
||||||
|
if yaml_text.strip():
|
||||||
|
try:
|
||||||
|
yaml.safe_load(yaml_text)
|
||||||
|
st.success("YAML синтаксически валиден.")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
st.error(f"Ошибка подключения к бекенду: {e}")
|
st.error(f"Ошибка YAML: {e}")
|
||||||
|
else:
|
||||||
|
st.warning("Вставьте YAML.")
|
||||||
|
|
||||||
|
with tab_history:
|
||||||
|
st.subheader("История (последние 50)")
|
||||||
|
|
||||||
|
if not st.session_state.history:
|
||||||
|
st.info("Пока пусто. Сгенерируйте конфигурацию во вкладке Pipeline generator.")
|
||||||
else:
|
else:
|
||||||
st.warning("Пожалуйста, введите описание.")
|
if st.button("Очистить историю"):
|
||||||
|
st.session_state.history = []
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
for idx, item in enumerate(st.session_state.history):
|
||||||
|
title = f"[{item['ts']}] {item['platform']} · {item['model']} · {item['status']}"
|
||||||
|
with st.expander(title, expanded=(idx == 0)):
|
||||||
|
st.caption(item.get("prompt", ""))
|
||||||
|
if item.get("error"):
|
||||||
|
st.error(f"Validation error: {item['error']}")
|
||||||
|
st.code(item.get("config", ""), language="yaml")
|
||||||
|
st.download_button(
|
||||||
|
"Скачать .yml",
|
||||||
|
item.get("config", ""),
|
||||||
|
file_name=f"pipeline-{idx+1}.yml",
|
||||||
|
key=f"download_{idx}",
|
||||||
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user