feat: fit DICOM previews and show searchable file metadata

This commit is contained in:
SantaSpeen committed 2026-10-22 11:07:27 +03:00
1 parent 7a1d18dfc6
commit a69fdf2e09
17 files changed
+471 -221

No files matched your search

+4
View File
@@ -4,4 +4,8 @@ PDF отображается локальным PDF.js в canvas, без пла
Файлы `.dcm` и `.dicom` открываются локальным DICOM-декодером в отдельном Worker. Поддерживаются 8/16-битные монохромные изображения (MONOCHROME1/2), 8-битный RGB и сжатые данные, поддерживаемые декодером Daikon. Доступны выбор кадра, ширина/уровень окна и сброс настроек. Неподдерживаемый формат сообщает об ошибке; файл остаётся доступен для скачивания. Файлы `.dcm` и `.dicom` открываются локальным DICOM-декодером в отдельном Worker. Поддерживаются 8/16-битные монохромные изображения (MONOCHROME1/2), 8-битный RGB и сжатые данные, поддерживаемые декодером Daikon. Доступны выбор кадра, ширина/уровень окна и сброс настроек. Неподдерживаемый формат сообщает об ошибке; файл остаётся доступен для скачивания.
Изображение DICOM целиком вписывается в доступную область под панелью инструментов с сохранением пропорций. Большие изображения уменьшаются, небольшие не увеличиваются.
Окно сведений показывает свойства файла и таблицу DICOM-тегов с поиском по коду, имени и значению: данные пациента, исследования, серии, оборудования и параметры изображения, если они присутствуют в файле. Чтение метаданных не требует распаковки пикселей и работает независимо от поддержки формата изображения. Бинарные данные и последовательности не выводятся; таблица ограничена 512 тегами, 64 значениями на тег и 2048 символами на значение. Метаданные обрабатываются локально, без внешних сервисов.
Для ограничения памяти DICOM-предпросмотр принимает файлы до 64 МиБ, изображения до 16 миллионов пикселей на кадр и до 128 МиБ распакованных пикселей. Первичное декодирование ограничено 30 секундами. Просмотр доступен в файловом менеджере и по публичным ссылкам с теми же проверками доступа, что и скачивание. Для ограничения памяти DICOM-предпросмотр принимает файлы до 64 МиБ, изображения до 16 миллионов пикселей на кадр и до 128 МиБ распакованных пикселей. Первичное декодирование ограничено 30 секундами. Просмотр доступен в файловом менеджере и по публичным ссылкам с теми же проверками доступа, что и скачивание.
+11 -1
View File
@@ -41,4 +41,14 @@ assert.equal(replies[0]?.rgba[12], 255);
self.onmessage({ data: { id: 2, frame: 1 } }); self.onmessage({ data: { id: 2, frame: 1 } });
assert.equal(replies[1]?.error, undefined); assert.equal(replies[1]?.error, undefined);
assert.equal(replies[1]?.rgba[0], 255); assert.equal(replies[1]?.rgba[0], 255);
console.log("Production DICOM worker: decode and frame switching passed"); self.onmessage({ data: { id: 3, mode: "metadata", buffer: fixture(32) } });
assert.equal(replies[2]?.error, undefined);
assert.ok(
replies[2]?.metadata.some(
(entry) => entry.tag === "(0010,0010)" && entry.value === "Example Patient"
)
);
assert.ok(!replies[2]?.metadata.some((entry) => entry.tag === "(7FE0,0010)"));
console.log(
"Production DICOM worker: decode, frame switching and metadata passed"
);
+14 -31
View File
@@ -1,5 +1,10 @@
<template> <template>
<div class="document-viewer" @wheel.stop @touchmove.stop @keydown.stop> <div
class="document-viewer dicom-viewer"
@wheel.stop
@touchmove.stop
@keydown.stop
>
<div class="document-tools"> <div class="document-tools">
<strong>DICOM</strong> <strong>DICOM</strong>
<template v-if="ready"> <template v-if="ready">
@@ -39,6 +44,7 @@
import { nextTick, onBeforeUnmount, ref, watch } from "vue"; import { nextTick, onBeforeUnmount, ref, watch } from "vue";
import { useI18n } from "vue-i18n"; import { useI18n } from "vue-i18n";
import DicomWorker from "@/utils/dicom.worker?worker"; import DicomWorker from "@/utils/dicom.worker?worker";
import { readDicomFile } from "@/utils/dicom-file";
const props = defineProps<{ source: string }>(); const props = defineProps<{ source: string }>();
const { t } = useI18n(); const { t } = useI18n();
const canvas = ref<HTMLCanvasElement>(); const canvas = ref<HTMLCanvasElement>();
@@ -100,35 +106,8 @@ watch(
controller = new AbortController(); controller = new AbortController();
const signal = controller.signal; const signal = controller.signal;
try { try {
const response = await fetch(source, { const buffer = await readDicomFile(source, signal);
credentials: "same-origin",
signal,
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const limit = 64 * 1024 * 1024;
if (Number(response.headers.get("Content-Length")) > limit)
throw new Error(t("documents.tooLarge"));
const reader = response.body?.getReader();
if (!reader) throw new Error(t("documents.loadFailed"));
const chunks: Uint8Array[] = [];
let length = 0;
while (true) {
const chunk = await reader.read();
if (chunk.done) break;
length += chunk.value.length;
if (length > limit) {
await reader.cancel();
throw new Error(t("documents.tooLarge"));
}
chunks.push(chunk.value);
}
if (signal.aborted || id !== sequence) return; if (signal.aborted || id !== sequence) return;
const data = new Uint8Array(length);
let offset = 0;
for (const chunk of chunks) {
data.set(chunk, offset);
offset += chunk.length;
}
worker = new DicomWorker(); worker = new DicomWorker();
timeout = setTimeout(() => { timeout = setTimeout(() => {
error.value = t("documents.loadFailed"); error.value = t("documents.loadFailed");
@@ -167,11 +146,15 @@ watch(
0 0
); );
}; };
worker.postMessage({ id, buffer: data.buffer }, [data.buffer]); worker.postMessage({ id, buffer }, [buffer]);
} catch (e) { } catch (e) {
if (!signal.aborted && id === sequence) if (!signal.aborted && id === sequence)
error.value = error.value =
e instanceof Error ? e.message : t("documents.loadFailed"); e instanceof Error && e.message === "DICOM_TOO_LARGE"
? t("documents.tooLarge")
: e instanceof Error
? e.message
: t("documents.loadFailed");
} }
}, },
{ immediate: true } { immediate: true }
+216 -175
View File
@@ -1,196 +1,237 @@
<template> <template>
<div class="card floating"> <div class="card floating file-info">
<div class="card-title"> <div class="card-title">
<h2>{{ $t("prompts.fileInfo") }}</h2> <h2>{{ t("prompts.fileInfo") }}</h2>
</div> </div>
<div class="card-content"> <div class="card-content">
<p v-if="selected.length > 1"> <table :aria-label="t('files.metadata')">
{{ $t("prompts.filesSelected", { count: selected.length }) }} <tbody>
</p> <tr v-for="row in properties" :key="row[0]">
<th scope="row">{{ row[0] }}</th>
<p class="break-word" v-if="selected.length < 2"> <td>{{ row[1] }}</td>
<strong>{{ $t("prompts.displayName") }}</strong> {{ name }} </tr>
</p> </tbody>
</table>
<p v-if="!dir || selected.length > 1"> <section v-if="isDicom">
<strong>{{ $t("prompts.size") }}:</strong> <h3>{{ t("fileInfo.dicom") }}</h3>
<span id="content_length"></span> {{ humanSize }} <p v-if="loading" role="status">{{ t("files.loading") }}</p>
</p> <p v-else-if="error" role="alert">{{ error }}</p>
<template v-else>
<div v-if="resolution"> <input
<strong>{{ $t("prompts.resolution") }}:</strong> v-model="filter"
{{ resolution.width }} x {{ resolution.height }} type="search"
</div> class="input"
:placeholder="t('fileInfo.searchTags')"
<p v-if="selected.length < 2" :title="modTime"> :aria-label="t('fileInfo.searchTags')"
<strong>{{ $t("prompts.lastModified") }}:</strong> {{ humanTime }} />
</p> <table :aria-label="t('fileInfo.dicom')">
<tbody>
<template v-if="dir && selected.length === 0"> <tr v-for="entry in filteredTags" :key="entry.tag">
<p> <th scope="row">
<strong>{{ $t("prompts.numberFiles") }}:</strong> {{ req.numFiles }} {{ entry.name }}<code class="dicom-tag">{{ entry.tag }}</code>
</p> </th>
<p> <td>{{ entry.value }}</td>
<strong>{{ $t("prompts.numberDirs") }}:</strong> {{ req.numDirs }} </tr>
</p> </tbody>
</template> </table>
<p v-if="!filteredTags.length">{{ t("fileInfo.noMetadata") }}</p>
<template v-if="!dir"> </template>
<p> </section>
<strong>MD5: </strong <details v-if="current && !current.isDir && !isPublic">
><code <summary>{{ t("fileInfo.checksums") }}</summary>
><a <table :aria-label="t('fileInfo.checksums')">
@click="checksum($event, 'md5')" <tbody>
@keypress.enter="checksum($event, 'md5')" <tr v-for="algo in algorithms" :key="algo">
tabindex="2" <th scope="row">{{ algo.toUpperCase() }}</th>
>{{ $t("prompts.show") }}</a <td>
></code <code v-if="hashes[algo]">{{ hashes[algo] }}</code>
> <button
</p> v-else
<p> class="button button--flat"
<strong>SHA1: </strong :disabled="pending[algo]"
><code @click="checksum(algo)"
><a >
@click="checksum($event, 'sha1')" {{ pending[algo] ? t("files.loading") : t("prompts.show") }}
@keypress.enter="checksum($event, 'sha1')" </button>
tabindex="3" <span v-if="hashErrors[algo]" role="alert">{{
>{{ $t("prompts.show") }}</a hashErrors[algo]
></code }}</span>
> </td>
</p> </tr>
<p> </tbody>
<strong>SHA256: </strong </table>
><code </details>
><a
@click="checksum($event, 'sha256')"
@keypress.enter="checksum($event, 'sha256')"
tabindex="4"
>{{ $t("prompts.show") }}</a
></code
>
</p>
<p>
<strong>SHA512: </strong
><code
><a
@click="checksum($event, 'sha512')"
@keypress.enter="checksum($event, 'sha512')"
tabindex="5"
>{{ $t("prompts.show") }}</a
></code
>
</p>
</template>
</div> </div>
<div class="card-action"> <div class="card-action">
<button <button
id="focus-prompt" id="focus-prompt"
type="submit"
@click="closeHovers"
class="button button--flat" class="button button--flat"
:aria-label="$t('buttons.ok')" @click="layout.closeHovers"
:title="$t('buttons.ok')"
> >
{{ $t("buttons.ok") }} {{ t("buttons.close") }}
</button> </button>
</div> </div>
</div> </div>
</template> </template>
<script setup lang="ts">
<script> import { computed, onBeforeUnmount, ref, watch } from "vue";
import { mapActions, mapState } from "pinia"; import { useI18n } from "vue-i18n";
import { useRoute } from "vue-router";
import { useFileStore } from "@/stores/file"; import { useFileStore } from "@/stores/file";
import { useLayoutStore } from "@/stores/layout"; import { useLayoutStore } from "@/stores/layout";
import { files as api, pub } from "@/api";
import { filesize } from "@/utils"; import { filesize } from "@/utils";
import dayjs from "dayjs"; import { readDicomFile } from "@/utils/dicom-file";
import { files as api } from "@/api"; import type { DicomMetadata } from "@/utils/dicom-metadata";
import DicomWorker from "@/utils/dicom.worker?worker";
export default { const fileStore = useFileStore(),
name: "info", layout = useLayoutStore(),
inject: ["$showError"], route = useRoute();
computed: { const { t } = useI18n();
...mapState(useFileStore, [ const entries = computed(() =>
"req", fileStore.isListing && fileStore.selected.length
"selected", ? fileStore.selected
"selectedCount", .map((i) => fileStore.req?.items[i])
"isListing", .filter((item): item is ResourceItem => !!item)
]), : fileStore.req
humanSize: function () { ? [fileStore.req]
if (this.selectedCount === 0 || !this.isListing) { : []
return filesize(this.req.size); );
} const current = computed(() =>
entries.value.length === 1 ? entries.value[0] : undefined
let sum = 0; );
const isPublic = computed(() => /^\/(s|share)\//.test(route.path));
for (const selected of this.selected) { const isDicom = computed(
sum += this.req.items[selected].size; () =>
} !!current.value &&
!current.value.isDir &&
return filesize(sum); /\.(dcm|dicom)$/i.test(current.value.name)
}, );
humanTime: function () { const properties = computed(() => {
if (this.selectedCount === 0) { const file = current.value;
return dayjs(this.req.modified).fromNow(); const rows: [string, string | number][] = [];
} if (file) {
rows.push(
return dayjs(this.req.items[this.selected[0]].modified).fromNow(); [t("files.name"), file.name],
}, [t("fileInfo.path"), file.path],
modTime: function () { [
if (this.selectedCount === 0) { t("fileInfo.type"),
return new Date(Date.parse(this.req.modified)).toLocaleString(); file.isDir ? t("buttons.folder") : isDicom.value ? "DICOM" : file.type,
} ]
);
return new Date( if (file.extension) rows.push([t("fileInfo.extension"), file.extension]);
Date.parse(this.req.items[this.selected[0]].modified) rows.push(
).toLocaleString(); [t("prompts.lastModified"), new Date(file.modified).toLocaleString()],
}, [t("fileInfo.mode"), (file.mode & 0o777).toString(8).padStart(3, "0")]
name: function () { );
return this.selectedCount === 0 if (file.isSymlink) rows.push([t("fileInfo.symlink"), t("fileInfo.yes")]);
? this.req.name if (file.resolution)
: this.req.items[this.selected[0]].name; rows.push([
}, t("prompts.resolution"),
dir: function () { `${file.resolution.width} × ${file.resolution.height}`,
return ( ]);
this.selectedCount > 1 || if (file.isDir && file === fileStore.req)
(this.selectedCount === 0 rows.push(
? this.req.isDir [t("prompts.numberFiles"), fileStore.req.numFiles],
: this.req.items[this.selected[0]].isDir) [t("prompts.numberDirs"), fileStore.req.numDirs]
); );
}, } else rows.push([t("fileInfo.selected"), entries.value.length]);
resolution: function () { if (!file?.isDir) {
if (this.selectedCount === 1) { const size = entries.value.reduce((sum, item) => sum + item.size, 0);
const selectedItem = this.req.items[this.selected[0]]; rows.push([
if (selectedItem && selectedItem.type === "image") { t("prompts.size"),
return selectedItem.resolution; `${filesize(size)} (${size.toLocaleString()} ${t("fileInfo.bytes")})`,
]);
}
return rows;
});
const metadata = ref<DicomMetadata[]>([]),
filter = ref(""),
error = ref(""),
loading = ref(false);
const filteredTags = computed(() => {
const search = filter.value.toLowerCase().trim();
return metadata.value.filter((entry) =>
`${entry.tag} ${entry.name} ${entry.value}`.toLowerCase().includes(search)
);
});
let worker: Worker | undefined, controller: AbortController | undefined;
let timeout: ReturnType<typeof setTimeout> | undefined;
function stop() {
controller?.abort();
worker?.terminate();
worker = undefined;
clearTimeout(timeout);
}
const algorithms: ChecksumAlg[] = ["md5", "sha1", "sha256", "sha512"];
const hashes = ref<Partial<Record<ChecksumAlg, string>>>({});
const pending = ref<Partial<Record<ChecksumAlg, boolean>>>({});
const hashErrors = ref<Partial<Record<ChecksumAlg, string>>>({});
async function checksum(algo: ChecksumAlg) {
const file = current.value;
if (!file) return;
pending.value[algo] = true;
hashErrors.value[algo] = "";
try {
const hash = await api.checksum(file.url, algo);
if (current.value === file) hashes.value[algo] = hash;
} catch (e) {
if (current.value === file) hashErrors.value[algo] = String(e);
} finally {
if (current.value === file) pending.value[algo] = false;
}
}
watch(
current,
async (file) => {
stop();
hashes.value = {};
pending.value = {};
hashErrors.value = {};
metadata.value = [];
filter.value = "";
error.value = "";
loading.value = false;
if (!file || !isDicom.value) return;
loading.value = true;
controller = new AbortController();
const signal = controller.signal;
const fail = (message: string) => {
error.value = message;
loading.value = false;
stop();
};
timeout = setTimeout(() => fail(t("documents.loadFailed")), 30000);
try {
const source =
isPublic.value && fileStore.req
? pub.getDownloadURL({ ...fileStore.req, ...file }, true)
: api.getDownloadURL(file, true);
const buffer = await readDicomFile(source, signal);
if (signal.aborted) return;
worker = new DicomWorker();
worker.onerror = () => fail(t("documents.loadFailed"));
worker.onmessage = ({ data }) => {
if (signal.aborted) return;
if (data.error) {
fail(`${t("documents.loadFailed")}: ${data.error}`);
return;
} }
} else if (this.req && this.req.type === "image") { metadata.value = data.metadata;
return this.req.resolution; loading.value = false;
} stop();
return null; };
}, worker.postMessage({ id: 1, mode: "metadata", buffer }, [buffer]);
} catch (e) {
if (!signal.aborted)
fail(
e instanceof Error && e.message === "DICOM_TOO_LARGE"
? t("documents.tooLarge")
: `${t("documents.loadFailed")}: ${String(e)}`
);
}
}, },
methods: { { immediate: true }
...mapActions(useLayoutStore, ["closeHovers"]), );
checksum: async function (event, algo) { onBeforeUnmount(stop);
event.preventDefault();
let link;
if (this.selectedCount) {
link = this.req.items[this.selected[0]].url;
} else {
link = this.$route.path;
}
try {
const hash = await api.checksum(link, algo);
event.target.textContent = hash;
} catch (e) {
this.$showError(e);
}
},
},
};
</script> </script>
+82
View File
@@ -48,6 +48,88 @@
max-width: 100%; max-width: 100%;
height: auto; height: auto;
} }
.dicom-viewer {
min-height: 0;
}
#previewer .preview.document-preview {
position: absolute;
top: 4em;
bottom: 0;
width: 100%;
height: auto;
}
.dicom-viewer .document-tools {
flex-shrink: 0;
}
.dicom-viewer .document-stage {
display: flex;
align-items: center;
justify-content: center;
min-width: 0;
overflow: hidden;
}
.dicom-viewer .document-stage canvas {
display: block;
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
object-fit: scale-down;
}
.file-info.card.floating {
width: min(860px, calc(100vw - 24px));
max-height: calc(100vh - 24px);
display: flex;
flex-direction: column;
}
.file-info .card-content {
min-height: 0;
overflow: auto;
}
.file-info .card-title,
.file-info .card-action {
flex-shrink: 0;
}
.file-info h3 {
margin: 20px 0 12px;
font-size: 15px;
}
.file-info table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
}
.file-info th,
.file-info td {
padding: 9px 12px;
border-bottom: 1px solid var(--divider);
text-align: start;
vertical-align: top;
overflow-wrap: anywhere;
}
.file-info th {
width: 34%;
font-weight: 500;
color: var(--textSecondary);
}
.file-info td {
color: var(--textPrimary);
}
.file-info .dicom-tag {
display: block;
font-size: 11px;
opacity: 0.7;
margin-top: 4px;
}
.file-info input {
width: 100%;
}
.file-info details {
margin-top: 20px;
}
.file-info summary {
cursor: pointer;
}
.document-error { .document-error {
padding: 16px; padding: 16px;
overflow-wrap: anywhere; overflow-wrap: anywhere;
+14
View File
@@ -354,5 +354,19 @@
"pdfPage": "PDF page", "pdfPage": "PDF page",
"tooLarge": "File too large for preview (64 MiB maximum).", "tooLarge": "File too large for preview (64 MiB maximum).",
"loadFailed": "Unable to display this file" "loadFailed": "Unable to display this file"
},
"fileInfo": {
"dicom": "DICOM metadata",
"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"
} }
} }
+14
View File
@@ -351,5 +351,19 @@
"pdfPage": "Страница PDF", "pdfPage": "Страница PDF",
"tooLarge": "Файл слишком большой для предпросмотра (максимум 64 МиБ).", "tooLarge": "Файл слишком большой для предпросмотра (максимум 64 МиБ).",
"loadFailed": "Не удалось отобразить файл" "loadFailed": "Не удалось отобразить файл"
},
"fileInfo": {
"dicom": "Метаданные DICOM",
"path": "Путь",
"type": "Тип",
"extension": "Расширение",
"mode": "Права доступа (Unix)",
"symlink": "Символическая ссылка",
"yes": "Да",
"selected": "Выбрано объектов",
"bytes": "байт",
"searchTags": "Поиск по тегам и значениям DICOM",
"noMetadata": "Метаданные не найдены",
"checksums": "Контрольные суммы"
} }
} }
+12
View File
@@ -1,5 +1,17 @@
declare module "daikon" { declare module "daikon" {
export interface Tag {
group: number;
element: number;
vr: string;
value: unknown;
sublist: boolean;
}
export const Dictionary: {
getDescription(group: number, element: number): string;
};
export interface Image { export interface Image {
tags: Record<string, Tag>;
tagsFlat: Record<string, Tag>;
littleEndian: boolean; littleEndian: boolean;
hasPixelData(): boolean; hasPixelData(): boolean;
isCompressed(): boolean; isCompressed(): boolean;
+2 -8
View File
@@ -1,4 +1,5 @@
interface ResourceBase { interface ResourceBase {
resolution?: { width: number; height: number };
path: string; path: string;
name: string; name: string;
size: number; size: number;
@@ -40,14 +41,7 @@ type ResourceType =
| "textImmutable"; | "textImmutable";
type DownloadFormat = type DownloadFormat =
| "zip" "zip" | "tar" | "targz" | "tarbz2" | "tarxz" | "tarlz4" | "tarsz" | null;
| "tar"
| "targz"
| "tarbz2"
| "tarxz"
| "tarlz4"
| "tarsz"
| null;
interface ClipItem { interface ClipItem {
from: string; from: string;
@@ -33,6 +33,22 @@ describe("DICOM rendering", () => {
expect(first.rgba[12]).toBe(255); expect(first.rgba[12]).toBe(255);
scope.onmessage({ data: { id: 2, frame: 1 } }); scope.onmessage({ data: { id: 2, frame: 1 } });
expect(postMessage.mock.calls[1][0].rgba[0]).toBe(255); expect(postMessage.mock.calls[1][0].rgba[0]).toBe(255);
scope.onmessage({
data: { id: 3, mode: "metadata", buffer: fixture(32) },
});
const metadata = postMessage.mock.calls[2][0];
expect(metadata.error).toBeUndefined();
expect(metadata.rgba).toBeUndefined();
expect(metadata.metadata).toContainEqual({
tag: "(0010,0010)",
name: "Patient Name",
value: "Example Patient",
});
expect(
metadata.metadata.some(
(tag: { tag: string }) => tag.tag === "(7FE0,0010)"
)
).toBe(false);
} finally { } finally {
vi.unstubAllGlobals(); vi.unstubAllGlobals();
} }
@@ -1,4 +1,4 @@
export function fixture() { export function fixture(bits = 16) {
const data: number[] = [...new Uint8Array(128), 68, 73, 67, 77]; const data: number[] = [...new Uint8Array(128), 68, 73, 67, 77];
const add = (group: number, element: number, vr: string, bytes: number[]) => { const add = (group: number, element: number, vr: string, bytes: number[]) => {
if (bytes.length % 2) bytes.push(vr === "UI" ? 0 : 32); if (bytes.length % 2) bytes.push(vr === "UI" ? 0 : 32);
@@ -17,12 +17,16 @@ export function fixture() {
}; };
const text = (s: string) => Array.from(new TextEncoder().encode(s)); const text = (s: string) => Array.from(new TextEncoder().encode(s));
add(2, 0x10, "UI", text("1.2.840.10008.1.2.1")); add(2, 0x10, "UI", text("1.2.840.10008.1.2.1"));
add(8, 0x20, "DA", text("20261022"));
add(8, 0x60, "CS", text("CT"));
add(0x10, 0x10, "PN", text("Example^Patient"));
add(0x10, 0x20, "LO", text("TEST-123"));
add(0x28, 2, "US", [1, 0]); add(0x28, 2, "US", [1, 0]);
add(0x28, 4, "CS", text("MONOCHROME2")); add(0x28, 4, "CS", text("MONOCHROME2"));
add(0x28, 8, "IS", text("2")); add(0x28, 8, "IS", text("2"));
add(0x28, 0x10, "US", [2, 0]); add(0x28, 0x10, "US", [2, 0]);
add(0x28, 0x11, "US", [2, 0]); add(0x28, 0x11, "US", [2, 0]);
add(0x28, 0x100, "US", [16, 0]); add(0x28, 0x100, "US", [bits, 0]);
add(0x28, 0x101, "US", [12, 0]); add(0x28, 0x101, "US", [12, 0]);
add(0x28, 0x102, "US", [11, 0]); add(0x28, 0x102, "US", [11, 0]);
add(0x28, 0x103, "US", [1, 0]); add(0x28, 0x103, "US", [1, 0]);
+28
View File
@@ -0,0 +1,28 @@
export async function readDicomFile(source: string, signal: AbortSignal) {
const response = await fetch(source, { credentials: "same-origin", signal });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const limit = 64 * 1024 * 1024;
if (Number(response.headers.get("Content-Length")) > limit)
throw new Error("DICOM_TOO_LARGE");
const reader = response.body?.getReader();
if (!reader) throw new Error("Empty response");
const chunks: Uint8Array[] = [];
let length = 0;
while (true) {
const chunk = await reader.read();
if (chunk.done) break;
length += chunk.value.length;
if (length > limit) {
await reader.cancel();
throw new Error("DICOM_TOO_LARGE");
}
chunks.push(chunk.value);
}
const data = new Uint8Array(length);
let offset = 0;
for (const chunk of chunks) {
data.set(chunk, offset);
offset += chunk.length;
}
return data.buffer;
}
+42
View File
@@ -0,0 +1,42 @@
import { Dictionary, type Image } from "daikon";
export interface DicomMetadata {
tag: string;
name: string;
value: string;
}
export function dicomMetadata(image: Image): DicomMetadata[] {
const hex = (n: number) => n.toString(16).toUpperCase().padStart(4, "0");
return Object.values({ ...image.tagsFlat, ...image.tags })
.filter(
(tag) =>
tag &&
!tag.sublist &&
tag.value != null &&
!["OB", "OW", "OF", "OD", "OL", "OV", "UN", "SQ"].includes(tag.vr) &&
!(tag.group === 0x7fe0 && tag.element === 0x10)
)
.sort((a, b) => a.group - b.group || a.element - b.element)
.slice(0, 512)
.flatMap((tag) => {
const values = Array.isArray(tag.value)
? tag.value.slice(0, 64)
: [tag.value];
const value = values
.filter((v) => typeof v === "string" || typeof v === "number")
.map((v) => String(v).replace(/\0/g, "").trim())
.join(" \\ ")
.slice(0, 2048);
if (!value) return [];
return [
{
tag: `(${hex(tag.group)},${hex(tag.element)})`,
name: (
Dictionary.getDescription(tag.group, tag.element) || "DICOM"
).replace(/([a-z])([A-Z])/g, "$1 $2"),
value,
},
];
});
}
+7 -1
View File
@@ -1,5 +1,6 @@
import { Series, type Image } from "daikon"; import { Series, type Image } from "daikon";
import { storedValue, windowPixel } from "./dicom-pixels"; import { storedValue, windowPixel } from "./dicom-pixels";
import { dicomMetadata } from "./dicom-metadata";
let image: Image; let image: Image;
let raw: DataView; let raw: DataView;
@@ -26,10 +27,15 @@ const pixel = (index: number) =>
intercept; intercept;
self.onmessage = (event: MessageEvent) => { self.onmessage = (event: MessageEvent) => {
const { id, buffer, frame = 0, center, width } = event.data; const { id, buffer, mode, frame = 0, center, width } = event.data;
try { try {
if (buffer) { if (buffer) {
const parsed = Series.parseImage(new DataView(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()) if (!parsed?.hasPixelData())
throw new Error("DICOM has no supported image data"); throw new Error("DICOM has no supported image data");
image = parsed; image = parsed;
+1 -1
View File
@@ -73,7 +73,7 @@
</div> </div>
</div> </div>
<template v-else> <template v-else>
<div class="preview"> <div class="preview" :class="{ 'document-preview': isDicom || isPdf }">
<div v-if="isEpub" class="epub-reader"> <div v-if="isEpub" class="epub-reader">
<vue-reader <vue-reader
:location="location" :location="location"
+1 -1
View File
@@ -1,4 +1,4 @@
param([string]$Version = '3.0.0-sso.8') param([string]$Version = '3.0.0-sso.9')
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path $repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Push-Location $repo Push-Location $repo
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/sh #!/bin/sh
set -eu set -eu
cd "$(dirname "$0")/.." cd "$(dirname "$0")/.."
VERSION="${VERSION:-3.0.0-sso.8}" VERSION="${VERSION:-3.0.0-sso.9}"
COMMIT=$(git rev-parse --short HEAD) COMMIT=$(git rev-parse --short HEAD)
(cd frontend && pnpm install --frozen-lockfile && pnpm run build) (cd frontend && pnpm install --frozen-lockfile && pnpm run build)
mkdir -p build/release/linux-amd64 mkdir -p build/release/linux-amd64