v3.38:阅读页更多菜单、作者主页与标签浏览、AI 摘要卡片
This commit is contained in:
@@ -11,7 +11,7 @@ import org.json.JSONObject
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* 润色 / 完善用的 AI 调用。
|
||||
* 润色 / 完善 / 摘要用的 AI 调用。
|
||||
*
|
||||
* 走的是 AIAssist 插件同一家的对话接口(DeepSeek / 智谱),请求体就是标准的
|
||||
* OpenAI 兼容格式:{model, messages[], stream:false}。
|
||||
@@ -30,6 +30,9 @@ object AiApi {
|
||||
/** 单次提交的字数上限:再长模型容易把结尾截掉,不如按住提示用户分段 */
|
||||
const val MAX_INPUT = 12000
|
||||
|
||||
/** 摘要只需要看懂主旨,正文太长反而拖慢并抬高费用,取开头这么多字足够 */
|
||||
private const val BRIEF_INPUT = 4500
|
||||
|
||||
private val JSON = "application/json; charset=utf-8".toMediaType()
|
||||
|
||||
/** AI 生成慢,读超时给足;发布与上传用的是另外的 client */
|
||||
@@ -54,6 +57,20 @@ object AiApi {
|
||||
"必须完整保留 Markdown 语法与图片  的写法、地址和位置,图片一行都不能丢。" +
|
||||
"保留第一人称与作者语气。只输出完整正文,不要任何解释、前言或后缀。"
|
||||
|
||||
/** 阅读页摘要:一段话概括 + 几个标签,一次性生成 */
|
||||
private const val BRIEF_PROMPT =
|
||||
"你是中文内容编辑,为文章写摘要并打标签。要求:\n" +
|
||||
"1. summary:2 到 4 句、80 到 140 个字,客观概括文章讲了什么、核心观点或结论。" +
|
||||
"直接陈述内容,不要用「本文」「这篇文章」开头,不要评价好坏,不要编造原文没有的信息。" +
|
||||
"纯文本,不要 Markdown 标记。\n" +
|
||||
"2. tags:3 到 5 个主题标签,每个 2 到 6 个字,体现文章的领域和主题;" +
|
||||
"不要空泛词(文章、其他、综合、杂谈),不要带 # 号,不要重复。\n" +
|
||||
"只输出一个 JSON 对象,格式:{\"summary\":\"……\",\"tags\":[\"……\",\"……\"]}," +
|
||||
"不要代码块标记,不要任何解释。"
|
||||
|
||||
/** 摘要 + 标签 */
|
||||
data class Brief(val summary: String, val tags: List<String>)
|
||||
|
||||
/**
|
||||
* 执行一次改写。
|
||||
*
|
||||
@@ -62,86 +79,152 @@ object AiApi {
|
||||
* @return 改写后的全文
|
||||
*/
|
||||
suspend fun run(prefs: Prefs, text: String, mode: String): String =
|
||||
withContext(Dispatchers.IO) {
|
||||
val key = prefs.aiKey
|
||||
if (key.isEmpty()) {
|
||||
throw ApiException("还没填 AI Key,先到设置里填一下")
|
||||
}
|
||||
chat(
|
||||
prefs = prefs,
|
||||
system = if (mode == MODE_POLISH) POLISH_PROMPT else EXPAND_PROMPT,
|
||||
user = text,
|
||||
// 校对要稳定,扩写允许一点发挥
|
||||
temperature = if (mode == MODE_POLISH) 0.2 else 0.7,
|
||||
maxTokens = 8192,
|
||||
)
|
||||
|
||||
val provider = prefs.aiProvider
|
||||
val endpoint: String
|
||||
val defaultModel: String
|
||||
when (provider) {
|
||||
PROVIDER_ZHIPU -> {
|
||||
endpoint = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
|
||||
defaultModel = "glm-4-flash"
|
||||
}
|
||||
else -> {
|
||||
endpoint = "https://api.deepseek.com/chat/completions"
|
||||
defaultModel = "deepseek-chat"
|
||||
}
|
||||
}
|
||||
val model = prefs.aiModel.ifEmpty { defaultModel }
|
||||
/**
|
||||
* 生成阅读页的 AI 摘要与标签。
|
||||
*
|
||||
* 调用方负责兜底:没配 Key、超时、模型返回垃圾都不能影响正文阅读,
|
||||
* 所以这里只抛异常,由界面决定「静默不显示」还是提示。
|
||||
*/
|
||||
suspend fun brief(prefs: Prefs, title: String, body: String): Brief {
|
||||
val plain = body
|
||||
// 阅读页会把图片换成 %%IMG%% / %%FLEXP%% token,摘要里不需要地址
|
||||
.replace(Regex("%%(?:IMG|FLEXP)%%[\\s\\S]*?%%/(?:IMG|FLEXP)%%"), " ")
|
||||
.replace(Regex("!\\[[^\\]]*\\]\\([^)]*\\)"), "")
|
||||
.replace(Regex("<[^>]*>"), " ")
|
||||
.replace(Regex("\\s+"), " ")
|
||||
.trim()
|
||||
if (plain.length < 120) throw ApiException("正文太短,不需要摘要")
|
||||
val input = buildString {
|
||||
if (title.isNotBlank()) append("标题:").append(title.trim()).append('\n')
|
||||
append("正文:").append(plain.take(BRIEF_INPUT))
|
||||
}
|
||||
val raw = chat(prefs, BRIEF_PROMPT, input, temperature = 0.3, maxTokens = 800)
|
||||
return parseBrief(raw)
|
||||
}
|
||||
|
||||
val messages = JSONArray().apply {
|
||||
put(JSONObject().apply {
|
||||
put("role", "system")
|
||||
put("content", if (mode == MODE_POLISH) POLISH_PROMPT else EXPAND_PROMPT)
|
||||
})
|
||||
put(JSONObject().apply {
|
||||
put("role", "user")
|
||||
put("content", text)
|
||||
})
|
||||
}
|
||||
|
||||
val payload = JSONObject().apply {
|
||||
put("model", model)
|
||||
put("messages", messages)
|
||||
put("stream", false)
|
||||
// 校对要稳定,扩写允许一点发挥
|
||||
put("temperature", if (mode == MODE_POLISH) 0.2 else 0.7)
|
||||
put("max_tokens", 8192)
|
||||
}
|
||||
|
||||
val request = Request.Builder()
|
||||
.url(endpoint)
|
||||
.header("Authorization", "Bearer $key")
|
||||
.header("Accept", "application/json")
|
||||
.post(payload.toString().toRequestBody(JSON))
|
||||
.build()
|
||||
|
||||
client.newCall(request).execute().use { response ->
|
||||
val body = response.body?.string().orEmpty()
|
||||
if (!response.isSuccessful) {
|
||||
throw ApiException(friendlyMessage(response.code, body), response.code)
|
||||
}
|
||||
|
||||
val json = try {
|
||||
JSONObject(body)
|
||||
} catch (e: Exception) {
|
||||
throw ApiException("AI 返回的不是 JSON,稍后再试")
|
||||
}
|
||||
|
||||
val content = json.optJSONArray("choices")
|
||||
?.optJSONObject(0)
|
||||
?.optJSONObject("message")
|
||||
?.optString("content")
|
||||
.orEmpty()
|
||||
/** 解析模型返回的 JSON:模型偶尔爱套 ```json 围栏或加前言,这里只截第一个 { 到最后一个 } */
|
||||
private fun parseBrief(raw: String): Brief {
|
||||
val start = raw.indexOf('{')
|
||||
val end = raw.lastIndexOf('}')
|
||||
if (start < 0 || end <= start) throw ApiException("AI 没有按要求返回摘要")
|
||||
val json = try {
|
||||
JSONObject(raw.substring(start, end + 1))
|
||||
} catch (e: Exception) {
|
||||
throw ApiException("AI 返回的摘要格式不对,稍后再试")
|
||||
}
|
||||
val summary = json.optString("summary").trim()
|
||||
if (summary.isEmpty()) throw ApiException("AI 没有返回摘要内容")
|
||||
val tags = ArrayList<String>()
|
||||
val array = json.optJSONArray("tags")
|
||||
if (array != null) {
|
||||
for (i in 0 until array.length()) {
|
||||
val tag = array.optString(i)
|
||||
.replace("#", "")
|
||||
.replace(Regex("\\s+"), " ")
|
||||
.trim()
|
||||
|
||||
if (content.isEmpty()) {
|
||||
val finish = json.optJSONArray("choices")
|
||||
?.optJSONObject(0)
|
||||
?.optString("finish_reason")
|
||||
.orEmpty()
|
||||
throw ApiException(
|
||||
if (finish == "length") "内容太长,AI 输出被截断了,试着分段处理"
|
||||
else "AI 没有返回内容,稍后再试"
|
||||
)
|
||||
}
|
||||
content
|
||||
if (tag.isEmpty() || tag.length > 12) continue
|
||||
if (tags.none { it.equals(tag, true) }) tags.add(tag)
|
||||
if (tags.size >= 6) break
|
||||
}
|
||||
}
|
||||
return Brief(summary, tags)
|
||||
}
|
||||
|
||||
/** 统一的 chat/completions 调用:选服务商、拼消息、取 choices[0].message.content */
|
||||
private suspend fun chat(
|
||||
prefs: Prefs,
|
||||
system: String,
|
||||
user: String,
|
||||
temperature: Double,
|
||||
maxTokens: Int,
|
||||
): String = withContext(Dispatchers.IO) {
|
||||
val key = prefs.aiKey
|
||||
if (key.isEmpty()) {
|
||||
throw ApiException("还没填 AI Key,先到设置里填一下")
|
||||
}
|
||||
|
||||
val provider = prefs.aiProvider
|
||||
val endpoint: String
|
||||
val defaultModel: String
|
||||
when (provider) {
|
||||
PROVIDER_ZHIPU -> {
|
||||
endpoint = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
|
||||
defaultModel = "glm-4-flash"
|
||||
}
|
||||
else -> {
|
||||
endpoint = "https://api.deepseek.com/chat/completions"
|
||||
defaultModel = "deepseek-chat"
|
||||
}
|
||||
}
|
||||
val model = prefs.aiModel.ifEmpty { defaultModel }
|
||||
|
||||
val messages = JSONArray().apply {
|
||||
put(JSONObject().apply {
|
||||
put("role", "system")
|
||||
put("content", system)
|
||||
})
|
||||
put(JSONObject().apply {
|
||||
put("role", "user")
|
||||
put("content", user)
|
||||
})
|
||||
}
|
||||
|
||||
val payload = JSONObject().apply {
|
||||
put("model", model)
|
||||
put("messages", messages)
|
||||
put("stream", false)
|
||||
put("temperature", temperature)
|
||||
put("max_tokens", maxTokens)
|
||||
}
|
||||
|
||||
val request = Request.Builder()
|
||||
.url(endpoint)
|
||||
.header("Authorization", "Bearer $key")
|
||||
.header("Accept", "application/json")
|
||||
.post(payload.toString().toRequestBody(JSON))
|
||||
.build()
|
||||
|
||||
client.newCall(request).execute().use { response ->
|
||||
val body = response.body?.string().orEmpty()
|
||||
if (!response.isSuccessful) {
|
||||
throw ApiException(friendlyMessage(response.code, body), response.code)
|
||||
}
|
||||
|
||||
val json = try {
|
||||
JSONObject(body)
|
||||
} catch (e: Exception) {
|
||||
throw ApiException("AI 返回的不是 JSON,稍后再试")
|
||||
}
|
||||
|
||||
val content = json.optJSONArray("choices")
|
||||
?.optJSONObject(0)
|
||||
?.optJSONObject("message")
|
||||
?.optString("content")
|
||||
.orEmpty()
|
||||
.trim()
|
||||
|
||||
if (content.isEmpty()) {
|
||||
val finish = json.optJSONArray("choices")
|
||||
?.optJSONObject(0)
|
||||
?.optString("finish_reason")
|
||||
.orEmpty()
|
||||
throw ApiException(
|
||||
if (finish == "length") "内容太长,AI 输出被截断了,试着分段处理"
|
||||
else "AI 没有返回内容,稍后再试"
|
||||
)
|
||||
}
|
||||
content
|
||||
}
|
||||
}
|
||||
|
||||
private fun friendlyMessage(code: Int, body: String): String {
|
||||
val detail = try {
|
||||
|
||||
401
src/main/java/com/shitoucuo/postpad/ArticleListActivity.kt
Normal file
401
src/main/java/com/shitoucuo/postpad/ArticleListActivity.kt
Normal file
File diff suppressed because it is too large
Load Diff
@@ -59,6 +59,15 @@ data class FeedItem(
|
||||
*/
|
||||
val account: String = "",
|
||||
val accountLabel: String = "",
|
||||
/**
|
||||
* RSS 条目自带的标签与来源站点信息。
|
||||
*
|
||||
* 列表本身不显示它们,但要透传给阅读页:条目标签是 AI 摘要失败时的兜底,
|
||||
* urlId / siteUrl 供「作者主页」按站点过滤并打开网站首页。
|
||||
*/
|
||||
val tags: List<String> = emptyList(),
|
||||
val urlId: Long = 0L,
|
||||
val siteUrl: String = "",
|
||||
)
|
||||
|
||||
class FeedAdapter(
|
||||
|
||||
@@ -900,6 +900,9 @@ class HomeActivity : AppCompatActivity() {
|
||||
link = item.link,
|
||||
read = prefs.isRssRead(item.id.toString()),
|
||||
content = item.excerpt,
|
||||
tags = item.tags,
|
||||
urlId = item.urlId,
|
||||
siteUrl = item.siteUrl,
|
||||
)
|
||||
} to memoHasMore
|
||||
}
|
||||
@@ -1052,7 +1055,8 @@ class HomeActivity : AppCompatActivity() {
|
||||
FeedItem(TAB_RSS, item.id.toString(), item.title,
|
||||
item.siteTitle.ifBlank { item.categoryName },
|
||||
parseDate(item.pubDate), item.excerpt, item.link,
|
||||
prefs.isRssRead(item.id.toString()), item.excerpt)
|
||||
prefs.isRssRead(item.id.toString()), item.excerpt,
|
||||
tags = item.tags, urlId = item.urlId, siteUrl = item.siteUrl)
|
||||
}
|
||||
}
|
||||
TAB_ARTICLE -> {
|
||||
@@ -1136,7 +1140,8 @@ class HomeActivity : AppCompatActivity() {
|
||||
if (markLocalRead(item)) RssApi.adjustUnread(-1)
|
||||
ReaderActivity.open(
|
||||
this, ReaderActivity.KIND_RSS, item.id, item.title,
|
||||
item.source, item.date, item.content, item.link
|
||||
item.source, item.date, item.content, item.link,
|
||||
item.tags, item.urlId, item.siteUrl,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -475,6 +475,62 @@ class Prefs(context: Context) {
|
||||
val aiReady: Boolean
|
||||
get() = aiKey.isNotEmpty()
|
||||
|
||||
// ==================== AI 摘要缓存 ====================
|
||||
|
||||
/**
|
||||
* 阅读页摘要 / 标签的本地缓存。
|
||||
*
|
||||
* 摘要对同一篇文章不会变,没必要每次点进来都花一次调用(还耗用户额度)。
|
||||
* 存在单独一份 SharedPreferences 里:条目上限 [BRIEF_MAX],超出就按写入时间
|
||||
* 淘汰最旧的一条,避免长期使用后文件无限膨胀。
|
||||
*/
|
||||
private val briefSp = appContext.getSharedPreferences("postpad_ai_brief", Context.MODE_PRIVATE)
|
||||
|
||||
private val briefLock = Any()
|
||||
|
||||
/** 读缓存;没有则返回 null(不是空对象,调用方据此决定要不要请求) */
|
||||
fun getBrief(key: String): AiApi.Brief? {
|
||||
if (key.isBlank()) return null
|
||||
val obj = synchronized(briefLock) { briefRoot().optJSONObject(key) } ?: return null
|
||||
val summary = obj.optString("s").trim()
|
||||
if (summary.isEmpty()) return null
|
||||
val tags = ArrayList<String>()
|
||||
obj.optJSONArray("t")?.let { array ->
|
||||
for (i in 0 until array.length()) {
|
||||
val tag = array.optString(i).trim()
|
||||
if (tag.isNotEmpty()) tags.add(tag)
|
||||
}
|
||||
}
|
||||
return AiApi.Brief(summary, tags)
|
||||
}
|
||||
|
||||
/** 写缓存,顺带裁掉超额的旧条目 */
|
||||
fun putBrief(key: String, brief: AiApi.Brief) {
|
||||
if (key.isBlank() || brief.summary.isBlank()) return
|
||||
synchronized(briefLock) {
|
||||
val root = briefRoot()
|
||||
root.put(
|
||||
key,
|
||||
JSONObject().apply {
|
||||
put("s", brief.summary)
|
||||
put("t", JSONArray().also { a -> brief.tags.forEach { a.put(it) } })
|
||||
put("at", System.currentTimeMillis())
|
||||
},
|
||||
)
|
||||
if (root.length() > BRIEF_MAX) {
|
||||
val keys = root.keys().asSequence()
|
||||
.sortedBy { root.optJSONObject(it)?.optLong("at", 0L) ?: 0L }
|
||||
.toList()
|
||||
keys.take(root.length() - BRIEF_MAX).forEach { root.remove(it) }
|
||||
}
|
||||
briefSp.edit().putString(KEY_BRIEF_ITEMS, root.toString()).apply()
|
||||
}
|
||||
}
|
||||
|
||||
private fun briefRoot(): JSONObject = runCatching {
|
||||
JSONObject(briefSp.getString(KEY_BRIEF_ITEMS, "").orEmpty())
|
||||
}.getOrDefault(JSONObject())
|
||||
|
||||
/** RSS 已读状态单独存,避免和主配置混在一起 */
|
||||
private val rssReadSp = appContext.getSharedPreferences("postpad_rss_read", Context.MODE_PRIVATE)
|
||||
|
||||
@@ -569,6 +625,10 @@ class Prefs(context: Context) {
|
||||
private const val KEY_AI_PROVIDER = "ai_provider"
|
||||
private const val KEY_AI_KEY = "ai_key"
|
||||
private const val KEY_AI_MODEL = "ai_model"
|
||||
/** AI 摘要缓存:全部条目存在这一个键下(一个 JSON 对象) */
|
||||
private const val KEY_BRIEF_ITEMS = "brief_items"
|
||||
/** 摘要缓存条数上限:一篇一条,200 篇足够日常回看,也不会让文件太大 */
|
||||
private const val BRIEF_MAX = 200
|
||||
|
||||
private const val KEY_RSS_SITE = "rss_site"
|
||||
private const val KEY_RSS_CODE = "rss_code"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -34,6 +34,9 @@ object RssApi {
|
||||
val categoryName: String,
|
||||
val pubDate: String,
|
||||
val tags: List<String>,
|
||||
/** 订阅站点 id 与站点首页:「作者主页」按它过滤该站文章,并作为「打开网站」的地址 */
|
||||
val urlId: Long = 0L,
|
||||
val siteUrl: String = "",
|
||||
)
|
||||
|
||||
data class Category(val id: Long, val name: String, val feedCount: Int)
|
||||
@@ -112,6 +115,8 @@ object RssApi {
|
||||
categoryName = obj.optString("categoryName"),
|
||||
pubDate = obj.optString("pubDate").ifBlank { obj.optString("srcPubDate") },
|
||||
tags = stringList(obj.opt("tags")),
|
||||
urlId = obj.optLong("urlId", 0L),
|
||||
siteUrl = obj.optString("siteUrl"),
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user