Jina AI가 Hugging Face를 통해 독일어-영어 및 중국어-영어 쌍에 대한 최신 오픈소스 이중 언어 임베딩 모델을 출시했습니다.


이 튜토리얼에서는 다음과 같은 최소한의 설치와 사용 사례를 살펴볼 것입니다:
- Hugging Face에서 Jina Embedding 모델 다운로드하기
- 모델을 사용하여 독일어와 영어 텍스트의 인코딩 얻기
- 교차 언어 쿼리를 위한 매우 기본적인 임베딩 기반 신경 검색 엔진 구축하기
영어로 쿼리하여 독일어 텍스트를 검색하고 그 반대의 경우도 가능하도록 Jina Embeddings를 사용하는 방법을 보여드리겠습니다.
이 튜토리얼은 중국어 모델에도 동일하게 적용됩니다. 중국어로 쿼리하기라는 제목의 섹션(끝 부분)의 지침을 따라 중국어-영어 이중 언어 모델과 중국어 예제 문서를 얻으세요.


tag이중 언어 임베딩 모델
이중 언어 임베딩 모델은 두 개의 언어 — 이 튜토리얼에서는 독일어와 영어, 중국어 모델의 경우 중국어와 영어 — 를 동일한 임베딩 공간에 매핑하는 모델입니다. 독일어 텍스트와 영어 텍스트가 같은 의미를 가질 경우, 해당하는 임베딩 벡터들이 서로 가깝게 위치하도록 합니다.
이러한 모델은 이 튜토리얼에서 보여드릴 교차 언어 정보 검색 애플리케이션에 매우 적합할 뿐만 아니라, RAG 기반 챗봇, 다국어 텍스트 분류, 요약, 감성 분석 및 임베딩을 사용하는 다른 모든 애플리케이션의 기반으로도 사용될 수 있습니다. 이러한 모델을 사용하면 두 언어로 된 텍스트를 마치 같은 언어로 작성된 것처럼 다룰 수 있습니다.
많은 거대 언어 모델이 다양한 언어를 지원한다고 주장하지만, 모든 언어를 동등하게 지원하지는 않습니다. 인터넷에서 영어가 지배적인 위치를 차지함으로 인한 편향과 기계 번역된 텍스트의 광범위한 온라인 출판으로 인한 왜곡된 입력 소스에 대한 우려가 커지고 있습니다. 두 개의 언어에 초점을 맞춤으로써, 편향을 최소화하면서 두 언어에 대한 임베딩 품질을 더 잘 제어할 수 있고, 수십 개의 언어를 처리한다고 주장하는 거대 모델과 비슷하거나 더 높은 성능을 내는 훨씬 작은 모델을 만들 수 있습니다.
Jina Embeddings v2 이중 언어 모델은 8,192 입력 컨텍스트 토큰을 지원하여, 두 언어를 지원할 뿐만 아니라 비슷한 모델들에 비해 상대적으로 긴 텍스트 세그먼트를 지원할 수 있습니다. 이는 임베딩으로 처리해야 할 텍스트 정보가 더 많은 복잡한 사용 사례에 이상적입니다.
tagGoogle Colab에서 따라하기
이 튜토리얼에는 관련 노트북이 있어 Google Colab이나 로컬 시스템에서 실행할 수 있습니다.

tag필수 요소 설치하기
현재 환경에 관련 라이브러리가 설치되어 있는지 확인하세요. transformers의 최신 버전이 필요하므로, 이미 설치되어 있더라도 다음을 실행하세요:
pip install -U transformers
이 튜토리얼은 벡터 검색과 비교를 위해 Meta의 FAISS 라이브러리를 사용할 것입니다. 설치하려면 다음을 실행하세요:
pip install faiss-cpu
또한 이 튜토리얼에서는 입력 데이터를 처리하기 위해 Beautiful Soup를 사용할 것이므로, 다음을 설치하세요:
pip install bs4
tagHugging Face 접근
모델을 다운로드하려면 Hugging Face 계정과 액세스 토큰이 필요합니다.
Hugging Face 계정이 없는 경우:
https://huggingface.co/로 이동하여 페이지 오른쪽 상단의 "Sign Up" 버튼을 클릭하세요. 지시에 따라 새 계정을 만드세요.

