fix: widen file information and decode DICOM text encodings

This commit is contained in:
SantaSpeen committed 2026-10-22 11:20:33 +03:00
1 parent a69fdf2e09
commit b87f8cb961
13 files changed
+279 -33

No files matched your search

+2
View File
@@ -9,3 +9,5 @@ PDF отображается локальным PDF.js в canvas, без пла
Окно сведений показывает свойства файла и таблицу DICOM-тегов с поиском по коду, имени и значению: данные пациента, исследования, серии, оборудования и параметры изображения, если они присутствуют в файле. Чтение метаданных не требует распаковки пикселей и работает независимо от поддержки формата изображения. Бинарные данные и последовательности не выводятся; таблица ограничена 512 тегами, 64 значениями на тег и 2048 символами на значение. Метаданные обрабатываются локально, без внешних сервисов.
Для ограничения памяти DICOM-предпросмотр принимает файлы до 64 МиБ, изображения до 16 миллионов пикселей на кадр и до 128 МиБ распакованных пикселей. Первичное декодирование ограничено 30 секундами. Просмотр доступен в файловом менеджере и по публичным ссылкам с теми же проверками доступа, что и скачивание.
Текстовые теги декодируются из исходных байтов. Автоматический режим распознаёт корректный UTF-8 и учитывает объявленную кодировку; при неверной маркировке UTF-8 использует Windows-1256. Для неоднозначных файлов кодировку можно выбрать вручную, в том числе Windows-1251 и Windows-1256, без повторной загрузки файла. Тег Specific Character Set сохраняет исходное значение из файла, а поле «Используется» показывает фактическую кодировку отображения.
+25 -1
View File
@@ -49,6 +49,30 @@ assert.ok(
)
);
assert.ok(!replies[2]?.metadata.some((entry) => entry.tag === "(7FE0,0010)"));
self.onmessage({
data: {
id: 4,
mode: "metadata",
buffer: fixture(16, {
charset: "ISO_IR 192",
patientBytes: [0xe3, 0xcd, 0xe3, 0xcf],
}),
},
});
assert.equal(replies[3]?.encoding, "windows-1256");
assert.ok(replies[3]?.metadata.some((entry) => entry.value === "محمد"));
self.onmessage({
data: {
id: 5,
mode: "metadata",
buffer: fixture(16, {
charset: "WINDOWS-1256",
patientBytes: Array.from(new TextEncoder().encode("Иван^Петров")),
}),
},
});
assert.equal(replies[4]?.encoding, "utf-8");
assert.ok(replies[4]?.metadata.some((entry) => entry.value === "Иван Петров"));
console.log(
"Production DICOM worker: decode, frame switching and metadata passed"
"Production DICOM worker: decode, metadata and text encodings passed"
);
+43 -8
View File
@@ -14,6 +14,21 @@
</table>
<section v-if="isDicom">
<h3>{{ t("fileInfo.dicom") }}</h3>
<label class="metadata-encoding">
{{ t("files.fileEncoding") }}
<select v-model="encoding">
<option value="auto">{{ t("fileInfo.autoEncoding") }}</option>
<option value="utf-8">UTF-8</option>
<option value="windows-1256">Windows-1256</option>
<option value="windows-1251">Windows-1251</option>
<option value="windows-1252">Windows-1252</option>
<option value="iso-8859-5">ISO-8859-5</option>
<option value="iso-8859-6">ISO-8859-6</option>
</select>
<small v-if="decodedEncoding"
>{{ t("fileInfo.usedEncoding") }}: {{ decodedEncoding }}</small
>
</label>
<p v-if="loading" role="status">{{ t("files.loading") }}</p>
<p v-else-if="error" role="alert">{{ error }}</p>
<template v-else>
@@ -120,11 +135,10 @@ const properties = computed(() => {
]
);
if (file.extension) rows.push([t("fileInfo.extension"), file.extension]);
rows.push(
[t("prompts.lastModified"), new Date(file.modified).toLocaleString()],
[t("fileInfo.mode"), (file.mode & 0o777).toString(8).padStart(3, "0")]
);
if (file.isSymlink) rows.push([t("fileInfo.symlink"), t("fileInfo.yes")]);
rows.push([
t("prompts.lastModified"),
new Date(file.modified).toLocaleString(),
]);
if (file.resolution)
rows.push([
t("prompts.resolution"),
@@ -149,6 +163,9 @@ const metadata = ref<DicomMetadata[]>([]),
filter = ref(""),
error = ref(""),
loading = ref(false);
const encoding = ref("auto"),
decodedEncoding = ref("");
let metadataRequest = 0;
const filteredTags = computed(() => {
const search = filter.value.toLowerCase().trim();
return metadata.value.filter((entry) =>
@@ -189,6 +206,7 @@ watch(
pending.value = {};
hashErrors.value = {};
metadata.value = [];
decodedEncoding.value = "";
filter.value = "";
error.value = "";
loading.value = false;
@@ -212,16 +230,25 @@ watch(
worker = new DicomWorker();
worker.onerror = () => fail(t("documents.loadFailed"));
worker.onmessage = ({ data }) => {
if (signal.aborted) return;
if (signal.aborted || data.id !== metadataRequest) return;
if (data.error) {
fail(`${t("documents.loadFailed")}: ${data.error}`);
return;
}
metadata.value = data.metadata;
decodedEncoding.value = data.encoding;
loading.value = false;
stop();
clearTimeout(timeout);
};
worker.postMessage({ id: 1, mode: "metadata", buffer }, [buffer]);
worker.postMessage(
{
id: ++metadataRequest,
mode: "metadata",
buffer,
encoding: encoding.value,
},
[buffer]
);
} catch (e) {
if (!signal.aborted)
fail(
@@ -234,4 +261,12 @@ watch(
{ immediate: true }
);
onBeforeUnmount(stop);
watch(encoding, () => {
if (!worker || error.value) return;
worker.postMessage({
id: ++metadataRequest,
mode: "metadata",
encoding: encoding.value,
});
});
</script>
+16 -2
View File
@@ -77,7 +77,8 @@
object-fit: scale-down;
}
.file-info.card.floating {
width: min(860px, calc(100vw - 24px));
width: min(1080px, calc(100vw - 32px));
max-width: calc(100vw - 32px);
max-height: calc(100vh - 24px);
display: flex;
flex-direction: column;
@@ -108,7 +109,9 @@
overflow-wrap: anywhere;
}
.file-info th {
width: 34%;
width: 38%;
word-break: normal;
overflow-wrap: normal;
font-weight: 500;
color: var(--textSecondary);
}
@@ -124,6 +127,17 @@
.file-info input {
width: 100%;
}
.file-info .metadata-encoding {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 12px;
}
.file-info .metadata-encoding select {
width: auto;
margin: 0;
}
.file-info details {
margin-top: 20px;
}
+3 -4
View File
@@ -360,13 +360,12 @@
"path": "Path",
"type": "Type",
"extension": "Extension",
"mode": "Permissions (Unix)",
"symlink": "Symbolic link",
"yes": "Yes",
"selected": "Selected items",
"bytes": "bytes",
"searchTags": "Search DICOM tags or values",
"noMetadata": "No matching metadata",
"checksums": "Checksums"
"checksums": "Checksums",
"autoEncoding": "Automatic",
"usedEncoding": "Using"
}
}
+3 -4
View File
@@ -357,13 +357,12 @@
"path": "Путь",
"type": "Тип",
"extension": "Расширение",
"mode": "Права доступа (Unix)",
"symlink": "Символическая ссылка",
"yes": "Да",
"selected": "Выбрано объектов",
"bytes": "байт",
"searchTags": "Поиск по тегам и значениям DICOM",
"noMetadata": "Метаданные не найдены",
"checksums": "Контрольные суммы"
"checksums": "Контрольные суммы",
"autoEncoding": "Автоматически",
"usedEncoding": "Используется"
}
}
+3
View File
@@ -5,11 +5,14 @@ declare module "daikon" {
vr: string;
value: unknown;
sublist: boolean;
offsetValue: number;
offsetEnd: number;
}
export const Dictionary: {
getDescription(group: number, element: number): string;
};
export interface Image {
inflated?: ArrayBuffer;
tags: Record<string, Tag>;
tagsFlat: Record<string, Tag>;
littleEndian: boolean;
@@ -49,6 +49,61 @@ describe("DICOM rendering", () => {
(tag: { tag: string }) => tag.tag === "(7FE0,0010)"
)
).toBe(false);
const checkName = (
id: number,
buffer: ArrayBuffer,
encoding: string,
expected: string
) => {
scope.onmessage({ data: { id, mode: "metadata", buffer, encoding } });
const result = postMessage.mock.lastCall![0];
expect(result.error).toBeUndefined();
expect(
result.metadata.find(
(entry: { tag: string }) => entry.tag === "(0010,0010)"
).value
).toBe(expected);
return result;
};
expect(
checkName(
4,
fixture(16, {
charset: "ISO_IR 192",
patientBytes: [0xe3, 0xcd, 0xe3, 0xcf],
}),
"auto",
"محمد"
).encoding
).toBe("windows-1256");
expect(
checkName(
5,
fixture(16, {
charset: "WINDOWS-1256",
patientBytes: Array.from(new TextEncoder().encode("Иван^Петров")),
}),
"auto",
"Иван Петров"
).encoding
).toBe("utf-8");
checkName(
6,
fixture(16, {
charset: "ISO_IR 192",
patientBytes: [0xc8, 0xe2, 0xe0, 0xed],
}),
"windows-1251",
"Иван"
);
scope.onmessage({
data: { id: 7, mode: "metadata", encoding: "windows-1251" },
});
expect(
postMessage.mock.lastCall![0].metadata.find(
(entry: { tag: string }) => entry.tag === "(0010,0010)"
).value
).toBe("Иван");
} finally {
vi.unstubAllGlobals();
}
@@ -1,4 +1,7 @@
export function fixture(bits = 16) {
export function fixture(
bits = 16,
options: { charset?: string; patientBytes?: number[] } = {}
) {
const data: number[] = [...new Uint8Array(128), 68, 73, 67, 77];
const add = (group: number, element: number, vr: string, bytes: number[]) => {
if (bytes.length % 2) bytes.push(vr === "UI" ? 0 : 32);
@@ -17,9 +20,10 @@ export function fixture(bits = 16) {
};
const text = (s: string) => Array.from(new TextEncoder().encode(s));
add(2, 0x10, "UI", text("1.2.840.10008.1.2.1"));
if (options.charset) add(8, 5, "CS", text(options.charset));
add(8, 0x20, "DA", text("20261022"));
add(8, 0x60, "CS", text("CT"));
add(0x10, 0x10, "PN", text("Example^Patient"));
add(0x10, 0x10, "PN", options.patientBytes || text("Example^Patient"));
add(0x10, 0x20, "LO", text("TEST-123"));
add(0x28, 2, "US", [1, 0]);
add(0x28, 4, "CS", text("MONOCHROME2"));
+86 -3
View File
@@ -1,4 +1,4 @@
import { Dictionary, type Image } from "daikon";
import { Dictionary, type Image, type Tag } from "daikon";
export interface DicomMetadata {
tag: string;
@@ -6,7 +6,85 @@ export interface DicomMetadata {
value: string;
}
export function dicomMetadata(image: Image): DicomMetadata[] {
const textVRs = ["PN", "LO", "SH", "ST", "LT", "UC", "UT"];
const encodings: Record<string, string> = {
ISO_IR192: "utf-8",
UTF8: "utf-8",
ISO_IR100: "windows-1252",
ISO_IR101: "iso-8859-2",
ISO_IR109: "iso-8859-3",
ISO_IR110: "iso-8859-4",
ISO_IR144: "iso-8859-5",
ISO_IR127: "iso-8859-6",
ISO_IR126: "iso-8859-7",
ISO_IR138: "iso-8859-8",
ISO_IR148: "iso-8859-9",
ISO_IR166: "windows-874",
GB18030: "gb18030",
GBK: "gbk",
ISO_IR13: "shift_jis",
WINDOWS1256: "windows-1256",
CP1256: "windows-1256",
WINDOWS1251: "windows-1251",
CP1251: "windows-1251",
};
function rawText(tag: Tag, buffer: ArrayBuffer) {
if (
tag.offsetValue < 0 ||
tag.offsetEnd < tag.offsetValue ||
tag.offsetEnd > buffer.byteLength
)
return new Uint8Array();
return new Uint8Array(
buffer,
tag.offsetValue,
Math.min(tag.offsetEnd - tag.offsetValue, 65536)
);
}
export function dicomTextEncoding(
image: Image,
buffer: ArrayBuffer,
preferred = "auto"
) {
if (preferred !== "auto") {
new TextDecoder(preferred);
return preferred;
}
const tags = Object.values(image.tags);
const charset = tags.find((tag) => tag.group === 8 && tag.element === 5);
const declared = String(
Array.isArray(charset?.value) ? charset.value[0] : charset?.value || ""
)
.replace(/[\s-]/g, "")
.toUpperCase();
let nonAscii = false,
validUtf8 = true;
for (const tag of tags.filter(
(tag) => textVRs.includes(tag.vr) && !tag.sublist
)) {
const bytes = rawText(tag, buffer);
if (!bytes.some((byte) => byte > 127)) continue;
nonAscii = true;
try {
new TextDecoder("utf-8", { fatal: true }).decode(bytes);
} catch {
validUtf8 = false;
break;
}
}
if (nonAscii && validUtf8) return "utf-8";
const known = encodings[declared];
// Broken exporters can declare UTF-8 while writing legacy Arabic bytes.
// Single-byte encodings are ambiguous; allow an explicit override in the UI.
if (known && !(known === "utf-8" && !validUtf8)) return known;
return nonAscii ? "windows-1256" : "utf-8";
}
export function dicomMetadata(
image: Image,
buffer?: ArrayBuffer,
encoding = "utf-8"
): DicomMetadata[] {
const hex = (n: number) => n.toString(16).toUpperCase().padStart(4, "0");
return Object.values({ ...image.tagsFlat, ...image.tags })
.filter(
@@ -20,9 +98,14 @@ export function dicomMetadata(image: Image): DicomMetadata[] {
.sort((a, b) => a.group - b.group || a.element - b.element)
.slice(0, 512)
.flatMap((tag) => {
const values = Array.isArray(tag.value)
let values = Array.isArray(tag.value)
? tag.value.slice(0, 64)
: [tag.value];
if (buffer && textVRs.includes(tag.vr)) {
let text = new TextDecoder(encoding).decode(rawText(tag, buffer));
if (tag.vr === "PN") text = text.replace(/\^/g, " ");
values = text.split("\\").slice(0, 64);
}
const value = values
.filter((v) => typeof v === "string" || typeof v === "number")
.map((v) => String(v).replace(/\0/g, "").trim())
+35 -7
View File
@@ -1,8 +1,10 @@
import { Series, type Image } from "daikon";
import { storedValue, windowPixel } from "./dicom-pixels";
import { dicomMetadata } from "./dicom-metadata";
import { dicomMetadata, dicomTextEncoding } from "./dicom-metadata";
let image: Image;
let metadataImage: Image | null = null,
metadataBuffer: ArrayBuffer | undefined;
let raw: DataView;
let rows = 0,
cols = 0,
@@ -27,15 +29,41 @@ const pixel = (index: number) =>
intercept;
self.onmessage = (event: MessageEvent) => {
const { id, buffer, mode, frame = 0, center, width } = event.data;
const {
id,
buffer,
mode,
encoding = "auto",
frame = 0,
center,
width,
} = event.data;
try {
if (mode === "metadata") {
if (buffer) {
metadataImage = Series.parseImage(new DataView(buffer));
metadataBuffer = metadataImage?.inflated || buffer;
}
if (!metadataImage || !metadataBuffer)
throw new Error("Invalid DICOM file");
const selectedEncoding = dicomTextEncoding(
metadataImage,
metadataBuffer,
encoding
);
self.postMessage({
id,
metadata: dicomMetadata(
metadataImage,
metadataBuffer,
selectedEncoding
),
encoding: selectedEncoding,
});
return;
}
if (buffer) {
const parsed = Series.parseImage(new DataView(buffer));
if (mode === "metadata") {
if (!parsed) throw new Error("Invalid DICOM file");
self.postMessage({ id, metadata: dicomMetadata(parsed) });
return;
}
if (!parsed?.hasPixelData())
throw new Error("DICOM has no supported image data");
image = parsed;
+1 -1
View File
@@ -1,4 +1,4 @@
param([string]$Version = '3.0.0-sso.9')
param([string]$Version = '3.0.0-sso.10')
$ErrorActionPreference = 'Stop'
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Push-Location $repo
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
VERSION="${VERSION:-3.0.0-sso.9}"
VERSION="${VERSION:-3.0.0-sso.10}"
COMMIT=$(git rev-parse --short HEAD)
(cd frontend && pnpm install --frozen-lockfile && pnpm run build)
mkdir -p build/release/linux-amd64