Ginigh leabaithe do chuid sonraí
Ar an leathanach seo
Cuspóirí
- Ullmhaigh do chuid sonraí téacs le haghaidh leabaithe
- Ginigh leabaithe go héifeachtach ar scála mór
- Stóráil veicteoirí le húsáid níos déanaí
Ullmhaigh do chuid sonraí
Braitheann cáilíocht do leabaithe go díreach ar cháilíocht do chuid sonraí. Cruthaíonn téacs atá lán de spásanna stray, carachtair rialaithe ó easpórtáil míchumraithe, nó briseadh líne neamhrialta veicteoir atá beagán as áit. Méadaíonn an claonadh sin ar gach cuardach. Ní cosmaideach é an glanadh: is é an chéad optamú ábharthachta is saoire é.
import re
def nettoyer_texte(texte: str) -> str:
"""Prepares text for embedding."""
# Remove multiple spaces
texte = re.sub(r"\s+", " ", texte)
# Remove control characters
texte = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", "", texte)
# Trim
texte = texte.strip()
return texte
# Example
brut = " Texte avec des espaces\n\n\nen trop "
propre = nettoyer_texte(brut)
print(propre) # "Texte avec des espaces en trop"
Saibhrigh an comhthéacs
Cailleann blúire doiciméadaithe aonair cuid dá bhrí gan a theideal. Tóg mír a thosaíonn le “Íoslódáil an pacáiste ón suíomh oifigiúil”: as comhthéacs, ní léiríonn aon rud go mbaineann sé le PostgreSQL, agus ní mheaitseálfaidh an veicteoir a thagann as sin riamh ceist faoi PostgreSQL. Trí an t-ábhar a réamhcheangal lena theideal agus lena rannán, athchuireann tú an fhaisnéis sin isteach sa téacs a fheiceann an tsamhail.
def enrichir_document(titre: str, section: str, contenu: str) -> str:
"""Creates enriched text for better embedding."""
return f"Titre : {titre}\nSection : {section}\n\n{contenu}"
texte_enrichi = enrichir_document(
titre="Installation de PostgreSQL",
section="Getting Started Guide",
contenu="Download the package from the official site..."
)
Ginigh leabaithe i mbaitseanna
Ar chorpas fíor de na céadta nó na mílte doiciméad, ní mór an phróiseáil a bheith ina slisní agus in ann seasamh in aghaidh fadhbanna líonra. Déanann an fheidhm thíos atriall ar théacsanna i slisní, déanann sí sórtáil córasach ar an bhfreagra de réir index chun a chinntiú go bhfuil veicteoir #7 ag teacht le doiciméad #7, agus déanann sí iarracht arís uair amháin tar éis sos má tharlaíonn earráid.
from openai import OpenAI
import time
import json
client = OpenAI()
def generer_embeddings(
textes: list[str],
model: str = "text-embedding-3-large",
batch_size: int = 100
) -> list[list[float]]:
"""Generates embeddings in batches with error handling."""
tous_les_embeddings = []
for i in range(0, len(textes), batch_size):
batch = textes[i:i + batch_size]
print(f"Processing batch {i // batch_size + 1}/"
f"{(len(textes) - 1) // batch_size + 1}")
try:
response = client.embeddings.create(
input=batch,
model=model
)
# Sort by index to guarantee order
batch_embeddings = sorted(
response.data, key=lambda x: x.index
)
tous_les_embeddings.extend(
[item.embedding for item in batch_embeddings]
)
except Exception as e:
print(f"Error on batch {i}: {e}")
# Retry after a pause
time.sleep(5)
response = client.embeddings.create(
input=batch,
model=model
)
batch_embeddings = sorted(
response.data, key=lambda x: x.index
)
tous_les_embeddings.extend(
[item.embedding for item in batch_embeddings]
)
return tous_les_embeddings
Is réamhchúram é an sórtáil de réir index nach mór duit a sheachaint riamh. Is leor aistriú ciúin de shraith amháin chun gach doiciméad a chur i gcomhcheangal le veicteoir a chomharsan. Is é an siomptóm a fheicfidh tú ná “filleann cuardaigh ar bhruscar”, gan aon earráid theicniúil chun tú a threorú sa treo ceart.
Stóráil leabaithe
Do chorpas beag de roinnt mílte doiciméad, oibríonn comhad JSON simplí ina bhfuil téacsanna, meiteashonraí, agus veicteoirí go foirfe. Tá an buntáiste aige a bheith inléite ag an duine nuair a theastaíonn uait toradh aisteach a dhíbhuail.
import json
documents = [
{"id": 1, "texte": "Premier document...", "metadata": {"source": "faq"}},
{"id": 2, "texte": "Deuxième document...", "metadata": {"source": "docs"}},
]
# Generate embeddings
textes = [d["texte"] for d in documents]
embeddings = generer_embeddings(textes)
# Add vectors to documents
for doc, emb in zip(documents, embeddings):
doc["embedding"] = emb
# Save
with open("corpus_embeddings.json", "w") as f:
json.dump(documents, f)
Thar an scála sin, éiríonn JSON ina bhac: scríobhtar gach uimhir amach go hiomlán, rud a mhéadaíonn an comhad go mór agus a fhorchuireann parsáil chostasach ar gach ualach. Stóráilíonn NumPy na luachanna céanna go déthreach ar 4 bheart agus athlódáil sé láithreach.
import numpy as np
# Convert to NumPy matrix
matrice = np.array(embeddings, dtype=np.float32)
print(f"Shape : {matrice.shape}") # (n_docs, 3072)
# Save in binary format
np.save("embeddings.npy", matrice)
# Load
matrice_chargee = np.load("embeddings.npy")
Píblíne iomlán: ó chomhaid téacs go leabaithe
Déanaimis na heilimintí seo a chur le chéile i bhfeidhm a léann fillteán, a ghlanann gach comhad, a ghineann veicteoirí, agus a roinneann an stóráil ina dhá chuid: meiteashonraí i JSON (inléite agus in-eagarthóireacht) agus an mhaitrís i NumPy (dlúth agus tapa).
from openai import OpenAI
from pathlib import Path
import json
import numpy as np
client = OpenAI()
def pipeline_embeddings(dossier: str, model: str = "text-embedding-3-large"):
"""Complete pipeline: files → embeddings → storage."""
dossier_path = Path(dossier)
# 1. Read files
documents = []
for fichier in sorted(dossier_path.glob("*.txt")):
contenu = fichier.read_text(encoding="utf-8")
contenu = nettoyer_texte(contenu)
if contenu:
documents.append({
"id": fichier.stem,
"fichier": fichier.name,
"texte": contenu
})
print(f"{len(documents)} documents found")
# 2. Generate embeddings
textes = [d["texte"] for d in documents]
embeddings = generer_embeddings(textes, model=model)
# 3. Save
# Metadata in JSON
meta = [{"id": d["id"], "fichier": d["fichier"]} for d in documents]
with open("metadata.json", "w") as f:
json.dump(meta, f, ensure_ascii=False, indent=2)
# Vectors in NumPy
np.save("embeddings.npy", np.array(embeddings, dtype=np.float32))
print(f"Embeddings saved: {len(embeddings)} vectors "
f"of {len(embeddings[0])} dimensions")
return documents, embeddings
# Usage
documents, embeddings = pipeline_embeddings("./mes_documents/")
Tabhair faoi deara an sorted() ar an glob: gan é, braitheann ord na gcomhad ar an gcóras comhaid, agus d’fhéadfadh do dhá chomhad aschur titim as sioncronaíocht tar éis athrú meaisín simplí.
Meastachán a dhéanamh ar chostais
Sula seolfaidh tú post ollmhór, comhair na tokenanna go háitiúil le tiktoken. Tógann an oibríocht cúpla soicind agus sábhálann sé ort a fháil amach ró-dhéanach go raibh deich n-uaire an méid toirte a bhí súil leis i gcorpas a scagadh go dona.
import tiktoken
encoder = tiktoken.get_encoding("cl100k_base")
def estimer_cout(textes: list[str], model: str = "text-embedding-3-large"):
"""Estimates embedding cost for a list of texts."""
total_tokens = sum(len(encoder.encode(t)) for t in textes)
# Approximate prices per million tokens (check current rates)
prix = {
"text-embedding-3-large": 0.13,
"text-embedding-3-small": 0.02,
}
cout = total_tokens / 1_000_000 * prix.get(model, 0.13)
print(f"Estimated tokens: {total_tokens:,}")
print(f"Estimated cost: ${cout:.4f}")
return total_tokens, cout
Tá na praghsanna sa fhoclóir táscach agus téann siad in éag go tapa: seiceáil na rátaí reatha i gcónaí sula gcuireann tú luachan i láthair do chliaint.
Príomhphointí
- Glan agus saibhrigh do chuid téacsanna sula ngineann tú leabaithe
- Úsáid próiseáil bhaitse do chorpaís mhóra
- Stóráil meiteashonraí i JSON agus veicteoirí i NumPy
- Déan meastachán ar do chostais sula seolann tú post ollmhór