계정에 로그인한 후:
액세스 토큰을 얻으려면 Hugging Face 웹사이트의 지침을 따르세요.

이 토큰을 HF_TOKEN이라는 환경 변수에 복사해야 합니다. 노트북(예: Google Colab)에서 작업하거나 Python 프로그램 내에서 설정하는 경우 다음 Python 코드를 사용하세요:
import os
os.environ['HF_TOKEN'] = "<your token here>"
쉘에서는 환경 변수를 설정하기 위한 제공된 구문을 사용하세요. bash에서는:
export HF_TOKEN="<your token here>"
tag독일어와 영어를 위한 Jina Embeddings v2 다운로드
토큰이 설정되면 transformers 라이브러리를 사용하여 Jina Embeddings 독일어-영어 이중 언어 모델을 다운로드할 수 있습니다:
from transformers import AutoModel
model = AutoModel.from_pretrained('jinaai/jina-embeddings-v2-base-de', trust_remote_code=True)
처음 실행할 때는 몇 분 정도 걸릴 수 있지만, 모델이 로컬에 캐시되므로 이후에 이 튜토리얼을 다시 시작할 때는 걱정하지 않아도 됩니다.
tag영어 데이터 다운로드
이 튜토리얼에서는 Pro Git: Everything You Need to Know About Git 책의 영어 버전을 사용할 것입니다. 이 책은 중국어와 독일어로도 제공되며, 이는 나중에 이 튜토리얼에서 사용할 것입니다.
EPUB 버전을 다운로드하려면 다음 명령을 실행하세요:
wget -O progit-en.epub https://open.umn.edu/opentextbooks/formats/3437이는 책을 로컬 디렉토리의 progit-en.epub 파일로 복사합니다.

