|
| 1 | +# Copyright (c) OpenMMLab. All rights reserved. |
| 2 | +import csv |
| 3 | +import os |
| 4 | +from io import BytesIO, StringIO |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +import pybase64 |
| 8 | +import requests |
| 9 | + |
| 10 | +from lmdeploy.utils import get_logger |
| 11 | + |
| 12 | +logger = get_logger('lmdeploy') |
| 13 | + |
| 14 | +FETCH_TIMEOUT = int(os.environ.get('LMDEPLOY_FETCH_TIMEOUT', 10)) |
| 15 | +HEADERS = { |
| 16 | + 'User-Agent': |
| 17 | + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' |
| 18 | + '(KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' |
| 19 | +} |
| 20 | + |
| 21 | + |
| 22 | +def encode_time_series_base64(data: str | np.ndarray) -> str: |
| 23 | + """Encode time series data to base64. |
| 24 | +
|
| 25 | + Supports: HTTP URL, local path, or numpy array. |
| 26 | + """ |
| 27 | + buffered = BytesIO() |
| 28 | + |
| 29 | + try: |
| 30 | + if isinstance(data, str): |
| 31 | + if data.startswith('http'): |
| 32 | + response = requests.get(data, headers=HEADERS, timeout=FETCH_TIMEOUT) |
| 33 | + response.raise_for_status() |
| 34 | + ts_array = _load_bytes(response.content, data) |
| 35 | + elif data.startswith('file://'): |
| 36 | + path = data.removeprefix('file://') |
| 37 | + ts_array = _load_path(path) |
| 38 | + elif os.path.exists(data): |
| 39 | + ts_array = _load_path(data) |
| 40 | + else: |
| 41 | + raise ValueError(f'Path does not exist: {data}') |
| 42 | + elif isinstance(data, np.ndarray): |
| 43 | + ts_array = data |
| 44 | + else: |
| 45 | + raise TypeError(f'Expected str or np.ndarray, got {type(data)}') |
| 46 | + |
| 47 | + np.save(buffered, ts_array) |
| 48 | + |
| 49 | + except Exception as error: |
| 50 | + data_info = str(data)[:100] + ' ...' if isinstance(data, str) and len(data) > 100 else str(data) |
| 51 | + logger.error(f'{error}, data={data_info}') |
| 52 | + np.save(buffered, np.zeros((6000, 3), dtype=np.float32)) # dummy |
| 53 | + |
| 54 | + return pybase64.b64encode(buffered.getvalue()).decode('utf-8') |
| 55 | + |
| 56 | + |
| 57 | +def load_time_series_from_base64(ts_base64: bytes | str) -> np.ndarray: |
| 58 | + """Load time series from base64 format.""" |
| 59 | + if isinstance(ts_base64, str): |
| 60 | + ts_base64 = ts_base64.encode('utf-8') |
| 61 | + return np.load(BytesIO(pybase64.b64decode(ts_base64)), allow_pickle=False) |
| 62 | + |
| 63 | + |
| 64 | +def load_time_series(data_source: str | np.ndarray) -> np.ndarray: |
| 65 | + """Load time series from URL, local path, base64 data URL, or numpy |
| 66 | + array.""" |
| 67 | + try: |
| 68 | + if isinstance(data_source, np.ndarray): |
| 69 | + return data_source |
| 70 | + |
| 71 | + if data_source.startswith('http'): |
| 72 | + response = requests.get(data_source, headers=HEADERS, timeout=FETCH_TIMEOUT) |
| 73 | + response.raise_for_status() |
| 74 | + return _load_bytes(response.content, data_source) |
| 75 | + |
| 76 | + if data_source.startswith('data:time_series'): |
| 77 | + return load_time_series_from_base64(data_source.split(',')[1]) |
| 78 | + |
| 79 | + if data_source.startswith('file://'): |
| 80 | + path = data_source.removeprefix('file://') |
| 81 | + return _load_path(path) |
| 82 | + |
| 83 | + if os.path.exists(data_source): |
| 84 | + return _load_path(data_source) |
| 85 | + |
| 86 | + raise ValueError(f'Invalid data source: {data_source}') |
| 87 | + except Exception as error: |
| 88 | + data_info = str(data_source)[:100] + ' ...' if isinstance(data_source, |
| 89 | + str) and len(data_source) > 100 else str(data_source) |
| 90 | + logger.error(f'{error}, data_source={data_info}') |
| 91 | + return np.zeros((6000, 3), dtype=np.float32) # dummy |
| 92 | + |
| 93 | + |
| 94 | +def _load_bytes(content: bytes, hint: str = '') -> np.ndarray: |
| 95 | + """Auto-detect format from bytes. |
| 96 | +
|
| 97 | + Try: npy -> csv -> audio. |
| 98 | + """ |
| 99 | + hint = hint.lower() |
| 100 | + |
| 101 | + # Format hints from URL/path |
| 102 | + if '.npy' in hint: |
| 103 | + return np.load(BytesIO(content)) |
| 104 | + if '.csv' in hint: |
| 105 | + return _load_csv(content) |
| 106 | + if any(ext in hint for ext in ['.wav', '.mp3', '.flac']): |
| 107 | + return _load_audio(content) |
| 108 | + |
| 109 | + # Fallback: try all formats |
| 110 | + loaders = [lambda: np.load(BytesIO(content)), lambda: _load_csv(content), lambda: _load_audio(content)] |
| 111 | + for loader in loaders: |
| 112 | + try: |
| 113 | + return loader() |
| 114 | + except Exception: |
| 115 | + continue |
| 116 | + raise ValueError(f'Cannot detect format from bytes: {hint[:50]}') |
| 117 | + |
| 118 | + |
| 119 | +def _load_path(path: str) -> np.ndarray: |
| 120 | + """Load from local file path based on extension.""" |
| 121 | + ext = os.path.splitext(path)[-1].lower() |
| 122 | + |
| 123 | + if ext == '.npy': |
| 124 | + return np.load(path) |
| 125 | + if ext == '.csv': |
| 126 | + return _load_csv(path) |
| 127 | + if ext in ['.wav', '.mp3', '.flac']: |
| 128 | + return _load_audio(path) |
| 129 | + |
| 130 | + raise ValueError(f'Unsupported format: {ext}') |
| 131 | + |
| 132 | + |
| 133 | +def _load_csv(source: bytes | str) -> np.ndarray: |
| 134 | + """Load CSV from bytes or file path.""" |
| 135 | + # Read content as text |
| 136 | + if isinstance(source, bytes): |
| 137 | + text = source.decode('utf-8') |
| 138 | + else: |
| 139 | + with open(source, 'r', newline='') as f: |
| 140 | + text = f.read() |
| 141 | + |
| 142 | + # Parse CSV |
| 143 | + f = StringIO(text) |
| 144 | + reader = csv.reader(f) |
| 145 | + rows = list(reader) |
| 146 | + |
| 147 | + return np.array(rows, dtype=np.float32) |
| 148 | + |
| 149 | + |
| 150 | +def _load_audio(source: bytes | str) -> np.ndarray: |
| 151 | + """Load audio from bytes or file path.""" |
| 152 | + try: |
| 153 | + import soundfile as sf |
| 154 | + except ImportError: |
| 155 | + raise ImportError('Please install soundfile to process audio files.') |
| 156 | + |
| 157 | + if isinstance(source, bytes): |
| 158 | + source = BytesIO(source) |
| 159 | + ts, sr = sf.read(source) |
| 160 | + return ts |
0 commit comments