|
| 1 | +/* |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * This source code is licensed under the BSD-style license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. |
| 7 | + */ |
| 8 | + |
| 9 | +package com.example.executorchllamademo |
| 10 | + |
| 11 | +import android.content.Context |
| 12 | +import android.util.Log |
| 13 | +import kotlinx.coroutines.Dispatchers |
| 14 | +import kotlinx.coroutines.withContext |
| 15 | +import org.json.JSONObject |
| 16 | +import java.io.File |
| 17 | +import java.net.HttpURLConnection |
| 18 | +import java.net.URL |
| 19 | + |
| 20 | +/** |
| 21 | + * Manages loading and parsing of preset model configurations from JSON. |
| 22 | + * Supports loading from bundled assets, local cache, or remote URL. |
| 23 | + */ |
| 24 | +class PresetConfigManager(private val context: Context) { |
| 25 | + |
| 26 | + companion object { |
| 27 | + private const val TAG = "PresetConfigManager" |
| 28 | + private const val ASSET_FILENAME = "preset_models.json" |
| 29 | + private const val CACHE_FILENAME = "preset_models_cache.json" |
| 30 | + private const val PREFS_NAME = "preset_config_prefs" |
| 31 | + private const val PREF_CUSTOM_URL = "custom_config_url" |
| 32 | + } |
| 33 | + |
| 34 | + private val cacheFile: File |
| 35 | + get() = File(context.filesDir, CACHE_FILENAME) |
| 36 | + |
| 37 | + private val prefs by lazy { |
| 38 | + context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Returns the currently configured custom URL, or null if using default. |
| 43 | + */ |
| 44 | + fun getCustomConfigUrl(): String? { |
| 45 | + return prefs.getString(PREF_CUSTOM_URL, null) |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Saves a custom config URL to preferences. |
| 50 | + */ |
| 51 | + fun setCustomConfigUrl(url: String?) { |
| 52 | + prefs.edit().apply { |
| 53 | + if (url.isNullOrBlank()) { |
| 54 | + remove(PREF_CUSTOM_URL) |
| 55 | + } else { |
| 56 | + putString(PREF_CUSTOM_URL, url) |
| 57 | + } |
| 58 | + apply() |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * Loads models from the current configuration source. |
| 64 | + * Priority: cached config (if custom URL was loaded) -> bundled asset |
| 65 | + */ |
| 66 | + fun loadModels(): Map<String, ModelInfo> { |
| 67 | + // If we have a cached config from a custom URL, use it |
| 68 | + if (cacheFile.exists() && getCustomConfigUrl() != null) { |
| 69 | + try { |
| 70 | + val json = cacheFile.readText() |
| 71 | + val models = parseModelsJson(json) |
| 72 | + if (models.isNotEmpty()) { |
| 73 | + Log.d(TAG, "Loaded ${models.size} models from cache") |
| 74 | + return models |
| 75 | + } |
| 76 | + } catch (e: Exception) { |
| 77 | + Log.w(TAG, "Failed to load cached config, falling back to asset", e) |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + // Fall back to bundled asset |
| 82 | + return loadFromAsset() |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * Loads models from the bundled asset file. |
| 87 | + */ |
| 88 | + private fun loadFromAsset(): Map<String, ModelInfo> { |
| 89 | + return try { |
| 90 | + val json = context.assets.open(ASSET_FILENAME).bufferedReader().use { it.readText() } |
| 91 | + val models = parseModelsJson(json) |
| 92 | + Log.d(TAG, "Loaded ${models.size} models from asset") |
| 93 | + models |
| 94 | + } catch (e: Exception) { |
| 95 | + Log.e(TAG, "Failed to load models from asset", e) |
| 96 | + emptyMap() |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + /** |
| 101 | + * Downloads config from a URL and caches it locally. |
| 102 | + * Returns the parsed models, or null if download/parse failed. |
| 103 | + */ |
| 104 | + suspend fun loadFromUrl(url: String): Result<Map<String, ModelInfo>> = withContext(Dispatchers.IO) { |
| 105 | + try { |
| 106 | + val connection = URL(url).openConnection() as HttpURLConnection |
| 107 | + connection.connectTimeout = 15000 |
| 108 | + connection.readTimeout = 15000 |
| 109 | + connection.requestMethod = "GET" |
| 110 | + |
| 111 | + val responseCode = connection.responseCode |
| 112 | + if (responseCode != HttpURLConnection.HTTP_OK) { |
| 113 | + return@withContext Result.failure( |
| 114 | + Exception("HTTP error: $responseCode ${connection.responseMessage}") |
| 115 | + ) |
| 116 | + } |
| 117 | + |
| 118 | + val json = connection.inputStream.bufferedReader().use { it.readText() } |
| 119 | + val models = parseModelsJson(json) |
| 120 | + |
| 121 | + if (models.isEmpty()) { |
| 122 | + return@withContext Result.failure(Exception("No valid models found in config")) |
| 123 | + } |
| 124 | + |
| 125 | + // Cache the config and save the URL |
| 126 | + cacheFile.writeText(json) |
| 127 | + setCustomConfigUrl(url) |
| 128 | + |
| 129 | + Log.d(TAG, "Loaded ${models.size} models from URL: $url") |
| 130 | + Result.success(models) |
| 131 | + } catch (e: Exception) { |
| 132 | + Log.e(TAG, "Failed to load config from URL: $url", e) |
| 133 | + Result.failure(e) |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + /** |
| 138 | + * Resets to the default bundled configuration. |
| 139 | + * Clears the cached config and custom URL. |
| 140 | + */ |
| 141 | + fun resetToDefault(): Map<String, ModelInfo> { |
| 142 | + // Delete cached config |
| 143 | + if (cacheFile.exists()) { |
| 144 | + cacheFile.delete() |
| 145 | + } |
| 146 | + // Clear custom URL |
| 147 | + setCustomConfigUrl(null) |
| 148 | + |
| 149 | + Log.d(TAG, "Reset to default configuration") |
| 150 | + return loadFromAsset() |
| 151 | + } |
| 152 | + |
| 153 | + /** |
| 154 | + * Parses the JSON string into a map of ModelInfo objects. |
| 155 | + * Handles invalid entries gracefully by skipping them. |
| 156 | + */ |
| 157 | + private fun parseModelsJson(json: String): Map<String, ModelInfo> { |
| 158 | + val result = linkedMapOf<String, ModelInfo>() |
| 159 | + |
| 160 | + try { |
| 161 | + val root = JSONObject(json) |
| 162 | + val models = root.optJSONObject("models") ?: return emptyMap() |
| 163 | + |
| 164 | + val keys = models.keys() |
| 165 | + while (keys.hasNext()) { |
| 166 | + val key = keys.next() |
| 167 | + try { |
| 168 | + val modelObj = models.getJSONObject(key) |
| 169 | + val modelInfo = parseModelInfo(modelObj) |
| 170 | + if (modelInfo != null) { |
| 171 | + result[key] = modelInfo |
| 172 | + } else { |
| 173 | + Log.w(TAG, "Skipping invalid model entry: $key") |
| 174 | + } |
| 175 | + } catch (e: Exception) { |
| 176 | + Log.w(TAG, "Error parsing model entry '$key': ${e.message}") |
| 177 | + } |
| 178 | + } |
| 179 | + } catch (e: Exception) { |
| 180 | + Log.e(TAG, "Error parsing models JSON", e) |
| 181 | + } |
| 182 | + |
| 183 | + return result |
| 184 | + } |
| 185 | + |
| 186 | + /** |
| 187 | + * Parses a single model JSON object into a ModelInfo. |
| 188 | + * Returns null if required fields are missing or invalid. |
| 189 | + */ |
| 190 | + private fun parseModelInfo(obj: JSONObject): ModelInfo? { |
| 191 | + val displayName = obj.optString("displayName").takeIf { it.isNotEmpty() } ?: return null |
| 192 | + val modelUrl = obj.optString("modelUrl").takeIf { it.isNotEmpty() } ?: return null |
| 193 | + val modelFilename = obj.optString("modelFilename").takeIf { it.isNotEmpty() } ?: return null |
| 194 | + val tokenizerUrl = obj.optString("tokenizerUrl", "") |
| 195 | + val tokenizerFilename = obj.optString("tokenizerFilename", "") |
| 196 | + |
| 197 | + val modelTypeStr = obj.optString("modelType", "LLAMA_3") |
| 198 | + val modelType = try { |
| 199 | + ModelType.valueOf(modelTypeStr) |
| 200 | + } catch (e: IllegalArgumentException) { |
| 201 | + Log.w(TAG, "Unknown model type '$modelTypeStr', defaulting to LLAMA_3") |
| 202 | + ModelType.LLAMA_3 |
| 203 | + } |
| 204 | + |
| 205 | + return ModelInfo( |
| 206 | + displayName = displayName, |
| 207 | + modelUrl = modelUrl, |
| 208 | + modelFilename = modelFilename, |
| 209 | + tokenizerUrl = tokenizerUrl, |
| 210 | + tokenizerFilename = tokenizerFilename, |
| 211 | + modelType = modelType |
| 212 | + ) |
| 213 | + } |
| 214 | +} |
0 commit comments