또는 https://open.umn.edu/opentextbooks/formats/3437 링크를 방문하여 로컬 드라이브로 다운로드할 수 있습니다. 이 책은 Creative Commons Attribution Non Commercial Share Alike 3.0 라이선스로 제공됩니다.
tag데이터 처리
이 텍스트는 계층적 섹션 구조를 가지고 있으며, 기본 XHTML 데이터에서 <section> 태그를 찾아 쉽게 찾을 수 있습니다. 아래 코드는 EPUB 파일을 읽고 EPUB 파일의 내부 구조와 <section> 태그를 사용하여 분할한 다음, 각 섹션을 XHTML 태그 없이 일반 텍스트로 변환합니다. 책의 각 섹션 위치를 나타내는 문자열 세트를 키로 하고 해당 섹션의 일반 텍스트 내용을 값으로 하는 Python 딕셔너리를 생성합니다.
from zipfile import ZipFile
from bs4 import BeautifulSoup
import copy
def decompose_epub(file_name):
def to_top_text(section):
selected = copy.copy(section)
while next_section := selected.find("section"):
next_section.decompose()
return selected.get_text().strip()
ret = {}
with ZipFile(file_name, 'r') as zip:
for name in zip.namelist():
if name.endswith(".xhtml"):
data = zip.read(name)
doc = BeautifulSoup(data.decode('utf-8'), 'html.parser')
ret[name + ":top"] = to_top_text(doc)
for num, sect in enumerate(doc.find_all("section")):
ret[name + f"::{num}"] = to_top_text(sect)
return ret
그런 다음 이전에 다운로드한 EPUB 파일에 대해 decompose_epub 함수를 실행하세요:
book_data = decompose_epub("progit-en.epub")
book_data 변수에는 이제 583개의 섹션이 포함됩니다. 예를 들면:
print(book_data['EPUB/ch01-getting-started.xhtml::12'])
결과:
The Command Line
There are a lot of different ways to use Git.
There are the original command-line tools, and there are many graphical user interfaces of varying capabilities.
For this book, we will be using Git on the command line.
For one, the command line is the only place you can run all Git commands — most of the GUIs implement only a partial subset of Git functionality for simplicity.
If you know how to run the command-line version, you can probably also figure out how to run the GUI version, while the opposite is not necessarily true.
Also, while your choice of graphical client is a matter of personal taste, all users will have the command-line tools installed and available.
So we will expect you to know how to open Terminal in macOS or Command Prompt or PowerShell in Windows.
If you don't know what we're talking about here, you may need to stop and research that quickly so that you can follow the rest of the examples and descriptions in this book.
tagJina Embeddings v2와 FAISS를 사용한 임베딩 생성 및 인덱싱
583개의 섹션 각각에 대해 임베딩을 생성하고 FAISS 인덱스에 저장할 것입니다. Jina Embeddings v2 모델은 최대 8192 토큰의 입력을 받아들이므로, 이 책과 같은 경우에는 추가 텍스트 세그멘테이션이나 섹션이 너무 많은 토큰을 가지고 있는지 확인할 필요가 없습니다. 책에서 가장 긴 섹션은 약 12,000자이며, 일반 영어의 경우 8k 토큰 제한보다 훨씬 적습니다.
단일 임베딩을 생성하려면 우리가 다운로드한 모델의 encode 메소드를 사용합니다. 예를 들면:
model.encode([book_data['EPUB/ch01-getting-started.xhtml::12']])
이는 768차원 벡터를 포함하는 배열을 반환합니다:
array([[ 6.11135997e-02, 1.67829826e-01, -1.94809273e-01,
4.45595086e-02, 3.28837298e-02, -1.33441269e-01,
1.35364473e-01, -1.23119736e-02, 7.51526654e-02,
-4.25386652e-02, -6.91794455e-02, 1.03527725e-01,
-2.90831417e-01, -6.21018047e-03, -2.16205455e-02,
-2.20803712e-02, 1.50471330e-01, -3.31433356e-01,
-1.48741454e-01, -2.10959971e-01, 8.80039856e-02,
....
이것이 임베딩입니다.
Jina Embeddings 모델은 배치 처리를 허용하도록 설정되어 있습니다. 최적의 배치 크기는 실행 시 사용하는 하드웨어에 따라 다릅니다. 큰 배치 크기는 메모리 부족 위험이 있습니다. 작은 배치 크기는 처리 시간이 더 오래 걸립니다.
batch_size=5로 설정하면 GPU 없는 무료 티어의 Google Colab에서 작동했으며, 전체 임베딩 세트를 생성하는 데 약 1시간이 걸렸습니다.프로덕션 환경에서는 훨씬 더 강력한 하드웨어를 사용하거나 Jina AI의 Embedding API 서비스를 사용하는 것을 추천합니다. 아래 링크를 따라가 작동 방식과 무료 액세스를 시작하는 방법을 알아보세요.

아래 코드는 임베딩을 생성하고 FAISS 인덱스에 저장합니다. batch_size 변수를 리소스에 맞게 설정하세요.
import faiss
batch_size = 5
vector_data = []
faiss_index = faiss.IndexFlatIP(768)
data = [(key, txt) for key, txt in book_data.items()]
batches = [data[i:i + batch_size] for i in range(0, len(data), batch_size)]
for ind, batch in enumerate(batches):
print(f"Processing batch {ind + 1} of {len(batches)}")
batch_embeddings = model.encode([x[1] for x in batch], normalize_embeddings=True)
vector_data.extend(batch)
faiss_index.add(batch_embeddings)
프로덕션 환경에서는 Python 딕셔너리가 문서와 임베딩을 처리하기에 적절하거나 성능이 좋지 않습니다. 데이터 삽입을 위한 자체 지침이 있는 목적에 맞게 제작된 벡터 데이터베이스를 사용해야 합니다.
tag독일어로 영어 결과 쿼리하기
텍스트 세트에서 무언가를 쿼리할 때 다음과 같은 일이 발생합니다:
- Jina Embeddings 독일어-영어 모델이 쿼리에 대한 임베딩을 생성합니다.
- FAISS 인덱스(
faiss_index)를 사용하여 쿼리 임베딩과 코사인이 가장 높은 저장된 임베딩을 찾아 인덱스의 위치를 반환합니다. - 벡터 데이터 배열(
vector_data)에서 해당 텍스트를 찾아 코사인, 텍스트 위치 및 텍스트 자체를 출력합니다.
이것이 아래 query 함수가 하는 일입니다.
def query(query_str):
query = model.encode([query_str], normalize_embeddings=True)
cosine, index = faiss_index.search(query, 1)
print(f"Cosine: {cosine[0][0]}")
loc, txt = vector_data[index[0][0]]
print(f"Location: {loc}\\nText:\\n\\n{txt}")
이제 시도해 보겠습니다.
# Translation: "How do I roll back to a previous version?"
query("Wie kann ich auf eine frühere Version zurücksetzen?")
결과:
Cosine: 0.5202275514602661
Location: EPUB/ch02-git-basics-chapter.xhtml::20
Text:
Undoing things with git restore
Git version 2.23.0 introduced a new command: git restore.
It's basically an alternative to git reset which we just covered.
From Git version 2.23.0 onwards, Git will use git restore instead of git reset for many undo operations.
Let's retrace our steps, and undo things with git restore instead of git reset.
이는 질문에 답하기에 매우 적절한 선택입니다. 다른 것도 시도해 보겠습니다:
# Translation: "What does 'version control' mean?"
query("Was bedeutet 'Versionsverwaltung'?")
결과:
Cosine: 0.5001817941665649
Location: EPUB/ch01-getting-started.xhtml::1
Text:
About Version Control
What is "version control", and why should you care?
Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later.
For the examples in this book, you will use software source code as the files being version controlled, though in reality you can do this with nearly any type of file on a computer.
If you are a graphic or web designer and want to keep every version of an image or layout (which you would most certainly want to), a Version Control System (VCS) is a very wise thing to use.
It allows you to revert selected files back to a previous state, revert the entire project back to a previous state, compare changes over time, see who last modified something that might be causing a problem, who introduced an issue and when, and more.
Using a VCS also generally means that if you screw things up or lose files, you can easily recover.
In addition, you get all this for very little overhead.
자신만의 독일어 질문으로 얼마나 잘 작동하는지 시도해 보세요. 텍스트 정보 검색을 다룰 때의 일반적인 관행으로, 단 하나의 응답 대신 3~5개의 응답을 요청해야 합니다. 최상의 답변이 첫 번째가 아닌 경우가 많기 때문입니다.
tag역할 바꾸기: 영어로 독일어 문서 검색하기
Pro Git: Everything You Need to Know About Git 책은 독일어로도 제공됩니다. 이 동일한 모델을 사용하여 언어를 반대로 바꾼 데모를 할 수 있습니다.
전자책 다운로드:
wget -O progit-de.epub https://open.umn.edu/opentextbooks/formats/3454
이는 책을 progit-de.epub라는 파일로 복사합니다. 그런 다음 영어 책과 동일한 방식으로 처리합니다:
book_data = decompose_epub("progit-de.epub")
그리고 이전과 동일한 방식으로 임베딩을 생성합니다:
batch_size = 5
vector_data = []
faiss_index = faiss.IndexFlatIP(768)
data = [(key, txt) for key, txt in book_data.items()]
batches = [data[i:i + batch_size] for i in range(0, len(data), batch_size)]
for ind, batch in enumerate(batches):
print(f"Processing batch {ind + 1} of {len(batches)}")
batch_embeddings = model.encode([x[1] for x in batch], normalize_embeddings=True)
vector_data.extend(batch)
faiss_index.add(batch_embeddings)
이제 동일한 query 함수를 사용하여 영어로 독일어 답변을 검색할 수 있습니다:
query("What is version control?")
결과:
Cosine: 0.6719034910202026
Location: EPUB/ch01-getting-started.xhtml::1
Text:
Was ist Versionsverwaltung?
Was ist „Versionsverwaltung", und warum sollten Sie sich dafür interessieren?
Versionsverwaltung ist ein System, welches die Änderungen an einer oder einer Reihe von Dateien über die Zeit hinweg protokolliert, sodass man später auf eine bestimmte Version zurückgreifen kann.
Die Dateien, die in den Beispielen in diesem Buch unter Versionsverwaltung gestellt werden, enthalten Quelltext von Software, tatsächlich kann in der Praxis nahezu jede Art von Datei per Versionsverwaltung nachverfolgt werden.
Als Grafik- oder Webdesigner möchte man zum Beispiel in der Lage sein, jede Version eines Bildes oder Layouts nachverfolgen zu können. Als solcher wäre es deshalb ratsam, ein Versionsverwaltungssystem (engl. Version Control System, VCS) einzusetzen.
Ein solches System erlaubt es, einzelne Dateien oder auch ein ganzes Projekt in einen früheren Zustand zurückzuversetzen, nachzuvollziehen, wer zuletzt welche Änderungen vorgenommen hat, die möglicherweise Probleme verursachen, herauszufinden wer eine Änderung ursprünglich vorgenommen hat und viele weitere Dinge.
Ein Versionsverwaltungssystem bietet allgemein die Möglichkeit, jederzeit zu einem vorherigen, funktionierenden Zustand zurückzukehren, auch wenn man einmal Mist gebaut oder aus irgendeinem Grund Dateien verloren hat.
All diese Vorteile erhält man für einen nur sehr geringen, zusätzlichen Aufwand.
이 섹션의 제목은 "버전 관리란 무엇인가?"로 번역되므로, 이는 좋은 응답입니다.
tag중국어로 검색하기
이러한 예제들은 중국어와 영어에 대한 Jina Embeddings v2로 정확히 동일한 방식으로 작동할 것입니다. 대신 중국어 모델을 사용하려면 다음을 실행하기만 하면 됩니다:
from transformers import AutoModel
model = AutoModel.from_pretrained('jinaai/jina-embeddings-v2-base-zh', trust_remote_code=True)
Pro Git: Everything You Need to Know About Git의 중국어 버전을 얻으려면:
wget -O progit-zh.epub https://open.umn.edu/opentextbooks/formats/3455
그런 다음 중국어 책을 처리합니다:
book_data = decompose_epub("progit-zh.epub")
이 튜토리얼의 다른 모든 코드는 동일한 방식으로 작동할 것입니다.
tag미래: 프로그래밍을 포함한 더 많은 언어
우리는 스페인어와 일본어가 이미 개발 중이며, 영어와 여러 주요 프로그래밍 언어를 지원하는 모델을 포함하여 더 많은 이중 언어 모델을 즉시 출시할 예정입니다. 이러한 모델들은 다국어 정보를 관리하는 국제 기업에 이상적으로 적합하며, AI 기반 정보 검색과 RAG 기반 생성형 언어 모델의 토대 역할을 하여 최첨단 AI 사용 사례에 통합될 수 있습니다.
Jina AI의 모델들은 작고 성능이 최고 수준이어서, 최고의 성능을 얻기 위해 가장 큰 모델이 필요하지 않다는 것을 보여줍니다. 이중 언어 성능에 중점을 둠으로써, 해당 언어들에 더 뛰어나고, 적응하기 쉬우며, 큐레이션되지 않은 데이터로 학습된 대형 모델보다 비용 효율적인 모델을 제작합니다.
Jina Embeddings는 Hugging Face, Sagemaker에서 사용할 수 있는 AWS 마켓플레이스, 그리고 Jina Embeddings 웹 API를 통해 이용할 수 있습니다. 이들은 많은 AI 프로세스 프레임워크와 벡터 데이터베이스에 완벽하게 통합되어 있습니다.
자세한 정보는 Jina Embeddings 웹사이트를 참조하거나, Jina AI의 제품이 귀사의 비즈니스 프로세스에 어떻게 적합할 수 있는지 논의하기 위해 연락해 주시기 바랍니다.








