feat: AI color matching

This commit is contained in:
zhoubinjia committed 2026-11-10 12:40:48 +08:00
1 parent d5d81edbf8
commit 833f6ce242
20 files changed
+815 -300

No files matched your search

+1
View File
@@ -24,3 +24,4 @@ __pycache__
/scripts/lut_training/runs
/scripts/nafnet_denoise_tflite/out
/scripts/scunet_denoise_tflite/out
/scripts/colorfm_tflite/out
@@ -476,6 +476,22 @@ object GalleryManager {
return File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), PHOTOS_DIR)
}
/** A photo's AI color match LUT (.plut), see [com.hinnka.mycamera.lut.PhotoColorMatch]. */
fun getAiColorMatchFile(context: Context, photoId: String, version: Long): File =
File(getPhotoDir(context, photoId, create = true), "$AI_COLOR_MATCH_FILE_PREFIX$version.plut")
/** Deletes the photo's AI color match LUTs except [keepVersions]. */
fun deleteAiColorMatchFiles(context: Context, photoId: String, keepVersions: Set<Long>) {
getPhotoDir(context, photoId).listFiles()?.forEach { file ->
val version = file.name.removePrefix(AI_COLOR_MATCH_FILE_PREFIX).removeSuffix(".plut").toLongOrNull()
if (file.name.startsWith(AI_COLOR_MATCH_FILE_PREFIX) && version != null && version !in keepVersions) {
if (!file.delete()) PLog.w(TAG, "Cannot delete AI color match LUT: ${file.absolutePath}")
}
}
}
private const val AI_COLOR_MATCH_FILE_PREFIX = "ai_color_match_"
private fun getPhotoDir(context: Context, photoId: String, create: Boolean = false): File {
val dir = File(getPhotosBaseDir(context), photoId)
if (create && !dir.exists()) {
@@ -9,6 +9,7 @@ import androidx.datastore.preferences.core.floatPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.hinnka.mycamera.data.CustomImportManager
import com.hinnka.mycamera.gallery.GalleryManager
import com.hinnka.mycamera.mgc.PhotonLookContract
import com.hinnka.mycamera.model.LegacyColorRecipeMigration
import com.hinnka.mycamera.model.ColorRecipeParams
@@ -244,6 +245,20 @@ class LutManager(private val context: Context) {
* @param id LUT ID
* @return LUT 配置,如果加载失败返回 null
*/
private fun loadPhotoColorMatch(id: String, ref: PhotoColorMatch.Ref): LutConfig? {
val file = GalleryManager.getAiColorMatchFile(context, ref.photoId, ref.version)
if (!file.isFile) {
PLog.w(TAG, "AI color match LUT is missing: ${file.absolutePath}")
return null
}
return try {
file.inputStream().use { LutParser.parse(it, "") }.takeIf { it.isValid() }?.also { lutCache.put(id, it) }
} catch (e: Exception) {
PLog.e(TAG, "Failed to load AI color match LUT: $id", e)
null
}
}
fun loadLut(id: String): LutConfig? {
// 先从缓存查找
lutCache.get(id)?.let {
@@ -251,6 +266,10 @@ class LutManager(private val context: Context) {
return it
}
PhotoColorMatch.parse(id)?.let { ref ->
return loadPhotoColorMatch(id, ref)
}
// 查找 LUT 信息
val lutInfo = getLutInfo(id) ?: run {
// PLog.w(TAG, "LUT not found: $id")
@@ -0,0 +1,31 @@
package com.hinnka.mycamera.lut
/**
* LUT ids of AI color matches, which belong to one photo and are not part of the filter library.
*
* A match is stored in the photo's directory (GalleryManager.getAiColorMatchFile) and referenced
* from that photo's metadata as `photo-color-match:<photoId>:<version>`; [LutManager.loadLut]
* resolves it. A new match gets a new version so cached LUTs never go stale. These ids must not
* be carried to other photos or presets ([transferable]).
*/
object PhotoColorMatch {
private const val PREFIX = "photo-color-match:"
data class Ref(val photoId: String, val version: Long)
fun lutId(photoId: String, version: Long): String = "$PREFIX$photoId:$version"
fun isId(lutId: String?): Boolean = lutId?.startsWith(PREFIX) == true
fun parse(lutId: String?): Ref? {
if (!isId(lutId)) return null
val body = lutId!!.removePrefix(PREFIX)
val split = body.lastIndexOf(':')
if (split <= 0) return null
val version = body.substring(split + 1).toLongOrNull() ?: return null
return Ref(body.substring(0, split), version)
}
/** [lutId], or null when it is a photo's own color match. */
fun transferable(lutId: String?): String? = lutId?.takeUnless(::isId)
}
@@ -0,0 +1,179 @@
package com.hinnka.mycamera.ml
import android.content.Context
import android.graphics.Bitmap
import android.os.SystemClock
import com.hinnka.mycamera.utils.PLog
import org.tensorflow.lite.DataType
import org.tensorflow.lite.Interpreter
import java.io.FileInputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.channels.FileChannel
import java.util.Locale
import kotlin.math.exp
import kotlin.math.floor
/**
* AI color match with ColorFM-L (conversion in docs/colorfm-tflite.md).
*
* The parameter network sees the content (the photo before its LUT) and the style reference, each
* stretched to 256 x 256 exactly like the original (bilinear, align_corners = false, no
* antialiasing; the result is sensitive to this), and outputs two per-pixel MLPs. Their
* composition is a pure RGB -> RGB function on sRGB values, baked here into a 33^3 .cube LUT.
* It runs once per match, so it uses the CPU (XNNPACK).
*/
object AiColorMatcher {
private const val TAG = "AiColorMatcher"
private const val SIZE = 256
private const val MAT = 16
private const val SIDE_PARAMS = 4 * MAT + MAT * MAT + MAT * MAT + MAT * 3
private const val PARAMS = 2 * SIDE_PARAMS
private const val LUT_SIZE = 33
private const val CPU_THREADS = 4
/** Returns the .cube text mapping colors of [content] toward the look of [style]. Throws on failure. */
fun createCube(context: Context, content: Bitmap, style: Bitmap, title: String): String {
val file = ColorFmModelManager.installedModelFileOrNull(context)
?: throw IllegalStateException("AI color match model is not installed")
val start = SystemClock.elapsedRealtime()
val input = ByteBuffer.allocateDirect(2 * SIZE * SIZE * 3 * Float.SIZE_BYTES).order(ByteOrder.nativeOrder())
val floats = input.asFloatBuffer()
floats.put(resize256(content))
floats.put(resize256(style))
val output = ByteBuffer.allocateDirect(PARAMS * Float.SIZE_BYTES).order(ByteOrder.nativeOrder())
val model = FileInputStream(file).channel.use { it.map(FileChannel.MapMode.READ_ONLY, 0, it.size()) }
Interpreter(model, Interpreter.Options().setNumThreads(CPU_THREADS).setUseXNNPACK(true)).use { interpreter ->
checkContract(interpreter)
interpreter.run(input, output)
}
val params = FloatArray(PARAMS)
output.rewind()
output.asFloatBuffer().get(params)
check(params.all { it.isFinite() }) { "AI color match produced non-finite parameters" }
val inferenceMs = SystemClock.elapsedRealtime() - start
val cube = bakeCube(params, title)
PLog.d(TAG, "AI color match finished: inference=${inferenceMs}ms total=${SystemClock.elapsedRealtime() - start}ms")
return cube
}
/** Model contract check, shared with [ColorFmModelManager] at install time. */
internal fun checkContract(interpreter: Interpreter) {
check(interpreter.inputTensorCount == 1 && interpreter.outputTensorCount == 1) {
"AI color match model must have one input and one output"
}
val input = interpreter.getInputTensor(0)
val output = interpreter.getOutputTensor(0)
check(
input.shape().contentEquals(intArrayOf(2, SIZE, SIZE, 3)) &&
output.shape().contentEquals(intArrayOf(1, PARAMS))
) {
"Unexpected AI color match tensor shapes: input=${input.shape().contentToString()} " +
"output=${output.shape().contentToString()}"
}
check(input.dataType() == DataType.FLOAT32 && output.dataType() == DataType.FLOAT32) {
"Unexpected AI color match tensor types: input=${input.dataType()} output=${output.dataType()}"
}
}
/**
* NHWC RGB [256, 256, 3] in [0, 1]: torch bilinear resize with align_corners = false and no
* antialiasing (source coordinate (i + 0.5) * scale - 0.5, clamped at 0).
*/
private fun resize256(bitmap: Bitmap): FloatArray {
val src = if (bitmap.config == Bitmap.Config.ARGB_8888) bitmap else bitmap.copy(Bitmap.Config.ARGB_8888, false)
try {
val w = src.width
val h = src.height
val out = FloatArray(SIZE * SIZE * 3)
val xs0 = IntArray(SIZE)
val xs1 = IntArray(SIZE)
val xf = FloatArray(SIZE)
for (i in 0 until SIZE) {
val sx = maxOf((i + 0.5f) * w / SIZE - 0.5f, 0f)
xs0[i] = minOf(floor(sx).toInt(), w - 1)
xs1[i] = minOf(xs0[i] + 1, w - 1)
xf[i] = sx - xs0[i]
}
val row0 = IntArray(w)
val row1 = IntArray(w)
for (j in 0 until SIZE) {
val sy = maxOf((j + 0.5f) * h / SIZE - 0.5f, 0f)
val y0 = minOf(floor(sy).toInt(), h - 1)
val y1 = minOf(y0 + 1, h - 1)
val fy = sy - y0
src.getPixels(row0, 0, w, 0, y0, w, 1)
src.getPixels(row1, 0, w, 0, y1, w, 1)
for (i in 0 until SIZE) {
val a = row0[xs0[i]]
val b = row0[xs1[i]]
val c = row1[xs0[i]]
val d = row1[xs1[i]]
val fx = xf[i]
val o = (j * SIZE + i) * 3
for (ch in 0 until 3) {
val shift = 16 - 8 * ch
val top = ((a shr shift) and 0xFF) * (1 - fx) + ((b shr shift) and 0xFF) * fx
val bottom = ((c shr shift) and 0xFF) * (1 - fx) + ((d shr shift) and 0xFF) * fx
out[o + ch] = (top * (1 - fy) + bottom * fy) / 255f
}
}
}
return out
} finally {
if (src !== bitmap) src.recycle()
}
}
/** m = c + mlp(c, 0, content); out = m - mlp(m, 1, style), evaluated on a 33^3 grid. */
private fun bakeCube(params: FloatArray, title: String): String {
val content = Mlp(params, 0)
val style = Mlp(params, SIDE_PARAMS)
val sb = StringBuilder(LUT_SIZE * LUT_SIZE * LUT_SIZE * 24)
sb.append("TITLE \"").append(title.replace("\"", "'")).append("\"\n")
sb.append("LUT_3D_SIZE ").append(LUT_SIZE).append('\n')
val c = FloatArray(3)
val m = FloatArray(3)
val delta = FloatArray(3)
val scale = 1f / (LUT_SIZE - 1)
// .cube order: red changes fastest, then green, then blue.
for (b in 0 until LUT_SIZE) for (g in 0 until LUT_SIZE) for (r in 0 until LUT_SIZE) {
c[0] = r * scale; c[1] = g * scale; c[2] = b * scale
content.eval(c, 0f, delta)
for (k in 0 until 3) m[k] = c[k] + delta[k]
style.eval(m, 1f, delta)
sb.append(String.format(Locale.US, "%.6f %.6f %.6f\n",
(m[0] - delta[0]).coerceIn(0f, 1f),
(m[1] - delta[1]).coerceIn(0f, 1f),
(m[2] - delta[2]).coerceIn(0f, 1f)))
}
return sb.toString()
}
/** One side's MLP: [v, t] (4) -> 16 -> 16 -> 16 -> 3, Swish between layers; matrices row-major. */
private class Mlp(p: FloatArray, offset: Int) {
private val k1 = p.copyOfRange(offset, offset + 4 * MAT)
private val k2 = p.copyOfRange(offset + 4 * MAT, offset + 4 * MAT + MAT * MAT)
private val k3 = p.copyOfRange(offset + 4 * MAT + MAT * MAT, offset + 4 * MAT + 2 * MAT * MAT)
private val k4 = p.copyOfRange(offset + 4 * MAT + 2 * MAT * MAT, offset + SIDE_PARAMS)
private val a = FloatArray(MAT)
private val b = FloatArray(MAT)
private val input = FloatArray(4)
fun eval(v: FloatArray, t: Float, out: FloatArray) {
input[0] = v[0]; input[1] = v[1]; input[2] = v[2]; input[3] = t
layer(input, 4, k1, MAT, a, swish = true)
layer(a, MAT, k2, MAT, b, swish = true)
layer(b, MAT, k3, MAT, a, swish = true)
layer(a, MAT, k4, 3, out, swish = false)
}
private fun layer(x: FloatArray, n: Int, k: FloatArray, cols: Int, y: FloatArray, swish: Boolean) {
for (j in 0 until cols) {
var s = 0f
for (i in 0 until n) s += x[i] * k[i * cols + j]
y[j] = if (swish) s / (1f + exp(-s)) else s
}
}
}
}
@@ -1,237 +1,13 @@
package com.hinnka.mycamera.ml
import android.content.Context
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import org.tensorflow.lite.Interpreter
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.nio.file.AtomicMoveNotSupportedException
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.security.MessageDigest
import java.util.concurrent.TimeUnit
sealed interface AiDenoiseModelState {
data object Missing : AiDenoiseModelState
data class Downloading(
val progress: Float?,
val isInstalling: Boolean
) : AiDenoiseModelState
data object Ready : AiDenoiseModelState
data object Failed : 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 (directly or via hf-mirror.com), verified by exact size,
* SHA-256 and tensor contract, and installed atomically into app-private storage.
*/
object AiDenoiseModelManager {
private const val TAG = "AiDenoiseModelManager"
private const val MODEL_DIRECTORY = "ml_models/scunet_color_25"
private const val MODEL_FILE_NAME = "scunet_color_25.tflite"
private const val MODEL_PART_FILE_NAME = "scunet_color_25.tflite.part"
private const val EXPECTED_MODEL_SIZE_BYTES = 47_200_352L
const val MODEL_SHA256 = "8d060b8e58d3224ab14ee2af72c737af30cc3dd68790f26aca20f364734dd10c"
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")
private val lock = Any()
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.MINUTES)
.build()
private val _state = MutableStateFlow<AiDenoiseModelState>(AiDenoiseModelState.Missing)
private var initialized = false
private var operationJob: Job? = null
fun observe(context: Context): StateFlow<AiDenoiseModelState> {
initialize(context.applicationContext)
return _state.asStateFlow()
}
fun isInstalled(context: Context): Boolean = installedModelFileOrNull(context) != null
/** The installed model; its SHA-256 was verified at install time and equals [MODEL_SHA256]. */
fun installedModelFileOrNull(context: Context): File? {
return modelFile(context.applicationContext).takeIf { it.isFile && it.length() == EXPECTED_MODEL_SIZE_BYTES }
}
fun download(context: Context, source: HfModelSource) {
val appContext = context.applicationContext
initialize(appContext)
synchronized(lock) {
if (installedModelFileOrNull(appContext) != null) {
_state.value = AiDenoiseModelState.Ready
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, source)
_state.value = AiDenoiseModelState.Ready
} catch (e: Exception) {
PLog.w(TAG, "Failed to download or install the AI denoise model from ${source.host}", e)
_state.value = AiDenoiseModelState.Failed
}
}
operationJob = newJob
newJob.invokeOnCompletion {
synchronized(lock) {
if (operationJob === newJob) operationJob = null
}
}
newJob.start()
}
}
private fun initialize(context: Context) {
synchronized(lock) {
if (initialized) return
removeLegacyModels(context)
_state.value = if (installedModelFileOrNull(context) != null) {
AiDenoiseModelState.Ready
} else {
AiDenoiseModelState.Missing
}
initialized = true
}
}
private fun removeLegacyModels(context: Context) {
for (path in LEGACY_MODEL_DIRECTORIES) {
val directory = File(context.filesDir, path)
if (directory.exists() && !directory.deleteRecursively()) {
PLog.w(TAG, "Cannot remove legacy model directory: ${directory.absolutePath}")
}
}
}
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}")
}
val partFile = File(directory, MODEL_PART_FILE_NAME)
if (partFile.exists() && !partFile.delete()) {
throw IOException("Cannot remove stale temporary file: ${partFile.absolutePath}")
}
try {
downloadTo(source.url(MODEL_PATH), partFile)
_state.value = AiDenoiseModelState.Downloading(progress = 1f, isInstalling = true)
validate(partFile)
installAtomically(partFile, modelFile(context))
PLog.d(TAG, "AI denoise model installed: ${modelFile(context).absolutePath}")
} finally {
if (partFile.exists() && !partFile.delete()) {
PLog.w(TAG, "Cannot remove temporary file: ${partFile.absolutePath}")
}
}
}
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}")
}
val body = response.body ?: throw IOException("Model download response has no body")
var downloaded = 0L
var lastPublished = 0L
body.byteStream().use { input ->
FileOutputStream(target).use { output ->
val buffer = ByteArray(BUFFER_SIZE)
while (true) {
val read = input.read(buffer)
if (read < 0) break
downloaded += read
if (downloaded > EXPECTED_MODEL_SIZE_BYTES) {
throw IOException("Model download exceeds the expected size")
}
output.write(buffer, 0, read)
if (downloaded - lastPublished >= PROGRESS_UPDATE_BYTES) {
publishProgress(downloaded)
lastPublished = downloaded
}
}
output.fd.sync()
}
}
publishProgress(downloaded)
if (downloaded != EXPECTED_MODEL_SIZE_BYTES) {
throw IOException("Incomplete model: downloaded=$downloaded expected=$EXPECTED_MODEL_SIZE_BYTES")
}
}
}
private fun publishProgress(downloaded: Long) {
_state.value = AiDenoiseModelState.Downloading(
progress = (downloaded.toDouble() / EXPECTED_MODEL_SIZE_BYTES).toFloat().coerceIn(0f, 1f),
isInstalling = false
)
}
private fun validate(file: File) {
if (file.length() != EXPECTED_MODEL_SIZE_BYTES) {
throw IOException("Unexpected model size: ${file.length()}")
}
if (sha256(file) != MODEL_SHA256) {
throw IOException("Model checksum mismatch")
}
Interpreter(file, Interpreter.Options().setUseXNNPACK(false)).use(AiDenoiser::checkContract)
}
private fun installAtomically(source: File, destination: File) {
try {
Files.move(
source.toPath(), destination.toPath(),
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING
)
} catch (_: AtomicMoveNotSupportedException) {
Files.move(source.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING)
}
}
private fun sha256(file: File): String {
val digest = MessageDigest.getInstance("SHA-256")
FileInputStream(file).use { input ->
val buffer = ByteArray(BUFFER_SIZE)
while (true) {
val read = input.read(buffer)
if (read < 0) break
digest.update(buffer, 0, read)
}
}
return digest.digest().joinToString("") { (it.toInt() and 0xFF).toString(16).padStart(2, '0') }
}
private fun modelFile(context: Context): File = File(File(context.filesDir, MODEL_DIRECTORY), MODEL_FILE_NAME)
private const val BUFFER_SIZE = 64 * 1024
private const val PROGRESS_UPDATE_BYTES = 256 * 1024L
}
/** The AI denoise model: SCUNet color σ=25 (see docs/scunet-tflite.md). */
object AiDenoiseModelManager : HfModelInstaller(
tag = "AiDenoiseModelManager",
directory = "ml_models/scunet_color_25",
fileName = "scunet_color_25.tflite",
expectedSizeBytes = 47_200_352L,
sha256 = "8d060b8e58d3224ab14ee2af72c737af30cc3dd68790f26aca20f364734dd10c",
path = "/Binjia/scunet-color-25-litert/resolve/9454c201ad03a74bbcbb7005232072f01a3b233c/scunet_color_25.tflite",
legacyDirectories = listOf("ml_models/nafnet_sidd_w32", "ml_models/scunet_color_real_psnr"),
checkContract = AiDenoiser::checkContract,
)
@@ -122,7 +122,7 @@ object AiDenoiser {
cacheName = "scunet_color_25_fp16",
modelAssetName = file.name,
modelSizeBytes = file.length().toInt(),
modelFingerprint = AiDenoiseModelManager.MODEL_SHA256,
modelFingerprint = AiDenoiseModelManager.sha256,
)
// FP16 is safe: LayerNorm is pre-scaled so its variance stays within FP16 range.
val gpu = LiteRtGpuModel.fromFile(
@@ -0,0 +1,13 @@
package com.hinnka.mycamera.ml
/** The AI color match model: ColorFM-L parameter network (see docs/colorfm-tflite.md). */
object ColorFmModelManager : HfModelInstaller(
tag = "ColorFmModelManager",
directory = "ml_models/colorfm_l",
fileName = "colorfm_l.tflite",
expectedSizeBytes = 62_198_448L,
sha256 = "5d6bd72e83409fc3f6441c6e7e2c9c081f95344d2aee46eecc981fdaedb9c2b8",
path = "/Binjia/colorfm-l-litert/resolve/ef882a92ac59aa2803a00fd050624441cc2a90c3/colorfm_l.tflite",
legacyDirectories = emptyList(),
checkContract = AiColorMatcher::checkContract,
)
@@ -0,0 +1,239 @@
package com.hinnka.mycamera.ml
import android.content.Context
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import org.tensorflow.lite.Interpreter
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.nio.file.AtomicMoveNotSupportedException
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.security.MessageDigest
import java.util.concurrent.TimeUnit
sealed interface HfModelState {
data object Missing : HfModelState
data class Downloading(
val progress: Float?,
val isInstalling: Boolean
) : HfModelState
data object Ready : HfModelState
data object Failed : HfModelState
}
/**
* Downloads, verifies and installs one TFLite model hosted on Hugging Face.
*
* The model is downloaded from a commit-pinned URL ([path] on huggingface.co or hf-mirror.com),
* verified by exact size, SHA-256 and tensor contract ([checkContract]), and installed
* atomically into app-private storage under [directory]. [legacyDirectories] hold earlier
* models of the same feature and are removed on first use.
*/
open class HfModelInstaller(
private val tag: String,
private val directory: String,
private val fileName: String,
private val expectedSizeBytes: Long,
val sha256: String,
private val path: String,
private val legacyDirectories: List<String>,
private val checkContract: (Interpreter) -> Unit,
) {
private val partFileName = "$fileName.part"
private val lock = Any()
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val _state = MutableStateFlow<HfModelState>(HfModelState.Missing)
private var initialized = false
private var operationJob: Job? = null
fun observe(context: Context): StateFlow<HfModelState> {
initialize(context.applicationContext)
return _state.asStateFlow()
}
fun isInstalled(context: Context): Boolean = installedModelFileOrNull(context) != null
/** The installed model; its SHA-256 was verified at install time and equals [sha256]. */
fun installedModelFileOrNull(context: Context): File? {
return modelFile(context.applicationContext).takeIf { it.isFile && it.length() == expectedSizeBytes }
}
fun download(context: Context, source: HfModelSource) {
val appContext = context.applicationContext
initialize(appContext)
synchronized(lock) {
if (installedModelFileOrNull(appContext) != null) {
_state.value = HfModelState.Ready
return
}
if (operationJob?.isActive == true) return
HfModelSource.remember(appContext, source)
_state.value = HfModelState.Downloading(progress = 0f, isInstalling = false)
val newJob = scope.launch(start = CoroutineStart.LAZY) {
try {
downloadAndInstall(appContext, source)
_state.value = HfModelState.Ready
} catch (e: Exception) {
PLog.w(tag, "Failed to download or install $fileName from ${source.host}", e)
_state.value = HfModelState.Failed
}
}
operationJob = newJob
newJob.invokeOnCompletion {
synchronized(lock) {
if (operationJob === newJob) operationJob = null
}
}
newJob.start()
}
}
private fun initialize(context: Context) {
synchronized(lock) {
if (initialized) return
removeLegacyModels(context)
_state.value = if (installedModelFileOrNull(context) != null) {
HfModelState.Ready
} else {
HfModelState.Missing
}
initialized = true
}
}
private fun removeLegacyModels(context: Context) {
for (legacy in legacyDirectories) {
val legacyDirectory = File(context.filesDir, legacy)
if (legacyDirectory.exists() && !legacyDirectory.deleteRecursively()) {
PLog.w(tag, "Cannot remove legacy model directory: ${legacyDirectory.absolutePath}")
}
}
}
private fun downloadAndInstall(context: Context, source: HfModelSource) {
val directory = File(context.filesDir, directory)
if (!directory.isDirectory && !directory.mkdirs()) {
throw IOException("Cannot create model directory: ${directory.absolutePath}")
}
val partFile = File(directory, partFileName)
if (partFile.exists() && !partFile.delete()) {
throw IOException("Cannot remove stale temporary file: ${partFile.absolutePath}")
}
try {
downloadTo(source.url(path), partFile)
_state.value = HfModelState.Downloading(progress = 1f, isInstalling = true)
validate(partFile)
installAtomically(partFile, modelFile(context))
PLog.d(tag, "Model installed: ${modelFile(context).absolutePath}")
} finally {
if (partFile.exists() && !partFile.delete()) {
PLog.w(tag, "Cannot remove temporary file: ${partFile.absolutePath}")
}
}
}
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}")
}
val body = response.body ?: throw IOException("Model download response has no body")
var downloaded = 0L
var lastPublished = 0L
body.byteStream().use { input ->
FileOutputStream(target).use { output ->
val buffer = ByteArray(BUFFER_SIZE)
while (true) {
val read = input.read(buffer)
if (read < 0) break
downloaded += read
if (downloaded > expectedSizeBytes) {
throw IOException("Model download exceeds the expected size")
}
output.write(buffer, 0, read)
if (downloaded - lastPublished >= PROGRESS_UPDATE_BYTES) {
publishProgress(downloaded)
lastPublished = downloaded
}
}
output.fd.sync()
}
}
publishProgress(downloaded)
if (downloaded != expectedSizeBytes) {
throw IOException("Incomplete model: downloaded=$downloaded expected=$expectedSizeBytes")
}
}
}
private fun publishProgress(downloaded: Long) {
_state.value = HfModelState.Downloading(
progress = (downloaded.toDouble() / expectedSizeBytes).toFloat().coerceIn(0f, 1f),
isInstalling = false
)
}
private fun validate(file: File) {
if (file.length() != expectedSizeBytes) {
throw IOException("Unexpected model size: ${file.length()}")
}
if (sha256(file) != sha256) {
throw IOException("Model checksum mismatch")
}
Interpreter(file, Interpreter.Options().setUseXNNPACK(false)).use(checkContract)
}
private fun installAtomically(source: File, destination: File) {
try {
Files.move(
source.toPath(), destination.toPath(),
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING
)
} catch (_: AtomicMoveNotSupportedException) {
Files.move(source.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING)
}
}
private fun sha256(file: File): String {
val digest = MessageDigest.getInstance("SHA-256")
FileInputStream(file).use { input ->
val buffer = ByteArray(BUFFER_SIZE)
while (true) {
val read = input.read(buffer)
if (read < 0) break
digest.update(buffer, 0, read)
}
}
return digest.digest().joinToString("") { (it.toInt() and 0xFF).toString(16).padStart(2, '0') }
}
private fun modelFile(context: Context): File = File(File(context.filesDir, directory), fileName)
private companion object {
const val BUFFER_SIZE = 64 * 1024
const val PROGRESS_UPDATE_BYTES = 256 * 1024L
val client: OkHttpClient = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.MINUTES)
.build()
}
}
@@ -15,37 +15,36 @@ 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 com.hinnka.mycamera.ml.HfModelState
import kotlin.math.roundToInt
/** Asks to download the AI denoise model; the caller continues once [state] becomes Ready. */
/** Asks to download a Hugging Face hosted model; the caller continues once [state] becomes Ready. */
@Composable
fun AiDenoiseModelDownloadDialog(
state: AiDenoiseModelState,
fun HfModelDownloadDialog(
title: String,
description: String,
state: HfModelState,
source: HfModelSource,
onSourceChange: (HfModelSource) -> Unit,
onDownload: () -> Unit,
onDismiss: () -> Unit
) {
val downloading = state as? AiDenoiseModelState.Downloading
val downloading = state as? HfModelState.Downloading
AlertDialog(
onDismissRequest = onDismiss,
title = {
Text(
text = stringResource(R.string.ai_denoise_model_title),
text = title,
style = MaterialTheme.typography.titleLarge
)
},
text = {
Column {
Text(
text = stringResource(
if (state == AiDenoiseModelState.Failed) R.string.ai_denoise_model_failed
else R.string.ai_denoise_model_description
),
text = if (state == HfModelState.Failed) stringResource(R.string.hf_model_failed) else description,
style = MaterialTheme.typography.bodyMedium
)
if (state == AiDenoiseModelState.Missing || state == AiDenoiseModelState.Failed) {
if (state == HfModelState.Missing || state == HfModelState.Failed) {
Spacer(modifier = Modifier.height(16.dp))
HfModelSourcePicker(source = source, onSourceChange = onSourceChange)
}
@@ -60,10 +59,10 @@ fun AiDenoiseModelDownloadDialog(
Spacer(modifier = Modifier.height(8.dp))
Text(
text = if (downloading.isInstalling) {
stringResource(R.string.ai_denoise_model_installing)
stringResource(R.string.hf_model_installing)
} else {
stringResource(
R.string.ai_denoise_model_downloading,
R.string.hf_model_downloading,
((progress ?: 0f) * 100f).roundToInt()
)
},
@@ -74,13 +73,13 @@ fun AiDenoiseModelDownloadDialog(
},
confirmButton = {
when (state) {
AiDenoiseModelState.Missing -> TextButton(onClick = onDownload) {
Text(stringResource(R.string.ai_denoise_model_download))
HfModelState.Missing -> TextButton(onClick = onDownload) {
Text(stringResource(R.string.hf_model_download))
}
AiDenoiseModelState.Failed -> TextButton(onClick = onDownload) {
Text(stringResource(R.string.ai_denoise_model_retry))
HfModelState.Failed -> TextButton(onClick = onDownload) {
Text(stringResource(R.string.hf_model_retry))
}
is AiDenoiseModelState.Downloading, AiDenoiseModelState.Ready -> Unit
is HfModelState.Downloading, HfModelState.Ready -> Unit
}
},
dismissButton = {
@@ -1,5 +1,9 @@
package com.hinnka.mycamera.ui.gallery
import com.hinnka.mycamera.lut.PhotoColorMatch
import android.net.Uri
import androidx.activity.result.PickVisualMediaRequest
import com.hinnka.mycamera.ml.ColorFmModelManager
import com.hinnka.mycamera.ui.prefs.preferenceValue
import android.annotation.SuppressLint
import android.app.Activity
@@ -74,7 +78,7 @@ 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.ml.HfModelState
import com.hinnka.mycamera.raw.SpectralFilmSelection
import com.hinnka.mycamera.raw.SpectralFilmTuning
import com.hinnka.mycamera.raw.DngEmbeddedProfile
@@ -210,6 +214,16 @@ fun GalleryEditScreen(
) { uri ->
uri?.let { DepthModelManager.importModel(context, it) }
}
val colorFmModelState by remember(context.applicationContext) {
ColorFmModelManager.observe(context)
}.collectAsState()
val isAiColorMatching by viewModel.isAiColorMatching.collectAsState()
var pendingColorMatchReference by remember { mutableStateOf<Uri?>(null) }
val colorMatchReferenceLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickVisualMedia()
) { uri ->
pendingColorMatchReference = uri
}
LaunchedEffect(depthModelState, pendingVirtualAperture) {
val pendingAperture = pendingVirtualAperture
@@ -631,7 +645,7 @@ fun GalleryEditScreen(
}
}
LaunchedEffect(aiDenoiseModelState, pendingAiDenoise) {
if (aiDenoiseModelState is AiDenoiseModelState.Ready && pendingAiDenoise) {
if (aiDenoiseModelState is HfModelState.Ready && pendingAiDenoise) {
pendingAiDenoise = false
startAiDenoise()
}
@@ -1565,6 +1579,19 @@ fun GalleryEditScreen(
categoryOrder = categoryOrder,
modifier = Modifier.fillMaxWidth()
)
if (!currentPhoto.isVideo) {
Spacer(modifier = Modifier.height(8.dp))
AiColorMatchRow(
active = PhotoColorMatch.isId(editLutId),
enabled = !isAiColorMatching,
onPickReference = {
colorMatchReferenceLauncher.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
)
},
onRemove = { viewModel.setEditLut(null) },
)
}
Spacer(modifier = Modifier.height(8.dp))
LutIntensitySlider(
@@ -2115,9 +2142,50 @@ fun GalleryEditScreen(
)
}
// AI color match: download the model first if needed, then run once it is Ready.
LaunchedEffect(pendingColorMatchReference, colorFmModelState) {
val reference = pendingColorMatchReference ?: return@LaunchedEffect
if (colorFmModelState !is HfModelState.Ready) return@LaunchedEffect
pendingColorMatchReference = null
val photo = editSourcePhoto ?: return@LaunchedEffect
viewModel.applyAiColorMatch(photo, reference) { success ->
if (!success) {
Toast.makeText(context, R.string.ai_color_match_failed, Toast.LENGTH_SHORT).show()
}
}
}
if (pendingColorMatchReference != null && colorFmModelState !is HfModelState.Ready) {
var colorFmModelSource by remember { mutableStateOf(HfModelSource.preferred(context)) }
HfModelDownloadDialog(
title = stringResource(R.string.ai_color_match_model_title),
description = stringResource(R.string.ai_color_match_model_description),
state = colorFmModelState,
source = colorFmModelSource,
onSourceChange = { colorFmModelSource = it },
onDownload = { ColorFmModelManager.download(context, colorFmModelSource) },
onDismiss = { pendingColorMatchReference = null }
)
}
if (isAiColorMatching) {
AlertDialog(
onDismissRequest = {},
title = { Text(stringResource(R.string.ai_color_match_action)) },
text = {
Column {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
Spacer(modifier = Modifier.height(8.dp))
Text(stringResource(R.string.ai_color_match_progress))
}
},
confirmButton = {}
)
}
if (pendingAiDenoise) {
var aiDenoiseModelSource by remember { mutableStateOf(HfModelSource.preferred(context)) }
AiDenoiseModelDownloadDialog(
HfModelDownloadDialog(
title = stringResource(R.string.ai_denoise_model_title),
description = stringResource(R.string.ai_denoise_model_description),
state = aiDenoiseModelState,
source = aiDenoiseModelSource,
onSourceChange = { aiDenoiseModelSource = it },
@@ -2640,3 +2708,45 @@ private fun VideoEditPlayer(
Spacer(modifier = modifier.fillMaxSize())
}
}
/**
* AI color match for the photo being edited. The match is this photo's own filter (not in the
* filter library): when [active] it can be re-run with another reference or removed.
*/
@Composable
private fun AiColorMatchRow(
active: Boolean,
enabled: Boolean,
onPickReference: () -> Unit,
onRemove: () -> Unit,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(12.dp))
.background(Color.White.copy(alpha = if (active) 0.12f else 0.06f))
.padding(horizontal = 12.dp, vertical = 10.dp)
) {
Text(
text = stringResource(if (active) R.string.ai_color_match_active else R.string.ai_color_match_action),
color = if (active) AccentColor else Color.White,
style = MaterialTheme.typography.titleSmall
)
Text(
text = stringResource(R.string.ai_color_match_hint),
color = Color.White.copy(alpha = 0.6f),
style = MaterialTheme.typography.bodySmall
)
Spacer(modifier = Modifier.height(8.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(onClick = onPickReference, enabled = enabled) {
Text(stringResource(if (active) R.string.ai_color_match_change else R.string.ai_color_match_pick))
}
if (active) {
TextButton(onClick = onRemove, enabled = enabled) {
Text(stringResource(R.string.ai_color_match_remove), color = Color.White)
}
}
}
}
}
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.viewmodel
import com.hinnka.mycamera.lut.PhotoColorMatch
import android.app.Application
import android.content.Context
import android.content.Intent
@@ -112,6 +113,9 @@ private data class CopiedEditSettings(
class GalleryViewModel(application: Application) : AndroidViewModel(application) {
companion object {
/** Long edge the content and reference are decoded at before the 256 x 256 resize. */
private const val AI_COLOR_MATCH_MAX_EDGE = 2048
private const val TAG = "GalleryViewModel"
private const val FULL_QUALITY_PREVIEW_MAX_EDGE = 4096
private const val HDR_DETAIL_MAX_BITMAP_BYTES = 80L * 1024L * 1024L
@@ -2437,6 +2441,54 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
/**
* 设置 LUT
*/
private val _isAiColorMatching = MutableStateFlow(false)
val isAiColorMatching = _isAiColorMatching.asStateFlow()
/**
* Matches the photo's colors to [referenceUri] with [com.hinnka.mycamera.ml.AiColorMatcher] and
* selects the result as this photo's filter. The LUT belongs to the photo only
* ([PhotoColorMatch]); it is stored in the photo's directory, not in the filter library.
*/
fun applyAiColorMatch(photo: MediaData, referenceUri: Uri, onComplete: (Boolean) -> Unit) {
if (_isAiColorMatching.value) return
_isAiColorMatching.value = true
viewModelScope.launch {
val lutId = withContext(Dispatchers.IO) {
val context = getApplication<Application>()
var content: Bitmap? = null
var reference: Bitmap? = null
try {
content = GalleryManager.loadOriginalBitmap(context, photo.id, AI_COLOR_MATCH_MAX_EDGE)
?: GalleryManager.loadBitmap(context, photo.uri, AI_COLOR_MATCH_MAX_EDGE)
?: error("Failed to load photo ${photo.id}")
reference = GalleryManager.loadBitmap(context, referenceUri, AI_COLOR_MATCH_MAX_EDGE)
?: error("Failed to load reference image")
val cube = com.hinnka.mycamera.ml.AiColorMatcher.createCube(context, content, reference, "AI color match")
val version = System.currentTimeMillis()
val file = GalleryManager.getAiColorMatchFile(context, photo.id, version)
val converted = FileOutputStream(file).use { output ->
com.hinnka.mycamera.lut.LutConverter.convertCubeToplut(cube.byteInputStream(), output)
}
check(converted) { "Failed to convert AI color match LUT" }
// Keep the match the saved metadata still refers to until the edit is saved.
val savedVersion = PhotoColorMatch.parse(GalleryManager.loadMetadata(context, photo.id)?.lutId)
?.takeIf { it.photoId == photo.id }?.version
GalleryManager.deleteAiColorMatchFiles(context, photo.id, setOfNotNull(version, savedVersion))
PhotoColorMatch.lutId(photo.id, version)
} catch (e: Exception) {
PLog.e(TAG, "AI color match failed", e)
null
} finally {
content?.recycle()
reference?.recycle()
}
}
_isAiColorMatching.value = false
if (lutId != null) setEditLut(lutId)
onComplete(lutId != null)
}
}
fun setEditLut(lutId: String?) {
if (lutId != null && getCurrentPhoto()?.isVideo == true &&
(editVideoSourceProfile == null || selectableEditLuts.none { it.id == lutId })
@@ -2552,7 +2604,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val sourceIsRaw = getCurrentPhoto()?.let(::isRawMedia) == true
copiedEditSettings = CopiedEditSettings(
metadata = MediaMetadata(
lutId = editLutId.value,
lutId = PhotoColorMatch.transferable(editLutId.value),
colorRecipeParams = (editPhotoRecipeParams.value ?: editLutRecipeParams.value)
.deepCopy(),
sharpening = editSharpening.value.takeUnless { sourceIsRaw },
@@ -2587,7 +2639,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val sourceIsRaw = sourcePhoto?.let(::isRawMedia) == true
val effectiveRecipe = editPhotoRecipeParams.value ?: editLutRecipeParams.value
val lookPreset = base.copy(
lutId = CameraPreset.normalizeLutId(editLutId.value),
lutId = CameraPreset.normalizeLutId(PhotoColorMatch.transferable(editLutId.value)),
colorRecipe = effectiveRecipe.withoutIndependentEffects(),
effects = effectiveRecipe.toEffectParams(),
frameId = editFrameId.value,
@@ -2709,7 +2761,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
copiedEditSettings = CopiedEditSettings(
metadata = MediaMetadata(
lutId = metadata.lutId,
lutId = PhotoColorMatch.transferable(metadata.lutId),
colorRecipeParams = effectiveRecipe?.deepCopy(),
sharpening = metadata.sharpening.takeUnless { sourceIsRaw },
noiseReduction = metadata.noiseReduction.takeUnless { sourceIsRaw },
+15 -5
View File
@@ -1443,11 +1443,21 @@
<!-- /Fotufilm controls -->
<string name="ai_denoise_model_title">AI 降噪模型</string>
<string name="ai_denoise_model_description">AI 降噪需要 SCUNet 降噪模型(約 47 MB),是否現在下載?模型僅儲存在應用程式私有目錄中。</string>
<string name="ai_denoise_model_downloading">正在下載模型… %1$d%%</string>
<string name="ai_denoise_model_installing">正在驗證並安裝模型…</string>
<string name="ai_denoise_model_failed">模型下載或驗證失敗,請檢查網路後重試。</string>
<string name="ai_denoise_model_download">下載</string>
<string name="ai_denoise_model_retry">重試</string>
<string name="hf_model_downloading">正在下載模型… %1$d%%</string>
<string name="hf_model_installing">正在驗證並安裝模型…</string>
<string name="hf_model_failed">模型下載或驗證失敗,請檢查網路後重試。</string>
<string name="hf_model_download">下載</string>
<string name="hf_model_retry">重試</string>
<string name="model_download_source">下載來源</string>
<string name="model_download_source_mirror">HF 鏡像站(hf-mirror.com)</string>
<string name="ai_color_match_action">AI 仿色</string>
<string name="ai_color_match_active">AI 仿色(僅此張照片)</string>
<string name="ai_color_match_hint">參考一張圖片的色調為此張照片調色,結果只用於這張照片,不會加入濾鏡庫。</string>
<string name="ai_color_match_pick">選擇參考圖</string>
<string name="ai_color_match_change">更換參考圖</string>
<string name="ai_color_match_remove">移除</string>
<string name="ai_color_match_progress">正在仿色…</string>
<string name="ai_color_match_failed">AI 仿色失敗,請換一張參考圖再試。</string>
<string name="ai_color_match_model_title">AI 仿色模型</string>
<string name="ai_color_match_model_description">AI 仿色需要 ColorFM 模型(約 62 MB)。現在下載嗎?模型將儲存在 App 的私人目錄中。模型權重僅限非商業用途(CC BY-NC 4.0)。</string>
</resources>
+15 -5
View File
@@ -1481,11 +1481,21 @@
<string name="gallery_denoise_processing">Réduction du bruit en cours…</string>
<string name="ai_denoise_model_title">Modèle de débruitage IA</string>
<string name="ai_denoise_model_description">Le débruitage IA nécessite le modèle SCUNet (environ 47 Mo). Le télécharger maintenant ? Il est stocké de façon privée par l\'application.</string>
<string name="ai_denoise_model_downloading">Téléchargement du modèle… %1$d%%</string>
<string name="ai_denoise_model_installing">Vérification et installation du modèle…</string>
<string name="ai_denoise_model_failed">Le modèle n\'a pas pu être téléchargé ou vérifié. Vérifiez votre connexion et réessayez.</string>
<string name="ai_denoise_model_download">Télécharger</string>
<string name="ai_denoise_model_retry">Réessayer</string>
<string name="hf_model_downloading">Téléchargement du modèle… %1$d%%</string>
<string name="hf_model_installing">Vérification et installation du modèle…</string>
<string name="hf_model_failed">Le modèle n\'a pas pu être téléchargé ou vérifié. Vérifiez votre connexion et réessayez.</string>
<string name="hf_model_download">Télécharger</string>
<string name="hf_model_retry">Réessayer</string>
<string name="model_download_source">Source de téléchargement</string>
<string name="model_download_source_mirror">Miroir HF (hf-mirror.com)</string>
<string name="ai_color_match_action">Correspondance des couleurs IA</string>
<string name="ai_color_match_active">Correspondance IA · cette photo uniquement</string>
<string name="ai_color_match_hint">Adapte les couleurs de cette photo à une image de référence. Le résultat s\'applique uniquement à cette photo et n\'est pas ajouté à la bibliothèque de filtres.</string>
<string name="ai_color_match_pick">Choisir une référence</string>
<string name="ai_color_match_change">Changer de référence</string>
<string name="ai_color_match_remove">Retirer</string>
<string name="ai_color_match_progress">Correspondance des couleurs…</string>
<string name="ai_color_match_failed">Échec de la correspondance des couleurs IA. Essayez une autre image de référence.</string>
<string name="ai_color_match_model_title">Modèle de correspondance des couleurs IA</string>
<string name="ai_color_match_model_description">La correspondance des couleurs IA nécessite le modèle ColorFM (environ 62 Mo). Le télécharger maintenant ? Il est stocké en privé par l\'application. Les poids du modèle sont réservés à un usage non commercial (CC BY-NC 4.0).</string>
</resources>
+15 -5
View File
@@ -1320,11 +1320,21 @@
<!-- /Fotufilm controls -->
<string name="ai_denoise_model_title">AI ノイズ除去モデル</string>
<string name="ai_denoise_model_description">AI ノイズ除去には SCUNet ノイズ除去モデル(約 47 MB)が必要です。今すぐダウンロードしますか?モデルはアプリ専用の領域に保存されます。</string>
<string name="ai_denoise_model_downloading">モデルをダウンロード中… %1$d%%</string>
<string name="ai_denoise_model_installing">モデルを検証してインストール中…</string>
<string name="ai_denoise_model_failed">モデルのダウンロードまたは検証に失敗しました。接続を確認して再試行してください。</string>
<string name="ai_denoise_model_download">ダウンロード</string>
<string name="ai_denoise_model_retry">再試行</string>
<string name="hf_model_downloading">モデルをダウンロード中… %1$d%%</string>
<string name="hf_model_installing">モデルを検証してインストール中…</string>
<string name="hf_model_failed">モデルのダウンロードまたは検証に失敗しました。接続を確認して再試行してください。</string>
<string name="hf_model_download">ダウンロード</string>
<string name="hf_model_retry">再試行</string>
<string name="model_download_source">ダウンロード元</string>
<string name="model_download_source_mirror">HF ミラー(hf-mirror.com)</string>
<string name="ai_color_match_action">AI カラーマッチ</string>
<string name="ai_color_match_active">AI カラーマッチ(この写真のみ)</string>
<string name="ai_color_match_hint">参照画像の色調にこの写真を合わせます。結果はこの写真だけに適用され、フィルターライブラリには追加されません。</string>
<string name="ai_color_match_pick">参照画像を選択</string>
<string name="ai_color_match_change">参照画像を変更</string>
<string name="ai_color_match_remove">削除</string>
<string name="ai_color_match_progress">カラーマッチ中…</string>
<string name="ai_color_match_failed">AI カラーマッチに失敗しました。別の参照画像でお試しください。</string>
<string name="ai_color_match_model_title">AI カラーマッチモデル</string>
<string name="ai_color_match_model_description">AI カラーマッチには ColorFM モデル(約 62 MB)が必要です。今すぐダウンロードしますか?モデルはアプリ内の非公開領域に保存されます。モデルの重みは非商用利用に限られます(CC BY-NC 4.0)。</string>
</resources>
+15 -5
View File
@@ -1116,11 +1116,21 @@
<string name="save_as_preset">บันทึกเป็นพรีเซ็ต</string>
<string name="ai_denoise_model_title">โมเดลลดสัญญาณรบกวน AI</string>
<string name="ai_denoise_model_description">การลดสัญญาณรบกวนด้วย AI ต้องใช้โมเดล SCUNet (ประมาณ 47 MB) ดาวน์โหลดตอนนี้หรือไม่? โมเดลจะถูกเก็บไว้เป็นส่วนตัวในแอป</string>
<string name="ai_denoise_model_downloading">กำลังดาวน์โหลดโมเดล… %1$d%%</string>
<string name="ai_denoise_model_installing">กำลังตรวจสอบและติดตั้งโมเดล…</string>
<string name="ai_denoise_model_failed">ไม่สามารถดาวน์โหลดหรือตรวจสอบโมเดลได้ โปรดตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง</string>
<string name="ai_denoise_model_download">ดาวน์โหลด</string>
<string name="ai_denoise_model_retry">ลองอีกครั้ง</string>
<string name="hf_model_downloading">กำลังดาวน์โหลดโมเดล… %1$d%%</string>
<string name="hf_model_installing">กำลังตรวจสอบและติดตั้งโมเดล…</string>
<string name="hf_model_failed">ไม่สามารถดาวน์โหลดหรือตรวจสอบโมเดลได้ โปรดตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง</string>
<string name="hf_model_download">ดาวน์โหลด</string>
<string name="hf_model_retry">ลองอีกครั้ง</string>
<string name="model_download_source">แหล่งดาวน์โหลด</string>
<string name="model_download_source_mirror">มิเรอร์ HF (hf-mirror.com)</string>
<string name="ai_color_match_action">จับคู่สีด้วย AI</string>
<string name="ai_color_match_active">จับคู่สีด้วย AI · เฉพาะภาพนี้</string>
<string name="ai_color_match_hint">ปรับสีภาพนี้ให้เข้ากับภาพอ้างอิง ผลลัพธ์ใช้กับภาพนี้เท่านั้นและไม่ถูกเพิ่มลงในคลังฟิลเตอร์</string>
<string name="ai_color_match_pick">เลือกภาพอ้างอิง</string>
<string name="ai_color_match_change">เปลี่ยนภาพอ้างอิง</string>
<string name="ai_color_match_remove">ลบ</string>
<string name="ai_color_match_progress">กำลังจับคู่สี…</string>
<string name="ai_color_match_failed">จับคู่สีด้วย AI ไม่สำเร็จ ลองใช้ภาพอ้างอิงอื่น</string>
<string name="ai_color_match_model_title">โมเดลจับคู่สีด้วย AI</string>
<string name="ai_color_match_model_description">การจับคู่สีด้วย AI ต้องใช้โมเดล ColorFM (ประมาณ 62 MB) ดาวน์โหลดตอนนี้ไหม? โมเดลจะถูกเก็บไว้เป็นส่วนตัวในแอป น้ำหนักโมเดลอนุญาตเฉพาะการใช้งานที่ไม่ใช่เชิงพาณิชย์ (CC BY-NC 4.0)</string>
</resources>
+15 -5
View File
@@ -1499,11 +1499,21 @@
<!-- /Fotufilm controls -->
<string name="ai_denoise_model_title">AI 降噪模型</string>
<string name="ai_denoise_model_description">AI 降噪需要 SCUNet 降噪模型(约 47 MB),是否现在下载?模型仅保存在应用私有目录中。</string>
<string name="ai_denoise_model_downloading">正在下载模型… %1$d%%</string>
<string name="ai_denoise_model_installing">正在校验并安装模型…</string>
<string name="ai_denoise_model_failed">模型下载或校验失败,请检查网络后重试。</string>
<string name="ai_denoise_model_download">下载</string>
<string name="ai_denoise_model_retry">重试</string>
<string name="hf_model_downloading">正在下载模型… %1$d%%</string>
<string name="hf_model_installing">正在校验并安装模型…</string>
<string name="hf_model_failed">模型下载或校验失败,请检查网络后重试。</string>
<string name="hf_model_download">下载</string>
<string name="hf_model_retry">重试</string>
<string name="model_download_source">下载源</string>
<string name="model_download_source_mirror">HF 镜像站(hf-mirror.com)</string>
<string name="ai_color_match_action">AI 仿色</string>
<string name="ai_color_match_active">AI 仿色(仅本张照片)</string>
<string name="ai_color_match_hint">参考一张图片的色调为本张照片调色,结果只用于这张照片,不会加入滤镜库。</string>
<string name="ai_color_match_pick">选择参考图</string>
<string name="ai_color_match_change">更换参考图</string>
<string name="ai_color_match_remove">移除</string>
<string name="ai_color_match_progress">正在仿色…</string>
<string name="ai_color_match_failed">AI 仿色失败,请换一张参考图再试。</string>
<string name="ai_color_match_model_title">AI 仿色模型</string>
<string name="ai_color_match_model_description">AI 仿色需要 ColorFM 模型(约 62 MB)。现在下载吗?模型将保存在应用的私有目录中。模型权重仅限非商业用途(CC BY-NC 4.0)。</string>
</resources>
+15 -5
View File
@@ -1437,11 +1437,21 @@
<!-- /Fotufilm controls -->
<string name="ai_denoise_model_title">AI 降噪模型</string>
<string name="ai_denoise_model_description">AI 降噪需要 SCUNet 降噪模型(約 47 MB),是否現在下載?模型僅儲存在應用程式私有目錄中。</string>
<string name="ai_denoise_model_downloading">正在下載模型… %1$d%%</string>
<string name="ai_denoise_model_installing">正在驗證並安裝模型…</string>
<string name="ai_denoise_model_failed">模型下載或驗證失敗,請檢查網絡後重試。</string>
<string name="ai_denoise_model_download">下載</string>
<string name="ai_denoise_model_retry">重試</string>
<string name="hf_model_downloading">正在下載模型… %1$d%%</string>
<string name="hf_model_installing">正在驗證並安裝模型…</string>
<string name="hf_model_failed">模型下載或驗證失敗,請檢查網絡後重試。</string>
<string name="hf_model_download">下載</string>
<string name="hf_model_retry">重試</string>
<string name="model_download_source">下載來源</string>
<string name="model_download_source_mirror">HF 鏡像站(hf-mirror.com)</string>
<string name="ai_color_match_action">AI 仿色</string>
<string name="ai_color_match_active">AI 仿色(僅此張照片)</string>
<string name="ai_color_match_hint">參考一張圖片的色調為此張照片調色,結果只用於這張照片,不會加入濾鏡庫。</string>
<string name="ai_color_match_pick">選擇參考圖</string>
<string name="ai_color_match_change">更換參考圖</string>
<string name="ai_color_match_remove">移除</string>
<string name="ai_color_match_progress">正在仿色…</string>
<string name="ai_color_match_failed">AI 仿色失敗,請換一張參考圖再試。</string>
<string name="ai_color_match_model_title">AI 仿色模型</string>
<string name="ai_color_match_model_description">AI 仿色需要 ColorFM 模型(約 62 MB)。現在下載嗎?模型將儲存在 App 的私人目錄中。模型權重僅限非商業用途(CC BY-NC 4.0)。</string>
</resources>
+15 -5
View File
@@ -1443,11 +1443,21 @@
<!-- /Fotufilm controls -->
<string name="ai_denoise_model_title">AI 降噪模型</string>
<string name="ai_denoise_model_description">AI 降噪需要 SCUNet 降噪模型(約 47 MB),是否現在下載?模型僅儲存在應用程式私有目錄中。</string>
<string name="ai_denoise_model_downloading">正在下載模型… %1$d%%</string>
<string name="ai_denoise_model_installing">正在驗證並安裝模型…</string>
<string name="ai_denoise_model_failed">模型下載或驗證失敗,請檢查網路後重試。</string>
<string name="ai_denoise_model_download">下載</string>
<string name="ai_denoise_model_retry">重試</string>
<string name="hf_model_downloading">正在下載模型… %1$d%%</string>
<string name="hf_model_installing">正在驗證並安裝模型…</string>
<string name="hf_model_failed">模型下載或驗證失敗,請檢查網路後重試。</string>
<string name="hf_model_download">下載</string>
<string name="hf_model_retry">重試</string>
<string name="model_download_source">下載來源</string>
<string name="model_download_source_mirror">HF 鏡像站(hf-mirror.com)</string>
<string name="ai_color_match_action">AI 仿色</string>
<string name="ai_color_match_active">AI 仿色(僅此張照片)</string>
<string name="ai_color_match_hint">參考一張圖片的色調為此張照片調色,結果只用於這張照片,不會加入濾鏡庫。</string>
<string name="ai_color_match_pick">選擇參考圖</string>
<string name="ai_color_match_change">更換參考圖</string>
<string name="ai_color_match_remove">移除</string>
<string name="ai_color_match_progress">正在仿色…</string>
<string name="ai_color_match_failed">AI 仿色失敗,請換一張參考圖再試。</string>
<string name="ai_color_match_model_title">AI 仿色模型</string>
<string name="ai_color_match_model_description">AI 仿色需要 ColorFM 模型(約 62 MB)。現在下載嗎?模型將儲存在 App 的私人目錄中。模型權重僅限非商業用途(CC BY-NC 4.0)。</string>
</resources>
+15 -5
View File
@@ -1523,12 +1523,22 @@
<!-- /Fotufilm controls -->
<string name="ai_denoise_model_title">AI Denoise Model</string>
<string name="ai_denoise_model_description">AI denoise needs the SCUNet denoise model (about 47 MB). Download it now? It is stored privately by the app.</string>
<string name="ai_denoise_model_downloading">Downloading model… %1$d%%</string>
<string name="ai_denoise_model_installing">Verifying and installing model…</string>
<string name="ai_denoise_model_failed">The model could not be downloaded or verified. Check your connection and try again.</string>
<string name="ai_denoise_model_download">Download</string>
<string name="ai_denoise_model_retry">Retry</string>
<string name="hf_model_downloading">Downloading model… %1$d%%</string>
<string name="hf_model_installing">Verifying and installing model…</string>
<string name="hf_model_failed">The model could not be downloaded or verified. Check your connection and try again.</string>
<string name="hf_model_download">Download</string>
<string name="hf_model_retry">Retry</string>
<string name="model_download_source">Download source</string>
<string name="model_download_source_hugging_face" translatable="false">Hugging Face</string>
<string name="model_download_source_mirror">HF Mirror (hf-mirror.com)</string>
<string name="ai_color_match_action">AI color match</string>
<string name="ai_color_match_active">AI color match · this photo only</string>
<string name="ai_color_match_hint">Matches this photo\'s colors to a reference image. The result applies to this photo only and is not added to the filter library.</string>
<string name="ai_color_match_pick">Choose reference</string>
<string name="ai_color_match_change">Change reference</string>
<string name="ai_color_match_remove">Remove</string>
<string name="ai_color_match_progress">Matching colors…</string>
<string name="ai_color_match_failed">AI color match failed. Try another reference image.</string>
<string name="ai_color_match_model_title">AI Color Match Model</string>
<string name="ai_color_match_model_description">AI color match needs the ColorFM model (about 62 MB). Download it now? It is stored privately by the app. The model weights are licensed for non-commercial use only (CC BY-NC 4.0).</string>
</resources>