diff --git a/app/src/main/java/com/hinnka/mycamera/ml/AiDenoiseModelManager.kt b/app/src/main/java/com/hinnka/mycamera/ml/AiDenoiseModelManager.kt index 07141884..ba3ef31b 100644 --- a/app/src/main/java/com/hinnka/mycamera/ml/AiDenoiseModelManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/ml/AiDenoiseModelManager.kt @@ -40,7 +40,7 @@ sealed interface AiDenoiseModelState { /** * Owns the AI denoise model (SCUNet color σ=25, see docs/scunet-tflite.md). * - * The model is downloaded from a commit-pinned Hugging Face URL, verified by exact size, + * The model is downloaded from a commit-pinned Hugging Face URL (directly or via hf-mirror.com), verified by exact size, * SHA-256 and tensor contract, and installed atomically into app-private storage. */ object AiDenoiseModelManager { @@ -51,9 +51,8 @@ object AiDenoiseModelManager { private const val EXPECTED_MODEL_SIZE_BYTES = 47_200_352L const val MODEL_SHA256 = "8d060b8e58d3224ab14ee2af72c737af30cc3dd68790f26aca20f364734dd10c" - const val MODEL_DOWNLOAD_URL = - "https://huggingface.co/Binjia/scunet-color-25-litert/resolve/" + - "9454c201ad03a74bbcbb7005232072f01a3b233c/scunet_color_25.tflite" + private const val MODEL_PATH = + "/Binjia/scunet-color-25-litert/resolve/9454c201ad03a74bbcbb7005232072f01a3b233c/scunet_color_25.tflite" /** Model directories of earlier AI denoise models, removed on first use. */ private val LEGACY_MODEL_DIRECTORIES = listOf("ml_models/nafnet_sidd_w32", "ml_models/scunet_color_real_psnr") @@ -80,7 +79,7 @@ object AiDenoiseModelManager { return modelFile(context.applicationContext).takeIf { it.isFile && it.length() == EXPECTED_MODEL_SIZE_BYTES } } - fun download(context: Context) { + fun download(context: Context, source: HfModelSource) { val appContext = context.applicationContext initialize(appContext) synchronized(lock) { @@ -89,14 +88,15 @@ object AiDenoiseModelManager { return } if (operationJob?.isActive == true) return + HfModelSource.remember(appContext, source) _state.value = AiDenoiseModelState.Downloading(progress = 0f, isInstalling = false) val newJob = scope.launch(start = CoroutineStart.LAZY) { try { - downloadAndInstall(appContext) + downloadAndInstall(appContext, source) _state.value = AiDenoiseModelState.Ready } catch (e: Exception) { - PLog.w(TAG, "Failed to download or install the AI denoise model", e) + PLog.w(TAG, "Failed to download or install the AI denoise model from ${source.host}", e) _state.value = AiDenoiseModelState.Failed } } @@ -132,7 +132,7 @@ object AiDenoiseModelManager { } } - private fun downloadAndInstall(context: Context) { + private fun downloadAndInstall(context: Context, source: HfModelSource) { val directory = File(context.filesDir, MODEL_DIRECTORY) if (!directory.isDirectory && !directory.mkdirs()) { throw IOException("Cannot create model directory: ${directory.absolutePath}") @@ -142,7 +142,7 @@ object AiDenoiseModelManager { throw IOException("Cannot remove stale temporary file: ${partFile.absolutePath}") } try { - downloadTo(partFile) + downloadTo(source.url(MODEL_PATH), partFile) _state.value = AiDenoiseModelState.Downloading(progress = 1f, isInstalling = true) validate(partFile) installAtomically(partFile, modelFile(context)) @@ -154,8 +154,8 @@ object AiDenoiseModelManager { } } - private fun downloadTo(target: File) { - val request = Request.Builder().url(MODEL_DOWNLOAD_URL).get().build() + private fun downloadTo(url: String, target: File) { + val request = Request.Builder().url(url).get().build() client.newCall(request).execute().use { response -> if (!response.isSuccessful) { throw IOException("Model download failed with HTTP ${response.code}") diff --git a/app/src/main/java/com/hinnka/mycamera/ml/DepthEstimator.kt b/app/src/main/java/com/hinnka/mycamera/ml/DepthEstimator.kt index 98582801..acabae52 100644 --- a/app/src/main/java/com/hinnka/mycamera/ml/DepthEstimator.kt +++ b/app/src/main/java/com/hinnka/mycamera/ml/DepthEstimator.kt @@ -5,58 +5,67 @@ import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect +import com.google.ai.edge.litert.CompiledModel import com.hinnka.mycamera.utils.LargeDirectBuffer import com.hinnka.mycamera.utils.PLog import com.hinnka.mycamera.utils.StartupTrace import org.tensorflow.lite.DataType import org.tensorflow.lite.Interpreter -import org.tensorflow.lite.Tensor import com.google.ai.edge.litert.support.tensorbuffer.TensorBuffer +import java.io.File import java.io.FileInputStream import java.nio.ByteBuffer +import java.nio.MappedByteBuffer +import java.nio.channels.FileChannel +/** + * Runs the installed monocular depth model and returns a normalized disparity map + * (larger is nearer) in the orientation of the input image. + * + * The default model (Depth Anything 3 Small, see [DepthModelManager]) takes an + * ImageNet-normalized NCHW image and outputs depth; imported models take [0, 1] RGB and + * their output polarity is resolved later by the bokeh preprocessor. Models with a + * non-square input of the other orientation get the image rotated by 90 degrees. + */ class DepthEstimator(context: Context) { - private var interpreter: Interpreter? = null + private var cpuInterpreter: Interpreter? = null + private var gpuModel: LiteRtGpuModel? = null + private var modelBuffer: MappedByteBuffer? = null + private lateinit var contract: DepthModelContract + private var isOfficialModel = false private var isInitialized = false - private var inputWidth = 518 - private var inputHeight = 518 - private var outputWidth = 518 - private var outputHeight = 518 - private var inputChannelsFirst = false - private var inputDataType = DataType.FLOAT32 - private var outputDataType = DataType.FLOAT32 - private var outputTensorIndex = 0 internal val isReady: Boolean get() = isInitialized init { val modelFile = DepthModelManager.requireInstalledModelFile(context) try { - val modelBuffer = StartupTrace.measure("DepthEstimator.mapModelFile") { + val fingerprint = StartupTrace.measure("DepthEstimator.fingerprint") { + DepthModelManager.installedModelFingerprint(context) + } + isOfficialModel = fingerprint == DepthModelManager.OFFICIAL_MODEL_SHA256 + val buffer = StartupTrace.measure("DepthEstimator.mapModelFile") { FileInputStream(modelFile).channel.use { channel -> - channel.map( - java.nio.channels.FileChannel.MapMode.READ_ONLY, - 0L, - channel.size() - ) + channel.map(FileChannel.MapMode.READ_ONLY, 0L, channel.size()) } } - // LiteRT 2.x no longer provides the NNAPI delegate. The GPU accelerator is - // deliberately not used: this model can compile but produce a constant map - // on affected Qualcomm drivers. XNNPACK runs every supported depth contract, - // including quantized inputs and multi-output graphs. - val cpuOptions = Interpreter.Options() - .setNumThreads(CPU_THREADS) - .setUseXNNPACK(true) - interpreter = StartupTrace.measure("DepthEstimator.Interpreter(CPU)") { - Interpreter(modelBuffer, cpuOptions) + modelBuffer = buffer + val outputCount = Interpreter(buffer, Interpreter.Options().setUseXNNPACK(false)).use { + contract = inspectDepthModelContract(it) + it.outputTensorCount + } + gpuModel = createGpuModel(context, modelFile, fingerprint, outputCount) + if (gpuModel == null) { + cpuInterpreter = createCpuInterpreter(buffer) } isInitialized = true - PLog.d(TAG, "Using CPU/XNNPACK for depth model threads=$CPU_THREADS") - - interpreter?.let { - applyModelContract(it, inspectDepthModelContract(it)) - } + PLog.d( + TAG, + "Depth model ready: backend=${if (gpuModel != null) "GPU" else "CPU"} official=$isOfficialModel " + + "input=${contract.inputWidth}x${contract.inputHeight} output=${contract.outputWidth}x${contract.outputHeight} " + + "inputLayout=${if (contract.inputChannelsFirst) "NCHW" else "NHWC"} " + + "inputType=${contract.inputDataType} outputType=${contract.outputDataType} outputIndex=${contract.outputTensorIndex}" + ) } catch (e: Exception) { close() PLog.e(TAG, "Error initializing depth model", e) @@ -64,162 +73,225 @@ class DepthEstimator(context: Context) { } /** - * Estimates depth for the given bitmap. - * @param inputBitmap Original image bitmap. - * @return Floating-point relative depth at the model output resolution, or null if failed. + * GPU needs one FLOAT32 input and one FLOAT32 output. The default model is converted + * for the LiteRT GPU delegate and is exact in FP16; imported models run in FP32. */ - fun estimateDepth(inputBitmap: Bitmap): RelativeDepthMap? { - if (!isInitialized || interpreter == null) { - PLog.e(TAG, "DepthEstimator is not initialized") + private fun createGpuModel(context: Context, file: File, fingerprint: String, outputCount: Int): LiteRtGpuModel? { + if ( + contract.inputDataType != DataType.FLOAT32 || + contract.outputDataType != DataType.FLOAT32 || + outputCount != 1 + ) { + PLog.d(TAG, "Depth model contract is not GPU-eligible; using CPU") return null } - - var modelInputBitmap: Bitmap? = null - try { - // 1. Get input/output metadata - val inputTensor = interpreter!!.getInputTensor(0) - val outputTensor = interpreter!!.getOutputTensor(outputTensorIndex) - - // 2. Preprocess the input image - val preparedInput = prepareModelInputBitmap(inputBitmap) - modelInputBitmap = preparedInput - val inputBuffer = createDepthModelInputBuffer(preparedInput, inputTensor) - - // 3. Prepare the output buffer - val outputBuffer = TensorBuffer.createFixedSize(outputTensor.shape(), outputDataType) - - try { - // 4. Run inference - if (interpreter!!.outputTensorCount == 1 && outputTensorIndex == 0) { - interpreter!!.run(inputBuffer, outputBuffer.buffer) - } else { - interpreter!!.runForMultipleInputsOutputs( - arrayOf(inputBuffer), - mapOf(outputTensorIndex to outputBuffer.buffer), - ) - } - - // 5. Normalize without quantizing the model output. - return if (outputDataType == DataType.FLOAT32) { - convertOutputToDepthMap(outputBuffer.floatArray, outputWidth, outputHeight) - } else { - // If quantized output, convert to float first or handle UINT8 directly - val floatArray = FloatArray(outputBuffer.flatSize) - if (outputDataType == DataType.UINT8 || outputDataType == DataType.INT8) { - val byteBuffer = outputBuffer.buffer - byteBuffer.rewind() - val bytes = ByteArray(outputBuffer.flatSize) - byteBuffer.get(bytes) - for (i in bytes.indices) { - floatArray[i] = if (outputDataType == DataType.UINT8) { - (bytes[i].toInt() and 0xFF).toFloat() - } else { - bytes[i].toFloat() - } - } - } - convertOutputToDepthMap(floatArray, outputWidth, outputHeight) - } - } finally { - LargeDirectBuffer.free(inputBuffer) + val precision = if (isOfficialModel) { + CompiledModel.GpuOptions.Precision.FP16 + } else { + CompiledModel.GpuOptions.Precision.FP32 + } + return try { + val cache = MlDelegateCacheFactory.create( + context = context, + tag = TAG, + cacheName = "depth_${precision.name.lowercase()}", + modelAssetName = file.name, + modelSizeBytes = file.length().toInt(), + modelFingerprint = fingerprint, + ) + StartupTrace.measure("DepthEstimator.CompiledModel(GPU)") { + LiteRtGpuModel.fromFile( + file = file, + cache = cache, + precision = precision, + inputElementCount = contract.inputWidth * contract.inputHeight * RGB_CHANNELS, + outputElementCount = contract.outputWidth * contract.outputHeight, + ) } - } catch (e: Exception) { - PLog.e(TAG, "Error during depth model inference", e) - return null - } finally { - modelInputBitmap?.let { bitmap -> - if (bitmap !== inputBitmap && !bitmap.isRecycled) { - bitmap.recycle() - } - } + PLog.w(TAG, "LiteRT GPU unavailable for the depth model, falling back to CPU", e) + null + } + } + + private fun createCpuInterpreter(buffer: MappedByteBuffer): Interpreter { + return StartupTrace.measure("DepthEstimator.Interpreter(CPU)") { + Interpreter(buffer, Interpreter.Options().setNumThreads(CPU_THREADS).setUseXNNPACK(true)) } } /** - * Depth models consume a small, display-referred RGB guide. Convert and resize - * in one Canvas draw so RGBA_F16 captures never create a full-resolution - * ARGB_8888 intermediate bitmap. + * Estimates depth for the given bitmap. + * @param inputBitmap Original image bitmap. + * @return Normalized disparity at the model output resolution (rotated back to the + * input orientation), or null if failed. */ - private fun prepareModelInputBitmap(inputBitmap: Bitmap): Bitmap { - if ( - inputBitmap.config == Bitmap.Config.ARGB_8888 && - inputBitmap.width == inputWidth && - inputBitmap.height == inputHeight - ) { - return inputBitmap + fun estimateDepth(inputBitmap: Bitmap): RelativeDepthMap? { + if (!isInitialized) { + PLog.e(TAG, "DepthEstimator is not initialized") + return null } - - return Bitmap.createBitmap(inputWidth, inputHeight, Bitmap.Config.ARGB_8888).also { output -> - Canvas(output).drawBitmap( - inputBitmap, - null, - Rect(0, 0, inputWidth, inputHeight), - Paint(Paint.FILTER_BITMAP_FLAG), - ) + val rotate = contract.inputWidth != contract.inputHeight && + (inputBitmap.width > inputBitmap.height) != (contract.inputWidth > contract.inputHeight) + return try { + val pixels = readModelInputPixels(inputBitmap, rotate) + val raw = runGpu(pixels) ?: runCpu(pixels) + val disparity = if (isOfficialModel) depthToDisparity(raw) else raw + val map = normalize(disparity, contract.outputWidth, contract.outputHeight) + if (rotate) rotateBack(map) else map + } catch (e: Exception) { + PLog.e(TAG, "Error during depth model inference", e) + null } } - private fun createDepthModelInputBuffer(inputBitmap: Bitmap, inputTensor: Tensor): ByteBuffer { - val resized = if (inputBitmap.width == inputWidth && inputBitmap.height == inputHeight) { + /** + * Returns null when no GPU model is active. A GPU result without a finite, non-constant + * range is a delegate failure (seen on some Qualcomm drivers): the GPU model is dropped + * for the rest of this estimator's lifetime and the CPU path is used. + */ + private fun runGpu(pixels: IntArray): FloatArray? { + val gpu = gpuModel ?: return null + val output = gpu.run(floatInput(pixels)) + var min = Float.POSITIVE_INFINITY + var max = Float.NEGATIVE_INFINITY + var finite = true + for (value in output) { + if (!value.isFinite()) { + finite = false + break + } + if (value < min) min = value + if (value > max) max = value + } + if (finite && max > min) return output + PLog.e(TAG, "GPU depth output is degenerate (finite=$finite min=$min max=$max); switching to CPU") + gpu.close() + gpuModel = null + cpuInterpreter = createCpuInterpreter(modelBuffer!!) + return null + } + + private fun runCpu(pixels: IntArray): FloatArray { + val interpreter = cpuInterpreter ?: error("CPU depth interpreter is not available") + val outputTensor = interpreter.getOutputTensor(contract.outputTensorIndex) + val outputBuffer = TensorBuffer.createFixedSize(outputTensor.shape(), contract.outputDataType) + val inputBuffer = cpuInput(pixels, interpreter) + try { + if (interpreter.outputTensorCount == 1 && contract.outputTensorIndex == 0) { + interpreter.run(inputBuffer, outputBuffer.buffer) + } else { + interpreter.runForMultipleInputsOutputs( + arrayOf(inputBuffer), + mapOf(contract.outputTensorIndex to outputBuffer.buffer), + ) + } + } finally { + LargeDirectBuffer.free(inputBuffer) + } + return when (contract.outputDataType) { + DataType.FLOAT32 -> outputBuffer.floatArray + DataType.UINT8, DataType.INT8 -> { + val byteBuffer = outputBuffer.buffer + byteBuffer.rewind() + val bytes = ByteArray(outputBuffer.flatSize) + byteBuffer.get(bytes) + FloatArray(bytes.size) { i -> + if (contract.outputDataType == DataType.UINT8) (bytes[i].toInt() and 0xFF).toFloat() + else bytes[i].toFloat() + } + } + else -> error("Unsupported depth model output type: ${contract.outputDataType}") + } + } + + /** + * Resizes (and, for [rotate], turns 90 degrees clockwise) the image into the model input + * size in one Canvas draw, so RGBA_F16 captures never create a full-resolution + * ARGB_8888 intermediate bitmap. + */ + private fun readModelInputPixels(inputBitmap: Bitmap, rotate: Boolean): IntArray { + val width = contract.inputWidth + val height = contract.inputHeight + val prepared = if ( + !rotate && + inputBitmap.config == Bitmap.Config.ARGB_8888 && + inputBitmap.width == width && + inputBitmap.height == height + ) { inputBitmap } else { - Bitmap.createScaledBitmap(inputBitmap, inputWidth, inputHeight, true) - } - val pixels = IntArray(inputWidth * inputHeight) - resized.getPixels(pixels, 0, inputWidth, 0, 0, inputWidth, inputHeight) - if (resized !== inputBitmap) { - resized.recycle() - } - - val bytesPerChannel = when (inputDataType) { - DataType.FLOAT32 -> Float.SIZE_BYTES - DataType.UINT8, DataType.INT8 -> Byte.SIZE_BYTES - else -> throw IllegalArgumentException("Unsupported depth model input type: $inputDataType") - } - val buffer = LargeDirectBuffer.allocate( - inputWidth.toLong() * inputHeight.toLong() * 3L * bytesPerChannel, - "Depth model input" - ) ?: throw OutOfMemoryError("Failed to allocate depth model input buffer") - fun normalizedChannelValue(pixel: Int, channel: Int): Float { - return when (channel) { - 0 -> (pixel shr 16) and 0xFF - 1 -> (pixel shr 8) and 0xFF - else -> pixel and 0xFF - } / 255.0f - } - val quantization = inputTensor.quantizationParams() - fun putChannel(pixel: Int, channel: Int) { - val value = normalizedChannelValue(pixel, channel) - when (inputDataType) { - DataType.FLOAT32 -> buffer.putFloat(value) - DataType.UINT8 -> { - val quantized = quantize(value, quantization.scale, quantization.zeroPoint) - .coerceIn(0, 255) - buffer.put(quantized.toByte()) + Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).also { output -> + val canvas = Canvas(output) + if (rotate) { + // (u, v) -> (width - v, u): the image's top edge becomes the right edge. + canvas.translate(width.toFloat(), 0f) + canvas.rotate(90f) + canvas.drawBitmap(inputBitmap, null, Rect(0, 0, height, width), Paint(Paint.FILTER_BITMAP_FLAG)) + } else { + canvas.drawBitmap(inputBitmap, null, Rect(0, 0, width, height), Paint(Paint.FILTER_BITMAP_FLAG)) } - DataType.INT8 -> { - val quantized = quantize(value, quantization.scale, quantization.zeroPoint) - .coerceIn(-128, 127) - buffer.put(quantized.toByte()) - } - else -> error("Unsupported depth model input type: $inputDataType") } } + val pixels = IntArray(width * height) + prepared.getPixels(pixels, 0, width, 0, 0, width, height) + if (prepared !== inputBitmap) prepared.recycle() + return pixels + } - if (inputChannelsFirst) { - for (channel in 0 until 3) { - for (pixel in pixels) { - putChannel(pixel, channel) - } + /** Normalized RGB channel value; ImageNet mean/std for the default model, [0, 1] otherwise. */ + private fun channelValue(pixel: Int, channel: Int): Float { + val value = when (channel) { + 0 -> (pixel shr 16) and 0xFF + 1 -> (pixel shr 8) and 0xFF + else -> pixel and 0xFF + } / 255.0f + return if (isOfficialModel) (value - IMAGENET_MEAN[channel]) / IMAGENET_STD[channel] else value + } + + private fun floatInput(pixels: IntArray): FloatArray { + val out = FloatArray(pixels.size * RGB_CHANNELS) + if (contract.inputChannelsFirst) { + for (channel in 0 until RGB_CHANNELS) { + val base = channel * pixels.size + for (i in pixels.indices) out[base + i] = channelValue(pixels[i], channel) } } else { - for (pixel in pixels) { - putChannel(pixel, 0) - putChannel(pixel, 1) - putChannel(pixel, 2) + for (i in pixels.indices) { + for (channel in 0 until RGB_CHANNELS) out[i * RGB_CHANNELS + channel] = channelValue(pixels[i], channel) } } + return out + } + + private fun cpuInput(pixels: IntArray, interpreter: Interpreter): ByteBuffer { + val bytesPerChannel = when (contract.inputDataType) { + DataType.FLOAT32 -> Float.SIZE_BYTES + DataType.UINT8, DataType.INT8 -> Byte.SIZE_BYTES + else -> throw IllegalArgumentException("Unsupported depth model input type: ${contract.inputDataType}") + } + val buffer = LargeDirectBuffer.allocate( + pixels.size.toLong() * RGB_CHANNELS * bytesPerChannel, + "Depth model input" + ) ?: throw OutOfMemoryError("Failed to allocate depth model input buffer") + if (contract.inputDataType == DataType.FLOAT32) { + buffer.asFloatBuffer().put(floatInput(pixels)) + buffer.rewind() + return buffer + } + val quantization = interpreter.getInputTensor(0).quantizationParams() + fun putChannel(pixel: Int, channel: Int) { + val quantized = quantize(channelValue(pixel, channel), quantization.scale, quantization.zeroPoint) + buffer.put( + if (contract.inputDataType == DataType.UINT8) quantized.coerceIn(0, 255).toByte() + else quantized.coerceIn(-128, 127).toByte() + ) + } + if (contract.inputChannelsFirst) { + for (channel in 0 until RGB_CHANNELS) for (pixel in pixels) putChannel(pixel, channel) + } else { + for (pixel in pixels) for (channel in 0 until RGB_CHANNELS) putChannel(pixel, channel) + } buffer.rewind() return buffer } @@ -229,81 +301,75 @@ class DepthEstimator(context: Context) { return kotlin.math.round(value / scale + zeroPoint.toFloat()).toInt() } - /** - * Normalizes relative depth while preserving floating-point precision. - */ - private fun convertOutputToDepthMap( - outputArray: FloatArray, - width: Int, - height: Int, - ): RelativeDepthMap { - val normalizedValues = FloatArray(width * height) - if (outputArray.isEmpty()) return RelativeDepthMap(width, height, normalizedValues) - - val validValues = FloatArray(outputArray.size) - var validCount = 0 - for (value in outputArray) { - if (value.isFinite()) { - validValues[validCount++] = value - } + /** The default model outputs positive depth; disparity is its reciprocal. */ + private fun depthToDisparity(depth: FloatArray): FloatArray { + return FloatArray(depth.size) { i -> + val d = depth[i] + if (d > 0f) 1f / d else Float.NaN } + } + /** Normalizes to [0, 1] between the 2nd and 98th percentiles of the finite values. */ + private fun normalize(values: FloatArray, width: Int, height: Int): RelativeDepthMap { + val normalizedValues = FloatArray(width * height) + val validValues = FloatArray(values.size) + var validCount = 0 + for (value in values) { + if (value.isFinite()) validValues[validCount++] = value + } if (validCount == 0) { PLog.e(TAG, "Depth output has no finite values") return RelativeDepthMap(width, height, normalizedValues) } validValues.sort(0, validCount) - val clipPercentile = 0.02f - val loIndex = (validCount * clipPercentile).toInt().coerceIn(0, validCount - 1) - val hiIndex = (validCount * (1.0f - clipPercentile)).toInt().coerceIn(0, validCount - 1) - + val loIndex = (validCount * CLIP_PERCENTILE).toInt().coerceIn(0, validCount - 1) + val hiIndex = (validCount * (1.0f - CLIP_PERCENTILE)).toInt().coerceIn(0, validCount - 1) var min = validValues[loIndex] var max = validValues[hiIndex] - if (min >= max) { min = validValues[0] max = validValues[validCount - 1] } + val range = (max - min).takeIf { it > 0f } ?: 1f - val range = max - min - val finalRange = if (range <= 0f) 1f else range // avoid division by zero -// PLog.d(TAG, "Depth output range: min=$min max=$max range=$range valid=$validCount") - - val limit = minOf(outputArray.size, normalizedValues.size) + val limit = minOf(values.size, normalizedValues.size) for (i in 0 until limit) { - val value = if (outputArray[i].isFinite()) outputArray[i] else min - normalizedValues[i] = ((value - min) / finalRange).coerceIn(0.0f, 1.0f) + val value = if (values[i].isFinite()) values[i] else min + normalizedValues[i] = ((value - min) / range).coerceIn(0.0f, 1.0f) } return RelativeDepthMap(width, height, normalizedValues) } - private fun applyModelContract(interpreter: Interpreter, contract: DepthModelContract) { - val inputShape = interpreter.getInputTensor(0).shape() - val outputShape = interpreter.getOutputTensor(contract.outputTensorIndex).shape() - inputWidth = contract.inputWidth - inputHeight = contract.inputHeight - inputChannelsFirst = contract.inputChannelsFirst - inputDataType = contract.inputDataType - outputTensorIndex = contract.outputTensorIndex - outputWidth = contract.outputWidth - outputHeight = contract.outputHeight - outputDataType = contract.outputDataType - - PLog.d( - TAG, - "Depth model ready: input=${inputWidth}x$inputHeight output=${outputWidth}x$outputHeight inputLayout=${if (inputChannelsFirst) "NCHW" else "NHWC"} inputType=$inputDataType outputType=$outputDataType outputIndex=$outputTensorIndex inputShape=${inputShape.contentToString()} outputShape=${outputShape.contentToString()}" - ) + /** Inverse of the clockwise input rotation: map (px, py) came from image (py, ow - 1 - px). */ + private fun rotateBack(map: RelativeDepthMap): RelativeDepthMap { + val ow = map.width + val oh = map.height + val values = FloatArray(ow * oh) + // The restored map is oh wide and ow tall. + for (y in 0 until ow) { + for (x in 0 until oh) { + values[y * oh + x] = map.values[x * ow + (ow - 1 - y)] + } + } + return RelativeDepthMap(oh, ow, values) } fun close() { - interpreter?.close() - interpreter = null + gpuModel?.close() + gpuModel = null + cpuInterpreter?.close() + cpuInterpreter = null + modelBuffer = null isInitialized = false } companion object { private const val TAG = "DepthEstimator" private const val CPU_THREADS = 4 + private const val RGB_CHANNELS = 3 + private const val CLIP_PERCENTILE = 0.02f + private val IMAGENET_MEAN = floatArrayOf(0.485f, 0.456f, 0.406f) + private val IMAGENET_STD = floatArrayOf(0.229f, 0.224f, 0.225f) } } diff --git a/app/src/main/java/com/hinnka/mycamera/ml/DepthModelManager.kt b/app/src/main/java/com/hinnka/mycamera/ml/DepthModelManager.kt index 1a8607b0..42505037 100644 --- a/app/src/main/java/com/hinnka/mycamera/ml/DepthModelManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/ml/DepthModelManager.kt @@ -47,22 +47,30 @@ sealed interface DepthModelDownloadState { * * The model is kept in app-private storage and is installed atomically only after * it has been verified as a TFLite model compatible with the app's depth pipeline. - * The bundled download additionally retains exact size and SHA-256 verification. + * The default model (Depth Anything 3 Small, LiteRT GPU FP16) is downloaded from a + * commit-pinned Hugging Face URL and additionally verified by exact size and SHA-256. */ object DepthModelManager { private const val TAG = "DepthModelManager" - private const val MODEL_DIRECTORY = "ml_models/depth_anything_v2" - private const val MODEL_FILE_NAME = "depth_anything_v2.tflite" - private const val MODEL_ARCHIVE_PART_FILE_NAME = "depth_anything_v2.zip.part" - private const val MODEL_IMPORT_PART_FILE_NAME = "depth_anything_v2.import.part" - private const val MODEL_PART_FILE_NAME = "depth_anything_v2.tflite.part" - private const val EXPECTED_MODEL_SIZE_BYTES = 98_920_480L + private const val MODEL_DIRECTORY = "ml_models/depth" + private const val MODEL_FILE_NAME = "depth.tflite" + private const val MODEL_IMPORT_PART_FILE_NAME = "depth.import.part" + private const val MODEL_PART_FILE_NAME = "depth.tflite.part" + private const val EXPECTED_MODEL_SIZE_BYTES = 55_035_456L private const val MAX_IMPORT_SIZE_BYTES = 256L * 1024L * 1024L - private const val OFFICIAL_MODEL_SHA256 = - "69302c7b94a2ebe6f31d5caa78cb72d7e15f5ba72804d0423e699787368a255f" + internal const val OFFICIAL_MODEL_SHA256 = + "e170369a72ba1bba7486a4d2de555639fccd0595a9bb5b5349f7733ed4aebd1f" + private const val MODEL_PATH = + "/litert-community/Depth-Anything-3-Small/resolve/" + + "5cd25d936e3fde2edef68f53b4123401454ac9c8/da3_small_gpu_fp16.tflite" - const val MODEL_DOWNLOAD_URL = - "https://qaihub-public-assets.s3.us-west-2.amazonaws.com/qai-hub-models/models/depth_anything_v2/releases/v0.59.0/depth_anything_v2-tflite-float.zip" + /** + * Before Depth Anything 3 the model lived here. The former default (Depth Anything V2, + * identified by its exact size) is removed; a user-imported model is carried over. + */ + private const val LEGACY_MODEL_DIRECTORY = "ml_models/depth_anything_v2" + private const val LEGACY_MODEL_FILE_NAME = "depth_anything_v2.tflite" + private const val LEGACY_DEFAULT_MODEL_SIZE_BYTES = 98_920_480L private val lock = Any() private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) @@ -104,7 +112,7 @@ object DepthModelManager { return sha256(requireInstalledModelFile(context.applicationContext)) } - fun download(context: Context) { + fun download(context: Context, source: HfModelSource) { val appContext = context.applicationContext initialize(appContext) synchronized(lock) { @@ -115,6 +123,7 @@ object DepthModelManager { if (operationJob?.isActive == true) { return } + HfModelSource.remember(appContext, source) _state.value = DepthModelDownloadState.Downloading( progress = 0f, @@ -122,10 +131,10 @@ object DepthModelManager { ) val newJob = scope.launch(start = CoroutineStart.LAZY) { try { - downloadAndInstall(appContext) + downloadAndInstall(appContext, source) _state.value = DepthModelDownloadState.Ready } catch (e: Exception) { - PLog.w(TAG, "Failed to download or install the default depth model", e) + PLog.w(TAG, "Failed to download or install the default depth model from ${source.host}", e) _state.value = DepthModelDownloadState.Failed } } @@ -176,6 +185,7 @@ object DepthModelManager { if (initialized) { return } + migrateLegacyModel(context) _state.value = if (installedModelFileOrNull(context) != null) { DepthModelDownloadState.Ready } else { @@ -185,30 +195,51 @@ object DepthModelManager { } } - private fun downloadAndInstall(context: Context) { + private fun migrateLegacyModel(context: Context) { + val legacyDirectory = File(context.filesDir, LEGACY_MODEL_DIRECTORY) + if (!legacyDirectory.exists()) return + val legacyModel = File(legacyDirectory, LEGACY_MODEL_FILE_NAME) + val target = modelFile(context) + if ( + hasValidInstalledModelFile(legacyModel) && + legacyModel.length() != LEGACY_DEFAULT_MODEL_SIZE_BYTES && + !target.exists() + ) { + try { + if (!modelDirectory(context).isDirectory && !modelDirectory(context).mkdirs()) { + throw IOException("Cannot create depth model directory") + } + installAtomically(legacyModel, target) + PLog.d(TAG, "Carried over imported depth model to ${target.absolutePath}") + } catch (e: IOException) { + PLog.e(TAG, "Cannot carry over imported depth model", e) + } + } + if (!legacyDirectory.deleteRecursively()) { + PLog.w(TAG, "Cannot remove legacy depth model directory: ${legacyDirectory.absolutePath}") + } + } + + private fun downloadAndInstall(context: Context, source: HfModelSource) { val modelDirectory = modelDirectory(context) if (!modelDirectory.isDirectory && !modelDirectory.mkdirs()) { throw IOException("Cannot create depth model directory: ${modelDirectory.absolutePath}") } - val archivePartFile = File(modelDirectory, MODEL_ARCHIVE_PART_FILE_NAME) val modelPartFile = File(modelDirectory, MODEL_PART_FILE_NAME) - archivePartFile.deleteIfExistsOrThrow() modelPartFile.deleteIfExistsOrThrow() try { - downloadArchive(archivePartFile) + downloadModel(source.url(MODEL_PATH), modelPartFile) _state.value = DepthModelDownloadState.Downloading( progress = 1f, isInstalling = true ) - extractOfficialModel(archivePartFile, modelPartFile) validateOfficialModel(modelPartFile) installAtomically(modelPartFile, modelFile(context)) publishInstallation() PLog.d(TAG, "Default depth model installed: ${modelFile(context).absolutePath}") } finally { - archivePartFile.deleteIfExistsOrLog() modelPartFile.deleteIfExistsOrLog() } } @@ -272,9 +303,9 @@ object DepthModelManager { } } - private fun downloadArchive(target: File) { + private fun downloadModel(url: String, target: File) { val request = Request.Builder() - .url(MODEL_DOWNLOAD_URL) + .url(url) .get() .build() client.newCall(request).execute().use { response -> @@ -282,7 +313,7 @@ object DepthModelManager { throw IOException("Model download failed with HTTP ${response.code}") } val body = response.body ?: throw IOException("Model download response has no body") - val totalBytes = body.contentLength().takeIf { it > 0L } + val totalBytes = EXPECTED_MODEL_SIZE_BYTES var downloadedBytes = 0L var lastPublishedBytes = 0L @@ -294,8 +325,11 @@ object DepthModelManager { if (read < 0) { break } - output.write(buffer, 0, read) downloadedBytes += read + if (downloadedBytes > totalBytes) { + throw IOException("Model download exceeds the expected size") + } + output.write(buffer, 0, read) if (downloadedBytes - lastPublishedBytes >= PROGRESS_UPDATE_BYTES) { publishDownloadProgress(downloadedBytes, totalBytes) lastPublishedBytes = downloadedBytes @@ -305,63 +339,21 @@ object DepthModelManager { } } publishDownloadProgress(downloadedBytes, totalBytes) - if (totalBytes != null && downloadedBytes != totalBytes) { + if (downloadedBytes != totalBytes) { throw IOException( - "Incomplete model archive: downloaded=$downloadedBytes expected=$totalBytes" + "Incomplete model: downloaded=$downloadedBytes expected=$totalBytes" ) } } } - private fun publishDownloadProgress(downloadedBytes: Long, totalBytes: Long?) { + private fun publishDownloadProgress(downloadedBytes: Long, totalBytes: Long) { _state.value = DepthModelDownloadState.Downloading( - progress = totalBytes?.let { - (downloadedBytes.toDouble() / it.toDouble()).toFloat().coerceIn(0f, 1f) - }, + progress = (downloadedBytes.toDouble() / totalBytes.toDouble()).toFloat().coerceIn(0f, 1f), isInstalling = false ) } - private fun extractOfficialModel(archive: File, target: File) { - var modelEntryFound = false - FileInputStream(archive).use { fileInput -> - ZipInputStream(fileInput).use { zipInput -> - var entry = zipInput.nextEntry - while (entry != null) { - if (!entry.isDirectory && entry.name.substringAfterLast('/') == MODEL_FILE_NAME) { - if (entry.size >= 0L && entry.size != EXPECTED_MODEL_SIZE_BYTES) { - throw IOException("Unexpected depth model entry size: ${entry.size}") - } - FileOutputStream(target).use { output -> - val buffer = ByteArray(DEFAULT_BUFFER_SIZE) - var extractedBytes = 0L - while (true) { - val read = zipInput.read(buffer) - if (read < 0) { - break - } - extractedBytes += read - if (extractedBytes > EXPECTED_MODEL_SIZE_BYTES) { - throw IOException("Depth model ZIP entry exceeds expected size") - } - output.write(buffer, 0, read) - } - output.fd.sync() - } - modelEntryFound = true - zipInput.closeEntry() - break - } - zipInput.closeEntry() - entry = zipInput.nextEntry - } - } - } - if (!modelEntryFound) { - throw IOException("Depth model archive does not contain $MODEL_FILE_NAME") - } - } - private fun extractImportedModel(archive: File, target: File) { var tfliteEntryFound = false var extractedBytes = 0L diff --git a/app/src/main/java/com/hinnka/mycamera/ml/HfModelSource.kt b/app/src/main/java/com/hinnka/mycamera/ml/HfModelSource.kt new file mode 100644 index 00000000..24151086 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/ml/HfModelSource.kt @@ -0,0 +1,29 @@ +package com.hinnka.mycamera.ml + +import android.content.Context +import java.util.Locale + +/** Host serving commit-pinned Hugging Face model files; the mirror serves the same repositories. */ +enum class HfModelSource(val host: String) { + HUGGING_FACE("https://huggingface.co"), + HF_MIRROR("https://hf-mirror.com"); + + fun url(path: String): String = host + path + + companion object { + private const val PREFS_NAME = "hf_model_source" + private const val KEY_SOURCE = "source" + + /** The last source the user downloaded from; hf-mirror by default in mainland China. */ + fun preferred(context: Context): HfModelSource { + val saved = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(KEY_SOURCE, null) + entries.firstOrNull { it.name == saved }?.let { return it } + return if (Locale.getDefault().country == "CN") HF_MIRROR else HUGGING_FACE + } + + fun remember(context: Context, source: HfModelSource) { + context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + .edit().putString(KEY_SOURCE, source.name).apply() + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ui/components/AiDenoiseModelDownloadDialog.kt b/app/src/main/java/com/hinnka/mycamera/ui/components/AiDenoiseModelDownloadDialog.kt index f5fdc6c1..a36bcf11 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/components/AiDenoiseModelDownloadDialog.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/components/AiDenoiseModelDownloadDialog.kt @@ -14,6 +14,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.hinnka.mycamera.R +import com.hinnka.mycamera.ml.HfModelSource import com.hinnka.mycamera.ml.AiDenoiseModelState import kotlin.math.roundToInt @@ -21,6 +22,8 @@ import kotlin.math.roundToInt @Composable fun AiDenoiseModelDownloadDialog( state: AiDenoiseModelState, + source: HfModelSource, + onSourceChange: (HfModelSource) -> Unit, onDownload: () -> Unit, onDismiss: () -> Unit ) { @@ -42,6 +45,10 @@ fun AiDenoiseModelDownloadDialog( ), style = MaterialTheme.typography.bodyMedium ) + if (state == AiDenoiseModelState.Missing || state == AiDenoiseModelState.Failed) { + Spacer(modifier = Modifier.height(16.dp)) + HfModelSourcePicker(source = source, onSourceChange = onSourceChange) + } if (downloading != null) { Spacer(modifier = Modifier.height(16.dp)) val progress = downloading.progress diff --git a/app/src/main/java/com/hinnka/mycamera/ui/components/DepthModelDownloadDialog.kt b/app/src/main/java/com/hinnka/mycamera/ui/components/DepthModelDownloadDialog.kt index 4c9f9058..4f292398 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/components/DepthModelDownloadDialog.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/components/DepthModelDownloadDialog.kt @@ -15,12 +15,15 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.hinnka.mycamera.R import com.hinnka.mycamera.ml.DepthModelDownloadState +import com.hinnka.mycamera.ml.HfModelSource import androidx.compose.ui.res.stringResource import kotlin.math.roundToInt @Composable fun DepthModelDownloadDialog( state: DepthModelDownloadState, + source: HfModelSource, + onSourceChange: (HfModelSource) -> Unit, onDownload: () -> Unit, onImport: () -> Unit, onDismiss: () -> Unit @@ -47,6 +50,10 @@ fun DepthModelDownloadDialog( }, style = MaterialTheme.typography.bodyMedium ) + if (state == DepthModelDownloadState.Missing || state == DepthModelDownloadState.Failed) { + Spacer(modifier = Modifier.height(16.dp)) + HfModelSourcePicker(source = source, onSourceChange = onSourceChange) + } if (isBusy) { Spacer(modifier = Modifier.height(16.dp)) val progress = (state as? DepthModelDownloadState.Downloading)?.progress diff --git a/app/src/main/java/com/hinnka/mycamera/ui/components/HfModelSourcePicker.kt b/app/src/main/java/com/hinnka/mycamera/ui/components/HfModelSourcePicker.kt new file mode 100644 index 00000000..44e30f9c --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/ui/components/HfModelSourcePicker.kt @@ -0,0 +1,63 @@ +package com.hinnka.mycamera.ui.components + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp +import com.hinnka.mycamera.R +import com.hinnka.mycamera.ml.HfModelSource + +/** Download source choice for models hosted on Hugging Face. */ +@Composable +fun HfModelSourcePicker( + source: HfModelSource, + onSourceChange: (HfModelSource) -> Unit, + modifier: Modifier = Modifier, +) { + Column(modifier = modifier) { + Text( + text = stringResource(R.string.model_download_source), + style = MaterialTheme.typography.labelLarge + ) + Column(modifier = Modifier.selectableGroup()) { + HfModelSource.entries.forEach { option -> + Row( + modifier = Modifier + .fillMaxWidth() + .height(40.dp) + .selectable( + selected = option == source, + onClick = { onSourceChange(option) }, + role = Role.RadioButton + ), + verticalAlignment = Alignment.CenterVertically + ) { + RadioButton(selected = option == source, onClick = null) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = stringResource( + when (option) { + HfModelSource.HUGGING_FACE -> R.string.model_download_source_hugging_face + HfModelSource.HF_MIRROR -> R.string.model_download_source_mirror + } + ), + style = MaterialTheme.typography.bodyMedium + ) + } + } + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt index 67f8d976..b902e1a6 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt @@ -72,6 +72,7 @@ import com.hinnka.mycamera.model.RecipeParam import com.hinnka.mycamera.model.toEffectParams import com.hinnka.mycamera.ml.DepthModelDownloadState import com.hinnka.mycamera.ml.DepthModelManager +import com.hinnka.mycamera.ml.HfModelSource import com.hinnka.mycamera.ml.AiDenoiseModelManager import com.hinnka.mycamera.ml.AiDenoiseModelState import com.hinnka.mycamera.raw.SpectralFilmSelection @@ -2115,9 +2116,12 @@ fun GalleryEditScreen( } if (pendingAiDenoise) { + var aiDenoiseModelSource by remember { mutableStateOf(HfModelSource.preferred(context)) } AiDenoiseModelDownloadDialog( state = aiDenoiseModelState, - onDownload = { AiDenoiseModelManager.download(context) }, + source = aiDenoiseModelSource, + onSourceChange = { aiDenoiseModelSource = it }, + onDownload = { AiDenoiseModelManager.download(context, aiDenoiseModelSource) }, onDismiss = { pendingAiDenoise = false viewModel.setAiDenoiseEnabled(false) @@ -2126,9 +2130,12 @@ fun GalleryEditScreen( } if (showDepthModelDownloadDialog) { + var depthModelSource by remember { mutableStateOf(HfModelSource.preferred(context)) } DepthModelDownloadDialog( + source = depthModelSource, + onSourceChange = { depthModelSource = it }, state = depthModelState, - onDownload = { DepthModelManager.download(context) }, + onDownload = { DepthModelManager.download(context, depthModelSource) }, onImport = { depthModelImportLauncher.launch(arrayOf("*/*")) }, onDismiss = { showDepthModelDownloadDialog = false diff --git a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt index 44b7b3a3..46ff0eab 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt @@ -147,6 +147,7 @@ import com.hinnka.mycamera.gallery.Jpeg444ExportEncoder import com.hinnka.mycamera.lut.creator.OpenAIApiClient import com.hinnka.mycamera.ml.DepthModelDownloadState import com.hinnka.mycamera.ml.DepthModelManager +import com.hinnka.mycamera.ml.HfModelSource import com.hinnka.mycamera.raw.RawCfaCorrection import com.hinnka.mycamera.raw.RawSharpeningDefaults import com.hinnka.mycamera.raw.RawDenoiseDefaults @@ -879,9 +880,12 @@ fun SettingsScreen( } if (showDepthModelDownloadDialog) { + var depthModelSource by remember { mutableStateOf(HfModelSource.preferred(context)) } DepthModelDownloadDialog( + source = depthModelSource, + onSourceChange = { depthModelSource = it }, state = depthModelState, - onDownload = { DepthModelManager.download(context) }, + onDownload = { DepthModelManager.download(context, depthModelSource) }, onImport = { depthModelImportLauncher.launch(arrayOf("*/*")) }, onDismiss = { showDepthModelDownloadDialog = false diff --git a/app/src/main/res/values-b+zh+Hant/strings.xml b/app/src/main/res/values-b+zh+Hant/strings.xml index e7a5c096..581c6b80 100644 --- a/app/src/main/res/values-b+zh+Hant/strings.xml +++ b/app/src/main/res/values-b+zh+Hant/strings.xml @@ -1103,7 +1103,7 @@ 展開編輯面板 最小化編輯面板 深度模型 - 景深虛化功能需要相容的 TFLite 深度模型:包含一個 RGB 影像輸入和一個單通道深度輸出。你可以下載預設的 Depth Anything V2 模型(約 100 MB),也可以匯入其他 TFLite 模型或包含模型的 ZIP 壓縮檔。模型將儲存在 App 的私人目錄中。 + 景深虛化功能需要相容的 TFLite 深度模型:包含一個 RGB 影像輸入和一個單通道深度輸出。你可以下載預設的 Depth Anything 3 模型(約 55 MB),也可以匯入其他 TFLite 模型或包含模型的 ZIP 壓縮檔。模型將儲存在 App 的私人目錄中。 下載 匯入 正在下載模型… @@ -1448,4 +1448,6 @@ 模型下載或驗證失敗,請檢查網路後重試。 下載 重試 + 下載來源 + HF 鏡像站(hf-mirror.com) diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index f9e011d9..4925def3 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1284,7 +1284,7 @@ Développer les commandes de retouche Réduire les commandes de retouche Modèle de profondeur - Le flou tenant compte de la profondeur nécessite un modèle de profondeur TFLite compatible, avec une entrée image RGB et une sortie de profondeur à un seul canal. Téléchargez le modèle Depth Anything V2 par défaut (environ 100 Mo), ou importez un autre modèle TFLite ou un ZIP en contenant un. Le modèle sera stocké en privé par l\'application. + Le flou tenant compte de la profondeur nécessite un modèle de profondeur TFLite compatible, avec une entrée image RGB et une sortie de profondeur à un seul canal. Téléchargez le modèle Depth Anything 3 par défaut (environ 55 Mo), ou importez un autre modèle TFLite ou un ZIP en contenant un. Le modèle sera stocké en privé par l\'application. Télécharger Importer Téléchargement du modèle… @@ -1486,4 +1486,6 @@ Le modèle n\'a pas pu être téléchargé ou vérifié. Vérifiez votre connexion et réessayez. Télécharger Réessayer + Source de téléchargement + Miroir HF (hf-mirror.com) diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 5184b582..97f84938 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -954,7 +954,7 @@ 編集コントロールを展開 編集コントロールを折りたたむ 深度モデル - 深度連動ボケには、RGB画像1入力・1ch深度出力の対応TFLite深度モデルが必要です。既定のDepth Anything V2モデル(約100MB)をダウンロードするか、別のTFLiteモデルまたはそれを含むZIPを読み込めます。モデルはアプリ内の非公開領域に保存されます。 + 深度連動ボケには、RGB画像1入力・1ch深度出力の対応TFLite深度モデルが必要です。既定のDepth Anything 3モデル(約55MB)をダウンロードするか、別のTFLiteモデルまたはそれを含むZIPを読み込めます。モデルはアプリ内の非公開領域に保存されます。 ダウンロード 読み込み モデルをダウンロード中… @@ -1325,4 +1325,6 @@ モデルのダウンロードまたは検証に失敗しました。接続を確認して再試行してください。 ダウンロード 再試行 + ダウンロード元 + HF ミラー(hf-mirror.com) diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 325cca0e..fca0188f 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -1121,4 +1121,6 @@ ไม่สามารถดาวน์โหลดหรือตรวจสอบโมเดลได้ โปรดตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง ดาวน์โหลด ลองอีกครั้ง + แหล่งดาวน์โหลด + มิเรอร์ HF (hf-mirror.com) diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index e904971a..853f3483 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1124,7 +1124,7 @@ 展开编辑面板 最小化编辑面板 深度模型 - 景深虚化功能需要兼容的 TFLite 深度模型:包含一个 RGB 图像输入和一个单通道深度输出。你可以下载默认的 Depth Anything V2 模型(约 100 MB),也可以导入其他 TFLite 模型或包含模型的 ZIP 压缩包。模型将保存在应用的私有目录中。 + 景深虚化功能需要兼容的 TFLite 深度模型:包含一个 RGB 图像输入和一个单通道深度输出。你可以下载默认的 Depth Anything 3 模型(约 55 MB),也可以导入其他 TFLite 模型或包含模型的 ZIP 压缩包。模型将保存在应用的私有目录中。 下载 导入 正在下载模型… @@ -1504,4 +1504,6 @@ 模型下载或校验失败,请检查网络后重试。 下载 重试 + 下载源 + HF 镜像站(hf-mirror.com) diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index bed6e8d0..ac57e815 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -1097,7 +1097,7 @@ 展開編輯面板 最小化編輯面板 深度模型 - 景深虛化功能需要兼容的 TFLite 深度模型:包含一個 RGB 圖像輸入和一個單通道深度輸出。你可以下載預設的 Depth Anything V2 模型(約 100 MB),也可以匯入其他 TFLite 模型或包含模型的 ZIP 壓縮檔。模型將儲存在 App 的私人目錄中。 + 景深虛化功能需要兼容的 TFLite 深度模型:包含一個 RGB 圖像輸入和一個單通道深度輸出。你可以下載預設的 Depth Anything 3 模型(約 55 MB),也可以匯入其他 TFLite 模型或包含模型的 ZIP 壓縮檔。模型將儲存在 App 的私人目錄中。 下載 匯入 正在下載模型… @@ -1442,4 +1442,6 @@ 模型下載或驗證失敗,請檢查網絡後重試。 下載 重試 + 下載來源 + HF 鏡像站(hf-mirror.com) diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 63d0de34..f71629d0 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -1103,7 +1103,7 @@ 展開編輯面板 最小化編輯面板 深度模型 - 景深虛化功能需要相容的 TFLite 深度模型:包含一個 RGB 影像輸入和一個單通道深度輸出。你可以下載預設的 Depth Anything V2 模型(約 100 MB),也可以匯入其他 TFLite 模型或包含模型的 ZIP 壓縮檔。模型將儲存在 App 的私人目錄中。 + 景深虛化功能需要相容的 TFLite 深度模型:包含一個 RGB 影像輸入和一個單通道深度輸出。你可以下載預設的 Depth Anything 3 模型(約 55 MB),也可以匯入其他 TFLite 模型或包含模型的 ZIP 壓縮檔。模型將儲存在 App 的私人目錄中。 下載 匯入 正在下載模型… @@ -1448,4 +1448,6 @@ 模型下載或驗證失敗,請檢查網路後重試。 下載 重試 + 下載來源 + HF 鏡像站(hf-mirror.com) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ffbc449e..f9eda980 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1136,7 +1136,7 @@ Expand editing controls Minimize editing controls Depth Model - Depth-aware blur requires a compatible TFLite depth model with one RGB image input and a single-channel depth output. Download the default Depth Anything V2 model (about 100 MB), or import another TFLite model or a ZIP containing one. The model will be stored privately by the app. + Depth-aware blur requires a compatible TFLite depth model with one RGB image input and a single-channel depth output. Download the default Depth Anything 3 model (about 55 MB), or import another TFLite model or a ZIP containing one. The model will be stored privately by the app. Download Import Downloading model… @@ -1528,4 +1528,7 @@ The model could not be downloaded or verified. Check your connection and try again. Download Retry + Download source + Hugging Face + HF Mirror (hf-mirror.com)