Вот полная реализация движка автодополнения с н-граммами:
1. Схема базы данных SQLite
-- schema.sql
CREATE TABLE IF NOT EXISTS ngrams (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ngram TEXT NOT NULL,
type INTEGER NOT NULL, -- 2 для биграмм, 3 для триграмм, и т.д.
frequency INTEGER DEFAULT 1,
context TEXT, -- контекст использования
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_ngram_type ON ngrams(ngram, type);
CREATE INDEX idx_frequency ON ngrams(frequency DESC);
CREATE TABLE IF NOT EXISTS completions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
prefix TEXT NOT NULL,
completion TEXT NOT NULL,
score REAL NOT NULL,
frequency INTEGER DEFAULT 1,
last_used DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_prefix ON completions(prefix);
CREATE INDEX idx_score ON completions(score DESC);
2. Backend на Node.js
// server.js
const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const cors = require('cors');
const path = require('path');
const app = express();
const PORT = 3000;
app.use(cors());
app.use(express.json());
// Инициализация базы данных
const db = new sqlite3.Database('./autocomplete.db');
// Инициализация схемы
const fs = require('fs');
const schema = fs.readFileSync('./schema.sql', 'utf8');
db.exec(schema);
class NgramProcessor {
static generateNgrams(text, n) {
const words = text.toLowerCase().split(/\s+/).filter(word => word.length > 0);
const ngrams = [];
for (let i = 0; i <= words.length - n; i++) {
ngrams.push(words.slice(i, i + n).join(' '));
}
return ngrams;
}
static async saveNgrams(text, context = '') {
return new Promise((resolve, reject) => {
db.serialize(() => {
const stmt = db.prepare(`
INSERT OR REPLACE INTO ngrams (ngram, type, frequency, context, updated_at)
VALUES (?, ?, COALESCE((SELECT frequency FROM ngrams WHERE ngram = ? AND type = ?) + 1, 1), ?, CURRENT_TIMESTAMP)
`);
// Сохраняем биграммы, триграммы и 4-граммы
for (let n = 2; n <= 4; n++) {
const ngrams = this.generateNgrams(text, n);
ngrams.forEach(ngram => {
stmt.run([ngram, n, ngram, n, context]);
});
}
stmt.finalize(resolve);
});
});
}
static async getCompletions(prefix, limit = 10) {
return new Promise((resolve, reject) => {
const query = `
SELECT DISTINCT
SUBSTR(ngram, LENGTH(?) + 2) as completion,
frequency,
type,
(frequency * 1.0 / type) as score
FROM ngrams
WHERE ngram LIKE ? || ' %'
ORDER BY score DESC, frequency DESC
LIMIT ?
`;
db.all(query, [prefix, prefix, limit], (err, rows) => {
if (err) reject(err);
else resolve(rows);
});
});
}
static async updateCompletionUsage(prefix, completion) {
return new Promise((resolve, reject) => {
const stmt = db.prepare(`
INSERT OR REPLACE INTO completions (prefix, completion, score, frequency, last_used)
VALUES (?, ?, COALESCE((SELECT score FROM completions WHERE prefix = ? AND completion = ?) + 0.1, 1),
COALESCE((SELECT frequency FROM completions WHERE prefix = ? AND completion = ?) + 1, 1),
CURRENT_TIMESTAMP)
`);
stmt.run([prefix, completion, prefix, completion, prefix, completion], function(err) {
if (err) reject(err);
else resolve(this.lastID);
});
stmt.finalize();
});
}
}
// API endpoints
app.post('/api/train', async (req, res) => {
try {
const { text, context } = req.body;
await NgramProcessor.saveNgrams(text, context || '');
res.json({ success: true, message: 'Текст обработан и сохранен' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/complete', async (req, res) => {
try {
const { prefix, limit } = req.query;
if (!prefix) {
return res.status(400).json({ error: 'Префикс обязателен' });
}
const completions = await NgramProcessor.getCompletions(prefix, parseInt(limit) || 10);
res.json({ completions });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/usage', async (req, res) => {
try {
const { prefix, completion } = req.body;
await NgramProcessor.updateCompletionUsage(prefix, completion);
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(PORT, () => {
console.log(`Сервер запущен на порту ${PORT}`);
});
3. Vue.js 3 компонент автодополнения
<!-- AutoComplete.vue -->
<template>
<div class="autocomplete-container">
<input
ref="inputRef"
v-model="inputValue"
@input="handleInput"
@keydown="handleKeydown"
@blur="handleBlur"
:placeholder="placeholder"
class="autocomplete-input"
/>
<div
v-if="showSuggestions && suggestions.length > 0"
class="suggestions-dropdown"
>
<div
v-for="(suggestion, index) in suggestions"
:key="index"
:class="['suggestion-item', { active: index === selectedIndex }]"
@click="selectSuggestion(suggestion)"
@mouseenter="selectedIndex = index"
>
<span class="suggestion-text">{{ suggestion.completion }}</span>
<span class="suggestion-score">{{ Math.round(suggestion.score * 100) }}%</span>
</div>
</div>
</div>
</template>
<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
const props = defineProps({
placeholder: {
type: String,
default: 'Начните вводить текст...'
},
minLength: {
type: Number,
default: 2
},
maxSuggestions: {
type: Number,
default: 5
}
})
const emit = defineEmits(['select', 'input'])
const inputRef = ref(null)
const inputValue = ref('')
const suggestions = ref([])
const showSuggestions = ref(false)
const selectedIndex = ref(-1)
const isLoading = ref(false)
const API_BASE = 'http://localhost:3000/api'
class AutoCompleteEngine {
static async getCompletions(prefix, limit = 10) {
try {
const response = await fetch(`${API_BASE}/complete?prefix=${encodeURIComponent(prefix)}&limit=${limit}`)
const data = await response.json()
return data.completions || []
} catch (error) {
console.error('Ошибка получения предложений:', error)
return []
}
}
static async recordUsage(prefix, completion) {
try {
await fetch(`${API_BASE}/usage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prefix, completion })
})
} catch (error) {
console.error('Ошибка записи использования:', error)
}
}
static async trainModel(text, context = '') {
try {
await fetch(`${API_BASE}/train`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text, context })
})
} catch (error) {
console.error('Ошибка обучения модели:', error)
}
}
}
const debounce = (func, wait) => {
let timeout
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout)
func(...args)
}
clearTimeout(timeout)
timeout = setTimeout(later, wait)
}
}
const fetchSuggestions = debounce(async (value) => {
if (value.length < props.minLength) {
suggestions.value = []
showSuggestions.value = false
return
}
isLoading.value = true
const words = value.split(' ')
const prefix = words.slice(-2).join(' ').toLowerCase() // Используем последние 2 слова как префикс
try {
const results = await AutoCompleteEngine.getCompletions(prefix, props.maxSuggestions)
suggestions.value = results
showSuggestions.value = results.length > 0
selectedIndex.value = -1
} catch (error) {
console.error('Ошибка загрузки предложений:', error)
} finally {
isLoading.value = false
}
}, 300)
const handleInput = (event) => {
const value = event.target.value
inputValue.value = value
emit('input', value)
fetchSuggestions(value)
}
const handleKeydown = async (event) => {
if (!showSuggestions.value) return
switch (event.key) {
case 'ArrowDown':
event.preventDefault()
selectedIndex.value = Math.min(selectedIndex.value + 1, suggestions.value.length - 1)
break
case 'ArrowUp':
event.preventDefault()
selectedIndex.value = Math.max(selectedIndex.value - 1, -1)
break
case 'Enter':
event.preventDefault()
if (selectedIndex.value >= 0) {
await selectSuggestion(suggestions.value[selectedIndex.value])
}
break
case 'Escape':
showSuggestions.value = false
selectedIndex.value = -1
break
}
}
const selectSuggestion = async (suggestion) => {
const words = inputValue.value.split(' ')
const prefix = words.slice(-2).join(' ').toLowerCase()
// Заменяем последнее слово на выбранное предложение
words[words.length - 1] = suggestion.completion
const newValue = words.join(' ')
inputValue.value = newValue
showSuggestions.value = false
selectedIndex.value = -1
// Записываем использование для улучшения модели
await AutoCompleteEngine.recordUsage(prefix, suggestion.completion)
emit('select', { suggestion, fullText: newValue })
// Фокусируемся обратно на input
await nextTick()
inputRef.value?.focus()
}
const handleBlur = () => {
// Задержка, чтобы клик по предложению успел сработать
setTimeout(() => {
showSuggestions.value = false
}, 150)
}
// Публичные методы для обучения модели
const trainModel = (text, context) => {
return AutoCompleteEngine.trainModel(text, context)
}
defineExpose({
trainModel,
focus: () => inputRef.value?.focus(),
clear: () => {
inputValue.value = ''
suggestions.value = []
showSuggestions.value = false
}
})
</script>
<style scoped>
.autocomplete-container {
position: relative;
width: 100%;
}
.autocomplete-input {
width: 100%;
padding: 12px 16px;
border: 2px solid #e1e5e9;
border-radius: 8px;
font-size: 16px;
outline: none;
transition: border-color 0.2s ease;
}
.autocomplete-input:focus {
border-color: #4f46e5;
}
.suggestions-dropdown {
position: absolute;
top: 100%;
left: 0;
right: 0;
background: white;
border: 1px solid #e1e5e9;
border-top: none;
border-radius: 0 0 8px 8px;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
max-height: 200px;
overflow-y: auto;
z-index: 1000;
}
.suggestion-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 16px;
cursor: pointer;
transition: background-color 0.15s ease;
}
.suggestion-item:hover,
.suggestion-item.active {
background-color: #f3f4f6;
}
.suggestion-text {
font-size: 16px;
color: #374151;
}
.suggestion-score {
font-size: 12px;
color: #6b7280;
font-weight: 500;
}
</style>
4. Manifest для Chrome расширения
{
"manifest_version": 3,
"name": "Smart AutoComplete",
"version": "1.0.0",
"description": "Интеллектуальное автодополнение с использованием н-грамм",
"permissions": [
"activeTab",
"storage",
"scripting"
],
"host_permissions": [
"http://localhost:3000/*"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"css": ["styles.css"]
}
],
"action": {
"default_popup": "popup.html",
"default_title": "Smart AutoComplete"
}
}
5. Content Script для внедрения автодополнения
// content.js
class ContentAutoComplete {
constructor() {
this.isEnabled = true
this.currentInput = null
this.init()
}
init() {
this.injectStyles()
this.attachToInputs()
this.observeNewInputs()
}
injectStyles() {
if (document.getElementById('autocomplete-styles')) return
const styles = `
.smart-autocomplete-container {
position: relative !important;
}
.smart-autocomplete-suggestions {
position: absolute !important;
top: 100% !important;
left: 0 !important;
right: 0 !important;
background: white !important;
border: 1px solid #ccc !important;
border-radius: 4px !important;
box-shadow: 0 2px 8px rgba(0,0,0,0.1) !important;
z-index: 10000 !important;
max-height: 200px !important;
overflow-y: auto !important;
}
.smart-autocomplete-item {
padding: 8px 12px !important;
cursor: pointer !important;
border-bottom: 1px solid #eee !important;
}
.smart-autocomplete-item:hover,
.smart-autocomplete-item.selected {
background-color: #f0f0f0 !important;
}
`
const styleSheet = document.createElement('style')
styleSheet.id = 'autocomplete-styles'
styleSheet.textContent = styles
document.head.appendChild(styleSheet)
}
attachToInputs() {
const inputs = document.querySelectorAll('input[type="text"], input[type="search"], textarea')
inputs.forEach(input => this.enhanceInput(input))
}
observeNewInputs() {
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
const inputs = node.querySelectorAll ?
node.querySelectorAll('input[type="text"], input[type="search"], textarea') : []
inputs.forEach(input => this.enhanceInput(input))
}
})
})
})
observer.observe(document.body, {
childList: true,
subtree: true
})
}
enhanceInput(input) {
if (input.dataset.smartAutocomplete) return
input.dataset.smartAutocomplete = 'true'
const container = document.createElement('div')
container.className = 'smart-autocomplete-container'
input.parentNode.insertBefore(container, input)
container.appendChild(input)
let suggestions = []
let selectedIndex = -1
let suggestionsEl = null
const showSuggestions = (items) => {
hideSuggestions()
if (items.length === 0) return
suggestionsEl = document.createElement('div')
suggestionsEl.className = 'smart-autocomplete-suggestions'
items.forEach((item, index) => {
const itemEl = document.createElement('div')
itemEl.className = 'smart-autocomplete-item'
itemEl.textContent = item.completion
itemEl.addEventListener('click', () => selectSuggestion(item))
suggestionsEl.appendChild(itemEl)
})
container.appendChild(suggestionsEl)
suggestions = items
}
const hideSuggestions = () => {
if (suggestionsEl) {
suggestionsEl.remove()
suggestionsEl = null
}
suggestions = []
selectedIndex = -1
}
const selectSuggestion = async (suggestion) => {
const words = input.value.split(' ')
words[words.length - 1] = suggestion.completion
input.value = words.join(' ')
hideSuggestions()
// Отправляем информацию об использовании
try {
await fetch('http://localhost:3000/api/usage', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
prefix: words.slice(-2, -1).join(' '),
completion: suggestion.completion
})
})
} catch (error) {
console.error('Ошибка отправки статистики:', error)
}
}
const fetchSuggestions = async (text) => {
if (text.length < 2) {
hideSuggestions()
return
}
const words = text.split(' ')
const prefix = words.slice(-2).join(' ').toLowerCase()
try {
const response = await fetch(`http://localhost:3000/api/complete?prefix=${encodeURIComponent(prefix)}&limit=5`)
const data = await response.json()
showSuggestions(data.completions || [])
} catch (error) {
console.error('Ошибка получения предложений:', error)
}
}
const debounce = (func, wait) => {
let timeout
return (...args) => {
clearTimeout(timeout)
timeout = setTimeout(() => func.apply(this, args), wait)
}
}
const debouncedFetch = debounce(fetchSuggestions, 300)
input.addEventListener('input', (e) => {
debouncedFetch(e.target.value)
})
input.addEventListener('keydown', (e) => {
if (!suggestions.length) return
switch (e.key) {
case 'ArrowDown':
e.preventDefault()
selectedIndex = Math.min(selectedIndex + 1, suggestions.length - 1)
updateSelection()
break
case 'ArrowUp':
e.preventDefault()
selectedIndex = Math.max(selectedIndex - 1, -1)
updateSelection()
break
case 'Enter':
e.preventDefault()
if (selectedIndex >= 0) {
selectSuggestion(suggestions[selectedIndex])
}
break
case 'Escape':
hideSuggestions()
break
}
})
const updateSelection = () => {
if (!suggestionsEl) return
const items = suggestionsEl.querySelectorAll('.smart-autocomplete-item')
items.forEach((item, index) => {
item.classList.toggle('selected', index === selectedIndex)
})
}
input.addEventListener('blur', () => {
setTimeout(hideSuggestions, 150)
})
}
}
// Инициализируем автодополнение
new ContentAutoComplete()
6. Инициализация и использование
// init.js - скрипт для инициализации и тестирования
async function initializeAutoComplete() {
// Обучаем модель на примерах текстов
const trainingTexts = [
"JavaScript является мощным языком программирования",
"Vue.js предоставляет отличные возможности для разработки",
"Node.js позволяет создавать серверные приложения",
"SQLite база данных обеспечивает быстрый доступ к данным",
"Chrome расширения могут значительно улучшить пользовательский опыт"
]
for (const text of trainingTexts) {
await fetch('http://localhost:3000/api/train', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text, context: 'programming' })
})
}
console.log('Модель обучена!')
}
// Запускаем инициализацию при загрузке
if (typeof window !== 'undefined') {
window.addEventListener('load', initializeAutoComplete)
}
Этот движок автодополнения использует н-граммы для генерации умных предложений на основе контекста ввода. Система обучается на тексте, который пользователь вводит, и постепенно улучшает качество предложений.