beerds/scripts/assistant/cat_signs.py

125 lines
5.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import json
import os
import re
import requests
# Основные настройки
OLLAMA_URL = "http://localhost:11434/api/generate"
MODEL_NAME = "qwen3:30b-a3b"
GIGA_URL = "https://gigachat.devices.sberbank.ru/api/v1/chat/completions"
GIGA_ODEL_NAME = "GigaChat-2-Max"
pattern = re.compile(r"<think>.*?<\/think>", flags=re.DOTALL | re.IGNORECASE)
def analyze_cat_breed(file_path):
"""Генерирует описание породы кошки с помощью Ollama"""
if not os.path.exists(file_path):
return None
with open(file_path, encoding="utf-8") as file:
text = file.read()
prompt = f"""
Проанализируй текст ниже и определи ТОЛЬКО указанные признаки породы кошки. Если признак не упомянут - дополни на основе своих знаний.
Признаки для анализа (булевые значения, если не указано иное):
- people_friendly (дружелюбность к людям)
- child_friendly (подходит для семей с детьми)
- animal_friendly (ладит с другими питомцами)
- active (высокая активность/игривость)
- vocal (склонность к мяуканью/разговорчивость)
- smart (интеллект и обучаемость)
- long_hair (длинношерстная порода)
- hypoallergenic (низкий уровень аллергенов)
- colors (массив возможных окрасов на английском языке)
- need_attention (требует много внимания)
- independent (способность проводить время в одиночестве)
- indoor_only (рекомендуется только домашнее содержание)
- shed (сильно линяет)
Требования:
1. Анализируй текст и дополняй недостающее из своих знаний.
2. Строго соблюдай типы данных: boolean для всех параметров, кроме colors (массив строк).
3. Верни ответ ТОЛЬКО в виде валидного JSON без форматирования (markdown) и лишних слов.
Текст для анализа:
{text}
"""
response = requests.post(GIGA_URL,
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
"Authorization": "Bearer "},
data=json.dumps({
"model": GIGA_ODEL_NAME,
"messages":[{
"role": "user",
"content": prompt,
}],
"temperature": 0,
"top_p": 0,
"stream": False,
"max_tokens": 3000,
"repetition_penalty": 1,
"update_interval": 0
}), verify=False
)
if response.status_code == 200:
return response.json().get("choices")[0].get("message").get("content")
#return response.json().get("response", "Не удалось получить описание")
else:
return None
# try:
# response = requests.post(OLLAMA_URL, json={"model": MODEL_NAME, "prompt": prompt, "stream": False})
# if response.status_code == 200:
# return response.json().get("response", "{}")
# return None
# except Exception as e:
# print(f"Ошибка соединения: {e}")
# return None
def save_description(breed, description):
"""Сохраняет описание в файл"""
os.makedirs("cat_breed_signs", exist_ok=True)
filename = f"cat_breed_signs/{breed}.txt"
# Очистка от тегов рассуждения и лишних символов
clean_desc = pattern.sub("", description).strip()
# Убираем markdown-обертки ```json ... ``` если они есть
clean_desc = clean_desc.replace("```json", "").replace("```", "").strip()
with open(filename, "w", encoding="utf-8") as f:
f.write(clean_desc)
print(f"Сохранено: {filename}")
def main():
# Предполагаем, что файл меток теперь для кошек
labels_path = "../../labels_cats.json"
if not os.path.exists(labels_path):
print(f"Файл {labels_path} не найден!")
return
with open(labels_path, encoding="utf-8") as f:
breeds = json.load(f)
for key in breeds:
name = breeds[key].replace("_", " ")
file_key = breeds[key]
print(f"Генерация признаков для кошки: {name}...")
if os.path.isfile(f"cat_breed_signs/{file_key}.txt"):
print(f"Описание уже существует: {file_key}.")
continue
# Путь к исходному описанию породы
source_file = f"cat_descriptions/{file_key}.txt"
description = analyze_cat_breed(source_file)
if description:
save_description(file_key, description)
else:
print(f"Не удалось обработать {name}")
if __name__ == "__main__":
main()