Files
hotels/N8N_NATASHA_CURL_IMPORT.md
Фёдор 0cf3297290 Проект аудита отелей: основные скрипты и документация
- Краулеры: smart_crawler.py, regional_crawler.py
- Аудит: audit_orel_to_excel.py, audit_chukotka_to_excel.py
- РКН проверка: check_rkn_registry.py, recheck_unclear_rkn.py
- Отчёты: create_orel_horizontal_report.py
- Обработка: process_all_hotels_embeddings.py
- Документация: README.md, DB_SCHEMA_REFERENCE.md
2025-10-16 10:52:09 +03:00

339 lines
9.2 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.

# 🎯 ВАЛИДНЫЕ cURL ДЛЯ ИМПОРТА В n8n HTTP REQUEST NODE
## 📋 ОБЩАЯ ИНФОРМАЦИЯ
**API URL:** `http://185.197.75.249:8004`
**Локально:** `http://localhost:8004`
**Статус:** ✅ Работает (проверено 13.10.2025 19:37)
---
## 🔍 ЭНДПОИНТЫ
### 1⃣ Проверка здоровья API
```bash
curl -X GET 'http://185.197.75.249:8004/health' \
-H 'Accept: application/json'
```
**Ответ:**
```json
{
"status": "healthy",
"natasha": "ready"
}
```
---
### 2⃣ Извлечение сущностей (УПРОЩЁННЫЙ - для n8n)
**⭐ РЕКОМЕНДУЕТСЯ ДЛЯ n8n! ⭐**
```bash
curl -X POST 'http://185.197.75.249:8004/extract_simple' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{
"text": "ИП Фролов С.А. находится по адресу г. Петропавловск-Камчатский, ул. Пограничная 39/1. Директор Иван Петров. ИНН: 8707003759, ОГРН: 1028700516476.",
"max_length": 5000
}'
```
**Реальный ответ (протестировано):**
```json
{
"organizations": ["ИП"],
"persons": ["Иван Петров", "Фролов С.А."],
"locations": ["Петропавловск-Камчатский"],
"has_organizations": true,
"has_persons": true,
"has_locations": true,
"total": 4
}
```
---
### 3⃣ Извлечение сущностей (ПОЛНЫЙ ФОРМАТ)
```bash
curl -X POST 'http://185.197.75.249:8004/extract' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{
"text": "Муниципальное предприятие «Чаунское районное коммунальное хозяйство». ИНН: 8707003759, ОГРН: 1028700516476. Юридический адрес: 689400, г. Певек, ул. Пугачева, 42",
"max_length": 5000
}'
```
**Ответ включает:**
```json
{
"organizations": ["Муниципальное предприятие"],
"persons": [],
"locations": ["Певек", "Пугачева"],
"entities": [
{
"type": "ORG",
"text": "Муниципальное предприятие",
"start": 0,
"end": 25
},
{
"type": "LOC",
"text": "Певек",
"start": 110,
"end": 115
}
],
"total_entities": 4
}
```
---
## 🔧 КАК ИМПОРТИРОВАТЬ В n8n HTTP REQUEST NODE
### Способ 1: Через Import from cURL
1. В n8n добавь **HTTP Request Node**
2. Нажми на кнопку **"Import from cURL"** (справа вверху в ноде)
3. Вставь этот cURL:
```bash
curl -X POST 'http://185.197.75.249:8004/extract_simple' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{"text": "ИП Фролов С.А. находится по адресу г. Петропавловск-Камчатский, ул. Пограничная 39/1. Директор Иван Петров.", "max_length": 5000}'
```
4. n8n автоматически заполнит все поля ✅
---
### Способ 2: Ручная настройка
**Параметры HTTP Request Node:**
| Поле | Значение |
|------|----------|
| **Method** | `POST` |
| **URL** | `http://185.197.75.249:8004/extract_simple` |
| **Authentication** | None |
| **Send Body** | Yes (JSON) |
| **Body Content Type** | JSON |
**Headers:**
```json
{
"Content-Type": "application/json",
"Accept": "application/json"
}
```
**Body (JSON):**
```json
{
"text": "{{ $json.quote }}",
"max_length": 5000
}
```
> 💡 **Где `{{ $json.quote }}`** - это данные из предыдущей ноды (текст для анализа)
---
## 📊 ПРИМЕР ИСПОЛЬЗОВАНИЯ В n8n WORKFLOW
### Схема:
```
┌────────────────┐
│ PostgreSQL │ → Получить текст из БД (hotel_website_processed)
└────────┬───────┘
┌────────────────┐
│ Code Node │ → Подготовить текст (cleaned_text)
└────────┬───────┘
┌────────────────┐
│ HTTP Request │ → http://185.197.75.249:8004/extract_simple
│ (Natasha API) │
└────────┬───────┘
┌────────────────┐
│ Code Node │ → Обработать результат (проверить has_organizations)
└────────────────┘
```
### Код для подготовки данных (Code Node ПЕРЕД HTTP Request):
```javascript
// Подготовка текста для Natasha API
const items = [];
for (const item of $input.all()) {
items.push({
json: {
hotel_id: item.json.hotel_id,
quote: item.json.cleaned_text || item.json.text || "",
criterion_id: item.json.criterion_id
}
});
}
return items;
```
### Код для обработки ответа (Code Node ПОСЛЕ HTTP Request):
```javascript
// Обработка ответа от Natasha API
const items = [];
for (const item of $input.all()) {
const organizations = item.json.organizations || [];
const persons = item.json.persons || [];
const locations = item.json.locations || [];
// Проверяем наличие нужных сущностей
const hasOrganizations = organizations.length > 0;
const hasPersons = persons.length > 0;
const hasLocations = locations.length > 0;
// Для критерия 1 (ИНН/ОГРН) проверяем организации
let ner_score = 0.0;
if (item.json.criterion_id === 1) {
ner_score = hasOrganizations ? 1.0 : 0.0;
}
// Для критерия 2 (Адрес) проверяем локации
else if (item.json.criterion_id === 2) {
ner_score = hasLocations ? 1.0 : 0.0;
}
items.push({
json: {
hotel_id: item.json.hotel_id,
criterion_id: item.json.criterion_id,
organizations: organizations,
persons: persons,
locations: locations,
ner_score: ner_score,
has_organizations: hasOrganizations,
has_persons: hasPersons,
has_locations: hasLocations,
total_entities: item.json.total || 0
}
});
}
return items;
```
---
## 🧪 ТЕСТИРОВАНИЕ
### Тест 1: Проверка API
```bash
curl http://185.197.75.249:8004/health
```
Ожидаем: `{"status":"healthy","natasha":"ready"}`
### Тест 2: Извлечение организации
```bash
curl -X POST http://185.197.75.249:8004/extract_simple \
-H 'Content-Type: application/json' \
-d '{"text": "ООО Рога и Копыта", "max_length": 5000}'
```
Ожидаем: `{"organizations": ["ООО"], ...}`
### Тест 3: Извлечение адреса
```bash
curl -X POST http://185.197.75.249:8004/extract_simple \
-H 'Content-Type: application/json' \
-d '{"text": "г. Москва, ул. Ленина, д. 1", "max_length": 5000}'
```
Ожидаем: `{"locations": ["Москва", "Ленина"], ...}`
---
## 🔥 ГОТОВЫЙ cURL ДЛЯ КОПИРОВАНИЯ
**Для критерия 1 (ИНН/ОГРН):**
```bash
curl -X POST 'http://185.197.75.249:8004/extract_simple' -H 'Content-Type: application/json' -H 'Accept: application/json' -d '{"text":"ИП Фролов С.А. ИНН: 8707003759, ОГРН: 1028700516476","max_length":5000}'
```
**Для критерия 2 (Адрес):**
```bash
curl -X POST 'http://185.197.75.249:8004/extract_simple' -H 'Content-Type: application/json' -H 'Accept: application/json' -d '{"text":"Юридический адрес: 689400, г. Певек, ул. Пугачева, 42","max_length":5000}'
```
---
## 📝 ДОКУМЕНТАЦИЯ API
**Swagger UI доступен по адресу:**
- Локально: `http://localhost:8004/docs`
- Извне: `http://185.197.75.249:8004/docs`
---
## ⚡ ПРОИЗВОДИТЕЛЬНОСТЬ
- **Скорость:** ~100-200ms на запрос
- **Лимит текста:** 5000 символов (настраивается через `max_length`)
- **Параллельность:** Поддерживает множество одновременных запросов
---
## 🐛 TROUBLESHOOTING
### Ошибка: Connection refused
**Решение:** Проверь, что API запущен:
```bash
ps aux | grep natasha_ner_api
```
Если не запущен:
```bash
cd /root/engine/public_oversight/hotels
python3 -m uvicorn natasha_ner_api:app --host 0.0.0.0 --port 8004 --reload
```
### Ошибка: 500 Internal Server Error
**Решение:** Проверь логи:
```bash
tail -f /root/engine/public_oversight/hotels/nohup.out
```
---
## ✅ ПРОВЕРЕНО
- ✅ API работает (13.10.2025 19:37)
- ✅ cURL валидный
- ✅ Протестирован на реальных данных
- ✅ Извлекает: организации, адреса, имена
- ✅ Готов для импорта в n8n
---
**Автор:** AI Assistant + Фёдор
**Дата:** 13 октября 2025
**Версия:** 1.0