Spaces:
Sleeping
Sleeping
Update api.py
Browse files
api.py
CHANGED
|
@@ -9,7 +9,7 @@ import chromadb
|
|
| 9 |
from sentence_transformers import SentenceTransformer
|
| 10 |
|
| 11 |
# --- КОНФИГУРАЦИЯ ---
|
| 12 |
-
|
| 13 |
BASE_URL = "https://api.deepseek.com"
|
| 14 |
TEMPLATES_DIR = "tagged_templates"
|
| 15 |
DOWNLOADS_DIR = "downloads"
|
|
@@ -19,63 +19,54 @@ DB_PATH = "./legal_db"
|
|
| 19 |
ZIP_PATH = "./legal_db.zip"
|
| 20 |
# --------------------
|
| 21 |
|
| 22 |
-
client = OpenAI(api_key=
|
| 23 |
|
| 24 |
# ==============================================================================
|
| 25 |
-
# 1. ИНИЦИАЛИЗАЦИЯ
|
| 26 |
# ==============================================================================
|
| 27 |
collection = None
|
| 28 |
encoder = None
|
| 29 |
|
| 30 |
-
print("⚙️ Инициализация нейросети и базы законов...")
|
| 31 |
-
|
| 32 |
-
# 1. Распаковка базы, если нужно
|
| 33 |
if not os.path.exists(DB_PATH) and os.path.exists(ZIP_PATH):
|
| 34 |
try:
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
z.extractall(".")
|
| 38 |
-
except Exception as e:
|
| 39 |
-
print(f"⚠️ Ошибка распаковки ZIP: {e}")
|
| 40 |
|
| 41 |
-
# 2. Подключение к ChromaDB
|
| 42 |
try:
|
| 43 |
encoder = SentenceTransformer('paraphrase-multilingual-mpnet-base-v2')
|
| 44 |
chroma_client = chromadb.PersistentClient(path=DB_PATH)
|
| 45 |
collection = chroma_client.get_collection(name="laws")
|
| 46 |
-
|
| 47 |
-
except Exception as e:
|
| 48 |
-
print(f"⚠️ База знаний НЕ подключена (буду отвечать без законов): {e}")
|
| 49 |
|
| 50 |
-
# ==============================================================================
|
| 51 |
-
# 2. ЗАГРУЗКА РЕСУРСОВ (ШАБЛОНЫ)
|
| 52 |
-
# ==============================================================================
|
| 53 |
try:
|
| 54 |
registry = json.load(open(REGISTRY_FILE, "r", encoding="utf-8"))
|
| 55 |
tags_db = json.load(open(TAGS_DB_FILE, "r", encoding="utf-8"))
|
| 56 |
clean_tags_db = {k: v for k, v in tags_db.items() if not k.startswith("_")}
|
| 57 |
-
|
| 58 |
-
except Exception as e:
|
| 59 |
-
print(f"❌ КРИТИЧЕСКАЯ ОШИБКА: Не найдены файлы реестра! {e}")
|
| 60 |
registry = []
|
| 61 |
clean_tags_db = {}
|
| 62 |
|
| 63 |
-
|
| 64 |
# ==============================================================================
|
| 65 |
-
#
|
| 66 |
# ==============================================================================
|
| 67 |
|
| 68 |
async def select_best_template(user_query):
|
| 69 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 70 |
docs_list = ""
|
| 71 |
for idx, item in enumerate(registry):
|
| 72 |
-
|
|
|
|
| 73 |
|
| 74 |
system_prompt = f"""
|
| 75 |
-
Ты
|
| 76 |
СПИСОК:
|
| 77 |
{docs_list}
|
| 78 |
-
|
|
|
|
|
|
|
| 79 |
"""
|
| 80 |
try:
|
| 81 |
response = client.chat.completions.create(
|
|
@@ -88,19 +79,48 @@ async def select_best_template(user_query):
|
|
| 88 |
temperature=0.0
|
| 89 |
)
|
| 90 |
result = json_repair.loads(response.choices[0].message.content)
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
except Exception as e:
|
| 93 |
-
print(f"⚠️
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
async def extract_data_from_chat(user_query, filename):
|
| 97 |
-
"
|
| 98 |
-
system_prompt = "Извлеки данные в JSON по схеме:\n"
|
| 99 |
for key, val in clean_tags_db.items():
|
| 100 |
system_prompt += f"- {val['tag']}: {val['description']}\n"
|
| 101 |
|
| 102 |
-
system_prompt += "\nДаты в формате dd.mm.yyyy. Клиент={{ client_name }}, Контрагент={{ opponent_name }}."
|
| 103 |
-
|
| 104 |
try:
|
| 105 |
response = client.chat.completions.create(
|
| 106 |
model="deepseek-chat",
|
|
@@ -116,80 +136,63 @@ async def extract_data_from_chat(user_query, filename):
|
|
| 116 |
return {}
|
| 117 |
|
| 118 |
async def consult_logic(user_text):
|
| 119 |
-
|
| 120 |
-
КОНСУЛЬТАЦИЯ С ИСПОЛЬЗОВАНИЕМ БАЗЫ ЗАКОНОВ (RAG)
|
| 121 |
-
"""
|
| 122 |
context = ""
|
| 123 |
-
|
| 124 |
-
# 1. Поиск в базе (если она жива)
|
| 125 |
if collection and encoder:
|
| 126 |
try:
|
| 127 |
vec = encoder.encode(user_text).tolist()
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
for i, doc_text in enumerate(results['documents'][0]):
|
| 133 |
-
source = results['metadatas'][0][i].get('title', 'Закон')
|
| 134 |
-
context += f"--- {source} ---\n{doc_text[:1500]}\n\n"
|
| 135 |
-
except Exception as e:
|
| 136 |
-
print(f"⚠️ Ошибка поиска в Chroma: {e}")
|
| 137 |
-
|
| 138 |
-
# 2. Запрос к LLM
|
| 139 |
-
system_prompt = "Ты — профессиональный юрист РФ. Отвечай точно, ссылайся на законы (если они даны в контексте)."
|
| 140 |
-
if not context:
|
| 141 |
-
system_prompt += " База законов недоступна, отвечай, опираясь на общие знания."
|
| 142 |
|
|
|
|
| 143 |
try:
|
| 144 |
-
|
| 145 |
model="deepseek-chat",
|
| 146 |
-
messages=[
|
| 147 |
-
{"role": "system", "content": system_prompt},
|
| 148 |
-
{"role": "user", "content": f"ВОПРОС: {user_text}\n\n{context}"}
|
| 149 |
-
],
|
| 150 |
temperature=0.3
|
| 151 |
)
|
| 152 |
-
return {"type": "text", "content":
|
| 153 |
except Exception as e:
|
| 154 |
-
return {"type": "text", "content": f"Ошибка
|
| 155 |
|
| 156 |
async def generate_doc_logic(user_text):
|
| 157 |
-
|
| 158 |
-
if not user_text or len(user_text) < 5:
|
| 159 |
-
return {"type": "text", "content": "Опишите подробнее."}
|
| 160 |
-
|
| 161 |
best_filename = await select_best_template(user_text)
|
| 162 |
|
|
|
|
| 163 |
if not best_filename:
|
| 164 |
-
|
| 165 |
-
|
|
|
|
|
|
|
| 166 |
|
|
|
|
| 167 |
template_path = os.path.join(TEMPLATES_DIR, best_filename)
|
| 168 |
if not os.path.exists(template_path):
|
| 169 |
-
return {"type": "text", "content": f"
|
| 170 |
|
|
|
|
| 171 |
context = await extract_data_from_chat(user_text, best_filename)
|
| 172 |
-
if "doc_date" not in context:
|
| 173 |
-
context["doc_date"] = datetime.now().strftime("%d.%m.%Y")
|
| 174 |
|
| 175 |
try:
|
| 176 |
doc = DocxTemplate(template_path)
|
| 177 |
doc.render(context)
|
| 178 |
|
| 179 |
-
if not os.path.exists(DOWNLOADS_DIR):
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
output_path = os.path.join(DOWNLOADS_DIR, output_filename)
|
| 185 |
|
| 186 |
-
doc.save(
|
| 187 |
|
| 188 |
return {
|
| 189 |
"type": "file",
|
| 190 |
-
"content": f"✅ Документ
|
| 191 |
-
"file_url":
|
| 192 |
}
|
| 193 |
-
|
| 194 |
except Exception as e:
|
| 195 |
-
return {"type": "text", "content": f"Ошибка
|
|
|
|
| 9 |
from sentence_transformers import SentenceTransformer
|
| 10 |
|
| 11 |
# --- КОНФИГУРАЦИЯ ---
|
| 12 |
+
API_KEY = os.getenv("DEEPSEEK_API_KEY") # Или вставь свой ключ жестко "sk-..."
|
| 13 |
BASE_URL = "https://api.deepseek.com"
|
| 14 |
TEMPLATES_DIR = "tagged_templates"
|
| 15 |
DOWNLOADS_DIR = "downloads"
|
|
|
|
| 19 |
ZIP_PATH = "./legal_db.zip"
|
| 20 |
# --------------------
|
| 21 |
|
| 22 |
+
client = OpenAI(api_key=API_KEY, base_url=BASE_URL)
|
| 23 |
|
| 24 |
# ==============================================================================
|
| 25 |
+
# 1. ИНИЦИАЛИЗАЦИЯ
|
| 26 |
# ==============================================================================
|
| 27 |
collection = None
|
| 28 |
encoder = None
|
| 29 |
|
|
|
|
|
|
|
|
|
|
| 30 |
if not os.path.exists(DB_PATH) and os.path.exists(ZIP_PATH):
|
| 31 |
try:
|
| 32 |
+
with zipfile.ZipFile(ZIP_PATH, 'r') as z: z.extractall(".")
|
| 33 |
+
except: pass
|
|
|
|
|
|
|
|
|
|
| 34 |
|
|
|
|
| 35 |
try:
|
| 36 |
encoder = SentenceTransformer('paraphrase-multilingual-mpnet-base-v2')
|
| 37 |
chroma_client = chromadb.PersistentClient(path=DB_PATH)
|
| 38 |
collection = chroma_client.get_collection(name="laws")
|
| 39 |
+
except: pass
|
|
|
|
|
|
|
| 40 |
|
|
|
|
|
|
|
|
|
|
| 41 |
try:
|
| 42 |
registry = json.load(open(REGISTRY_FILE, "r", encoding="utf-8"))
|
| 43 |
tags_db = json.load(open(TAGS_DB_FILE, "r", encoding="utf-8"))
|
| 44 |
clean_tags_db = {k: v for k, v in tags_db.items() if not k.startswith("_")}
|
| 45 |
+
except:
|
|
|
|
|
|
|
| 46 |
registry = []
|
| 47 |
clean_tags_db = {}
|
| 48 |
|
|
|
|
| 49 |
# ==============================================================================
|
| 50 |
+
# 2. ЛОГИКА
|
| 51 |
# ==============================================================================
|
| 52 |
|
| 53 |
async def select_best_template(user_query):
|
| 54 |
+
"""
|
| 55 |
+
Гибридный поиск: Сначала ИИ, потом перебор ключевых слов.
|
| 56 |
+
"""
|
| 57 |
+
# 1. Попытка через ИИ
|
| 58 |
docs_list = ""
|
| 59 |
for idx, item in enumerate(registry):
|
| 60 |
+
# Ограничиваем длину списка, чтобы не забить контекст
|
| 61 |
+
docs_list += f"{idx}. {item['filename']} ({item['description'][:100]}...)\n"
|
| 62 |
|
| 63 |
system_prompt = f"""
|
| 64 |
+
Ты библиотекарь. Твоя цель - найти имя файла из списка, которое лучше всего подходит к запросу.
|
| 65 |
СПИСОК:
|
| 66 |
{docs_list}
|
| 67 |
+
|
| 68 |
+
ВЕРНИ ТОЛЬКО JSON: {{"filename": "имя_файла.docx"}}
|
| 69 |
+
ЕСЛИ НИЧЕГО НЕ ПОДХОДИТ, ВЕРНИ: {{"filename": null}}
|
| 70 |
"""
|
| 71 |
try:
|
| 72 |
response = client.chat.completions.create(
|
|
|
|
| 79 |
temperature=0.0
|
| 80 |
)
|
| 81 |
result = json_repair.loads(response.choices[0].message.content)
|
| 82 |
+
ai_choice = result.get("filename")
|
| 83 |
+
|
| 84 |
+
if ai_choice:
|
| 85 |
+
return ai_choice
|
| 86 |
+
|
| 87 |
except Exception as e:
|
| 88 |
+
print(f"⚠️ ИИ поиск не удался: {e}")
|
| 89 |
+
|
| 90 |
+
# 2. ФОЛЛБЭК: Тупой поиск по словам (Если ИИ не справился)
|
| 91 |
+
print("⚠️ ИИ не нашел шаблон. Запускаю поиск по ключевым словам...")
|
| 92 |
+
query_words = user_query.lower().replace(",", "").split()
|
| 93 |
+
# Убираем мусорные слова
|
| 94 |
+
stop_words = ["хочу", "мне", "нужен", "составь", "сделай", "договор", "бланк", "образец"]
|
| 95 |
+
keywords = [w for w in query_words if w not in stop_words and len(w) > 3]
|
| 96 |
+
|
| 97 |
+
if not keywords: return None
|
| 98 |
+
|
| 99 |
+
best_match = None
|
| 100 |
+
max_hits = 0
|
| 101 |
+
|
| 102 |
+
for item in registry:
|
| 103 |
+
hits = 0
|
| 104 |
+
fname = item['filename'].lower()
|
| 105 |
+
desc = item.get('description', '').lower()
|
| 106 |
+
|
| 107 |
+
for kw in keywords:
|
| 108 |
+
# Ищем совпадения корней (очень примитивно, но работает)
|
| 109 |
+
root = kw[:-2] if len(kw) > 5 else kw
|
| 110 |
+
if root in fname or root in desc:
|
| 111 |
+
hits += 1
|
| 112 |
+
|
| 113 |
+
if hits > max_hits:
|
| 114 |
+
max_hits = hits
|
| 115 |
+
best_match = item['filename']
|
| 116 |
+
|
| 117 |
+
return best_match
|
| 118 |
|
| 119 |
async def extract_data_from_chat(user_query, filename):
|
| 120 |
+
system_prompt = "Извлеки данные в JSON. Даты dd.mm.yyyy.\nСХЕМА:\n"
|
|
|
|
| 121 |
for key, val in clean_tags_db.items():
|
| 122 |
system_prompt += f"- {val['tag']}: {val['description']}\n"
|
| 123 |
|
|
|
|
|
|
|
| 124 |
try:
|
| 125 |
response = client.chat.completions.create(
|
| 126 |
model="deepseek-chat",
|
|
|
|
| 136 |
return {}
|
| 137 |
|
| 138 |
async def consult_logic(user_text):
|
| 139 |
+
# Логика консультации (если файл не найден)
|
|
|
|
|
|
|
| 140 |
context = ""
|
|
|
|
|
|
|
| 141 |
if collection and encoder:
|
| 142 |
try:
|
| 143 |
vec = encoder.encode(user_text).tolist()
|
| 144 |
+
res = collection.query(query_embeddings=[vec], n_results=3)
|
| 145 |
+
if res['documents'][0]:
|
| 146 |
+
for txt in res['documents'][0]: context += f"{txt[:1000]}\n...\n"
|
| 147 |
+
except: pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
+
sys_p = "Ты юрист. Отвечай, используя законы (если есть)."
|
| 150 |
try:
|
| 151 |
+
r = client.chat.completions.create(
|
| 152 |
model="deepseek-chat",
|
| 153 |
+
messages=[{"role":"system","content":sys_p}, {"role":"user","content":f"Вопрос: {user_text}\nКонтекст: {context}"}],
|
|
|
|
|
|
|
|
|
|
| 154 |
temperature=0.3
|
| 155 |
)
|
| 156 |
+
return {"type": "text", "content": r.choices[0].message.content}
|
| 157 |
except Exception as e:
|
| 158 |
+
return {"type": "text", "content": f"Ошибка: {e}"}
|
| 159 |
|
| 160 |
async def generate_doc_logic(user_text):
|
| 161 |
+
# 1. Ищем шаблон
|
|
|
|
|
|
|
|
|
|
| 162 |
best_filename = await select_best_template(user_text)
|
| 163 |
|
| 164 |
+
# ЕСЛИ ШАБЛОН НЕ НАЙДЕН — ВОЗВРАЩАЕМ ТЕКСТ (КОНСУЛЬТАЦИЮ)
|
| 165 |
if not best_filename:
|
| 166 |
+
fallback_res = await consult_logic(f"Составь текст документа: {user_text}")
|
| 167 |
+
# Добавляем приписку, почему так вышло
|
| 168 |
+
fallback_res["content"] = "⚠️ **Шаблон файла не найден в базе.**\nЯ составил текст документа вручную:\n\n" + fallback_res["content"]
|
| 169 |
+
return fallback_res
|
| 170 |
|
| 171 |
+
# 2. Проверяем файл на диске
|
| 172 |
template_path = os.path.join(TEMPLATES_DIR, best_filename)
|
| 173 |
if not os.path.exists(template_path):
|
| 174 |
+
return {"type": "text", "content": f"⚠️ Ошибка: Шаблон '{best_filename}' есть в реестре, но файл отсутствует на сервере."}
|
| 175 |
|
| 176 |
+
# 3. Извлекаем данные и заполняем
|
| 177 |
context = await extract_data_from_chat(user_text, best_filename)
|
| 178 |
+
if "doc_date" not in context: context["doc_date"] = datetime.now().strftime("%d.%m.%Y")
|
|
|
|
| 179 |
|
| 180 |
try:
|
| 181 |
doc = DocxTemplate(template_path)
|
| 182 |
doc.render(context)
|
| 183 |
|
| 184 |
+
if not os.path.exists(DOWNLOADS_DIR): os.makedirs(DOWNLOADS_DIR)
|
| 185 |
+
|
| 186 |
+
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 187 |
+
out_name = f"Ready_{best_filename.replace('.docx', '')[:20]}_{ts}.docx"
|
| 188 |
+
out_path = os.path.join(DOWNLOADS_DIR, out_name)
|
|
|
|
| 189 |
|
| 190 |
+
doc.save(out_path)
|
| 191 |
|
| 192 |
return {
|
| 193 |
"type": "file",
|
| 194 |
+
"content": f"✅ Документ сформирован на основе шаблона: **{best_filename}**",
|
| 195 |
+
"file_url": out_path
|
| 196 |
}
|
|
|
|
| 197 |
except Exception as e:
|
| 198 |
+
return {"type": "text", "content": f"Ошибка при заполнении: {e}"}
|