I file con lo stesso nome non rappresentano la stessa copia: utilizzare l'hashing del contenuto per identificare l'input

Il cliente ha inviato due documenti, entrambi denominati `final.pdf`, quale è stato tradotto? È pericoloso fare affidamento sui nomi dei file per rispondere a questa domanda. I file con lo stesso nome potrebbero avere contenuti diversi e i file con nomi modificati potrebbero avere gli stessi byte. Gli hash dei contenuti sono adatti per stabilire corrispondenze di versione, ma non dovrebbero essere loro assegnati significati che non hanno.

I file con lo stesso nome non sono necessariamente uguali e i file con nomi modificati potrebbero avere esattamente lo stesso contenuto. Se un team fa affidamento sui nomi dei file per tenere traccia delle traduzioni, è facile ottenere la versione sbagliata. Questo articolo spiega come utilizzare l'hashing del contenuto per lasciare impronte a livello di byte di input e output e cosa può e cosa non può dimostrare l'hash.

Gli esempi utilizzano campioni sintetici per dimostrare i metodi di elaborazione. Il codice è stato testato solo in un ambiente isolato e non rappresenta una garanzia di tutti i file reali o degli effetti del prodotto. Prima di elaborare documenti importanti, conservare gli originali e rivederli rispettando i limiti e gli elementi di accettazione nel testo.

Perché i nomi dei file sono inaffidabili? Conclusione di una frase

Utilizza l'hash del contenuto per corrispondere alla versione e il nome del file è solo di riferimento. La tabella seguente spiega cosa fare nelle situazioni comuni.

la tua situazionePratiche consigliatemotivo
Entrambi i documenti si chiamano final.pdfConfronta i digest SHA-256, non i nomi dei fileIl contenuto dei file con lo stesso nome può essere diverso
Il file è stato rinominatoUtilizzare digest per confermare se si tratta dello stesso contenuto in byteIl nome non partecipa al byte digest
È necessario confermare a quale input corrisponde la traduzioneRegistrare riepiloghi di input e output separatamenteL'input e l'output hanno contenuti in byte diversi
I file potrebbero essere salvati nuovamente o i metadati potrebbero essere sovrascrittiRegistrare nuovamente come nuovo contenuto byteLe modifiche ai metadati o ai parametri di compressione possono influire sugli hash

Lascia un'impronta digitale in byte per l'input

SHA-256 calcola il digest in base ai byte del file. I file di grandi dimensioni possono essere letti in blocchi senza dover essere caricati in memoria contemporaneamente. Il risultato hash non ha nulla a che fare con la dimensione del blocco, il blocco è solo una strategia di lettura e non fa parte dell'identità del file. I flussi di memoria riportati di seguito sono campioni sintetici e non contengono documenti reali.

Utilizza lo stesso contenuto e blocchi diversi per verificarne l'implementazione

import hashlib
from io import BytesIO

def digest(stream, chunk_size=65536):
    if type(chunk_size) is not int or chunk_size <= 0:
        raise ValueError("positive chunk size required")
    h = hashlib.sha256()
    while block := stream.read(chunk_size):
        h.update(block)
    return h.hexdigest()

raw = b"synthetic document version A\n"
a = digest(BytesIO(raw), 3)
assert a == digest(BytesIO(raw), 4096)
assert a == hashlib.sha256(raw).hexdigest()
assert a != digest(BytesIO(raw.replace(b"A", b"B")))
assert digest(BytesIO(b"")) == hashlib.sha256(b"").hexdigest()
try:
    digest(BytesIO(raw), 0)
except ValueError:
    pass
else:
    raise AssertionError("zero chunk must be rejected")

La funzione inizia a leggere dalla posizione corrente del flusso. Prima di effettuare la chiamata formale, dovrebbe essere chiaro se lo streaming è all'inizio. Se il parser ha già letto parte del contenuto, il risultato del calcolo diretto non è "l'hash dell'intero file". L'approccio più sicuro consiste nell'attivare individualmente l'input di sola lettura o reimpostarlo in modo esplicito prima di calcolarlo su un flusso selezionabile come destinazione.

Qual è la differenza tra gli stessi byte e lo stesso contenuto?

L'hash riflette solo se i byte sono coerenti e le diverse operazioni hanno effetti diversi su di esso.

CondizioneHow the hash may changeHow to explain
Only change the file nameNo changeThe name does not participate in the byte summary
PDF metadata is rewrittenChangeThe page looks the same or may be different
Resave the compressed packageChangeCompression parameters or timestamps can affect bytes
Translate into another languageUsually changeInput and output should be recorded separately

# Core comparison

Judgment modeWhat does that mean?It doesn't mean anything.
Compare file namesIt can only mean the same name.Is the content consistent?
Compare SHA-256 feedsIs the byte content exactly the same?Whether you have the right to use the file, or whether you have copyright

# which method is suitable for you?

if you need to confirm whether the two documents are consistent

Compare the SHA-256 summary, the same description byte content is the same, the file name is not used as the basis.

if you need to track the source of translation

Record the input summary and output summary respectively, and then associate the language and terminology version.

if you plan to use hash to determine file permissions

Don't do this. Hash is not a permission credential and requires additional access control.

# frequently asked questions (FAQ)

1. Will the hash change after changing the file name?

No, I won't. The name does not participate in the byte summary, and the file hash that only changes the file name remains the same.

2. The page looks the same, does the hash have to be the same?

Not necessarily. When PDF metadata is rewritten, the hash may change, even if the page appears the same.

3. Can you use hash to determine whether the user has the right to download the file?

No, I can't. Knowing the summary of the file does not mean you have the right to download it, nor does it mean that you have copyright.

4. What is the risk of cross-tenant resurrection?

Information about whether a file already exists may be disclosed, so access control still needs to be done after a cache hit.

# Translation list starts here

Record the input summary before sending the file to OmniDoc (Product Import); after downloading the translation, record the output summary and associate the language and terminology version. After that, if a colleague reports that "the result is wrong," both parties can first confirm that they are checking the same set of files without having to guess repeatedly around multiple final file names.

Riferimenti: Python hashlib.

# Summary

The same name does not represent the same copy, and the file name can only be used as a reference. Recording input and output with a content hash allows the team to align the file itself before discussing the translation results.

Experience now: upload the document and start translation, keeping the original typesetting

Aggiornato il 2026-11-11