repo_id
stringlengths 6
101
| size
int64 367
5.14M
| file_path
stringlengths 2
269
| content
stringlengths 367
5.14M
|
---|---|---|---|
000haoji/deep-student
| 9,108 |
src-tauri/src/enhanced_anki_service.rs
|
use crate::models::{
DocumentTask, TaskStatus, AnkiCard, AnkiGenerationOptions, AppError, StreamedCardPayload,
StreamEvent, AnkiDocumentGenerationRequest
};
use crate::database::Database;
use crate::llm_manager::LLMManager;
use crate::document_processing_service::DocumentProcessingService;
use crate::streaming_anki_service::StreamingAnkiService;
use std::sync::Arc;
use tauri::{Window, Emitter};
use tokio::task::JoinHandle;
pub struct EnhancedAnkiService {
db: Arc<Database>,
doc_processor: DocumentProcessingService,
streaming_service: StreamingAnkiService,
}
impl EnhancedAnkiService {
pub fn new(db: Arc<Database>, llm_manager: Arc<LLMManager>) -> Self {
let doc_processor = DocumentProcessingService::new(db.clone());
let streaming_service = StreamingAnkiService::new(db.clone(), llm_manager);
Self {
db,
doc_processor,
streaming_service,
}
}
/// 开始文档处理 - 主要入口点
pub async fn start_document_processing(
&self,
request: AnkiDocumentGenerationRequest,
window: Window,
) -> Result<String, AppError> {
let document_content = request.document_content;
let subject_name = request.subject_name;
let options = request.options.unwrap_or_else(|| AnkiGenerationOptions {
deck_name: "默认牌组".to_string(),
note_type: "Basic".to_string(),
enable_images: false,
max_cards_per_mistake: 10,
max_tokens: None,
temperature: None,
max_output_tokens_override: None,
temperature_override: None,
template_id: None,
custom_anki_prompt: None,
template_fields: None,
field_extraction_rules: None,
custom_requirements: None,
segment_overlap_size: 200,
system_prompt: None,
});
// 确定文档名称
let document_name = format!("文档_{}", chrono::Utc::now().format("%Y%m%d_%H%M%S"));
// 创建分段任务
let (document_id, tasks) = self.doc_processor
.process_document_and_create_tasks(
document_content,
document_name,
subject_name,
options,
)
.await?;
// 发送文档处理开始事件
let start_event = StreamEvent {
payload: StreamedCardPayload::DocumentProcessingStarted {
document_id: document_id.clone(),
total_segments: tasks.len() as u32,
},
};
if let Err(e) = window.emit("anki_generation_event", &start_event) {
println!("发送文档处理开始事件失败: {}", e);
}
// 异步处理所有任务
let window_clone = window.clone();
let streaming_service = Arc::new(self.streaming_service.clone());
let document_id_clone = document_id.clone();
tokio::spawn(async move {
Self::process_all_tasks_async(streaming_service, tasks, window_clone, document_id_clone).await;
});
Ok(document_id)
}
/// 异步处理所有任务
async fn process_all_tasks_async(
streaming_service: Arc<StreamingAnkiService>,
tasks: Vec<DocumentTask>,
window: Window,
document_id: String,
) {
let mut task_handles: Vec<JoinHandle<()>> = Vec::new();
// 顺序处理任务以避免API限制
for task in tasks {
let service = streaming_service.clone();
let window_clone = window.clone();
let handle = tokio::spawn(async move {
if let Err(e) = service.process_task_and_generate_cards_stream(task, window_clone).await {
println!("任务处理失败: {}", e);
}
});
task_handles.push(handle);
// 等待当前任务完成再开始下一个,避免并发API调用
if let Some(handle) = task_handles.last_mut() {
let _ = handle.await;
}
}
// 所有任务已在循环内按顺序等待完成,这里不需要再次等待。
// for handle in task_handles {
// let _ = handle.await;
// }
// 发送文档处理完成事件
let complete_event = StreamEvent {
payload: StreamedCardPayload::DocumentProcessingCompleted {
document_id,
},
};
if let Err(e) = window.emit("anki_generation_event", &complete_event) {
println!("发送文档处理完成事件失败: {}", e);
}
}
/// 手动触发单个任务处理
pub async fn trigger_task_processing(
&self,
task_id: String,
window: Window,
) -> Result<(), AppError> {
let task = self.doc_processor.get_task(&task_id)?;
if task.status != TaskStatus::Pending {
return Err(AppError::validation("任务状态不是待处理"));
}
let streaming_service = Arc::new(self.streaming_service.clone());
let window_clone = window.clone();
tokio::spawn(async move {
if let Err(e) = streaming_service.process_task_and_generate_cards_stream(task, window_clone).await {
println!("任务处理失败: {}", e);
}
});
Ok(())
}
/// 获取文档任务列表
pub fn get_document_tasks(&self, document_id: String) -> Result<Vec<DocumentTask>, AppError> {
self.doc_processor.get_document_tasks(&document_id)
}
/// 获取任务的卡片列表
pub fn get_task_cards(&self, task_id: String) -> Result<Vec<AnkiCard>, AppError> {
self.db.get_cards_for_task(&task_id)
.map_err(|e| AppError::database(format!("获取任务卡片失败: {}", e)))
}
/// 更新卡片
pub fn update_anki_card(&self, card: AnkiCard) -> Result<(), AppError> {
self.db.update_anki_card(&card)
.map_err(|e| AppError::database(format!("更新卡片失败: {}", e)))
}
/// 删除卡片
pub fn delete_anki_card(&self, card_id: String) -> Result<(), AppError> {
self.db.delete_anki_card(&card_id)
.map_err(|e| AppError::database(format!("删除卡片失败: {}", e)))
}
/// 删除任务
pub fn delete_document_task(&self, task_id: String) -> Result<(), AppError> {
self.db.delete_document_task(&task_id)
.map_err(|e| AppError::database(format!("删除任务失败: {}", e)))
}
/// 删除文档会话
pub fn delete_document_session(&self, document_id: String) -> Result<(), AppError> {
self.db.delete_document_session(&document_id)
.map_err(|e| AppError::database(format!("删除文档会话失败: {}", e)))
}
/// 导出选定内容为APKG
pub async fn export_apkg_for_selection(
&self,
document_id: Option<String>,
task_ids: Option<Vec<String>>,
card_ids: Option<Vec<String>>,
options: AnkiGenerationOptions,
) -> Result<String, AppError> {
// 根据选择获取卡片
let cards = if let Some(ids) = card_ids {
self.db.get_cards_by_ids(&ids)
.map_err(|e| AppError::database(format!("获取指定卡片失败: {}", e)))?
} else if let Some(task_ids) = task_ids {
let mut all_cards = Vec::new();
for task_id in task_ids {
let mut task_cards = self.db.get_cards_for_task(&task_id)
.map_err(|e| AppError::database(format!("获取任务卡片失败: {}", e)))?;
all_cards.append(&mut task_cards);
}
all_cards
} else if let Some(doc_id) = document_id {
self.db.get_cards_for_document(&doc_id)
.map_err(|e| AppError::database(format!("获取文档卡片失败: {}", e)))?
} else {
return Err(AppError::validation("必须指定要导出的内容"));
};
// 过滤掉错误卡片(除非用户明确要求包含)
let valid_cards: Vec<AnkiCard> = cards.into_iter()
.filter(|card| !card.is_error_card)
.collect();
if valid_cards.is_empty() {
return Err(AppError::validation("没有有效的卡片可以导出"));
}
// 调用现有的APKG导出服务
// 注意:这里需要将enhanced AnkiCard转换为原始AnkiCard格式
let simple_cards: Vec<crate::models::AnkiCard> = valid_cards.into_iter()
.map(|card| crate::models::AnkiCard {
front: card.front,
back: card.back,
text: None, // enhanced_anki_service 中的卡片没有text字段
tags: card.tags,
images: card.images,
id: card.id,
task_id: card.task_id,
is_error_card: card.is_error_card,
error_content: card.error_content,
created_at: card.created_at,
updated_at: card.updated_at,
extra_fields: std::collections::HashMap::new(),
template_id: None,
})
.collect();
// 使用现有的导出服务
let output_path = std::env::temp_dir().join(format!("anki_export_{}.apkg", uuid::Uuid::new_v4()));
crate::apkg_exporter_service::export_cards_to_apkg(
simple_cards,
options.deck_name,
options.note_type,
output_path.clone()
).await
.map_err(|e| AppError::file_system(format!("导出APKG失败: {}", e)))?;
Ok(output_path.to_string_lossy().to_string())
}
}
|
000haoji/deep-student
| 13,878 |
src-tauri/src/lib.rs
|
// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
pub mod models;
pub mod llm_manager;
pub mod analysis_service;
pub mod commands;
pub mod crypto;
pub mod database;
pub mod file_manager;
pub mod batch_operations;
pub mod database_optimizations;
pub mod anki_connect_service;
pub mod apkg_exporter_service;
pub mod document_processing_service;
pub mod streaming_anki_service;
pub mod enhanced_anki_service;
pub mod image_occlusion_service;
pub mod vector_store;
pub mod rag_manager;
pub mod document_parser;
pub mod gemini_adapter;
pub mod cogni_graph;
pub use commands::{
AppState, TempSession,
analyze_new_mistake, analyze_new_mistake_stream, continue_chat, continue_chat_stream, save_mistake_from_analysis,
get_mistakes, get_review_analyses, delete_review_analysis, get_mistake_details, update_mistake, delete_mistake, continue_mistake_chat, continue_mistake_chat_stream, continue_mistake_chat_stream_v2,
analyze_review_session_stream, continue_review_chat, continue_review_chat_stream,
get_statistics, save_setting, get_setting,
test_api_connection, get_supported_subjects,
get_image_as_base64, save_image_from_base64_path, cleanup_orphaned_images, get_image_statistics,
get_api_configurations, save_api_configurations, get_model_assignments, save_model_assignments,
analyze_step_by_step, start_streaming_answer, get_model_adapter_options, save_model_adapter_options, reset_model_adapter_options,
// 科目配置管理
get_all_subject_configs, get_subject_config_by_id, get_subject_config_by_name,
create_subject_config, update_subject_config, delete_subject_config, initialize_default_subject_configs,
// 批量操作
batch_delete_mistakes, batch_update_mistake_statuses, batch_update_mistake_tags,
batch_cleanup_database, batch_export_mistakes, batch_save_mistakes,
// 数据库优化
get_mistakes_optimized, get_tag_statistics_optimized, search_mistakes_fulltext,
get_mistakes_by_date_range, create_performance_indexes, analyze_query_performance,
// 回顾分析功能
start_consolidated_review_analysis, trigger_consolidated_review_stream, continue_consolidated_review_stream,
get_consolidated_review_session, get_review_analysis_by_id,
// ANKI制卡功能
generate_anki_cards_from_document,
generate_anki_cards_from_document_file,
generate_anki_cards_from_document_base64,
// AnkiConnect集成功能
check_anki_connect_status, get_anki_deck_names, get_anki_model_names,
create_anki_deck, add_cards_to_anki_connect,
// APKG导出功能
export_cards_as_apkg, export_cards_as_apkg_with_template,
// 增强ANKI功能
start_enhanced_document_processing, trigger_task_processing,
get_document_tasks, get_task_cards, update_anki_card,
delete_anki_card, delete_document_task, delete_document_session,
export_apkg_for_selection, get_document_cards,
// RAG知识库管理功能
rag_add_documents, rag_add_documents_from_content, rag_get_knowledge_base_status, rag_delete_document,
rag_query_knowledge_base, rag_get_all_documents, rag_clear_knowledge_base,
// RAG增强的AI分析功能
start_rag_enhanced_streaming_answer, continue_rag_enhanced_chat_stream,
// 独立RAG查询功能
llm_generate_answer_with_context,
// RAG配置管理功能
get_rag_settings, update_rag_settings, reset_rag_settings,
// RAG分库管理功能
create_rag_sub_library, get_rag_sub_libraries, get_rag_sub_library_by_id,
update_rag_sub_library, delete_rag_sub_library, rag_add_documents_to_library,
rag_add_documents_from_content_to_library, get_rag_documents_by_library,
move_document_to_rag_library, rag_query_knowledge_base_in_libraries,
// 文档解析功能
parse_document_from_path, parse_document_from_base64,
// 错题总结生成功能
generate_mistake_summary,
// 自定义模板管理功能
get_all_custom_templates, get_custom_template_by_id, create_custom_template,
update_custom_template, delete_custom_template, export_template, import_template,
// 图片遮罩卡功能
extract_image_text_coordinates, create_image_occlusion_card, get_all_image_occlusion_cards,
get_image_occlusion_card, update_image_occlusion_card, delete_image_occlusion_card,
// 默认模板管理功能
set_default_template, get_default_template_id,
// 测试日志相关功能
save_test_log, get_test_logs, open_log_file, open_logs_folder
};
// CogniGraph模块导入
pub use cogni_graph::handlers::{
initialize_knowledge_graph, create_problem_card, get_problem_card, search_knowledge_graph,
get_ai_recommendations, search_similar_cards, get_cards_by_tag, get_all_tags,
get_graph_config, update_graph_config, test_neo4j_connection, process_handwritten_input,
// Tag管理功能
create_tag, get_tag_hierarchy, get_tags_by_type, initialize_default_tag_hierarchy
};
use analysis_service::AnalysisService;
use database::Database;
use file_manager::FileManager;
use llm_manager::LLMManager;
use cogni_graph::handlers::GraphState;
use std::sync::Arc;
use std::collections::HashMap;
use tauri::Manager;
use tokio::sync::RwLock;
#[tauri::command]
fn greet(name: &str) -> String {
format!("Hello, {}! You've been greeted from Rust!", name)
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.setup(|app| {
// 获取系统级应用数据目录
let app_handle = app.handle().clone();
let app_data_dir = app_handle.path()
.app_data_dir()
.expect("无法获取应用数据目录")
.join("ai-mistake-manager");
// 确保目录存在
std::fs::create_dir_all(&app_data_dir).expect("无法创建应用数据目录");
// 初始化文件管理器
let file_manager = Arc::new(
FileManager::new(app_data_dir.clone())
.expect("Failed to initialize file manager")
);
// 初始化数据库
let database_path = file_manager.get_database_path();
let database = Arc::new(
Database::new(&database_path)
.expect("Failed to initialize database")
);
// 初始化默认科目配置
if let Err(e) = database.initialize_default_subject_configs() {
println!("警告:初始化默认科目配置失败: {}", e);
}
// 初始化LLM管理器
let llm_manager = Arc::new(LLMManager::new(database.clone(), file_manager.clone()));
// 初始化分析服务
let analysis_service = Arc::new(AnalysisService::new(database.clone(), file_manager.clone()));
// 初始化临时会话存储
let temp_sessions: Arc<tokio::sync::Mutex<HashMap<String, TempSession>>> =
Arc::new(tokio::sync::Mutex::new(HashMap::new()));
// 初始化回顾分析会话存储
let review_sessions: Arc<tokio::sync::Mutex<HashMap<String, models::ConsolidatedReviewSession>>> =
Arc::new(tokio::sync::Mutex::new(HashMap::new()));
// 初始化RAG管理器
let rag_manager = Arc::new(
rag_manager::RagManager::new(database.clone(), llm_manager.clone(), file_manager.clone())
.expect("Failed to initialize RAG manager")
);
// 初始化图片遮罩服务
let image_occlusion_service = Arc::new(
image_occlusion_service::ImageOcclusionService::new(database.clone(), llm_manager.clone())
);
// 初始化CogniGraph状态
let graph_state = Arc::new(RwLock::new(GraphState::new()));
let app_state = AppState {
analysis_service,
database,
file_manager,
temp_sessions,
llm_manager: llm_manager.clone(),
review_sessions,
rag_manager,
image_occlusion_service,
};
// 将状态注册到Tauri应用
app.manage(app_state);
app.manage(graph_state);
app.manage(llm_manager);
Ok(())
})
.invoke_handler(tauri::generate_handler![
greet,
// 错题分析相关
analyze_new_mistake,
analyze_new_mistake_stream,
continue_chat,
continue_chat_stream,
save_mistake_from_analysis,
// 分步骤分析
analyze_step_by_step,
start_streaming_answer,
// 错题库管理
get_mistakes,
get_review_analyses,
delete_review_analysis,
get_mistake_details,
update_mistake,
delete_mistake,
continue_mistake_chat,
continue_mistake_chat_stream,
continue_mistake_chat_stream_v2,
// 回顾分析
analyze_review_session_stream,
continue_review_chat,
continue_review_chat_stream,
// 统计和设置
get_statistics,
save_setting,
get_setting,
test_api_connection,
get_supported_subjects,
// 专用配置管理
get_api_configurations,
save_api_configurations,
get_model_assignments,
save_model_assignments,
get_model_adapter_options,
save_model_adapter_options,
reset_model_adapter_options,
// 文件管理
get_image_as_base64,
save_image_from_base64_path,
cleanup_orphaned_images,
get_image_statistics,
// 科目配置管理
get_all_subject_configs,
get_subject_config_by_id,
get_subject_config_by_name,
create_subject_config,
update_subject_config,
delete_subject_config,
initialize_default_subject_configs,
// 批量操作
batch_delete_mistakes,
batch_update_mistake_statuses,
batch_update_mistake_tags,
batch_cleanup_database,
batch_export_mistakes,
batch_save_mistakes,
// 数据库优化
get_mistakes_optimized,
get_tag_statistics_optimized,
search_mistakes_fulltext,
get_mistakes_by_date_range,
create_performance_indexes,
analyze_query_performance,
// 回顾分析功能
start_consolidated_review_analysis,
trigger_consolidated_review_stream,
continue_consolidated_review_stream,
get_consolidated_review_session,
get_review_analysis_by_id,
// ANKI制卡功能
generate_anki_cards_from_document,
generate_anki_cards_from_document_file,
generate_anki_cards_from_document_base64,
// AnkiConnect集成功能
check_anki_connect_status,
get_anki_deck_names,
get_anki_model_names,
create_anki_deck,
add_cards_to_anki_connect,
// APKG导出功能
export_cards_as_apkg,
export_cards_as_apkg_with_template,
// 增强ANKI功能
start_enhanced_document_processing,
trigger_task_processing,
get_document_tasks,
get_task_cards,
update_anki_card,
delete_anki_card,
delete_document_task,
delete_document_session,
export_apkg_for_selection,
get_document_cards,
// RAG知识库管理功能
rag_add_documents,
rag_add_documents_from_content,
rag_get_knowledge_base_status,
rag_delete_document,
rag_query_knowledge_base,
rag_get_all_documents,
rag_clear_knowledge_base,
// RAG增强的AI分析功能
start_rag_enhanced_streaming_answer,
continue_rag_enhanced_chat_stream,
// 独立RAG查询功能
llm_generate_answer_with_context,
// RAG配置管理功能
get_rag_settings,
update_rag_settings,
reset_rag_settings,
// RAG分库管理功能
create_rag_sub_library,
get_rag_sub_libraries,
get_rag_sub_library_by_id,
update_rag_sub_library,
delete_rag_sub_library,
rag_add_documents_to_library,
rag_add_documents_from_content_to_library,
get_rag_documents_by_library,
move_document_to_rag_library,
rag_query_knowledge_base_in_libraries,
// 文档解析功能
parse_document_from_path,
parse_document_from_base64,
// 错题总结生成
generate_mistake_summary,
// 自定义模板管理功能
get_all_custom_templates,
get_custom_template_by_id,
create_custom_template,
update_custom_template,
delete_custom_template,
export_template,
import_template,
// 图片遮罩卡功能
extract_image_text_coordinates,
create_image_occlusion_card,
get_all_image_occlusion_cards,
get_image_occlusion_card,
update_image_occlusion_card,
delete_image_occlusion_card,
// 默认模板管理功能
set_default_template,
get_default_template_id,
// 测试日志相关功能
save_test_log,
get_test_logs,
open_log_file,
open_logs_folder,
// CogniGraph知识图谱功能
initialize_knowledge_graph,
create_problem_card,
get_problem_card,
search_knowledge_graph,
get_ai_recommendations,
search_similar_cards,
get_cards_by_tag,
get_all_tags,
get_graph_config,
update_graph_config,
test_neo4j_connection,
process_handwritten_input,
// Tag管理功能
create_tag,
get_tag_hierarchy,
get_tags_by_type,
initialize_default_tag_hierarchy
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
|
000haoji/deep-student
| 55,374 |
src-tauri/src/rag_manager.rs
|
use crate::models::{
DocumentChunk, DocumentChunkWithEmbedding, RetrievedChunk, RagQueryOptions,
KnowledgeBaseStatusPayload, DocumentProcessingStatus, DocumentProcessingStage,
RagQueryResponse, AppError
};
use crate::vector_store::{SqliteVectorStore, VectorStore};
use crate::llm_manager::LLMManager;
use crate::database::Database;
use crate::file_manager::FileManager;
use std::sync::Arc;
use std::collections::HashMap;
use uuid::Uuid;
use tauri::{Window, Emitter};
use serde_json::Value;
use base64::{Engine as _, engine::general_purpose};
use regex::Regex;
type Result<T> = std::result::Result<T, AppError>;
/// 文档分块策略
#[derive(Debug, Clone, PartialEq)]
pub enum ChunkingStrategy {
FixedSize,
Semantic,
}
/// 分块配置
#[derive(Debug, Clone)]
pub struct ChunkingConfig {
pub strategy: ChunkingStrategy,
pub chunk_size: usize,
pub chunk_overlap: usize,
pub min_chunk_size: usize,
}
impl Default for ChunkingConfig {
fn default() -> Self {
Self {
strategy: ChunkingStrategy::FixedSize,
chunk_size: 512,
chunk_overlap: 50,
min_chunk_size: 20,
}
}
}
/// RAG管理器 - 协调整个RAG流程
pub struct RagManager {
vector_store: SqliteVectorStore,
llm_manager: Arc<LLMManager>,
file_manager: Arc<FileManager>,
database: Arc<Database>,
}
impl RagManager {
/// 创建新的RAG管理器实例
pub fn new(
database: Arc<Database>,
llm_manager: Arc<LLMManager>,
file_manager: Arc<FileManager>
) -> Result<Self> {
let vector_store = SqliteVectorStore::new(database.clone())?;
Ok(Self {
vector_store,
llm_manager,
file_manager,
database,
})
}
/// 添加文档到知识库
pub async fn add_documents_to_knowledge_base(
&self,
file_paths: Vec<String>,
window: Window
) -> Result<String> {
self.add_documents_to_knowledge_base_with_library(file_paths, window, None).await
}
/// 添加文档到指定分库
pub async fn add_documents_to_knowledge_base_with_library(
&self,
file_paths: Vec<String>,
window: Window,
sub_library_id: Option<String>
) -> Result<String> {
println!("🚀 开始处理 {} 个文档到知识库", file_paths.len());
let mut processed_documents = Vec::new();
let mut total_chunks = 0;
for (index, file_path) in file_paths.iter().enumerate() {
let progress = (index as f32) / (file_paths.len() as f32);
// 发送处理状态更新
self.emit_processing_status(&window, "overall", "processing", progress,
&format!("正在处理文档 {}/{}", index + 1, file_paths.len())).await;
match self.process_single_document_with_library(file_path, &window, sub_library_id.as_deref()).await {
Ok(chunk_count) => {
total_chunks += chunk_count;
processed_documents.push(file_path.clone());
println!("✅ 文档处理完成: {} ({} 个块)", file_path, chunk_count);
}
Err(e) => {
println!("❌ 文档处理失败: {} - {}", file_path, e);
self.emit_processing_status(&window, "overall", "error", progress,
&format!("文档处理失败: {}", e)).await;
}
}
}
// 发送完成状态
self.emit_processing_status(&window, "overall", "completed", 1.0,
&format!("处理完成:{} 个文档,{} 个文本块", processed_documents.len(), total_chunks)).await;
Ok(format!("成功处理 {} 个文档,共 {} 个文本块", processed_documents.len(), total_chunks))
}
/// 处理单个文档
async fn process_single_document(&self, file_path: &str, window: &Window) -> Result<usize> {
self.process_single_document_with_library(file_path, window, None).await
}
/// 处理单个文档到指定分库
async fn process_single_document_with_library(&self, file_path: &str, window: &Window, sub_library_id: Option<&str>) -> Result<usize> {
let document_id = Uuid::new_v4().to_string();
let file_name = std::path::Path::new(file_path)
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("unknown")
.to_string();
println!("📄 开始处理文档: {} (ID: {})", file_name, document_id);
// 1. 读取文件内容
self.emit_document_status(window, &document_id, &file_name, DocumentProcessingStage::Reading, 0.1).await;
let content = self.read_file_content(file_path).await?;
// 2. 预处理
self.emit_document_status(window, &document_id, &file_name, DocumentProcessingStage::Preprocessing, 0.2).await;
let processed_content = self.preprocess_content(&content);
// 3. 文本分块
self.emit_document_status(window, &document_id, &file_name, DocumentProcessingStage::Chunking, 0.3).await;
let chunks = self.chunk_text_with_progress(&document_id, &processed_content, &file_name, Some(window), &document_id, &file_name).await?;
// 4. 生成向量嵌入
let chunks_with_embeddings = self.generate_embeddings_for_chunks_with_progress(chunks, Some(window), &document_id, &file_name).await?;
// 5. 存储到向量数据库
self.emit_document_status(window, &document_id, &file_name, DocumentProcessingStage::Storing, 0.8).await;
self.vector_store.add_chunks(chunks_with_embeddings.clone()).await?;
// 6. 更新文档记录
let target_library_id = sub_library_id.unwrap_or("default");
self.vector_store.add_document_record_with_library(&document_id, &file_name, Some(file_path), None, target_library_id)?;
self.vector_store.update_document_chunk_count(&document_id, chunks_with_embeddings.len())?;
// 7. 完成
self.emit_document_status(window, &document_id, &file_name, DocumentProcessingStage::Completed, 1.0).await;
Ok(chunks_with_embeddings.len())
}
/// 从文件内容添加文档到知识库
pub async fn add_documents_from_content(
&self,
documents: Vec<serde_json::Value>,
window: Window
) -> Result<String> {
println!("🚀 开始从内容处理 {} 个文档到知识库", documents.len());
let mut processed_documents = Vec::new();
let mut total_chunks = 0;
for (index, doc_data) in documents.iter().enumerate() {
let progress = (index as f32) / (documents.len() as f32);
// 解析文档数据
let file_name = doc_data.get("fileName")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
let content = doc_data.get("content")
.and_then(|v| v.as_str())
.unwrap_or("");
if content.is_empty() {
println!("⚠️ 跳过空内容文档: {}", file_name);
continue;
}
// 发送处理状态更新
self.emit_processing_status(&window, "overall", "processing", progress,
&format!("正在处理文档 {}/{}", index + 1, documents.len())).await;
match self.process_document_content(&file_name, content, &window).await {
Ok(chunk_count) => {
total_chunks += chunk_count;
processed_documents.push(file_name.clone());
println!("✅ 文档内容处理完成: {} ({} 个块)", file_name, chunk_count);
}
Err(e) => {
println!("❌ 文档内容处理失败: {} - {}", file_name, e);
self.emit_processing_status(&window, "overall", "error", progress,
&format!("文档处理失败: {}", e)).await;
}
}
}
// 发送完成状态
self.emit_processing_status(&window, "overall", "completed", 1.0,
&format!("处理完成:{} 个文档,{} 个文本块", processed_documents.len(), total_chunks)).await;
Ok(format!("成功处理 {} 个文档,共 {} 个文本块", processed_documents.len(), total_chunks))
}
/// 从文件内容添加文档到指定分库
pub async fn add_documents_from_content_to_library(
&self,
documents: Vec<serde_json::Value>,
window: Window,
sub_library_id: Option<String>
) -> Result<String> {
println!("🚀 开始从内容处理 {} 个文档到分库: {:?}", documents.len(), sub_library_id);
let mut processed_documents = Vec::new();
let mut total_chunks = 0;
for (index, doc_data) in documents.iter().enumerate() {
let progress = (index as f32) / (documents.len() as f32);
// 解析文档数据
let file_name = doc_data.get("fileName")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
let content = doc_data.get("content")
.and_then(|v| v.as_str())
.unwrap_or("");
if content.is_empty() {
println!("⚠️ 跳过空内容文档: {}", file_name);
continue;
}
// 发送处理状态更新
self.emit_processing_status(&window, "overall", "processing", progress,
&format!("正在处理文档 {}/{}", index + 1, documents.len())).await;
match self.process_document_content_with_library(&file_name, content, &window, sub_library_id.as_deref()).await {
Ok(chunk_count) => {
total_chunks += chunk_count;
processed_documents.push(file_name.clone());
println!("✅ 文档内容处理完成: {} ({} 个块)", file_name, chunk_count);
}
Err(e) => {
println!("❌ 文档内容处理失败: {} - {}", file_name, e);
self.emit_processing_status(&window, "overall", "error", progress,
&format!("文档处理失败: {}", e)).await;
}
}
}
// 发送完成状态
self.emit_processing_status(&window, "overall", "completed", 1.0,
&format!("处理完成:{} 个文档,{} 个文本块", processed_documents.len(), total_chunks)).await;
Ok(format!("成功处理 {} 个文档,共 {} 个文本块", processed_documents.len(), total_chunks))
}
/// 处理文档内容(不从文件路径读取,直接使用提供的内容)
async fn process_document_content(&self, file_name: &str, content: &str, window: &Window) -> Result<usize> {
let document_id = Uuid::new_v4().to_string();
println!("📄 开始处理文档内容: {} (ID: {})", file_name, document_id);
// 发送文档开始处理状态
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Reading, 0.1).await;
// 根据文件扩展名判断是否需要解码base64
let processed_content = if file_name.ends_with(".txt") || file_name.ends_with(".md") {
// 文本文件,直接使用内容
println!("📝 处理文本文件: {}", file_name);
content.to_string()
} else {
// 二进制文件,假设是base64编码,需要解码后处理
println!("🔄 开始解码Base64内容: {} 字节", content.len());
match general_purpose::STANDARD.decode(content) {
Ok(decoded_bytes) => {
println!("✅ Base64解码成功,解码后大小: {} 字节", decoded_bytes.len());
// 根据文件扩展名处理二进制文件
if file_name.ends_with(".pdf") {
println!("📄 开始解析PDF文件: {}", file_name);
self.extract_pdf_text_from_memory(&decoded_bytes).await?
} else if file_name.ends_with(".docx") {
println!("📄 开始解析DOCX文件: {}", file_name);
self.extract_docx_text_from_memory(&decoded_bytes).await?
} else {
return Err(AppError::validation(format!(
"不支持的文件格式: {}",
file_name
)));
}
}
Err(_) => {
// 不是有效的base64,当作普通文本处理
println!("⚠️ Base64解码失败,当作普通文本处理: {}", file_name);
content.to_string()
}
}
};
println!("📊 文档解析完成,提取文本长度: {} 字符", processed_content.len());
// 预处理内容
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Preprocessing, 0.2).await;
println!("🔧 开始预处理文档内容: {}", file_name);
let preprocessed_content = self.preprocess_content(&processed_content);
println!("✅ 预处理完成,处理后长度: {} 字符", preprocessed_content.len());
// 分块
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Chunking, 0.3).await;
println!("✂️ 开始文本分块: {}", file_name);
let chunks = self.chunk_text_with_progress(&document_id, &preprocessed_content, file_name, Some(window), &document_id, file_name).await?;
println!("✅ 分块完成,生成 {} 个文本块", chunks.len());
if chunks.is_empty() {
return Err(AppError::validation("文档内容为空或无法分块"));
}
// 生成嵌入
println!("🧠 开始生成向量嵌入: {} 个文本块", chunks.len());
let chunks_with_embeddings = self.generate_embeddings_for_chunks_with_progress(chunks, Some(window), &document_id, file_name).await?;
println!("✅ 向量嵌入生成完成: {} 个向量", chunks_with_embeddings.len());
// 记录文档信息
let file_size = processed_content.len() as u64;
self.vector_store.add_document_record(&document_id, file_name, None, Some(file_size))?;
// 存储到向量数据库
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Storing, 0.8).await;
self.vector_store.add_chunks(chunks_with_embeddings.clone()).await?;
// 更新文档块数统计
self.vector_store.update_document_chunk_count(&document_id, chunks_with_embeddings.len())?;
// 发送完成状态
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Completed, 1.0).await;
println!("🎉 文档处理完全完成: {} ({} 个文本块)", file_name, chunks_with_embeddings.len());
Ok(chunks_with_embeddings.len())
}
/// 处理文档内容到指定分库(不从文件路径读取,直接使用提供的内容)
async fn process_document_content_with_library(&self, file_name: &str, content: &str, window: &Window, sub_library_id: Option<&str>) -> Result<usize> {
let document_id = Uuid::new_v4().to_string();
println!("📄 开始处理文档内容到分库: {} (ID: {}, 分库: {:?})", file_name, document_id, sub_library_id);
println!("📊 文档原始大小: {} 字节", content.len());
// 发送文档开始处理状态
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Reading, 0.1).await;
// 根据文件扩展名判断是否需要解码base64
println!("🔍 开始解析文档内容: {}", file_name);
let processed_content = if file_name.ends_with(".txt") || file_name.ends_with(".md") {
// 文本文件,直接使用内容
println!("📝 处理文本文件: {}", file_name);
content.to_string()
} else {
// 二进制文件,假设是base64编码,需要解码后处理
println!("🔄 开始解码Base64内容: {} 字节", content.len());
match general_purpose::STANDARD.decode(content) {
Ok(decoded_bytes) => {
println!("✅ Base64解码成功,解码后大小: {} 字节", decoded_bytes.len());
// 根据文件扩展名处理二进制文件
if file_name.ends_with(".pdf") {
println!("📄 开始解析PDF文件: {}", file_name);
self.extract_pdf_text_from_memory(&decoded_bytes).await?
} else if file_name.ends_with(".docx") {
println!("📄 开始解析DOCX文件: {}", file_name);
self.extract_docx_text_from_memory(&decoded_bytes).await?
} else {
return Err(AppError::validation(format!(
"不支持的文件格式: {}",
file_name
)));
}
}
Err(_) => {
// 不是有效的base64,当作普通文本处理
println!("⚠️ Base64解码失败,当作普通文本处理: {}", file_name);
content.to_string()
}
}
};
println!("📊 文档解析完成,提取文本长度: {} 字符", processed_content.len());
// 预处理内容
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Preprocessing, 0.2).await;
println!("🔧 开始预处理文档内容: {}", file_name);
let preprocessed_content = self.preprocess_content(&processed_content);
println!("✅ 预处理完成,处理后长度: {} 字符", preprocessed_content.len());
// 分块
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Chunking, 0.3).await;
println!("✂️ 开始文本分块: {}", file_name);
let chunks = self.chunk_text_with_progress(&document_id, &preprocessed_content, file_name, Some(window), &document_id, file_name).await?;
println!("✅ 分块完成,生成 {} 个文本块", chunks.len());
if chunks.is_empty() {
return Err(AppError::validation("文档内容为空或无法分块"));
}
// 生成嵌入
println!("🧠 开始生成向量嵌入: {} 个文本块", chunks.len());
let chunks_with_embeddings = self.generate_embeddings_for_chunks_with_progress(chunks, Some(window), &document_id, file_name).await?;
println!("✅ 向量嵌入生成完成: {} 个向量", chunks_with_embeddings.len());
// 记录文档信息到指定分库
let file_size = processed_content.len() as u64;
let target_library_id = sub_library_id.unwrap_or("default");
println!("📋 添加文档记录到分库: {} -> {}", file_name, target_library_id);
self.vector_store.add_document_record_with_library(&document_id, file_name, None, Some(file_size), target_library_id)?;
// 存储到向量数据库
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Storing, 0.8).await;
println!("💾 开始存储到向量数据库: {} 个向量", chunks_with_embeddings.len());
self.vector_store.add_chunks(chunks_with_embeddings.clone()).await?;
println!("✅ 向量存储完成");
// 更新文档块数统计
println!("📊 更新文档统计信息");
self.vector_store.update_document_chunk_count(&document_id, chunks_with_embeddings.len())?;
// 发送完成状态
self.emit_document_status(window, &document_id, file_name, DocumentProcessingStage::Completed, 1.0).await;
println!("🎉 文档处理完全完成: {} ({} 个文本块)", file_name, chunks_with_embeddings.len());
Ok(chunks_with_embeddings.len())
}
/// 读取文件内容
async fn read_file_content(&self, file_path: &str) -> Result<String> {
let path = std::path::Path::new(file_path);
// 检查文件是否存在
if !path.exists() {
return Err(AppError::file_system(format!("读取文档文件失败: 系统找不到指定的文件。文件路径: {}", file_path)));
}
// 检查是否为文件(而非目录)
if !path.is_file() {
return Err(AppError::file_system(format!("读取文档文件失败: 指定路径不是文件。文件路径: {}", file_path)));
}
let extension = path.extension()
.and_then(|ext| ext.to_str())
.unwrap_or("")
.to_lowercase();
println!("📖 正在读取文件: {} (类型: {})", file_path, extension);
match extension.as_str() {
"txt" | "md" | "markdown" => {
std::fs::read_to_string(file_path)
.map_err(|e| AppError::file_system(format!("读取文本文件失败: {} (文件路径: {})", e, file_path)))
}
"pdf" => {
self.extract_pdf_text(file_path).await
}
"docx" => {
self.extract_docx_text(file_path).await
}
_ => {
Err(AppError::validation(format!("不支持的文件类型: {} (文件路径: {})", extension, file_path)))
}
}
}
/// 预处理文本内容
fn preprocess_content(&self, content: &str) -> String {
// 基础文本清理
content
.lines()
.map(|line| line.trim())
.filter(|line| !line.is_empty())
.collect::<Vec<_>>()
.join("\n")
}
/// 从数据库加载分块配置
fn load_chunking_config(&self) -> Result<ChunkingConfig> {
match self.database.get_rag_configuration() {
Ok(Some(config)) => {
let strategy = match config.chunking_strategy.as_str() {
"semantic" => ChunkingStrategy::Semantic,
_ => ChunkingStrategy::FixedSize,
};
Ok(ChunkingConfig {
strategy,
chunk_size: config.chunk_size as usize,
chunk_overlap: config.chunk_overlap as usize,
min_chunk_size: config.min_chunk_size as usize,
})
}
Ok(None) => {
// 没有配置时使用默认值
Ok(ChunkingConfig::default())
}
Err(e) => {
println!("⚠️ 无法加载RAG配置,使用默认值: {}", e);
Ok(ChunkingConfig::default())
}
}
}
/// 将文本分块 - 支持不同策略
fn chunk_text(&self, document_id: &str, content: &str, file_name: &str) -> Result<Vec<DocumentChunk>> {
// 从数据库加载分块配置
let config = self.load_chunking_config()?;
match config.strategy {
ChunkingStrategy::FixedSize => {
self.chunk_text_fixed_size(document_id, content, file_name, &config)
}
ChunkingStrategy::Semantic => {
self.chunk_text_semantic(document_id, content, file_name, &config)
}
}
}
/// 将文本分块并发送进度更新
async fn chunk_text_with_progress(&self, document_id: &str, content: &str, file_name: &str, window: Option<&Window>, doc_id: &str, doc_name: &str) -> Result<Vec<DocumentChunk>> {
// 从数据库加载分块配置
let config = self.load_chunking_config()?;
match config.strategy {
ChunkingStrategy::FixedSize => {
self.chunk_text_fixed_size_with_progress(document_id, content, file_name, &config, window, doc_id, doc_name).await
}
ChunkingStrategy::Semantic => {
self.chunk_text_semantic_with_progress(document_id, content, file_name, &config, window, doc_id, doc_name).await
}
}
}
/// 固定大小分块策略
fn chunk_text_fixed_size(&self, document_id: &str, content: &str, file_name: &str, config: &ChunkingConfig) -> Result<Vec<DocumentChunk>> {
let mut chunks = Vec::new();
let chars: Vec<char> = content.chars().collect();
let mut start = 0;
let mut chunk_index = 0;
while start < chars.len() {
let end = std::cmp::min(start + config.chunk_size, chars.len());
let chunk_text: String = chars[start..end].iter().collect();
// 跳过过短的块
if chunk_text.trim().len() < config.min_chunk_size {
start = end;
continue;
}
let mut metadata = HashMap::new();
metadata.insert("file_name".to_string(), file_name.to_string());
metadata.insert("chunk_index".to_string(), chunk_index.to_string());
metadata.insert("start_pos".to_string(), start.to_string());
metadata.insert("end_pos".to_string(), end.to_string());
metadata.insert("chunking_strategy".to_string(), "fixed_size".to_string());
let chunk = DocumentChunk {
id: Uuid::new_v4().to_string(),
document_id: document_id.to_string(),
chunk_index,
text: chunk_text.trim().to_string(),
metadata,
};
chunks.push(chunk);
chunk_index += 1;
// 计算下一个起始位置,考虑重叠
start = if end == chars.len() {
end
} else {
std::cmp::max(start + 1, end - config.chunk_overlap)
};
}
println!("📝 固定大小分块完成: {} 个块", chunks.len());
Ok(chunks)
}
/// 固定大小分块策略(带进度更新)
async fn chunk_text_fixed_size_with_progress(&self, document_id: &str, content: &str, file_name: &str, config: &ChunkingConfig, window: Option<&Window>, doc_id: &str, doc_name: &str) -> Result<Vec<DocumentChunk>> {
let mut chunks = Vec::new();
let chars: Vec<char> = content.chars().collect();
let mut start = 0;
let mut chunk_index = 0;
// 估算总的分块数量(用于进度计算)
let estimated_total_chunks = (chars.len() / config.chunk_size) + 1;
while start < chars.len() {
let end = std::cmp::min(start + config.chunk_size, chars.len());
let chunk_text: String = chars[start..end].iter().collect();
// 跳过过短的块
if chunk_text.trim().len() < config.min_chunk_size {
start = end;
continue;
}
let mut metadata = HashMap::new();
metadata.insert("file_name".to_string(), file_name.to_string());
metadata.insert("chunk_index".to_string(), chunk_index.to_string());
metadata.insert("start_pos".to_string(), start.to_string());
metadata.insert("end_pos".to_string(), end.to_string());
metadata.insert("chunking_strategy".to_string(), "fixed_size".to_string());
let chunk = DocumentChunk {
id: Uuid::new_v4().to_string(),
document_id: document_id.to_string(),
chunk_index,
text: chunk_text.trim().to_string(),
metadata,
};
chunks.push(chunk);
chunk_index += 1;
// 发送进度更新
if let Some(w) = window {
let progress = 0.3 + (chunk_index as f32 / estimated_total_chunks as f32) * 0.15; // 从30%到45%
self.emit_document_status_with_chunks(w, doc_id, doc_name, DocumentProcessingStage::Chunking, progress, chunk_index, estimated_total_chunks).await;
}
// 计算下一个起始位置,考虑重叠
start = if end == chars.len() {
end
} else {
std::cmp::max(start + 1, end - config.chunk_overlap)
};
}
// 发送分块完成状态
if let Some(w) = window {
self.emit_document_status_with_chunks(w, doc_id, doc_name, DocumentProcessingStage::Chunking, 0.45, chunks.len(), chunks.len()).await;
}
println!("📝 固定大小分块完成: {} 个块", chunks.len());
Ok(chunks)
}
/// 语义分块策略
fn chunk_text_semantic(&self, document_id: &str, content: &str, file_name: &str, config: &ChunkingConfig) -> Result<Vec<DocumentChunk>> {
let mut chunks = Vec::new();
let mut chunk_index = 0;
// 1. 首先按段落分割
let paragraphs = self.split_into_paragraphs(content);
let mut current_chunk = String::new();
let mut current_sentences = Vec::new();
let mut paragraph_index = 0;
for paragraph in paragraphs {
if paragraph.trim().is_empty() {
continue;
}
// 2. 将段落按句子分割
let sentences = self.split_into_sentences(¶graph);
for sentence in sentences {
let sentence = sentence.trim();
if sentence.is_empty() {
continue;
}
// 检查当前块加上新句子是否超过目标大小
let potential_chunk = if current_chunk.is_empty() {
sentence.to_string()
} else {
format!("{} {}", current_chunk, sentence)
};
if potential_chunk.len() <= config.chunk_size {
// 可以添加到当前块
current_chunk = potential_chunk;
current_sentences.push(sentence.to_string());
} else {
// 当前块已满,保存当前块并开始新块
if !current_chunk.is_empty() && current_chunk.len() >= config.min_chunk_size {
let chunk = self.create_semantic_chunk(
document_id,
¤t_chunk,
file_name,
chunk_index,
paragraph_index,
¤t_sentences,
);
chunks.push(chunk);
chunk_index += 1;
// 实现重叠:保留最后1-2个句子作为新块的开始
let overlap_sentences = if current_sentences.len() > 2 {
current_sentences[current_sentences.len()-2..].to_vec()
} else if current_sentences.len() > 1 {
current_sentences[current_sentences.len()-1..].to_vec()
} else {
Vec::new()
};
current_chunk = if overlap_sentences.is_empty() {
sentence.to_string()
} else {
format!("{} {}", overlap_sentences.join(" "), sentence)
};
current_sentences = overlap_sentences;
current_sentences.push(sentence.to_string());
} else {
// 如果当前句子本身就很长,直接作为一个块
if sentence.len() >= config.min_chunk_size {
let chunk = self.create_semantic_chunk(
document_id,
sentence,
file_name,
chunk_index,
paragraph_index,
&vec![sentence.to_string()],
);
chunks.push(chunk);
chunk_index += 1;
}
current_chunk.clear();
current_sentences.clear();
}
}
}
paragraph_index += 1;
}
// 处理最后一个块
if !current_chunk.is_empty() && current_chunk.len() >= config.min_chunk_size {
let chunk = self.create_semantic_chunk(
document_id,
¤t_chunk,
file_name,
chunk_index,
paragraph_index,
¤t_sentences,
);
chunks.push(chunk);
}
println!("📝 语义分块完成: {} 个块", chunks.len());
Ok(chunks)
}
/// 语义分块策略(带进度更新)
async fn chunk_text_semantic_with_progress(&self, document_id: &str, content: &str, file_name: &str, config: &ChunkingConfig, window: Option<&Window>, doc_id: &str, doc_name: &str) -> Result<Vec<DocumentChunk>> {
let mut chunks = Vec::new();
let mut chunk_index = 0;
// 1. 首先按段落分割
let paragraphs = self.split_into_paragraphs(content);
let total_paragraphs = paragraphs.len();
let mut current_chunk = String::new();
let mut current_sentences = Vec::new();
let mut paragraph_index = 0;
for paragraph in paragraphs {
if paragraph.trim().is_empty() {
paragraph_index += 1;
continue;
}
// 2. 将段落按句子分割
let sentences = self.split_into_sentences(¶graph);
for sentence in sentences {
let sentence = sentence.trim();
if sentence.is_empty() {
continue;
}
// 检查当前块加上新句子是否超过目标大小
let potential_chunk = if current_chunk.is_empty() {
sentence.to_string()
} else {
format!("{} {}", current_chunk, sentence)
};
if potential_chunk.len() <= config.chunk_size {
// 可以添加到当前块
current_chunk = potential_chunk;
current_sentences.push(sentence.to_string());
} else {
// 当前块已满,保存当前块并开始新块
if !current_chunk.is_empty() && current_chunk.len() >= config.min_chunk_size {
let chunk = self.create_semantic_chunk(
document_id,
¤t_chunk,
file_name,
chunk_index,
paragraph_index,
¤t_sentences,
);
chunks.push(chunk);
chunk_index += 1;
// 发送进度更新
if let Some(w) = window {
let progress = 0.3 + (paragraph_index as f32 / total_paragraphs as f32) * 0.15; // 从30%到45%
let estimated_total_chunks = (content.len() / config.chunk_size) + 1;
self.emit_document_status_with_chunks(w, doc_id, doc_name, DocumentProcessingStage::Chunking, progress, chunk_index, estimated_total_chunks).await;
}
// 实现重叠:保留最后1-2个句子作为新块的开始
let overlap_sentences = if current_sentences.len() > 2 {
current_sentences[current_sentences.len()-2..].to_vec()
} else if current_sentences.len() > 1 {
current_sentences[current_sentences.len()-1..].to_vec()
} else {
Vec::new()
};
current_chunk = if overlap_sentences.is_empty() {
sentence.to_string()
} else {
format!("{} {}", overlap_sentences.join(" "), sentence)
};
current_sentences = overlap_sentences;
current_sentences.push(sentence.to_string());
} else {
// 如果当前句子本身就很长,直接作为一个块
if sentence.len() >= config.min_chunk_size {
let chunk = self.create_semantic_chunk(
document_id,
sentence,
file_name,
chunk_index,
paragraph_index,
&vec![sentence.to_string()],
);
chunks.push(chunk);
chunk_index += 1;
}
current_chunk.clear();
current_sentences.clear();
}
}
}
paragraph_index += 1;
}
// 处理最后一个块
if !current_chunk.is_empty() && current_chunk.len() >= config.min_chunk_size {
let chunk = self.create_semantic_chunk(
document_id,
¤t_chunk,
file_name,
chunk_index,
paragraph_index,
¤t_sentences,
);
chunks.push(chunk);
}
// 发送分块完成状态
if let Some(w) = window {
self.emit_document_status_with_chunks(w, doc_id, doc_name, DocumentProcessingStage::Chunking, 0.45, chunks.len(), chunks.len()).await;
}
println!("📝 语义分块完成: {} 个块", chunks.len());
Ok(chunks)
}
/// 按段落分割文本
fn split_into_paragraphs(&self, content: &str) -> Vec<String> {
// 使用双换行符或多个换行符分割段落
let paragraph_regex = Regex::new(r"\n\s*\n").unwrap();
paragraph_regex.split(content)
.map(|p| p.trim().to_string())
.filter(|p| !p.is_empty())
.collect()
}
/// 按句子分割文本
fn split_into_sentences(&self, text: &str) -> Vec<String> {
// 使用句号、问号、感叹号等标点符号分割句子
let sentence_regex = Regex::new(r"[.!?。!?]+").unwrap();
let mut sentences = Vec::new();
let mut last_end = 0;
for mat in sentence_regex.find_iter(text) {
let sentence = text[last_end..mat.end()].trim();
if !sentence.is_empty() {
sentences.push(sentence.to_string());
}
last_end = mat.end();
}
// 处理最后一个句子(如果没有以标点结尾)
if last_end < text.len() {
let sentence = text[last_end..].trim();
if !sentence.is_empty() {
sentences.push(sentence.to_string());
}
}
// 如果没有找到句子分隔符,将整个文本作为一个句子
if sentences.is_empty() {
sentences.push(text.trim().to_string());
}
sentences
}
/// 创建语义块
fn create_semantic_chunk(
&self,
document_id: &str,
content: &str,
file_name: &str,
chunk_index: usize,
paragraph_index: usize,
sentences: &[String],
) -> DocumentChunk {
let mut metadata = HashMap::new();
metadata.insert("file_name".to_string(), file_name.to_string());
metadata.insert("chunk_index".to_string(), chunk_index.to_string());
metadata.insert("paragraph_index".to_string(), paragraph_index.to_string());
metadata.insert("sentence_count".to_string(), sentences.len().to_string());
metadata.insert("chunking_strategy".to_string(), "semantic".to_string());
DocumentChunk {
id: Uuid::new_v4().to_string(),
document_id: document_id.to_string(),
chunk_index,
text: content.to_string(),
metadata,
}
}
/// 为文本块生成向量嵌入
async fn generate_embeddings_for_chunks(&self, chunks: Vec<DocumentChunk>) -> Result<Vec<DocumentChunkWithEmbedding>> {
self.generate_embeddings_for_chunks_with_progress(chunks, None, "", "").await
}
/// 为文本块生成向量嵌入并发送进度更新
async fn generate_embeddings_for_chunks_with_progress(
&self,
chunks: Vec<DocumentChunk>,
window: Option<&Window>,
document_id: &str,
file_name: &str
) -> Result<Vec<DocumentChunkWithEmbedding>> {
println!("🧠 开始为 {} 个文本块生成向量嵌入", chunks.len());
let mut chunks_with_embeddings = Vec::new();
let total_chunks = chunks.len();
// 如果提供了window,发送初始状态并显示总块数
if let Some(w) = window {
self.emit_document_status_with_chunks(w, document_id, file_name, DocumentProcessingStage::Embedding, 0.0, 0, total_chunks).await;
}
for (index, chunk) in chunks.into_iter().enumerate() {
if index % 10 == 0 || index == total_chunks - 1 {
println!("📊 向量生成进度: {}/{} ({:.1}%)", index + 1, total_chunks, (index + 1) as f32 / total_chunks as f32 * 100.0);
}
println!("🔤 正在为文本块 {} 生成向量 (长度: {} 字符)", index + 1, chunk.text.len());
// 获取嵌入模型配置
let model_assignments = self.llm_manager.get_model_assignments().await
.map_err(|e| AppError::configuration(format!("获取模型分配失败: {}", e)))?;
let embedding_model_id = model_assignments.embedding_model_config_id
.ok_or_else(|| AppError::configuration("未配置嵌入模型"))?;
// 调用LLM管理器生成嵌入
let embeddings = self.llm_manager.call_embedding_api(vec![chunk.text.clone()], &embedding_model_id).await
.map_err(|e| AppError::llm(format!("生成嵌入向量失败: {}", e)))?;
let embedding = embeddings.into_iter().next()
.ok_or_else(|| AppError::llm("嵌入向量生成失败"))?;
if index % 10 == 0 {
println!("✅ 文本块 {} 向量生成完成 (维度: {})", index + 1, embedding.len());
}
chunks_with_embeddings.push(DocumentChunkWithEmbedding {
chunk,
embedding,
});
// 发送进度更新
if let Some(w) = window {
let progress = 0.5 + (index + 1) as f32 / total_chunks as f32 * 0.3; // 从50%到80%
self.emit_document_status_with_chunks(w, document_id, file_name, DocumentProcessingStage::Embedding, progress, index + 1, total_chunks).await;
}
}
println!("🎉 所有向量嵌入生成完成: {} 个向量", chunks_with_embeddings.len());
Ok(chunks_with_embeddings)
}
/// 获取默认RAG查询选项
pub fn get_default_rag_query_options(&self) -> RagQueryOptions {
match self.database.get_rag_configuration() {
Ok(Some(config)) => {
RagQueryOptions {
top_k: config.default_top_k as usize,
enable_reranking: Some(config.default_rerank_enabled),
}
}
_ => {
// 使用默认值
RagQueryOptions {
top_k: 5,
enable_reranking: Some(false),
}
}
}
}
/// 查询知识库
pub async fn query_knowledge_base(&self, user_query: &str, options: RagQueryOptions) -> Result<RagQueryResponse> {
let start_time = std::time::Instant::now();
println!("🔍 开始RAG查询: '{}' (top_k: {})", user_query, options.top_k);
// 1. 生成查询向量
let query_vector_start = std::time::Instant::now();
let model_assignments = self.llm_manager.get_model_assignments().await
.map_err(|e| AppError::configuration(format!("获取模型分配失败: {}", e)))?;
let embedding_model_id = model_assignments.embedding_model_config_id
.ok_or_else(|| AppError::configuration("未配置嵌入模型"))?;
let query_embeddings = self.llm_manager.call_embedding_api(vec![user_query.to_string()], &embedding_model_id).await
.map_err(|e| AppError::llm(format!("生成查询向量失败: {}", e)))?;
let query_embedding = query_embeddings.into_iter().next()
.ok_or_else(|| AppError::llm("未获取到查询向量"))?;
let query_vector_time = query_vector_start.elapsed();
// 2. 向量搜索
let search_start = std::time::Instant::now();
let mut retrieved_chunks = self.vector_store.search_similar_chunks(query_embedding, options.top_k).await?;
let search_time = search_start.elapsed();
// 3. 可选的重排序
let reranking_time = if options.enable_reranking.unwrap_or(false) {
let rerank_start = std::time::Instant::now();
retrieved_chunks = self.rerank_chunks(user_query, retrieved_chunks).await?;
Some(rerank_start.elapsed())
} else {
None
};
let total_time = start_time.elapsed();
println!("✅ RAG查询完成: {} 个结果 (总耗时: {:?})", retrieved_chunks.len(), total_time);
Ok(RagQueryResponse {
retrieved_chunks,
query_vector_time_ms: query_vector_time.as_millis() as u64,
search_time_ms: search_time.as_millis() as u64,
reranking_time_ms: reranking_time.map(|t| t.as_millis() as u64),
total_time_ms: total_time.as_millis() as u64,
})
}
/// 在指定分库中查询知识库
pub async fn query_knowledge_base_in_libraries(&self, user_query: &str, options: RagQueryOptions, sub_library_ids: Option<Vec<String>>) -> Result<RagQueryResponse> {
let start_time = std::time::Instant::now();
let library_filter_msg = if let Some(ref lib_ids) = sub_library_ids {
format!(" (分库: {:?})", lib_ids)
} else {
" (所有分库)".to_string()
};
println!("🔍 开始RAG查询: '{}' (top_k: {}){}", user_query, options.top_k, library_filter_msg);
// 1. 生成查询向量
let query_vector_start = std::time::Instant::now();
let model_assignments = self.llm_manager.get_model_assignments().await
.map_err(|e| AppError::configuration(format!("获取模型分配失败: {}", e)))?;
let embedding_model_id = model_assignments.embedding_model_config_id
.ok_or_else(|| AppError::configuration("未配置嵌入模型"))?;
let query_embeddings = self.llm_manager.call_embedding_api(vec![user_query.to_string()], &embedding_model_id).await
.map_err(|e| AppError::llm(format!("生成查询向量失败: {}", e)))?;
if query_embeddings.is_empty() {
return Err(AppError::llm("查询向量生成失败"));
}
let query_vector = query_embeddings.into_iter().next().unwrap();
let query_vector_time = query_vector_start.elapsed();
// 2. 在指定分库中检索相似文档块
let search_start = std::time::Instant::now();
let mut retrieved_chunks = self.vector_store.search_similar_chunks_in_libraries(query_vector, options.top_k, sub_library_ids).await?;
let search_time = search_start.elapsed();
// 3. 可选的重排序
let reranking_time = if options.enable_reranking.unwrap_or(false) && !retrieved_chunks.is_empty() {
let rerank_start = std::time::Instant::now();
retrieved_chunks = self.rerank_chunks(user_query, retrieved_chunks).await?;
Some(rerank_start.elapsed())
} else {
None
};
let total_time = start_time.elapsed();
println!("✅ RAG查询完成: 返回 {} 个结果 (总耗时: {}ms){}",
retrieved_chunks.len(), total_time.as_millis(), library_filter_msg);
Ok(RagQueryResponse {
retrieved_chunks,
query_vector_time_ms: query_vector_time.as_millis() as u64,
search_time_ms: search_time.as_millis() as u64,
reranking_time_ms: reranking_time.map(|t| t.as_millis() as u64),
total_time_ms: total_time.as_millis() as u64,
})
}
/// 重排序检索结果
async fn rerank_chunks(&self, query: &str, chunks: Vec<RetrievedChunk>) -> Result<Vec<RetrievedChunk>> {
println!("🔄 开始重排序 {} 个检索结果", chunks.len());
let model_assignments = self.llm_manager.get_model_assignments().await
.map_err(|e| AppError::configuration(format!("获取模型分配失败: {}", e)))?;
if let Some(reranker_model_id) = model_assignments.reranker_model_config_id {
// 调用重排序模型
let reranked_chunks = self.llm_manager.call_reranker_api(query.to_string(), chunks, &reranker_model_id).await
.map_err(|e| AppError::llm(format!("重排序失败: {}", e)))?;
println!("✅ 重排序完成");
Ok(reranked_chunks)
} else {
println!("⚠️ 未配置重排序模型,跳过重排序");
Ok(chunks)
}
}
/// 获取知识库状态
pub async fn get_knowledge_base_status(&self) -> Result<KnowledgeBaseStatusPayload> {
let stats = self.vector_store.get_stats().await?;
// 获取当前嵌入模型名称
let embedding_model_name = match self.llm_manager.get_model_assignments().await {
Ok(assignments) => {
if let Some(model_id) = assignments.embedding_model_config_id {
match self.llm_manager.get_api_configs().await {
Ok(configs) => {
configs.iter()
.find(|config| config.id == model_id)
.map(|config| config.name.clone())
}
Err(_) => None
}
} else {
None
}
}
Err(_) => None
};
Ok(KnowledgeBaseStatusPayload {
total_documents: stats.total_documents,
total_chunks: stats.total_chunks,
embedding_model_name,
vector_store_type: "SQLite".to_string(),
})
}
/// 删除文档
pub async fn delete_document_from_knowledge_base(&self, document_id: &str) -> Result<()> {
println!("🗑️ 删除文档: {}", document_id);
self.vector_store.delete_chunks_by_document_id(document_id).await
}
/// 清空知识库
pub async fn clear_knowledge_base(&self) -> Result<()> {
println!("🧹 清空知识库");
self.vector_store.clear_all().await
}
/// 获取所有文档列表
pub async fn get_all_documents(&self) -> Result<Vec<Value>> {
self.vector_store.get_all_documents()
}
// 辅助方法:发送处理状态更新
async fn emit_processing_status(&self, window: &Window, id: &str, status: &str, progress: f32, message: &str) {
let payload = serde_json::json!({
"id": id,
"status": status,
"progress": progress,
"message": message,
"timestamp": chrono::Utc::now().to_rfc3339()
});
if let Err(e) = window.emit("rag_processing_status", payload) {
println!("⚠️ 发送处理状态失败: {}", e);
}
}
// 辅助方法:发送文档处理状态
async fn emit_document_status(&self, window: &Window, document_id: &str, file_name: &str, stage: DocumentProcessingStage, progress: f32) {
let status = DocumentProcessingStatus {
document_id: document_id.to_string(),
file_name: file_name.to_string(),
status: stage,
progress,
error_message: None,
chunks_processed: 0,
total_chunks: 0,
};
if let Err(e) = window.emit("rag_document_status", &status) {
println!("⚠️ 发送文档状态失败: {}", e);
}
}
// 辅助方法:发送带详细信息的文档处理状态
async fn emit_document_status_with_chunks(&self, window: &Window, document_id: &str, file_name: &str, stage: DocumentProcessingStage, progress: f32, chunks_processed: usize, total_chunks: usize) {
let status = DocumentProcessingStatus {
document_id: document_id.to_string(),
file_name: file_name.to_string(),
status: stage,
progress,
error_message: None,
chunks_processed,
total_chunks,
};
if let Err(e) = window.emit("rag_document_status", &status) {
println!("⚠️ 发送文档状态失败: {}", e);
}
}
/// 提取PDF文件文本内容
async fn extract_pdf_text(&self, file_path: &str) -> Result<String> {
use pdf_extract::extract_text;
println!("📕 开始提取PDF文本: {}", file_path);
// 再次检查文件是否存在
let path = std::path::Path::new(file_path);
if !path.exists() {
return Err(AppError::file_system(format!("PDF文件不存在: {}", file_path)));
}
let text = extract_text(file_path)
.map_err(|e| AppError::validation(format!("PDF文本提取失败: {} (文件路径: {})", e, file_path)))?;
if text.trim().is_empty() {
return Err(AppError::validation(format!("PDF文件没有可提取的文本内容 (文件路径: {})", file_path)));
}
println!("✅ PDF文本提取完成,长度: {} 字符", text.len());
Ok(text)
}
/// 提取DOCX文件文本内容
async fn extract_docx_text(&self, file_path: &str) -> Result<String> {
use docx_rs::*;
println!("📘 开始提取DOCX文本: {}", file_path);
// 再次检查文件是否存在
let path = std::path::Path::new(file_path);
if !path.exists() {
return Err(AppError::file_system(format!("DOCX文件不存在: {}", file_path)));
}
let bytes = std::fs::read(file_path)
.map_err(|e| AppError::file_system(format!("读取DOCX文件失败: {} (文件路径: {})", e, file_path)))?;
let docx = read_docx(&bytes)
.map_err(|e| AppError::validation(format!("DOCX文件解析失败: {} (文件路径: {})", e, file_path)))?;
// 提取文档中的所有文本
let mut text_content = String::new();
// 遍历文档的所有段落
for child in docx.document.children {
match child {
docx_rs::DocumentChild::Paragraph(paragraph) => {
for run in paragraph.children {
match run {
docx_rs::ParagraphChild::Run(run) => {
for run_child in run.children {
if let docx_rs::RunChild::Text(text) = run_child {
text_content.push_str(&text.text);
}
}
}
_ => {}
}
}
text_content.push('\n'); // 段落结束添加换行
}
_ => {}
}
}
if text_content.trim().is_empty() {
return Err(AppError::validation(format!("DOCX文件没有可提取的文本内容 (文件路径: {})", file_path)));
}
println!("✅ DOCX文本提取完成,长度: {} 字符", text_content.len());
Ok(text_content)
}
/// 从内存中的PDF字节数据提取文本
async fn extract_pdf_text_from_memory(&self, pdf_bytes: &[u8]) -> Result<String> {
println!("📄 开始解析PDF文件 (大小: {} 字节)", pdf_bytes.len());
// 使用文档解析器处理PDF
let parser = crate::document_parser::DocumentParser::new();
println!("🔧 初始化PDF解析器");
match parser.extract_text_from_bytes("document.pdf", pdf_bytes.to_vec()) {
Ok(text) => {
println!("✅ PDF解析成功,提取文本长度: {} 字符", text.len());
if text.trim().is_empty() {
println!("⚠️ PDF文件解析结果为空");
Err(AppError::validation("PDF文件内容为空或无法解析"))
} else {
Ok(text)
}
}
Err(e) => {
println!("❌ PDF解析失败: {}", e);
Err(AppError::file_system(format!("PDF解析失败: {}", e)))
}
}
}
/// 从内存中的DOCX字节数据提取文本
async fn extract_docx_text_from_memory(&self, docx_bytes: &[u8]) -> Result<String> {
println!("📄 开始解析DOCX文件 (大小: {} 字节)", docx_bytes.len());
// 使用文档解析器处理DOCX
let parser = crate::document_parser::DocumentParser::new();
println!("🔧 初始化DOCX解析器");
match parser.extract_text_from_bytes("document.docx", docx_bytes.to_vec()) {
Ok(text) => {
println!("✅ DOCX解析成功,提取文本长度: {} 字符", text.len());
if text.trim().is_empty() {
println!("⚠️ DOCX文件解析结果为空");
Err(AppError::validation("DOCX文件内容为空或无法解析"))
} else {
Ok(text)
}
}
Err(e) => {
println!("❌ DOCX解析失败: {}", e);
Err(AppError::file_system(format!("DOCX解析失败: {}", e)))
}
}
}
}
|
0015/map_tiles
| 9,617 |
README.md
|
# Map Tiles Component for LVGL 9.x
A comprehensive map tiles component for ESP-IDF projects using LVGL 9.x. This component provides functionality to load and display map tiles with GPS coordinate conversion, designed for embedded applications requiring offline map display capabilities.
## Features
- **LVGL 9.x Compatible**: Fully compatible with LVGL 9.x image handling
- **GPS Coordinate Conversion**: Convert GPS coordinates to tile coordinates and vice versa
- **Dynamic Tile Loading**: Load map tiles on demand from file system
- **Configurable Grid Size**: Support for different grid sizes (3x3, 5x5, 7x7, etc.)
- **Multiple Tile Types**: Support for up to 8 different tile types (street, satellite, terrain, hybrid, etc.)
- **Memory Efficient**: Configurable memory allocation (SPIRAM or regular RAM)
- **Multiple Zoom Levels**: Support for different map zoom levels
- **Error Handling**: Comprehensive error handling and logging
- **C API**: Clean C API for easy integration
## Requirements
- ESP-IDF 5.0 or later
- LVGL 9.3
- File system support (FAT/SPIFFS/LittleFS)
- Map tiles in binary format (RGB565, 256x256 pixels)
## Installation
### Using ESP-IDF Component Manager
You can easily add this component to your project using the idf.py command or by manually updating your idf_component.yml file.
#### Option 1: Using the idf.py add-dependency command (Recommended)
From your project's root directory, simply run the following command in your terminal:
```bash
idf.py add-dependency "0015/map_tiles^1.2.0"
```
This command will automatically add the component to your idf_component.yml file and download the required files the next time you build your project.
#### Option 2: Manual idf_component.yml update
Add to your project's `main/idf_component.yml`:
```yaml
dependencies:
map_tiles:
git: "https://github.com/0015/map_tiles.git"
version: "^1.2.0"
```
### Manual Installation
1. Copy the `map_tiles` folder to your project's `components` directory
2. The component will be automatically included in your build
## Usage
### Basic Setup
```c
#include "map_tiles.h"
// Configure the map tiles with multiple tile types and custom grid size
const char* tile_folders[] = {"street_map", "satellite", "terrain", "hybrid"};
map_tiles_config_t config = {
.base_path = "/sdcard", // Base path to tile storage
.tile_folders = {tile_folders[0], tile_folders[1], tile_folders[2], tile_folders[3]},
.tile_type_count = 4, // Number of tile types
.default_zoom = 10, // Default zoom level
.use_spiram = true, // Use SPIRAM if available
.default_tile_type = 0, // Start with street map (index 0)
.grid_cols = 5, // Grid width (tiles)
.grid_rows = 5 // Grid height (tiles)
};
// Initialize map tiles
map_tiles_handle_t map_handle = map_tiles_init(&config);
if (!map_handle) {
ESP_LOGE(TAG, "Failed to initialize map tiles");
return;
}
```
### Loading Tiles
```c
// Set center position from GPS coordinates
map_tiles_set_center_from_gps(map_handle, 37.7749, -122.4194); // San Francisco
// Get grid dimensions
int grid_cols, grid_rows;
map_tiles_get_grid_size(map_handle, &grid_cols, &grid_rows);
int tile_count = map_tiles_get_tile_count(map_handle);
// Load tiles for the configured grid size
for (int row = 0; row < grid_rows; row++) {
for (int col = 0; col < grid_cols; col++) {
int index = row * grid_cols + col;
int tile_x, tile_y;
map_tiles_get_position(map_handle, &tile_x, &tile_y);
bool loaded = map_tiles_load_tile(map_handle, index,
tile_x + col, tile_y + row);
if (!loaded) {
ESP_LOGW(TAG, "Failed to load tile %d", index);
}
}
}
```
### Displaying Tiles with LVGL
```c
// Get grid dimensions and tile count
int grid_cols, grid_rows;
map_tiles_get_grid_size(map_handle, &grid_cols, &grid_rows);
int tile_count = map_tiles_get_tile_count(map_handle);
// Create image widgets for each tile
lv_obj_t** tile_images = malloc(tile_count * sizeof(lv_obj_t*));
for (int i = 0; i < tile_count; i++) {
tile_images[i] = lv_image_create(parent_container);
// Get the tile image descriptor
lv_image_dsc_t* img_dsc = map_tiles_get_image(map_handle, i);
if (img_dsc) {
lv_image_set_src(tile_images[i], img_dsc);
// Position the tile in the grid
int row = i / grid_cols;
int col = i % grid_cols;
lv_obj_set_pos(tile_images[i],
col * MAP_TILES_TILE_SIZE,
row * MAP_TILES_TILE_SIZE);
}
}
```
### Switching Tile Types
```c
// Switch to different tile types
map_tiles_set_tile_type(map_handle, 0); // Street map
map_tiles_set_tile_type(map_handle, 1); // Satellite
map_tiles_set_tile_type(map_handle, 2); // Terrain
map_tiles_set_tile_type(map_handle, 3); // Hybrid
// Get current tile type
int current_type = map_tiles_get_tile_type(map_handle);
// Get available tile types
int type_count = map_tiles_get_tile_type_count(map_handle);
for (int i = 0; i < type_count; i++) {
const char* folder = map_tiles_get_tile_type_folder(map_handle, i);
printf("Tile type %d: %s\n", i, folder);
}
```
### GPS Coordinate Conversion
```c
// Convert GPS to tile coordinates
double tile_x, tile_y;
map_tiles_gps_to_tile_xy(map_handle, 37.7749, -122.4194, &tile_x, &tile_y);
// Check if GPS position is within current tile grid
bool within_tiles = map_tiles_is_gps_within_tiles(map_handle, 37.7749, -122.4194);
// Get marker offset for precise positioning
int offset_x, offset_y;
map_tiles_get_marker_offset(map_handle, &offset_x, &offset_y);
```
### Memory Management
```c
// Clean up when done
map_tiles_cleanup(map_handle);
```
## Tile File Format
The component expects map tiles in a specific binary format:
- **File Structure**: `{base_path}/{map_tile}/{zoom}/{tile_x}/{tile_y}.bin`
- **Format**: 12-byte header + raw RGB565 pixel data
- **Size**: 256x256 pixels
- **Color Format**: RGB565 (16-bit per pixel)
### Example Tile Structure
```
/sdcard/
├── street_map/ // Tile type 0
│ ├── 10/
│ │ ├── 164/
│ │ │ ├── 395.bin
│ │ │ ├── 396.bin
│ │ │ └── ...
│ │ └── ...
│ └── ...
├── satellite/ // Tile type 1
│ ├── 10/
│ │ ├── 164/
│ │ │ ├── 395.bin
│ │ │ └── ...
│ │ └── ...
│ └── ...
├── terrain/ // Tile type 2
│ └── ...
└── hybrid/ // Tile type 3
└── ...
```
## Configuration Options
| Parameter | Type | Description | Default |
|-----------|------|-------------|---------|
| `base_path` | `const char*` | Base directory for tile storage | Required |
| `tile_folders` | `const char*[]` | Array of folder names for different tile types | Required |
| `tile_type_count` | `int` | Number of tile types (max 8) | Required |
| `default_zoom` | `int` | Initial zoom level | Required |
| `use_spiram` | `bool` | Use SPIRAM for tile buffers | `false` |
| `default_tile_type` | `int` | Initial tile type index | Required |
| `grid_cols` | `int` | Number of tile columns (max 10) | 5 |
| `grid_rows` | `int` | Number of tile rows (max 10) | 5 |
## API Reference
### Initialization
- `map_tiles_init()` - Initialize map tiles system
- `map_tiles_cleanup()` - Clean up resources
### Tile Management
- `map_tiles_load_tile()` - Load a specific tile
- `map_tiles_get_image()` - Get LVGL image descriptor
- `map_tiles_get_buffer()` - Get raw tile buffer
### Grid Management
- `map_tiles_get_grid_size()` - Get current grid dimensions
- `map_tiles_get_tile_count()` - Get total number of tiles in grid
### Coordinate Conversion
- `map_tiles_gps_to_tile_xy()` - Convert GPS to tile coordinates
- `map_tiles_set_center_from_gps()` - Set center from GPS
- `map_tiles_is_gps_within_tiles()` - Check if GPS is within current tiles
### Position Management
- `map_tiles_get_position()` - Get current tile position
- `map_tiles_set_position()` - Set tile position
- `map_tiles_get_marker_offset()` - Get marker offset
- `map_tiles_set_marker_offset()` - Set marker offset
### Tile Type Management
- `map_tiles_set_tile_type()` - Set active tile type
- `map_tiles_get_tile_type()` - Get current tile type
- `map_tiles_get_tile_type_count()` - Get number of available types
- `map_tiles_get_tile_type_folder()` - Get folder name for a type
### Zoom Control
- `map_tiles_set_zoom()` - Set zoom level
- `map_tiles_get_zoom()` - Get current zoom level
### Error Handling
- `map_tiles_set_loading_error()` - Set error state
- `map_tiles_has_loading_error()` - Check error state
## Performance Considerations
- **Memory Usage**: Each tile uses ~128KB (256×256×2 bytes)
- **Grid Size**: Larger grids use more memory (3x3=9 tiles, 5x5=25 tiles, 7x7=49 tiles)
- **SPIRAM**: Recommended for ESP32-S3 with PSRAM for better performance
- **File System**: Ensure adequate file system performance for tile loading
- **Tile Caching**: Component maintains tile buffers until cleanup
## Example Projects
See the `examples` directory for complete implementation examples:
- Basic map display
- GPS tracking with map updates
- Interactive map with touch controls
## License
This component is released under the MIT License. See LICENSE file for details.
## Contributing
Contributions are welcome! Please feel free to submit pull requests or open issues for bugs and feature requests.
## Support
For questions and support, please open an issue on the GitHub repository.
|
000haoji/deep-student
| 16,777 |
src-tauri/src/debug_logger.rs
|
/**
* 后端调试日志记录模块
* 用于记录数据库操作、API调用、流式处理等关键信息
*/
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use tauri::Manager;
use tracing::{error, info, warn};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum LogLevel {
DEBUG,
INFO,
WARN,
ERROR,
TRACE,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct LogContext {
pub user_id: Option<String>,
pub session_id: Option<String>,
pub mistake_id: Option<String>,
pub stream_id: Option<String>,
pub business_id: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct LogEntry {
pub timestamp: String,
pub level: LogLevel,
pub module: String,
pub operation: String,
pub data: serde_json::Value,
pub context: Option<LogContext>,
pub stack_trace: Option<String>,
}
#[derive(Debug, Clone)]
pub struct DebugLogger {
log_dir: PathBuf,
log_queue: Arc<Mutex<Vec<LogEntry>>>,
}
impl DebugLogger {
pub fn new(app_data_dir: PathBuf) -> Self {
let log_dir = app_data_dir.join("logs");
// 确保日志目录存在
if let Err(e) = std::fs::create_dir_all(&log_dir.join("frontend")) {
error!("Failed to create frontend log directory: {}", e);
}
if let Err(e) = std::fs::create_dir_all(&log_dir.join("backend")) {
error!("Failed to create backend log directory: {}", e);
}
if let Err(e) = std::fs::create_dir_all(&log_dir.join("debug")) {
error!("Failed to create debug log directory: {}", e);
}
Self {
log_dir,
log_queue: Arc::new(Mutex::new(Vec::new())),
}
}
/// 记录数据库操作相关日志
pub async fn log_database_operation(
&self,
operation: &str,
table: &str,
query: &str,
params: Option<&serde_json::Value>,
result: Option<&serde_json::Value>,
error: Option<&str>,
duration_ms: Option<u64>,
) {
let level = if error.is_some() { LogLevel::ERROR } else { LogLevel::DEBUG };
let data = serde_json::json!({
"table": table,
"query": query,
"params": params,
"result": self.sanitize_database_result(result),
"error": error,
"duration_ms": duration_ms
});
self.log(level, "DATABASE", operation, data, None).await;
}
/// 记录聊天记录相关操作
pub async fn log_chat_record_operation(
&self,
operation: &str,
mistake_id: &str,
chat_history: Option<&serde_json::Value>,
expected_vs_actual: Option<(usize, usize)>,
error: Option<&str>,
) {
let level = if error.is_some() { LogLevel::ERROR } else { LogLevel::INFO };
let data = serde_json::json!({
"mistake_id": mistake_id,
"chat_history_length": chat_history.and_then(|ch| ch.as_array().map(|arr| arr.len())),
"chat_history": self.sanitize_chat_history(chat_history),
"expected_vs_actual": expected_vs_actual,
"error": error,
"timestamp": Utc::now().to_rfc3339()
});
let context = LogContext {
user_id: None,
session_id: None,
mistake_id: Some(mistake_id.to_string()),
stream_id: None,
business_id: Some(mistake_id.to_string()),
};
self.log(level, "CHAT_RECORD", operation, data, Some(context)).await;
}
/// 记录RAG操作
pub async fn log_rag_operation(
&self,
operation: &str,
query: Option<&str>,
top_k: Option<usize>,
sources_found: Option<usize>,
sources_returned: Option<usize>,
error: Option<&str>,
duration_ms: Option<u64>,
) {
let level = if error.is_some() { LogLevel::ERROR } else { LogLevel::INFO };
let data = serde_json::json!({
"query_length": query.map(|q| q.len()),
"query_preview": query.map(|q| if q.len() > 100 { &q[..100] } else { q }),
"top_k": top_k,
"sources_found": sources_found,
"sources_returned": sources_returned,
"error": error,
"duration_ms": duration_ms,
"sources_missing": sources_found.and_then(|found|
sources_returned.map(|returned| found.saturating_sub(returned))
)
});
self.log(level, "RAG", operation, data, None).await;
}
/// 记录流式处理操作
pub async fn log_streaming_operation(
&self,
operation: &str,
stream_id: &str,
event_type: &str,
payload_size: Option<usize>,
error: Option<&str>,
) {
let level = if error.is_some() { LogLevel::ERROR } else { LogLevel::DEBUG };
let data = serde_json::json!({
"stream_id": stream_id,
"event_type": event_type,
"payload_size": payload_size,
"error": error,
"timestamp": Utc::now().to_rfc3339()
});
let context = LogContext {
user_id: None,
session_id: None,
mistake_id: None,
stream_id: Some(stream_id.to_string()),
business_id: None,
};
self.log(level, "STREAMING", operation, data, Some(context)).await;
}
/// 记录API调用
pub async fn log_api_call(
&self,
operation: &str,
method: &str,
url: &str,
request_body: Option<&serde_json::Value>,
response_body: Option<&serde_json::Value>,
status_code: Option<u16>,
error: Option<&str>,
duration_ms: Option<u64>,
) {
let level = if error.is_some() || status_code.map_or(false, |code| code >= 400) {
LogLevel::ERROR
} else {
LogLevel::INFO
};
let data = serde_json::json!({
"method": method,
"url": url,
"request_body": self.sanitize_api_body(request_body),
"response_body": self.sanitize_api_body(response_body),
"status_code": status_code,
"error": error,
"duration_ms": duration_ms
});
self.log(level, "API", operation, data, None).await;
}
/// 记录状态变化
pub async fn log_state_change(
&self,
component: &str,
operation: &str,
old_state: Option<&serde_json::Value>,
new_state: Option<&serde_json::Value>,
trigger: Option<&str>,
) {
let data = serde_json::json!({
"component": component,
"old_state": self.sanitize_state(old_state),
"new_state": self.sanitize_state(new_state),
"state_diff": self.calculate_state_diff(old_state, new_state),
"trigger": trigger
});
self.log(LogLevel::TRACE, "STATE_CHANGE", operation, data, None).await;
}
/// 通用日志记录方法
pub async fn log(
&self,
level: LogLevel,
module: &str,
operation: &str,
data: serde_json::Value,
context: Option<LogContext>,
) {
let log_entry = LogEntry {
timestamp: Utc::now().to_rfc3339(),
level: level.clone(),
module: module.to_string(),
operation: operation.to_string(),
data,
context,
stack_trace: if matches!(level, LogLevel::ERROR) {
Some(format!("{:?}", std::backtrace::Backtrace::capture()))
} else {
None
},
};
// 添加到队列
if let Ok(mut queue) = self.log_queue.lock() {
queue.push(log_entry.clone());
// 如果是错误级别,立即写入
if matches!(level, LogLevel::ERROR) {
drop(queue);
self.flush_logs().await;
}
}
// 同时输出到控制台
match level {
LogLevel::ERROR => error!("[{}] [{}] {}: {:?}", module, operation, log_entry.timestamp, log_entry.data),
LogLevel::WARN => warn!("[{}] [{}] {}: {:?}", module, operation, log_entry.timestamp, log_entry.data),
LogLevel::INFO => info!("[{}] [{}] {}: {:?}", module, operation, log_entry.timestamp, log_entry.data),
_ => tracing::debug!("[{}] [{}] {}: {:?}", module, operation, log_entry.timestamp, log_entry.data),
}
}
/// 刷新日志到文件
pub async fn flush_logs(&self) {
let logs = {
let mut queue = match self.log_queue.lock() {
Ok(queue) => queue,
Err(_) => return,
};
if queue.is_empty() {
return;
}
let logs = queue.clone();
queue.clear();
logs
};
// 按日期和模块分组写入不同文件
let mut grouped_logs: HashMap<String, Vec<LogEntry>> = HashMap::new();
for log in logs {
let date = log.timestamp.split('T').next().unwrap_or("unknown").to_string();
let key = format!("{}_{}", date, log.module.to_lowercase());
grouped_logs.entry(key).or_insert_with(Vec::new).push(log);
}
for (key, group_logs) in grouped_logs {
let file_path = self.log_dir.join("backend").join(format!("{}.log", key));
if let Err(e) = self.write_logs_to_file(&file_path, &group_logs) {
error!("Failed to write logs to {}: {}", file_path.display(), e);
}
}
}
fn write_logs_to_file(&self, file_path: &PathBuf, logs: &[LogEntry]) -> Result<(), Box<dyn std::error::Error>> {
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(file_path)?;
for log in logs {
let log_line = serde_json::to_string(log)?;
writeln!(file, "{}", log_line)?;
}
file.flush()?;
Ok(())
}
fn sanitize_database_result(&self, result: Option<&serde_json::Value>) -> Option<serde_json::Value> {
result.map(|r| {
if let Some(arr) = r.as_array() {
if arr.len() > 10 {
serde_json::json!({
"_truncated": true,
"_count": arr.len(),
"_preview": &arr[..5]
})
} else {
r.clone()
}
} else {
r.clone()
}
})
}
fn sanitize_chat_history(&self, chat_history: Option<&serde_json::Value>) -> Option<serde_json::Value> {
chat_history.and_then(|ch| {
ch.as_array().map(|arr| {
if arr.len() > 10 {
serde_json::json!({
"_truncated": true,
"_count": arr.len(),
"_preview": &arr[..3],
"_latest": &arr[arr.len().saturating_sub(2)..]
})
} else {
serde_json::Value::Array(arr.clone())
}
})
})
}
fn sanitize_api_body(&self, body: Option<&serde_json::Value>) -> Option<serde_json::Value> {
body.map(|b| {
let body_str = b.to_string();
if body_str.len() > 1000 {
serde_json::json!({
"_truncated": true,
"_size": body_str.len(),
"_preview": &body_str[..500]
})
} else {
b.clone()
}
})
}
fn sanitize_state(&self, state: Option<&serde_json::Value>) -> Option<serde_json::Value> {
state.map(|s| {
// 移除大型数组和对象,只保留关键信息
if let Some(obj) = s.as_object() {
let mut sanitized = serde_json::Map::new();
for (key, value) in obj {
match key.as_str() {
"chatHistory" | "thinkingContent" => {
if let Some(arr) = value.as_array() {
sanitized.insert(key.clone(), serde_json::json!({
"_type": "array",
"_length": arr.len()
}));
} else {
sanitized.insert(key.clone(), serde_json::json!({
"_type": "object",
"_size": value.to_string().len()
}));
}
},
_ => {
sanitized.insert(key.clone(), value.clone());
}
}
}
serde_json::Value::Object(sanitized)
} else {
s.clone()
}
})
}
fn calculate_state_diff(&self, old_state: Option<&serde_json::Value>, new_state: Option<&serde_json::Value>) -> serde_json::Value {
match (old_state, new_state) {
(Some(old), Some(new)) => {
if let (Some(old_obj), Some(new_obj)) = (old.as_object(), new.as_object()) {
let mut diff = serde_json::Map::new();
// 检查所有键
let mut all_keys = std::collections::HashSet::new();
all_keys.extend(old_obj.keys());
all_keys.extend(new_obj.keys());
for key in all_keys {
let old_val = old_obj.get(key);
let new_val = new_obj.get(key);
if old_val != new_val {
diff.insert(key.clone(), serde_json::json!({
"from": old_val,
"to": new_val
}));
}
}
serde_json::Value::Object(diff)
} else {
serde_json::json!({
"changed": old != new,
"from": old,
"to": new
})
}
},
_ => serde_json::json!({
"from": old_state,
"to": new_state
})
}
}
}
// Tauri命令,用于从前端写入日志
#[tauri::command]
pub async fn write_debug_logs(
app: tauri::AppHandle,
logs: Vec<LogEntry>,
) -> Result<(), String> {
let app_data_dir = app.path_resolver()
.app_data_dir()
.ok_or("Failed to get app data directory")?;
let logger = DebugLogger::new(app_data_dir);
// 写入前端日志到frontend目录
let frontend_dir = logger.log_dir.join("frontend");
std::fs::create_dir_all(&frontend_dir).map_err(|e| e.to_string())?;
// 按日期分组
let mut grouped_logs: HashMap<String, Vec<LogEntry>> = HashMap::new();
for log in logs {
let date = log.timestamp.split('T').next().unwrap_or("unknown").to_string();
let key = format!("{}_{}", date, log.module.to_lowercase());
grouped_logs.entry(key).or_insert_with(Vec::new).push(log);
}
for (key, group_logs) in grouped_logs {
let file_path = frontend_dir.join(format!("{}.log", key));
logger.write_logs_to_file(&file_path, &group_logs)
.map_err(|e| e.to_string())?;
}
Ok(())
}
// 全局日志记录器实例
lazy_static::lazy_static! {
static ref GLOBAL_LOGGER: Arc<Mutex<Option<DebugLogger>>> = Arc::new(Mutex::new(None));
}
/// 初始化全局日志记录器
pub fn init_global_logger(app_data_dir: PathBuf) {
if let Ok(mut logger) = GLOBAL_LOGGER.lock() {
*logger = Some(DebugLogger::new(app_data_dir));
}
}
/// 获取全局日志记录器
pub fn get_global_logger() -> Option<DebugLogger> {
GLOBAL_LOGGER.lock().ok()?.clone()
}
/// 便捷宏用于记录日志
#[macro_export]
macro_rules! debug_log {
($level:expr, $module:expr, $operation:expr, $data:expr) => {
if let Some(logger) = crate::debug_logger::get_global_logger() {
tokio::spawn(async move {
logger.log($level, $module, $operation, $data, None).await;
});
}
};
($level:expr, $module:expr, $operation:expr, $data:expr, $context:expr) => {
if let Some(logger) = crate::debug_logger::get_global_logger() {
tokio::spawn(async move {
logger.log($level, $module, $operation, $data, Some($context)).await;
});
}
};
}
|
000ylop/galgame_cn
| 5,667 |
readme.md
|
# galgame_cn
如标题所叙,本项目主要收集galgame汉化资源站点/频道
附带一个 `generate_list` 工具来生成markdown文档。
## 免责声明
本项目只是出于个人兴趣,收集一些入门门槛较低的资源站点/频道。
本项目不保证您通过这些站点/频道下载的资源是安全的,请您自行斟酌。
## 生成
```bash
cd generate_list &&
touch ../readme.md &&
mkdir res &&
cargo run -- -o ../readme.md -s ../sites.txt &&
mv res ..
```
## 频道
[莱茵图书馆](https://t.me/RhineLibrary)
[galgame搬运工](https://t.me/gal_porter)
[Galgame Patch Collection](https://t.me/galpatch)
[Galgame Cloud](https://t.me/galgame_in_telegram)
[Galgame频道](https://t.me/Galgamer_channel)
[Visual Novel Channel](https://t.me/erogamecloud)
[秘密基地之游戏仓储中心](https://t.me/heiheinon)
[『雨夜凉亭』ACG频道](https://t.me/yuyeweimian)
[夏风小分队](https://t.me/XiafengButter)
[黄油仓库](https://t.me/quzimingyue)
[Farr的黄油(游)仓库SLG.RPG.ADV.3D](https://t.me/farrslgrpg)
[山の黄油阁](https://t.me/HY_QingYan)
[里番 黄油聚集地](https://t.me/lifanhuang)
[一起钓大鱼](https://t.me/dayuyud)
## 网站
<figure class="image">
<a href="https://galgamer.eu.org">
<img src="res/d0444cdec08d12f61d70b8c31044e08b.webp" alt="Galgamer"></img>
</a>
<figcaption>主要是介绍博客</figcaption>
</figure>
<figure class="image">
<a href="https://www.xygalgame.com">
<img src="res/a368d461aa60cede7affa9ada86bdabb.webp" alt="初音的青葱发布页"></img>
</a>
<figcaption>需要长期签到才可以无限制下载</figcaption>
</figure>
<figure class="image">
<a href="https://bbs.kfmax.com/">
<img src="res/64f0454e9029767adb5ae68caa84921a.webp" alt="绯月ScarletMoon"></img>
</a>
<figcaption>绯月</figcaption>
</figure>
<figure class="image">
<a href="https://sstm.moe/">
<img src="res/012d766c880eacc8cd6cb4f698862a61.webp" alt="SS同盟首页"></img>
</a>
<figcaption>SS同盟</figcaption>
</figure>
<figure class="image">
<a href="https://lzacg.org/">
<img src="res/52def5c0828203b948c4e2b7318db193.webp" alt="量子ACG"></img>
</a>
<figcaption>量子ACG</figcaption>
</figure>
<figure class="image">
<a href="https://hacg.meme/wp/category/all/game/">
<img src="res/b69be616c4f83786efc3faf36acab2ac.webp" alt="游戏 | 琉璃神社 ★ HACG.LA"></img>
</a>
<figcaption>琉璃神社</figcaption>
</figure>
<figure class="image">
<a href="https://blog.reimu.net/">
<img src="res/da51cdf90485ee7c90ffb613cb911bfe.webp" alt="灵梦御所 – 绅士的幻想乡"></img>
</a>
<figcaption>灵梦御所</figcaption>
</figure>
<figure class="image">
<a href="https://www.galzy.eu.org/">
<img src="res/3ef4974827e7894f71ea9bc9bf20c2a9.webp" alt="主页 | 紫缘社- Galgame资源站"></img>
</a>
<figcaption>紫缘社</figcaption>
</figure>
<figure class="image">
<a href="https://www.banbaog.com/">
<img src="res/ec5b7089407143629af1f4e633d941b0.webp" alt="梦幻星空电脑单机游戏下载-最新PC单机游戏下载,破解单机游戏下载 - 梦幻星空"></img>
</a>
<figcaption>梦幻星空</figcaption>
</figure>
<figure class="image">
<a href="https://spare.qingju.org/">
<img src="res/b3a10995eab4897215ab48370df82a95.webp" alt="青桔网-galgame免费分享平台"></img>
</a>
<figcaption>青桔网,百度云盘</figcaption>
</figure>
<figure class="image">
<a href="https://www.ymgal.games/">
<img src="res/92465a3a8ecd124c0170edac6ad0443a.webp" alt="月幕Galgame-最戳你XP的美少女游戏综合交流平台 | 来感受这绝妙的文艺体裁"></img>
</a>
<figcaption>月幕</figcaption>
</figure>
<figure class="image">
<a href="https://hmoe.top/">
<img src="res/f0e5e8251d4b7678ad4bd82cdb02511f.webp" alt="萌幻之乡"></img>
</a>
<figcaption>萌幻之乡</figcaption>
</figure>
<figure class="image">
<a href="https://www.touchgal.com">
<img src="res/5404300909bbfdc9cbf9c0ac9e9726f1.webp" alt="TouchGAL-一站式Galgame文化社区!"></img>
</a>
<figcaption>TouchGal</figcaption>
</figure>
<figure class="image">
<a href="https://www.acgnsq.com/">
<img src="res/414d3d342a1f381445df6d966036381b.webp" alt="ACGN社区"></img>
</a>
<figcaption>ACGN社区</figcaption>
</figure>
<figure class="image">
<a href="https://www.tianshie.com">
<img src="res/a46207b605878b31788c83e4cacb57ca.webp" alt="天使二次元 — 本站专注ACG,主攻Galgame,兼攻Comic,Anime。以汉化版Galgame为主,为未来Gal中文界培养生力军。"></img>
</a>
<figcaption>天使二次元</figcaption>
</figure>
<figure class="image">
<a href="https://moe.best/">
<img src="res/731d3781a6f594a6caea853df1012531.webp" alt="神代綺凛の随波逐流 - 平时都在不务正业些什么?有没有空?可以写多点文章吗?"></img>
</a>
<figcaption>神代綺凛の随波逐流</figcaption>
</figure>
<figure class="image">
<a href="https://galgamer.eu.org">
<img src="res/d0444cdec08d12f61d70b8c31044e08b.webp" alt="Galgamer"></img>
</a>
<figcaption>主要是介绍博客</figcaption>
</figure>
<figure class="image">
<a href="https://www.ryuugames.com/">
<img src="res/98b63ccf7ce07a629a3ff654a0626a05.webp" alt="Free Download Visual Novel Hentai Games Japanese (RAW) and English Translation - Ryuugames"></img>
</a>
<figcaption>RyuuGames,有官中和英翻</figcaption>
</figure>
<figure class="image">
<a href="https://www.mkwgame.com/">
<img src="res/afac9e68d200d2a878f0758dbce9b4d4.webp" alt="梦灵神社 – 梦之神灵 零梦初醒"></img>
</a>
<figcaption>梦灵神社</figcaption>
</figure>
<figure class="image">
<a href="https://www.vikacg.com/post">
<img src="res/51699cef745408b068c3329611365456.webp" alt="维咔VikACG[V站] - 肥宅们的欢乐家园"></img>
</a>
<figcaption>维咔VikACG</figcaption>
</figure>
<figure class="image">
<a href="https://shinnku.com/">
<img src="res/8eaaddd2f65b786478075c8dbeac6ede.webp" alt="失落小站 - galgame资源站"></img>
</a>
<figcaption>失落的小站</figcaption>
</figure>
<figure class="image">
<a href="https://bbs.sumisora.net/">
<img src="res/4fadefab4e3d7b121ab38f8a6f890600.webp" alt="『澄空学园』 GalGame专题网"></img>
</a>
<figcaption>澄空学园,BBS</figcaption>
</figure>
[](https://www.acgndog.com/)
[](https://south-plus.org/ )
|
0015/map_tiles
| 15,307 |
map_tiles.cpp
|
#include "map_tiles.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "esp_log.h"
#include "esp_heap_caps.h"
static const char* TAG = "map_tiles";
// Internal structure for map tiles instance
struct map_tiles_t {
// Configuration
char* base_path;
char* tile_folders[MAP_TILES_MAX_TYPES];
int tile_type_count;
int current_tile_type;
int grid_cols;
int grid_rows;
int tile_count;
int zoom;
bool use_spiram;
bool initialized;
// Tile management
int tile_x;
int tile_y;
int marker_offset_x;
int marker_offset_y;
bool tile_loading_error;
// Tile data - arrays will be allocated dynamically based on actual grid size
uint8_t** tile_bufs;
lv_image_dsc_t* tile_imgs;
};
map_tiles_handle_t map_tiles_init(const map_tiles_config_t* config)
{
if (!config || !config->base_path || config->tile_type_count <= 0 ||
config->tile_type_count > MAP_TILES_MAX_TYPES ||
config->default_tile_type < 0 || config->default_tile_type >= config->tile_type_count) {
ESP_LOGE(TAG, "Invalid configuration");
return NULL;
}
// Validate grid size - use defaults if not specified or invalid
int grid_cols = config->grid_cols;
int grid_rows = config->grid_rows;
if (grid_cols <= 0 || grid_cols > MAP_TILES_MAX_GRID_COLS) {
ESP_LOGW(TAG, "Invalid grid_cols %d, using default %d", grid_cols, MAP_TILES_DEFAULT_GRID_COLS);
grid_cols = MAP_TILES_DEFAULT_GRID_COLS;
}
if (grid_rows <= 0 || grid_rows > MAP_TILES_MAX_GRID_ROWS) {
ESP_LOGW(TAG, "Invalid grid_rows %d, using default %d", grid_rows, MAP_TILES_DEFAULT_GRID_ROWS);
grid_rows = MAP_TILES_DEFAULT_GRID_ROWS;
}
int tile_count = grid_cols * grid_rows;
// Validate that all tile folders are provided
for (int i = 0; i < config->tile_type_count; i++) {
if (!config->tile_folders[i]) {
ESP_LOGE(TAG, "Tile folder %d is NULL", i);
return NULL;
}
}
map_tiles_handle_t handle = (map_tiles_handle_t)calloc(1, sizeof(struct map_tiles_t));
if (!handle) {
ESP_LOGE(TAG, "Failed to allocate handle");
return NULL;
}
// Copy base path
handle->base_path = strdup(config->base_path);
if (!handle->base_path) {
ESP_LOGE(TAG, "Failed to allocate base path");
free(handle);
return NULL;
}
// Copy tile folder names
handle->tile_type_count = config->tile_type_count;
for (int i = 0; i < config->tile_type_count; i++) {
handle->tile_folders[i] = strdup(config->tile_folders[i]);
if (!handle->tile_folders[i]) {
ESP_LOGE(TAG, "Failed to allocate tile folder %d", i);
// Clean up previously allocated folders
for (int j = 0; j < i; j++) {
free(handle->tile_folders[j]);
}
free(handle->base_path);
free(handle);
return NULL;
}
}
handle->zoom = config->default_zoom;
handle->use_spiram = config->use_spiram;
handle->current_tile_type = config->default_tile_type;
handle->grid_cols = grid_cols;
handle->grid_rows = grid_rows;
handle->tile_count = tile_count;
handle->initialized = true;
handle->tile_loading_error = false;
// Initialize tile data - allocate arrays based on actual tile count
handle->tile_bufs = (uint8_t**)calloc(tile_count, sizeof(uint8_t*));
handle->tile_imgs = (lv_image_dsc_t*)calloc(tile_count, sizeof(lv_image_dsc_t));
if (!handle->tile_bufs || !handle->tile_imgs) {
ESP_LOGE(TAG, "Failed to allocate tile arrays");
// Clean up
if (handle->tile_bufs) free(handle->tile_bufs);
if (handle->tile_imgs) free(handle->tile_imgs);
for (int i = 0; i < handle->tile_type_count; i++) {
free(handle->tile_folders[i]);
}
free(handle->base_path);
free(handle);
return NULL;
}
ESP_LOGI(TAG, "Map tiles initialized with base path: %s, %d tile types, current type: %s, zoom: %d, grid: %dx%d",
handle->base_path, handle->tile_type_count,
handle->tile_folders[handle->current_tile_type], handle->zoom,
handle->grid_cols, handle->grid_rows);
return handle;
}
void map_tiles_set_zoom(map_tiles_handle_t handle, int zoom_level)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return;
}
handle->zoom = zoom_level;
ESP_LOGI(TAG, "Zoom level set to %d", zoom_level);
}
int map_tiles_get_zoom(map_tiles_handle_t handle)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return 0;
}
return handle->zoom;
}
bool map_tiles_set_tile_type(map_tiles_handle_t handle, int tile_type)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return false;
}
if (tile_type < 0 || tile_type >= handle->tile_type_count) {
ESP_LOGE(TAG, "Invalid tile type: %d (valid range: 0-%d)", tile_type, handle->tile_type_count - 1);
return false;
}
handle->current_tile_type = tile_type;
ESP_LOGI(TAG, "Tile type set to %d (%s)", tile_type, handle->tile_folders[tile_type]);
return true;
}
int map_tiles_get_tile_type(map_tiles_handle_t handle)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return -1;
}
return handle->current_tile_type;
}
int map_tiles_get_tile_type_count(map_tiles_handle_t handle)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return 0;
}
return handle->tile_type_count;
}
const char* map_tiles_get_tile_type_folder(map_tiles_handle_t handle, int tile_type)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return NULL;
}
if (tile_type < 0 || tile_type >= handle->tile_type_count) {
ESP_LOGE(TAG, "Invalid tile type: %d", tile_type);
return NULL;
}
return handle->tile_folders[tile_type];
}
bool map_tiles_load_tile(map_tiles_handle_t handle, int index, int tile_x, int tile_y)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return false;
}
if (index < 0 || index >= handle->tile_count) {
ESP_LOGE(TAG, "Invalid tile index: %d", index);
return false;
}
char path[256];
const char* folder = handle->tile_folders[handle->current_tile_type];
snprintf(path, sizeof(path), "%s/%s/%d/%d/%d.bin",
handle->base_path, folder, handle->zoom, tile_x, tile_y);
FILE *f = fopen(path, "rb");
if (!f) {
ESP_LOGW(TAG, "Tile not found: %s", path);
return false;
}
// Skip 12-byte header
fseek(f, 12, SEEK_SET);
// Allocate buffer if needed
if (!handle->tile_bufs[index]) {
uint32_t caps = handle->use_spiram ? (MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT) : MALLOC_CAP_DMA;
handle->tile_bufs[index] = (uint8_t*)heap_caps_malloc(
MAP_TILES_TILE_SIZE * MAP_TILES_TILE_SIZE * MAP_TILES_BYTES_PER_PIXEL, caps);
if (!handle->tile_bufs[index]) {
ESP_LOGE(TAG, "Tile %d: allocation failed", index);
fclose(f);
return false;
}
}
// Clear buffer
memset(handle->tile_bufs[index], 0,
MAP_TILES_TILE_SIZE * MAP_TILES_TILE_SIZE * MAP_TILES_BYTES_PER_PIXEL);
// Read tile data
size_t bytes_read = fread(handle->tile_bufs[index], 1,
MAP_TILES_TILE_SIZE * MAP_TILES_TILE_SIZE * MAP_TILES_BYTES_PER_PIXEL, f);
fclose(f);
if (bytes_read != MAP_TILES_TILE_SIZE * MAP_TILES_TILE_SIZE * MAP_TILES_BYTES_PER_PIXEL) {
ESP_LOGW(TAG, "Incomplete tile read: %zu bytes", bytes_read);
}
// Setup image descriptor
handle->tile_imgs[index].header.w = MAP_TILES_TILE_SIZE;
handle->tile_imgs[index].header.h = MAP_TILES_TILE_SIZE;
handle->tile_imgs[index].header.cf = MAP_TILES_COLOR_FORMAT;
handle->tile_imgs[index].header.stride = MAP_TILES_TILE_SIZE * MAP_TILES_BYTES_PER_PIXEL;
handle->tile_imgs[index].data = (const uint8_t*)handle->tile_bufs[index];
handle->tile_imgs[index].data_size = MAP_TILES_TILE_SIZE * MAP_TILES_TILE_SIZE * MAP_TILES_BYTES_PER_PIXEL;
handle->tile_imgs[index].reserved = NULL;
handle->tile_imgs[index].reserved_2 = NULL;
ESP_LOGD(TAG, "Loaded tile %d from %s", index, path);
return true;
}
void map_tiles_gps_to_tile_xy(map_tiles_handle_t handle, double lat, double lon, double* x, double* y)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return;
}
if (!x || !y) {
ESP_LOGE(TAG, "Invalid output parameters");
return;
}
double lat_rad = lat * M_PI / 180.0;
int n = 1 << handle->zoom;
*x = (lon + 180.0) / 360.0 * n;
*y = (1.0 - log(tan(lat_rad) + 1.0 / cos(lat_rad)) / M_PI) / 2.0 * n;
}
void map_tiles_tile_xy_to_gps(map_tiles_handle_t handle, double x, double y, double* lat, double* lon)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return;
}
if (!lat || !lon) {
ESP_LOGE(TAG, "Invalid output parameters");
return;
}
int n = 1 << handle->zoom;
*lon = x / n * 360.0 - 180.0;
double lat_rad = atan(sinh(M_PI * (1 - 2 * y / n)));
*lat = lat_rad * 180.0 / M_PI;
}
void map_tiles_get_center_gps(map_tiles_handle_t handle, double* lat, double* lon)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return;
}
if (!lat || !lon) {
ESP_LOGE(TAG, "Invalid output parameters");
return;
}
// Calculate center tile coordinates (center of the grid)
double center_x = handle->tile_x + handle->grid_cols / 2.0;
double center_y = handle->tile_y + handle->grid_rows / 2.0;
// Convert to GPS coordinates
map_tiles_tile_xy_to_gps(handle, center_x, center_y, lat, lon);
}
void map_tiles_set_center_from_gps(map_tiles_handle_t handle, double lat, double lon)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return;
}
double x, y;
map_tiles_gps_to_tile_xy(handle, lat, lon, &x, &y);
handle->tile_x = (int)x - handle->grid_cols / 2;
handle->tile_y = (int)y - handle->grid_rows / 2;
// Calculate pixel offset within the tile
handle->marker_offset_x = (int)((x - (int)x) * MAP_TILES_TILE_SIZE);
handle->marker_offset_y = (int)((y - (int)y) * MAP_TILES_TILE_SIZE);
ESP_LOGI(TAG, "GPS to tile: tile_x=%d, tile_y=%d, offset_x=%d, offset_y=%d",
handle->tile_x, handle->tile_y, handle->marker_offset_x, handle->marker_offset_y);
}
bool map_tiles_is_gps_within_tiles(map_tiles_handle_t handle, double lat, double lon)
{
if (!handle || !handle->initialized) {
return false;
}
double x, y;
map_tiles_gps_to_tile_xy(handle, lat, lon, &x, &y);
int gps_tile_x = (int)x;
int gps_tile_y = (int)y;
bool within_x = (gps_tile_x >= handle->tile_x && gps_tile_x < handle->tile_x + handle->grid_cols);
bool within_y = (gps_tile_y >= handle->tile_y && gps_tile_y < handle->tile_y + handle->grid_rows);
return within_x && within_y;
}
void map_tiles_get_position(map_tiles_handle_t handle, int* tile_x, int* tile_y)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return;
}
if (tile_x) *tile_x = handle->tile_x;
if (tile_y) *tile_y = handle->tile_y;
}
void map_tiles_set_position(map_tiles_handle_t handle, int tile_x, int tile_y)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return;
}
handle->tile_x = tile_x;
handle->tile_y = tile_y;
}
void map_tiles_get_marker_offset(map_tiles_handle_t handle, int* offset_x, int* offset_y)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return;
}
if (offset_x) *offset_x = handle->marker_offset_x;
if (offset_y) *offset_y = handle->marker_offset_y;
}
void map_tiles_set_marker_offset(map_tiles_handle_t handle, int offset_x, int offset_y)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return;
}
handle->marker_offset_x = offset_x;
handle->marker_offset_y = offset_y;
}
lv_image_dsc_t* map_tiles_get_image(map_tiles_handle_t handle, int index)
{
if (!handle || !handle->initialized || index < 0 || index >= handle->tile_count) {
return NULL;
}
return &handle->tile_imgs[index];
}
uint8_t* map_tiles_get_buffer(map_tiles_handle_t handle, int index)
{
if (!handle || !handle->initialized || index < 0 || index >= handle->tile_count) {
return NULL;
}
return handle->tile_bufs[index];
}
void map_tiles_set_loading_error(map_tiles_handle_t handle, bool error)
{
if (!handle || !handle->initialized) {
ESP_LOGE(TAG, "Handle not initialized");
return;
}
handle->tile_loading_error = error;
}
bool map_tiles_has_loading_error(map_tiles_handle_t handle)
{
if (!handle || !handle->initialized) {
return true;
}
return handle->tile_loading_error;
}
void map_tiles_cleanup(map_tiles_handle_t handle)
{
if (!handle) {
return;
}
if (handle->initialized) {
// Free tile buffers
if (handle->tile_bufs) {
for (int i = 0; i < handle->tile_count; i++) {
if (handle->tile_bufs[i]) {
heap_caps_free(handle->tile_bufs[i]);
handle->tile_bufs[i] = NULL;
}
}
free(handle->tile_bufs);
handle->tile_bufs = NULL;
}
// Free tile image descriptors array
if (handle->tile_imgs) {
free(handle->tile_imgs);
handle->tile_imgs = NULL;
}
handle->initialized = false;
ESP_LOGI(TAG, "Map tiles cleaned up");
}
// Free base path and folder names, then handle
if (handle->base_path) {
free(handle->base_path);
}
for (int i = 0; i < handle->tile_type_count; i++) {
if (handle->tile_folders[i]) {
free(handle->tile_folders[i]);
}
}
free(handle);
}
void map_tiles_get_grid_size(map_tiles_handle_t handle, int* cols, int* rows)
{
if (!handle || !handle->initialized || !cols || !rows) {
if (cols) *cols = 0;
if (rows) *rows = 0;
return;
}
*cols = handle->grid_cols;
*rows = handle->grid_rows;
}
int map_tiles_get_tile_count(map_tiles_handle_t handle)
{
if (!handle || !handle->initialized) {
return 0;
}
return handle->tile_count;
}
|
0015/map_tiles
| 5,525 |
script/lvgl_map_tile_converter.py
|
import os
import struct
import argparse
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from PIL import Image # pip install pillow
# No implicit defaults; these are set from CLI in main()
INPUT_ROOT = None
OUTPUT_ROOT = None
# Convert RGB to 16-bit RGB565
def to_rgb565(r, g, b):
return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3)
# Strip .png or .bin extensions
def clean_tile_name(filename):
name = filename
while True:
name, ext = os.path.splitext(name)
if ext.lower() not in [".png", ".bin", ".jpg", ".jpeg"]:
break
filename = name
return filename
# Create LVGL v9-compatible .bin image
def make_lvgl_bin(png_path, bin_path):
im = Image.open(png_path).convert("RGB")
w, h = im.size
pixels = im.load()
stride = (w * 16 + 7) // 8 # bytes per row (RGB565 = 16 bpp)
flags = 0x00 # no compression, no premult
color_format = 0x12 # RGB565
magic = 0x19
header = bytearray()
header += struct.pack("<B", magic)
header += struct.pack("<B", color_format)
header += struct.pack("<H", flags)
header += struct.pack("<H", w)
header += struct.pack("<H", h)
header += struct.pack("<H", stride)
header += struct.pack("<H", 0) # reserved
body = bytearray()
for y in range(h):
for x in range(w):
r, g, b = pixels[x, y]
rgb565 = to_rgb565(r, g, b)
body += struct.pack("<H", rgb565)
os.makedirs(os.path.dirname(bin_path), exist_ok=True)
if os.path.isdir(bin_path):
# In case a folder mistakenly exists where a file should
print(f"[Fix] Removing incorrect folder: {bin_path}")
os.rmdir(bin_path)
with open(bin_path, "wb") as f:
f.write(header)
f.write(body)
print(f"[OK] {png_path} → {bin_path}")
# Yield (input_path, output_path) pairs for all PNG tiles under INPUT_ROOT
def _iter_tile_paths():
for zoom in sorted(os.listdir(INPUT_ROOT)):
zoom_path = os.path.join(INPUT_ROOT, zoom)
if not os.path.isdir(zoom_path) or not zoom.isdigit():
continue
for x_tile in sorted(os.listdir(zoom_path)):
x_path = os.path.join(zoom_path, x_tile)
if not os.path.isdir(x_path) or not x_tile.isdigit():
continue
for y_file in sorted(os.listdir(x_path)):
if not y_file.lower().endswith(".png"):
continue
tile_base = clean_tile_name(y_file)
input_path = os.path.join(INPUT_ROOT, zoom, x_tile, y_file)
output_path = os.path.join(OUTPUT_ROOT, zoom, x_tile, f"{tile_base}.bin")
yield input_path, output_path
def convert_all_tiles(jobs=1, force=False):
"""
Convert tiles with optional threading.
- jobs: number of worker threads (>=1)
- force: if True, re-generate even if output exists
"""
if not os.path.isdir(INPUT_ROOT):
print(f"[ERROR] '{INPUT_ROOT}' not found.")
return
# Build task list (skip existing unless --force)
tasks = []
for input_path, output_path in _iter_tile_paths():
if not force and os.path.isfile(output_path):
print(f"[Skip] {output_path}")
continue
tasks.append((input_path, output_path))
if not tasks:
print("[INFO] Nothing to do.")
return
print(f"[INFO] Converting {len(tasks)} tiles with {jobs} thread(s)...")
if jobs <= 1:
# Serial path
for inp, outp in tasks:
try:
make_lvgl_bin(inp, outp)
except Exception as e:
print(f"[Error] Failed to convert {inp} → {e}")
return
# Threaded path
print_lock = threading.Lock()
with ThreadPoolExecutor(max_workers=jobs) as ex:
future_map = {ex.submit(make_lvgl_bin, inp, outp): (inp, outp) for inp, outp in tasks}
for fut in as_completed(future_map):
inp, outp = future_map[fut]
try:
fut.result()
except Exception as e:
with print_lock:
print(f"[Error] Failed to convert {inp} → {e}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Convert OSM PNG tiles into LVGL-friendly .bin files (RGB565).",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"-i", "--input",
required=True,
default=argparse.SUPPRESS, # hide '(default: None)'
help="Input root folder containing tiles in zoom/x/y.png structure",
)
parser.add_argument(
"-o", "--output",
required=True,
default=argparse.SUPPRESS, # hide '(default: None)'
help="Output root folder where .bin tiles will be written",
)
parser.add_argument(
"-j", "--jobs",
type=int,
default=os.cpu_count(),
help="Number of worker threads",
)
parser.add_argument(
"-f", "--force",
action="store_true",
help="Rebuild even if output file already exists",
)
args = parser.parse_args()
# Basic checks
if not os.path.isdir(args.input):
parser.error(f"Input folder not found or not a directory: {args.input}")
os.makedirs(args.output, exist_ok=True)
# Apply CLI values
INPUT_ROOT = args.input
OUTPUT_ROOT = args.output
convert_all_tiles(jobs=max(1, args.jobs), force=args.force)
|
0015/map_tiles
| 2,451 |
script/README.md
|
# **LVGL Map Tile Converter**
This Python script is designed to convert a directory of PNG map tiles into a format compatible with LVGL (Light and Versatile Graphics Library) version 9\. The output is a series of binary files (.bin) with a header and pixel data in the RGB565 format, optimized for direct use with LVGL's image APIs.
The script is multithreaded and can significantly speed up the conversion process for large tile sets.
## **Features**
* **PNG to RGB565 Conversion**: Converts standard 24-bit PNG images into 16-bit RGB565.
* **LVGL v9 Compatibility**: Generates a .bin file with the correct LVGL v9 header format.
* **Multithreaded Conversion**: Utilizes a ThreadPoolExecutor to process tiles in parallel, configurable with the \--jobs flag.
* **Directory Traversal**: Automatically finds and converts all .png files within a specified input directory structure.
* **Skip Existing Files**: Skips conversion for tiles that already exist in the output directory unless the \--force flag is used.
## **Requirements**
The script requires the Pillow library to handle image processing. You can install it using pip:
```bash
pip install Pillow
```
## **Usage**
The script is a command-line tool. You can run it from your terminal with the following arguments:
```bash
python lvgl_map_tile_converter.py --input <input_folder> --output <output_folder> [options]
```
### **Arguments**
* \-i, \--input: **Required**. The root folder containing your map tiles. The script expects a tile structure like zoom/x/y.png.
* \-o, \--output: **Required**. The root folder where the converted .bin tiles will be saved. The output structure will mirror the input: zoom/x/y.bin.
* \-j, \--jobs: **Optional**. The number of worker threads to use for the conversion. Defaults to the number of CPU cores on your system. Using more jobs can speed up the process.
* \-f, \--force: **Optional**. If this flag is set, the script will re-convert all tiles, even if the output .bin files already exist.
### **Examples**
**1\. Basic conversion with default settings:**
```bash
python lvgl_map_tile_converter.py --input ./map_tiles --output ./tiles1
```
**2\. Conversion using a specific number of threads (e.g., 8):**
```bash
python lvgl_map_tile_converter.py --input ./map_tiles --output ./tiles1 --jobs 8
```
**3\. Forcing a full re-conversion:**
```bash
python lvgl_map_tile_converter.py --input ./map_tiles --output ./tiles1 --force
```
|
0015/map_tiles
| 8,744 |
examples/basic_map_display.c
|
#include "map_tiles.h"
#include "lvgl.h"
#include "esp_log.h"
static const char* TAG = "map_example";
// Map tiles handle
static map_tiles_handle_t map_handle = NULL;
// LVGL objects for displaying tiles
static lv_obj_t* map_container = NULL;
static lv_obj_t** tile_images = NULL; // Dynamic array for configurable grid
static int grid_cols = 0, grid_rows = 0, tile_count = 0;
/**
* @brief Initialize the map display
*/
void map_display_init(void)
{
// Configure map tiles with multiple tile types and custom grid size
const char* tile_folders[] = {"street_map", "satellite", "terrain", "hybrid"};
map_tiles_config_t config = {
.base_path = "/sdcard",
.tile_folders = {tile_folders[0], tile_folders[1], tile_folders[2], tile_folders[3]},
.tile_type_count = 4,
.default_zoom = 10,
.use_spiram = true,
.default_tile_type = 0, // Start with street map
.grid_cols = 5, // 5x5 grid (configurable)
.grid_rows = 5
};
// Initialize map tiles
map_handle = map_tiles_init(&config);
if (!map_handle) {
ESP_LOGE(TAG, "Failed to initialize map tiles");
return;
}
// Get grid dimensions
map_tiles_get_grid_size(map_handle, &grid_cols, &grid_rows);
tile_count = map_tiles_get_tile_count(map_handle);
// Allocate tile images array
tile_images = malloc(tile_count * sizeof(lv_obj_t*));
if (!tile_images) {
ESP_LOGE(TAG, "Failed to allocate tile images array");
map_tiles_cleanup(map_handle);
return;
}
// Create map container
map_container = lv_obj_create(lv_screen_active());
lv_obj_set_size(map_container,
grid_cols * MAP_TILES_TILE_SIZE,
grid_rows * MAP_TILES_TILE_SIZE);
lv_obj_center(map_container);
lv_obj_set_style_pad_all(map_container, 0, 0);
lv_obj_set_style_border_width(map_container, 0, 0);
// Create image widgets for each tile
for (int i = 0; i < tile_count; i++) {
tile_images[i] = lv_image_create(map_container);
// Position tile in grid
int row = i / grid_cols;
int col = i % grid_cols;
lv_obj_set_pos(tile_images[i],
col * MAP_TILES_TILE_SIZE,
row * MAP_TILES_TILE_SIZE);
lv_obj_set_size(tile_images[i], MAP_TILES_TILE_SIZE, MAP_TILES_TILE_SIZE);
}
ESP_LOGI(TAG, "Map display initialized");
}
/**
* @brief Load and display map tiles for a GPS location
*
* @param lat Latitude in degrees
* @param lon Longitude in degrees
*/
void map_display_load_location(double lat, double lon)
{
if (!map_handle) {
ESP_LOGE(TAG, "Map not initialized");
return;
}
ESP_LOGI(TAG, "Loading map for GPS: %.6f, %.6f", lat, lon);
// Set center from GPS coordinates
map_tiles_set_center_from_gps(map_handle, lat, lon);
// Get current tile position
int base_tile_x, base_tile_y;
map_tiles_get_position(map_handle, &base_tile_x, &base_tile_y);
// Load tiles in a configurable grid
for (int row = 0; row < grid_rows; row++) {
for (int col = 0; col < grid_cols; col++) {
int index = row * grid_cols + col;
int tile_x = base_tile_x + col;
int tile_y = base_tile_y + row;
// Load the tile
bool loaded = map_tiles_load_tile(map_handle, index, tile_x, tile_y);
if (loaded) {
// Update the image widget
lv_image_dsc_t* img_dsc = map_tiles_get_image(map_handle, index);
if (img_dsc) {
lv_image_set_src(tile_images[index], img_dsc);
ESP_LOGD(TAG, "Loaded tile %d (%d, %d)", index, tile_x, tile_y);
}
} else {
ESP_LOGW(TAG, "Failed to load tile %d (%d, %d)", index, tile_x, tile_y);
// Set a placeholder or clear the image
lv_image_set_src(tile_images[index], NULL);
}
}
}
ESP_LOGI(TAG, "Map tiles loaded for location");
}
/**
* @brief Set the map tile type and reload tiles
*
* @param tile_type Tile type index (0=street, 1=satellite, 2=terrain, 3=hybrid)
* @param lat Current latitude
* @param lon Current longitude
*/
void map_display_set_tile_type(int tile_type, double lat, double lon)
{
if (!map_handle) {
ESP_LOGE(TAG, "Map not initialized");
return;
}
// Validate tile type
int max_types = map_tiles_get_tile_type_count(map_handle);
if (tile_type < 0 || tile_type >= max_types) {
ESP_LOGW(TAG, "Invalid tile type %d (valid range: 0-%d)", tile_type, max_types - 1);
return;
}
ESP_LOGI(TAG, "Setting tile type to %d (%s)", tile_type,
map_tiles_get_tile_type_folder(map_handle, tile_type));
// Set tile type
if (map_tiles_set_tile_type(map_handle, tile_type)) {
// Reload tiles for the new type
map_display_load_location(lat, lon);
}
}
/**
* @brief Set the zoom level and reload tiles
*
* @param zoom New zoom level
* @param lat Current latitude
* @param lon Current longitude
*/
void map_display_set_zoom(int zoom, double lat, double lon)
{
if (!map_handle) {
ESP_LOGE(TAG, "Map not initialized");
return;
}
ESP_LOGI(TAG, "Setting zoom to %d", zoom);
// Update zoom level
map_tiles_set_zoom(map_handle, zoom);
// Reload tiles for the new zoom level
map_display_load_location(lat, lon);
}
/**
* @brief Add a GPS marker to the map
*
* @param lat Latitude in degrees
* @param lon Longitude in degrees
*/
void map_display_add_marker(double lat, double lon)
{
if (!map_handle) {
ESP_LOGE(TAG, "Map not initialized");
return;
}
// Check if GPS position is within current tiles
if (!map_tiles_is_gps_within_tiles(map_handle, lat, lon)) {
ESP_LOGW(TAG, "GPS position outside current tiles, reloading map");
map_display_load_location(lat, lon);
return;
}
// Get marker offset within the current tile grid
int offset_x, offset_y;
map_tiles_get_marker_offset(map_handle, &offset_x, &offset_y);
// Create or update marker object
static lv_obj_t* marker = NULL;
if (!marker) {
marker = lv_obj_create(map_container);
lv_obj_set_size(marker, 10, 10);
lv_obj_set_style_bg_color(marker, lv_color_hex(0xFF0000), 0);
lv_obj_set_style_radius(marker, 5, 0);
lv_obj_set_style_border_width(marker, 1, 0);
lv_obj_set_style_border_color(marker, lv_color_hex(0xFFFFFF), 0);
}
// Position marker based on GPS offset
int center_tile_col = grid_cols / 2;
int center_tile_row = grid_rows / 2;
int marker_x = center_tile_col * MAP_TILES_TILE_SIZE + offset_x - 5;
int marker_y = center_tile_row * MAP_TILES_TILE_SIZE + offset_y - 5;
lv_obj_set_pos(marker, marker_x, marker_y);
ESP_LOGI(TAG, "GPS marker positioned at (%d, %d)", marker_x, marker_y);
}
/**
* @brief Clean up map display resources
*/
void map_display_cleanup(void)
{
if (tile_images) {
free(tile_images);
tile_images = NULL;
}
if (map_handle) {
map_tiles_cleanup(map_handle);
map_handle = NULL;
}
if (map_container) {
lv_obj_delete(map_container);
map_container = NULL;
}
grid_cols = grid_rows = tile_count = 0;
ESP_LOGI(TAG, "Map display cleaned up");
}
/**
* @brief Example usage in main application
*/
void app_main(void)
{
// Initialize LVGL and display driver first...
// Initialize map display
map_display_init();
// Load map for San Francisco
double lat = 37.7749;
double lon = -122.4194;
map_display_load_location(lat, lon);
// Add GPS marker
map_display_add_marker(lat, lon);
// Example: Change to satellite view (tile type 1)
// map_display_set_tile_type(1, lat, lon);
// Example: Change to terrain view (tile type 2)
// map_display_set_tile_type(2, lat, lon);
// Example: Change zoom level
// map_display_set_zoom(12, lat, lon);
// Example: Update GPS position
// map_display_add_marker(37.7849, -122.4094);
// NOTE: To use different grid sizes, modify the grid_cols and grid_rows
// in the config structure above. Examples:
// - 3x3 grid: .grid_cols = 3, .grid_rows = 3 (9 tiles, ~1.1MB RAM)
// - 5x5 grid: .grid_cols = 5, .grid_rows = 5 (25 tiles, ~3.1MB RAM)
// - 7x7 grid: .grid_cols = 7, .grid_rows = 7 (49 tiles, ~6.1MB RAM)
}
|
0015/map_tiles
| 7,960 |
include/map_tiles.h
|
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include "lvgl.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Map tiles component for LVGL 9.x
*
* This component provides functionality to load and display map tiles with GPS coordinate conversion.
* Tiles are assumed to be 256x256 pixels in RGB565 format, stored in binary files.
*/
// Constants
#define MAP_TILES_TILE_SIZE 256
#define MAP_TILES_DEFAULT_GRID_COLS 5
#define MAP_TILES_DEFAULT_GRID_ROWS 5
#define MAP_TILES_MAX_GRID_COLS 9
#define MAP_TILES_MAX_GRID_ROWS 9
#define MAP_TILES_MAX_TILES (MAP_TILES_MAX_GRID_COLS * MAP_TILES_MAX_GRID_ROWS)
#define MAP_TILES_BYTES_PER_PIXEL 2
#define MAP_TILES_COLOR_FORMAT LV_COLOR_FORMAT_RGB565
#define MAP_TILES_MAX_TYPES 8
#define MAP_TILES_MAX_FOLDER_NAME 32
/**
* @brief Configuration structure for map tiles
*/
typedef struct {
const char* base_path; /**< Base path where tiles are stored (e.g., "/sdcard") */
const char* tile_folders[MAP_TILES_MAX_TYPES]; /**< Array of folder names for different tile types */
int tile_type_count; /**< Number of tile types configured */
int grid_cols; /**< Number of tile columns (default: 5, max: 9) */
int grid_rows; /**< Number of tile rows (default: 5, max: 9) */
int default_zoom; /**< Default zoom level */
bool use_spiram; /**< Whether to use SPIRAM for tile buffers */
int default_tile_type; /**< Default tile type index (0 to tile_type_count-1) */
} map_tiles_config_t;
/**
* @brief Map tiles handle
*/
typedef struct map_tiles_t* map_tiles_handle_t;
/**
* @brief Initialize the map tiles system
*
* @param config Configuration structure
* @return map_tiles_handle_t Handle to the map tiles instance, NULL on failure
*/
map_tiles_handle_t map_tiles_init(const map_tiles_config_t* config);
/**
* @brief Set the zoom level
*
* @param handle Map tiles handle
* @param zoom_level Zoom level (typically 0-18)
*/
void map_tiles_set_zoom(map_tiles_handle_t handle, int zoom_level);
/**
* @brief Get the current zoom level
*
* @param handle Map tiles handle
* @return Current zoom level
*/
int map_tiles_get_zoom(map_tiles_handle_t handle);
/**
* @brief Set tile type
*
* @param handle Map tiles handle
* @param tile_type Tile type index (0 to configured tile_type_count-1)
* @return true if tile type was set successfully, false otherwise
*/
bool map_tiles_set_tile_type(map_tiles_handle_t handle, int tile_type);
/**
* @brief Get current tile type
*
* @param handle Map tiles handle
* @return Current tile type index, -1 if error
*/
int map_tiles_get_tile_type(map_tiles_handle_t handle);
/**
* @brief Get grid dimensions
*
* @param handle Map tiles handle
* @param cols Output grid columns (can be NULL)
* @param rows Output grid rows (can be NULL)
*/
void map_tiles_get_grid_size(map_tiles_handle_t handle, int* cols, int* rows);
/**
* @brief Get total tile count for current grid
*
* @param handle Map tiles handle
* @return Total number of tiles in the grid, 0 if error
*/
int map_tiles_get_tile_count(map_tiles_handle_t handle);
/**
* @brief Get tile type count
*
* @param handle Map tiles handle
* @return Number of configured tile types, 0 if error
*/
int map_tiles_get_tile_type_count(map_tiles_handle_t handle);
/**
* @brief Get tile type folder name
*
* @param handle Map tiles handle
* @param tile_type Tile type index
* @return Folder name for the tile type, NULL if invalid
*/
const char* map_tiles_get_tile_type_folder(map_tiles_handle_t handle, int tile_type);
/**
* @brief Load a specific tile dynamically
*
* @param handle Map tiles handle
* @param index Tile index (0 to total_tile_count-1)
* @param tile_x Tile X coordinate
* @param tile_y Tile Y coordinate
* @return true if tile loaded successfully, false otherwise
*/
bool map_tiles_load_tile(map_tiles_handle_t handle, int index, int tile_x, int tile_y);
/**
* @brief Convert GPS coordinates to tile coordinates
*
* @param handle Map tiles handle
* @param lat Latitude in degrees
* @param lon Longitude in degrees
* @param x Output tile X coordinate
* @param y Output tile Y coordinate
*/
void map_tiles_gps_to_tile_xy(map_tiles_handle_t handle, double lat, double lon, double* x, double* y);
/**
* @brief Convert tile coordinates to GPS coordinates
*
* @param handle Map tiles handle
* @param x Tile X coordinate
* @param y Tile Y coordinate
* @param lat Output latitude in degrees
* @param lon Output longitude in degrees
*/
void map_tiles_tile_xy_to_gps(map_tiles_handle_t handle, double x, double y, double* lat, double* lon);
/**
* @brief Get center GPS coordinates of current map view
*
* @param handle Map tiles handle
* @param lat Output latitude in degrees
* @param lon Output longitude in degrees
*/
void map_tiles_get_center_gps(map_tiles_handle_t handle, double* lat, double* lon);
/**
* @brief Set the tile center from GPS coordinates
*
* @param handle Map tiles handle
* @param lat Latitude in degrees
* @param lon Longitude in degrees
*/
void map_tiles_set_center_from_gps(map_tiles_handle_t handle, double lat, double lon);
/**
* @brief Check if GPS coordinates are within current tile grid
*
* @param handle Map tiles handle
* @param lat Latitude in degrees
* @param lon Longitude in degrees
* @return true if GPS position is within current tiles, false otherwise
*/
bool map_tiles_is_gps_within_tiles(map_tiles_handle_t handle, double lat, double lon);
/**
* @brief Get current tile position
*
* @param handle Map tiles handle
* @param tile_x Output tile X coordinate (can be NULL)
* @param tile_y Output tile Y coordinate (can be NULL)
*/
void map_tiles_get_position(map_tiles_handle_t handle, int* tile_x, int* tile_y);
/**
* @brief Set tile position
*
* @param handle Map tiles handle
* @param tile_x Tile X coordinate
* @param tile_y Tile Y coordinate
*/
void map_tiles_set_position(map_tiles_handle_t handle, int tile_x, int tile_y);
/**
* @brief Get marker offset within the current tile
*
* @param handle Map tiles handle
* @param offset_x Output X offset in pixels (can be NULL)
* @param offset_y Output Y offset in pixels (can be NULL)
*/
void map_tiles_get_marker_offset(map_tiles_handle_t handle, int* offset_x, int* offset_y);
/**
* @brief Set marker offset within the current tile
*
* @param handle Map tiles handle
* @param offset_x X offset in pixels
* @param offset_y Y offset in pixels
*/
void map_tiles_set_marker_offset(map_tiles_handle_t handle, int offset_x, int offset_y);
/**
* @brief Get tile image descriptor
*
* @param handle Map tiles handle
* @param index Tile index (0 to total_tile_count-1)
* @return Pointer to LVGL image descriptor, NULL if invalid
*/
lv_image_dsc_t* map_tiles_get_image(map_tiles_handle_t handle, int index);
/**
* @brief Get tile buffer
*
* @param handle Map tiles handle
* @param index Tile index (0 to total_tile_count-1)
* @return Pointer to tile buffer, NULL if invalid
*/
uint8_t* map_tiles_get_buffer(map_tiles_handle_t handle, int index);
/**
* @brief Set tile loading error state
*
* @param handle Map tiles handle
* @param error Error state
*/
void map_tiles_set_loading_error(map_tiles_handle_t handle, bool error);
/**
* @brief Check if there's a tile loading error
*
* @param handle Map tiles handle
* @return true if there's an error, false otherwise
*/
bool map_tiles_has_loading_error(map_tiles_handle_t handle);
/**
* @brief Clean up and free map tiles resources
*
* @param handle Map tiles handle
*/
void map_tiles_cleanup(map_tiles_handle_t handle);
#ifdef __cplusplus
}
#endif
|
000haoji/deep-student
| 31,459 |
src-tauri/src/models.rs
|
use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};
use std::fmt;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatMessage {
pub role: String, // "user" 或 "assistant"
pub content: String,
pub timestamp: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thinking_content: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rag_sources: Option<Vec<RagSourceInfo>>,
// 🎯 修复BUG-05:新增图片字段支持多模态对话
#[serde(default, skip_serializing_if = "Option::is_none")]
pub image_paths: Option<Vec<String>>, // 用户消息中包含的图片路径
#[serde(default, skip_serializing_if = "Option::is_none")]
pub image_base64: Option<Vec<String>>, // 备用:base64编码的图片数据
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RagSourceInfo {
pub document_id: String,
pub file_name: String,
pub chunk_text: String,
pub score: f32,
pub chunk_index: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MistakeItem {
pub id: String,
pub subject: String,
pub created_at: DateTime<Utc>,
pub question_images: Vec<String>, // 本地存储路径
pub analysis_images: Vec<String>, // 本地存储路径
pub user_question: String,
pub ocr_text: String,
pub tags: Vec<String>,
pub mistake_type: String,
pub status: String, // "analyzing", "completed", "error", "summary_required"
pub updated_at: DateTime<Utc>,
pub chat_history: Vec<ChatMessage>,
// 新增字段:用于回顾分析的结构化总结
pub mistake_summary: Option<String>, // 错题简要解析:题目要点、正确解法、关键知识点
pub user_error_analysis: Option<String>, // 用户错误分析:错误原因、思维误区、薄弱点总结
}
#[derive(Debug, Deserialize)]
pub struct AnalysisRequest {
pub subject: String,
pub question_image_files: Vec<String>, // base64编码的图片
pub analysis_image_files: Vec<String>, // base64编码的图片
pub user_question: String,
#[serde(default)]
pub enable_chain_of_thought: bool, // 是否启用思维链
}
// 回顾分析数据库表 - 复用错题分析结构但保留特殊性
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReviewAnalysisItem {
pub id: String, // 回顾分析ID
pub name: String, // 分析会话名称
pub subject: String, // 科目(继承自关联错题)
pub created_at: DateTime<Utc>, // 创建时间
pub updated_at: DateTime<Utc>, // 更新时间
pub mistake_ids: Vec<String>, // 关联的错题ID列表(特殊性)
pub consolidated_input: String, // 合并后的输入内容(特殊性)
pub user_question: String, // 用户问题描述
pub status: String, // "analyzing", "completed", "error"
pub chat_history: Vec<ChatMessage>, // 聊天历史(复用通用结构)
// 扩展字段
pub tags: Vec<String>, // 分析标签
pub analysis_type: String, // 分析类型:"consolidated_review"
}
#[derive(Debug, Serialize)]
pub struct AnalysisResponse {
pub temp_id: String,
pub initial_data: InitialAnalysisData,
}
#[derive(Debug, Serialize)]
pub struct InitialAnalysisData {
pub ocr_text: String,
pub tags: Vec<String>,
pub mistake_type: String,
pub first_answer: String,
}
#[derive(Debug, Deserialize)]
pub struct ContinueChatRequest {
pub temp_id: String,
pub chat_history: Vec<ChatMessage>,
pub enable_chain_of_thought: Option<bool>,
}
#[derive(Debug, Serialize)]
pub struct ContinueChatResponse {
pub new_assistant_message: String,
}
#[derive(Debug, Deserialize)]
pub struct SaveMistakeRequest {
pub temp_id: String,
pub final_chat_history: Vec<ChatMessage>,
}
#[derive(Debug, Serialize)]
pub struct SaveMistakeResponse {
pub success: bool,
pub final_mistake_item: Option<MistakeItem>,
}
// 回顾分析相关结构
#[derive(Debug, Serialize)]
pub struct ReviewSessionResponse {
pub review_id: String,
pub analysis_summary: String,
pub chat_history: Option<Vec<ChatMessage>>,
}
#[derive(Debug, Deserialize)]
pub struct ReviewChatRequest {
pub review_id: String,
pub new_message: ChatMessage,
pub chat_history: Vec<ChatMessage>,
}
#[derive(Debug, Serialize)]
pub struct ReviewChatResponse {
pub new_assistant_message: String,
pub chain_of_thought_details: Option<serde_json::Value>,
}
// 回顾分析会话数据结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReviewSession {
pub id: String,
pub subject: String,
pub mistake_ids: Vec<String>,
pub analysis_summary: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub chat_history: Vec<ReviewChatMessage>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReviewChatMessage {
pub id: String,
pub session_id: String,
pub role: String, // "user" 或 "assistant"
pub content: String,
pub timestamp: DateTime<Utc>,
}
// 结构化错误处理
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AppErrorType {
Validation,
Database,
LLM,
FileSystem,
NotFound,
Configuration,
Network,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppError {
pub error_type: AppErrorType,
pub message: String,
pub details: Option<serde_json::Value>,
}
impl AppError {
pub fn new(error_type: AppErrorType, message: impl Into<String>) -> Self {
Self {
error_type,
message: message.into(),
details: None,
}
}
pub fn with_details(error_type: AppErrorType, message: impl Into<String>, details: serde_json::Value) -> Self {
Self {
error_type,
message: message.into(),
details: Some(details),
}
}
pub fn validation(message: impl Into<String>) -> Self {
Self::new(AppErrorType::Validation, message)
}
pub fn database(message: impl Into<String>) -> Self {
Self::new(AppErrorType::Database, message)
}
pub fn llm(message: impl Into<String>) -> Self {
Self::new(AppErrorType::LLM, message)
}
pub fn file_system(message: impl Into<String>) -> Self {
Self::new(AppErrorType::FileSystem, message)
}
pub fn not_found(message: impl Into<String>) -> Self {
Self::new(AppErrorType::NotFound, message)
}
pub fn configuration(message: impl Into<String>) -> Self {
Self::new(AppErrorType::Configuration, message)
}
pub fn network(message: impl Into<String>) -> Self {
Self::new(AppErrorType::Network, message)
}
pub fn unknown(message: impl Into<String>) -> Self {
Self::new(AppErrorType::Unknown, message)
}
}
// 为AppError实现From trait以支持自动转换
impl From<String> for AppError {
fn from(message: String) -> Self {
AppError::validation(message)
}
}
impl From<&str> for AppError {
fn from(message: &str) -> Self {
AppError::validation(message.to_string())
}
}
// 实现Display trait
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.message)
}
}
// 实现Error trait
impl std::error::Error for AppError {}
// 实现从其他错误类型的转换
impl From<zip::result::ZipError> for AppError {
fn from(err: zip::result::ZipError) -> Self {
AppError::file_system(format!("ZIP操作错误: {}", err))
}
}
impl From<anyhow::Error> for AppError {
fn from(err: anyhow::Error) -> Self {
AppError::unknown(err.to_string())
}
}
impl From<serde_json::Error> for AppError {
fn from(err: serde_json::Error) -> Self {
AppError::validation(format!("JSON序列化错误: {}", err))
}
}
impl From<std::io::Error> for AppError {
fn from(err: std::io::Error) -> Self {
AppError::file_system(format!("文件系统错误: {}", err))
}
}
// 新增:错题总结生成相关结构
#[derive(Debug, Deserialize)]
pub struct GenerateMistakeSummaryRequest {
pub mistake_id: String,
pub force_regenerate: Option<bool>, // 是否强制重新生成总结
}
#[derive(Debug, Serialize)]
pub struct GenerateMistakeSummaryResponse {
pub success: bool,
pub mistake_summary: Option<String>,
pub user_error_analysis: Option<String>,
pub error_message: Option<String>,
}
// anyhow 会自动为实现了 std::error::Error 的类型提供转换
// 统一AI接口的输出结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StandardModel1Output {
pub ocr_text: String,
pub tags: Vec<String>,
pub mistake_type: String,
pub raw_response: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StandardModel2Output {
pub assistant_message: String,
pub raw_response: Option<String>,
pub chain_of_thought_details: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreamChunk {
pub content: String,
pub is_complete: bool,
pub chunk_id: String,
}
// 模型分配结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelAssignments {
pub model1_config_id: Option<String>,
pub model2_config_id: Option<String>,
pub review_analysis_model_config_id: Option<String>, // 回顾分析模型配置ID
pub anki_card_model_config_id: Option<String>, // 新增: ANKI制卡模型配置ID
pub embedding_model_config_id: Option<String>, // 新增: 第五模型(嵌入模型)配置ID
pub reranker_model_config_id: Option<String>, // 新增: 第六模型(重排序模型)配置ID
pub summary_model_config_id: Option<String>, // 新增: 总结模型配置ID
}
#[derive(Debug, Deserialize)]
pub struct ReviewAnalysisRequest {
pub subject: String,
pub mistake_ids: Vec<String>,
}
#[derive(Debug, Serialize)]
pub struct Statistics {
pub total_mistakes: i32,
pub total_reviews: i32,
pub subject_stats: std::collections::HashMap<String, i32>,
pub type_stats: std::collections::HashMap<String, i32>,
pub tag_stats: std::collections::HashMap<String, i32>,
pub recent_mistakes: Vec<serde_json::Value>,
}
#[derive(Debug, Deserialize)]
pub struct StartStreamingAnswerRequest {
pub temp_id: String,
pub enable_chain_of_thought: bool,
}
// 科目配置系统相关结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubjectConfig {
pub id: String,
pub subject_name: String,
pub display_name: String,
pub description: String,
pub is_enabled: bool,
pub prompts: SubjectPrompts,
pub mistake_types: Vec<String>,
pub default_tags: Vec<String>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubjectPrompts {
pub analysis_prompt: String, // 错题分析提示词
pub review_prompt: String, // 回顾分析提示词
pub chat_prompt: String, // 对话追问提示词
pub ocr_prompt: String, // OCR识别提示词
pub classification_prompt: String, // 分类标记提示词
pub consolidated_review_prompt: String, // 统一回顾分析提示词
pub anki_generation_prompt: String, // 新增: ANKI制卡提示词
}
// 默认的科目配置模板
impl Default for SubjectPrompts {
fn default() -> Self {
Self {
analysis_prompt: "请仔细分析这道{subject}错题,提供详细的解题思路和知识点讲解。".to_string(),
review_prompt: "请分析这些{subject}错题的共同问题和改进建议。".to_string(),
chat_prompt: "基于这道{subject}题目,请回答学生的问题。".to_string(),
ocr_prompt: "请识别这张{subject}题目图片中的文字内容。".to_string(),
classification_prompt: "请分析这道{subject}题目的类型和相关知识点标签。".to_string(),
consolidated_review_prompt: "你是一个资深{subject}老师,请仔细阅读以下学生提交的多道错题的详细信息(包括题目原文、原始提问和历史交流)。请基于所有这些信息,对学生提出的总体回顾问题进行全面、深入的分析和解答。请注意识别错题间的关联,总结共性问题,并给出针对性的学习建议。".to_string(),
anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。请创建多样化的卡片类型,包括概念定义、要点列举、关系分析等。每张卡片应包含:\n- front(正面):简洁明确的问题或概念名\n- back(背面):详细准确的答案或解释\n- tags(标签):相关的知识点标签\n\n请以JSON数组格式返回结果,每个对象包含 front、back、tags 三个字段。示例格式:[{\"front\": \"什么是...?\", \"back\": \"...的定义是...\", \"tags\": [\"概念\", \"定义\"]}]".to_string(),
}
}
}
#[derive(Debug, Deserialize)]
pub struct CreateSubjectConfigRequest {
pub subject_name: String,
pub display_name: String,
pub description: Option<String>,
pub prompts: Option<SubjectPrompts>,
pub mistake_types: Option<Vec<String>>,
pub default_tags: Option<Vec<String>>,
}
#[derive(Debug, Deserialize)]
pub struct UpdateSubjectConfigRequest {
pub id: String,
pub display_name: Option<String>,
pub description: Option<String>,
pub is_enabled: Option<bool>,
pub prompts: Option<SubjectPrompts>,
pub mistake_types: Option<Vec<String>>,
pub default_tags: Option<Vec<String>>,
}
// 回顾分析相关的新结构
#[derive(Debug, Deserialize)]
pub struct StartConsolidatedReviewAnalysisRequest {
pub subject: String,
pub consolidated_input: String,
pub overall_prompt: String,
pub enable_chain_of_thought: bool,
pub mistake_ids: Vec<String>, // 参与回顾分析的错题ID列表
}
#[derive(Debug, Serialize)]
pub struct StartConsolidatedReviewAnalysisResponse {
pub review_session_id: String,
}
#[derive(Debug, Deserialize)]
pub struct TriggerConsolidatedReviewStreamRequest {
pub review_session_id: String,
pub enable_chain_of_thought: bool,
}
#[derive(Debug, Deserialize)]
pub struct ContinueConsolidatedReviewStreamRequest {
pub review_session_id: String,
pub chat_history: Vec<ChatMessage>,
pub enable_chain_of_thought: bool,
}
// 临时会话数据结构,用于存储回顾分析过程中的状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsolidatedReviewSession {
pub review_session_id: String,
pub subject: String,
pub consolidated_input: String,
pub overall_prompt: String,
pub enable_chain_of_thought: bool,
pub created_at: DateTime<Utc>,
pub chat_history: Vec<ChatMessage>,
pub mistake_ids: Vec<String>, // 🎯 新增:关联的错题ID列表,用于获取图片信息
}
// ANKI相关结构体
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnkiGenerationOptions {
pub deck_name: String,
pub note_type: String,
pub enable_images: bool,
pub max_cards_per_mistake: i32,
#[serde(default)]
pub max_tokens: Option<u32>,
#[serde(default)]
pub temperature: Option<f32>,
// 新增:AI行为参数覆盖值
#[serde(default)]
pub max_output_tokens_override: Option<u32>,
#[serde(default)]
pub temperature_override: Option<f32>,
// 新增:模板系统参数
#[serde(default)]
pub template_id: Option<String>,
#[serde(default)]
pub custom_anki_prompt: Option<String>,
#[serde(default)]
pub template_fields: Option<Vec<String>>,
// 新增:字段提取规则用于动态解析
#[serde(default)]
pub field_extraction_rules: Option<std::collections::HashMap<String, FieldExtractionRule>>,
// 新增:用户自定义制卡要求
#[serde(default)]
pub custom_requirements: Option<String>,
// 新增:任务间重叠区域大小控制
#[serde(default = "default_overlap_size")]
pub segment_overlap_size: u32,
// 新增:用户自定义系统 prompt
#[serde(default)]
pub system_prompt: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnkiCardGenerationResponse {
pub success: bool,
pub cards: Vec<AnkiCard>,
pub error_message: Option<String>,
}
// 增强的AnkiCard结构体,支持数据库存储和任务关联
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnkiCard {
pub front: String,
pub back: String,
#[serde(default)]
pub text: Option<String>, // 新增:用于Cloze填空题模板
pub tags: Vec<String>,
pub images: Vec<String>,
// 新增字段用于数据库存储和内部管理
#[serde(default = "default_uuid_id")]
pub id: String,
#[serde(default)]
pub task_id: String,
#[serde(default)]
pub is_error_card: bool,
#[serde(default)]
pub error_content: Option<String>,
#[serde(default = "default_timestamp")]
pub created_at: String,
#[serde(default = "default_timestamp")]
pub updated_at: String,
// 新增:扩展字段支持,用于自定义模板
#[serde(default)]
pub extra_fields: std::collections::HashMap<String, String>,
#[serde(default)]
pub template_id: Option<String>,
}
// 自定义模板系统相关结构体
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomAnkiTemplate {
pub id: String,
pub name: String,
pub description: String,
pub author: Option<String>,
pub version: String,
pub preview_front: String,
pub preview_back: String,
pub note_type: String,
pub fields: Vec<String>,
pub generation_prompt: String,
pub front_template: String,
pub back_template: String,
pub css_style: String,
// 字段解析规则:指定如何从AI输出中提取和验证字段
pub field_extraction_rules: std::collections::HashMap<String, FieldExtractionRule>,
// 模板元数据
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub is_active: bool,
pub is_built_in: bool,
}
// 字段解析规则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldExtractionRule {
pub field_type: FieldType,
pub is_required: bool,
pub default_value: Option<String>,
pub validation_pattern: Option<String>, // 正则表达式
pub description: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FieldType {
Text,
Array,
Number,
Boolean,
}
// 模板创建/更新请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateTemplateRequest {
pub name: String,
pub description: String,
pub author: Option<String>,
pub preview_front: String,
pub preview_back: String,
pub note_type: String,
pub fields: Vec<String>,
pub generation_prompt: String,
pub front_template: String,
pub back_template: String,
pub css_style: String,
pub field_extraction_rules: std::collections::HashMap<String, FieldExtractionRule>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateTemplateRequest {
pub name: Option<String>,
pub description: Option<String>,
pub author: Option<String>,
pub preview_front: Option<String>,
pub preview_back: Option<String>,
pub note_type: Option<String>,
pub fields: Option<Vec<String>>,
pub generation_prompt: Option<String>,
pub front_template: Option<String>,
pub back_template: Option<String>,
pub css_style: Option<String>,
pub field_extraction_rules: Option<std::collections::HashMap<String, FieldExtractionRule>>,
pub is_active: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateImportRequest {
pub template_data: String, // JSON格式的模板数据
pub overwrite_existing: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateExportResponse {
pub template_data: String, // JSON格式的模板数据
pub filename: String,
}
// DocumentTask 结构体 - 支持文档分段任务管理
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocumentTask {
pub id: String, // UUID
pub document_id: String, // 关联的原始文档ID
pub original_document_name: String, // 原始文档名,用于UI显示
pub segment_index: u32, // 在原始文档中的分段序号 (从0开始)
pub content_segment: String, // 该任务对应的文档内容片段
pub status: TaskStatus, // 任务状态
pub created_at: String, // ISO8601 格式时间戳
pub updated_at: String, // ISO8601 格式时间戳
pub error_message: Option<String>, // 存储任务级别的错误信息
pub subject_name: String, // 处理该任务时使用的科目
pub anki_generation_options_json: String, // 存储处理该任务时使用的选项
}
// 任务状态枚举
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum TaskStatus {
Pending, // 待处理
Processing, // 处理中 (AI正在生成卡片)
Streaming, // 正在流式返回卡片 (细化Processing状态)
Completed, // 处理完成,所有卡片已生成
Failed, // 任务处理失败 (例如,AI调用失败,无法分段等)
Truncated, // AI输出因达到最大长度等原因被截断
Cancelled, // 用户取消
}
impl TaskStatus {
pub fn to_db_string(&self) -> String {
match self {
TaskStatus::Pending => "Pending".to_string(),
TaskStatus::Processing => "Processing".to_string(),
TaskStatus::Streaming => "Streaming".to_string(),
TaskStatus::Completed => "Completed".to_string(),
TaskStatus::Failed => "Failed".to_string(),
TaskStatus::Truncated => "Truncated".to_string(),
TaskStatus::Cancelled => "Cancelled".to_string(),
}
}
}
// 流式卡片数据结构
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "data")]
pub enum StreamedCardPayload {
NewCard(AnkiCard), // 一个新生成的、完整的卡片
NewErrorCard(AnkiCard), // 一个新生成的、标识错误的卡片
TaskStatusUpdate {
task_id: String,
status: TaskStatus,
message: Option<String>,
segment_index: Option<u32>, // 新增: 用于前端关联临时任务
}, // 任务状态更新
TaskProcessingError {
task_id: String,
error_message: String
}, // 任务处理过程中的严重错误
TaskCompleted {
task_id: String,
final_status: TaskStatus,
total_cards_generated: u32
}, // 单个任务完成信号
DocumentProcessingStarted {
document_id: String,
total_segments: u32
}, //整个文档开始处理,告知总任务数
DocumentProcessingCompleted {
document_id: String
}, // 整个文档所有任务处理完毕
RateLimitWarning {
message: String,
retry_after_seconds: Option<u32>
}, // API频率限制警告
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreamEvent {
pub payload: StreamedCardPayload,
}
// 默认值辅助函数
fn default_uuid_id() -> String {
uuid::Uuid::new_v4().to_string()
}
fn default_timestamp() -> String {
chrono::Utc::now().to_rfc3339()
}
fn default_overlap_size() -> u32 {
200 // 默认重叠200个字符
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnkiExportResponse {
pub success: bool,
pub file_path: Option<String>,
pub card_count: i32,
pub error_message: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnkiConnectResult {
pub success: bool,
pub result: Option<serde_json::Value>,
pub error: Option<String>,
}
// 新增:ANKI文档制卡请求结构
#[derive(Debug, Deserialize)]
pub struct AnkiDocumentGenerationRequest {
pub document_content: String,
pub subject_name: String,
pub options: Option<AnkiGenerationOptions>,
}
// 新增:ANKI文档制卡响应结构
#[derive(Debug, Serialize)]
pub struct AnkiDocumentGenerationResponse {
pub success: bool,
pub cards: Vec<AnkiCard>,
pub error_message: Option<String>,
}
// ==================== 图片遮罩卡相关数据结构 ====================
// 图片文字识别区域
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextRegion {
pub text: String, // 识别到的文字内容
pub bbox: [f32; 4], // 边界框坐标 [x1, y1, x2, y2]
pub confidence: f32, // 识别置信度
pub region_id: String, // 区域唯一标识
}
// 图片OCR识别请求
#[derive(Debug, Deserialize)]
pub struct ImageOcrRequest {
pub image_base64: String, // base64编码的图片数据
pub extract_coordinates: bool, // 是否提取坐标信息
pub target_text: Option<String>, // 可选:指定要识别的目标文字
#[serde(default)]
pub vl_high_resolution_images: bool, // 是否启用高分辨率模式(Qwen2.5-VL模型)
}
// 图片OCR识别响应
#[derive(Debug, Serialize)]
pub struct ImageOcrResponse {
pub success: bool,
pub text_regions: Vec<TextRegion>, // 识别到的文字区域列表
pub full_text: String, // 完整的OCR文字
pub image_width: u32, // 图片宽度
pub image_height: u32, // 图片高度
pub error_message: Option<String>,
}
// 遮罩区域定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OcclusionMask {
pub mask_id: String, // 遮罩唯一标识
pub bbox: [f32; 4], // 遮罩区域坐标
pub original_text: String, // 被遮罩的原始文字
pub hint: Option<String>, // 可选提示信息
pub mask_style: MaskStyle, // 遮罩样式
}
// 遮罩样式枚举
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MaskStyle {
SolidColor { color: String }, // 纯色遮罩
BlurEffect { intensity: u8 }, // 模糊效果
Rectangle { color: String, opacity: f32 }, // 半透明矩形
}
// 图片遮罩卡片数据结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageOcclusionCard {
pub id: String, // 卡片ID
pub task_id: String, // 关联任务ID
pub image_path: String, // 原始图片路径
pub image_base64: Option<String>, // 图片base64数据(用于导出)
pub image_width: u32, // 图片尺寸
pub image_height: u32,
pub masks: Vec<OcclusionMask>, // 遮罩区域列表
pub title: String, // 卡片标题
pub description: Option<String>, // 卡片描述
pub tags: Vec<String>, // 标签
pub created_at: String, // 创建时间
pub updated_at: String, // 更新时间
pub subject: String, // 学科
}
// 创建图片遮罩卡请求
#[derive(Debug, Deserialize)]
pub struct CreateImageOcclusionRequest {
pub image_base64: String, // 图片数据
pub title: String, // 卡片标题
pub description: Option<String>, // 卡片描述
pub subject: String, // 学科
pub tags: Vec<String>, // 标签
pub selected_regions: Vec<String>, // 用户选择的要遮罩的区域ID
pub mask_style: MaskStyle, // 遮罩样式
#[serde(default)]
pub use_high_resolution: bool, // 是否使用高分辨率模式
}
// 图片遮罩卡生成响应
#[derive(Debug, Serialize)]
pub struct ImageOcclusionResponse {
pub success: bool,
pub card: Option<ImageOcclusionCard>,
pub error_message: Option<String>,
}
// ==================== RAG相关数据结构 ====================
use std::collections::HashMap;
// 文档块结构
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DocumentChunk {
pub id: String, // UUID for the chunk
pub document_id: String, // ID of the source document
pub chunk_index: usize, // Order of the chunk within the document
pub text: String,
pub metadata: HashMap<String, String>, // e.g., filename, page_number
}
// 带向量的文档块结构
#[derive(Debug, Clone)]
pub struct DocumentChunkWithEmbedding {
pub chunk: DocumentChunk,
pub embedding: Vec<f32>,
}
// 检索到的文档块结构
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RetrievedChunk {
pub chunk: DocumentChunk,
pub score: f32, // Similarity score
}
// RAG查询选项
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RagQueryOptions {
pub top_k: usize,
pub enable_reranking: Option<bool>,
// pub filters: Option<HashMap<String, String>>, // Future: metadata-based filtering
}
// 知识库状态结构
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct KnowledgeBaseStatusPayload {
pub total_documents: usize,
pub total_chunks: usize,
pub embedding_model_name: Option<String>, // Name of the currently used embedding model
pub vector_store_type: String,
}
// RAG设置结构
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RagSettings {
pub knowledge_base_path: String, // Path to the vector store / knowledge base files
pub default_embedding_model_id: Option<String>, // ID of ApiConfig to use for embeddings
pub default_reranker_model_id: Option<String>, // ID of ApiConfig to use for reranking
pub default_top_k: usize,
pub enable_rag_by_default: bool,
}
// RAG增强的分析请求
#[derive(Debug, Deserialize)]
pub struct RagEnhancedAnalysisRequest {
pub temp_id: String,
pub enable_chain_of_thought: bool,
pub enable_rag: Option<bool>,
pub rag_options: Option<RagQueryOptions>,
}
// RAG增强的对话请求
#[derive(Debug, Deserialize)]
pub struct RagEnhancedChatRequest {
pub temp_id: String,
pub chat_history: Vec<ChatMessage>,
pub enable_chain_of_thought: Option<bool>,
pub enable_rag: Option<bool>,
pub rag_options: Option<RagQueryOptions>,
}
// 向量存储统计信息
#[derive(Debug, Clone)]
pub struct VectorStoreStats {
pub total_documents: usize,
pub total_chunks: usize,
pub storage_size_bytes: u64,
}
// 文档上传和处理相关结构
#[derive(Debug, Deserialize)]
pub struct DocumentUploadRequest {
pub file_paths: Vec<String>,
pub chunk_size: Option<usize>,
pub chunk_overlap: Option<usize>,
pub enable_preprocessing: Option<bool>,
}
#[derive(Debug, Serialize)]
pub struct DocumentProcessingStatus {
pub document_id: String,
pub file_name: String,
pub status: DocumentProcessingStage,
pub progress: f32, // 0.0 to 1.0
pub error_message: Option<String>,
pub chunks_processed: usize,
pub total_chunks: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DocumentProcessingStage {
Pending,
Reading,
Preprocessing,
Chunking,
Embedding,
Storing,
Completed,
Failed,
}
// RAG查询响应结构
#[derive(Debug, Serialize)]
pub struct RagQueryResponse {
pub retrieved_chunks: Vec<RetrievedChunk>,
pub query_vector_time_ms: u64,
pub search_time_ms: u64,
pub reranking_time_ms: Option<u64>,
pub total_time_ms: u64,
}
// RAG配置结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RagConfiguration {
pub id: String,
pub chunk_size: i32,
pub chunk_overlap: i32,
pub chunking_strategy: String, // "fixed_size" or "semantic"
pub min_chunk_size: i32,
pub default_top_k: i32,
pub default_rerank_enabled: bool,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
// RAG配置请求
#[derive(Debug, Deserialize)]
pub struct RagConfigRequest {
pub chunk_size: i32,
pub chunk_overlap: i32,
pub chunking_strategy: String,
pub min_chunk_size: i32,
pub default_top_k: i32,
pub default_rerank_enabled: bool,
}
// RAG配置响应
#[derive(Debug, Serialize)]
pub struct RagConfigResponse {
pub chunk_size: i32,
pub chunk_overlap: i32,
pub chunking_strategy: String,
pub min_chunk_size: i32,
pub default_top_k: i32,
pub default_rerank_enabled: bool,
}
// ==================== RAG多分库相关数据结构 ====================
/// RAG分库/子库实体
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubLibrary {
pub id: String, // UUID 主键
pub name: String, // 分库名称,用户定义
pub description: Option<String>, // 可选描述
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub document_count: usize, // 文档数量(查询时计算)
pub chunk_count: usize, // 文本块数量(查询时计算)
}
/// 创建分库请求
#[derive(Debug, Deserialize)]
pub struct CreateSubLibraryRequest {
pub name: String,
pub description: Option<String>,
}
/// 更新分库请求
#[derive(Debug, Deserialize)]
pub struct UpdateSubLibraryRequest {
pub name: Option<String>,
pub description: Option<String>,
}
/// 删除分库选项
#[derive(Debug, Deserialize)]
pub struct DeleteSubLibraryOptions {
/// 是否删除包含的文档,默认false(移到默认分库)
pub delete_contained_documents: Option<bool>,
}
/// 带分库信息的文档上传请求
#[derive(Debug, Deserialize)]
pub struct RagAddDocumentsRequest {
pub file_paths: Vec<String>,
pub sub_library_id: Option<String>, // 目标分库ID,None为默认分库
}
/// 带分库信息的Base64文档上传请求
#[derive(Debug, Deserialize)]
pub struct RagAddDocumentsFromContentRequest {
pub documents: Vec<RagDocumentContent>,
pub sub_library_id: Option<String>, // 目标分库ID,None为默认分库
}
/// RAG文档内容
#[derive(Debug, Deserialize)]
pub struct RagDocumentContent {
pub file_name: String,
pub base64_content: String,
}
/// 带分库过滤的RAG查询选项
#[derive(Debug, Deserialize)]
pub struct RagQueryOptionsWithLibraries {
pub top_k: usize,
pub enable_reranking: Option<bool>,
pub target_sub_library_ids: Option<Vec<String>>, // 目标分库ID列表,None表示查询所有分库
}
/// 获取文档列表请求
#[derive(Debug, Deserialize)]
pub struct GetDocumentsRequest {
pub sub_library_id: Option<String>, // 分库ID过滤,None表示获取所有文档
pub page: Option<usize>, // 分页页码
pub page_size: Option<usize>, // 每页大小
}
/// RAG增强的分析请求(带分库支持)
#[derive(Debug, Deserialize)]
pub struct RagEnhancedAnalysisRequestWithLibraries {
pub temp_id: String,
pub enable_chain_of_thought: bool,
pub enable_rag: Option<bool>,
pub rag_options: Option<RagQueryOptionsWithLibraries>,
}
/// RAG增强的对话请求(带分库支持)
#[derive(Debug, Deserialize)]
pub struct RagEnhancedChatRequestWithLibraries {
pub temp_id: String,
pub chat_history: Vec<ChatMessage>,
pub enable_chain_of_thought: Option<bool>,
pub enable_rag: Option<bool>,
pub rag_options: Option<RagQueryOptionsWithLibraries>,
}
|
000haoji/deep-student
| 10,538 |
src-tauri/src/document_parser.rs
|
/**
* 文档解析核心模块
*
* 提供统一的文档文本提取功能,支持DOCX和PDF格式
* 支持文件路径、字节流和Base64编码三种输入方式
*/
use std::io::Cursor;
use std::fs;
use std::path::Path;
use serde::{Deserialize, Serialize};
use base64::{Engine, engine::general_purpose};
/// 文档文件大小限制 (100MB)
const MAX_DOCUMENT_SIZE: usize = 100 * 1024 * 1024;
/// 流式处理时的缓冲区大小 (1MB)
const BUFFER_SIZE: usize = 1024 * 1024;
/// 文档解析错误枚举
#[derive(Debug, Serialize, Deserialize)]
pub enum ParsingError {
/// 文件不存在或无法访问
FileNotFound(String),
/// IO错误
IoError(String),
/// 不支持的文件格式
UnsupportedFormat(String),
/// DOCX解析错误
DocxParsingError(String),
/// PDF解析错误
PdfParsingError(String),
/// Base64解码错误
Base64DecodingError(String),
/// 文件过大错误
FileTooLarge(String),
/// 其他错误
Other(String),
}
impl std::fmt::Display for ParsingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ParsingError::FileNotFound(msg) => write!(f, "文件未找到: {}", msg),
ParsingError::IoError(msg) => write!(f, "IO错误: {}", msg),
ParsingError::UnsupportedFormat(msg) => write!(f, "不支持的文件格式: {}", msg),
ParsingError::DocxParsingError(msg) => write!(f, "DOCX解析错误: {}", msg),
ParsingError::PdfParsingError(msg) => write!(f, "PDF解析错误: {}", msg),
ParsingError::Base64DecodingError(msg) => write!(f, "Base64解码错误: {}", msg),
ParsingError::FileTooLarge(msg) => write!(f, "文件过大: {}", msg),
ParsingError::Other(msg) => write!(f, "其他错误: {}", msg),
}
}
}
impl std::error::Error for ParsingError {}
/// 从IO错误转换
impl From<std::io::Error> for ParsingError {
fn from(error: std::io::Error) -> Self {
ParsingError::IoError(error.to_string())
}
}
/// 从Base64解码错误转换
impl From<base64::DecodeError> for ParsingError {
fn from(error: base64::DecodeError) -> Self {
ParsingError::Base64DecodingError(error.to_string())
}
}
/// 文档解析器结构体
pub struct DocumentParser;
impl DocumentParser {
/// 创建新的文档解析器实例
pub fn new() -> Self {
DocumentParser
}
/// 检查文件大小是否超出限制
fn check_file_size(&self, size: usize) -> Result<(), ParsingError> {
if size > MAX_DOCUMENT_SIZE {
return Err(ParsingError::FileTooLarge(
format!("文件大小 {}MB 超过限制 {}MB",
size / (1024 * 1024),
MAX_DOCUMENT_SIZE / (1024 * 1024))
));
}
Ok(())
}
/// 安全地检查并读取文件
fn read_file_safely(&self, file_path: &str) -> Result<Vec<u8>, ParsingError> {
let metadata = fs::metadata(file_path)?;
let file_size = metadata.len() as usize;
self.check_file_size(file_size)?;
let bytes = fs::read(file_path)?;
Ok(bytes)
}
/// 从文件路径提取文本
pub fn extract_text_from_path(&self, file_path: &str) -> Result<String, ParsingError> {
let path = Path::new(file_path);
// 检查文件是否存在
if !path.exists() {
return Err(ParsingError::FileNotFound(file_path.to_string()));
}
// 根据文件扩展名确定处理方式
let extension = path.extension()
.and_then(|ext| ext.to_str())
.ok_or_else(|| ParsingError::UnsupportedFormat("无法确定文件扩展名".to_string()))?
.to_lowercase();
match extension.as_str() {
"docx" => self.extract_docx_from_path(file_path),
"pdf" => self.extract_pdf_from_path(file_path),
"txt" => self.extract_txt_from_path(file_path),
"md" => self.extract_md_from_path(file_path),
_ => Err(ParsingError::UnsupportedFormat(format!("不支持的文件格式: .{}", extension))),
}
}
/// 从字节流提取文本
pub fn extract_text_from_bytes(&self, file_name: &str, bytes: Vec<u8>) -> Result<String, ParsingError> {
// 检查文件大小
self.check_file_size(bytes.len())?;
// 从文件名确定文件类型
let extension = Path::new(file_name)
.extension()
.and_then(|ext| ext.to_str())
.ok_or_else(|| ParsingError::UnsupportedFormat("无法确定文件扩展名".to_string()))?
.to_lowercase();
match extension.as_str() {
"docx" => self.extract_docx_from_bytes(bytes),
"pdf" => self.extract_pdf_from_bytes(bytes),
"txt" => self.extract_txt_from_bytes(bytes),
"md" => self.extract_md_from_bytes(bytes),
_ => Err(ParsingError::UnsupportedFormat(format!("不支持的文件格式: .{}", extension))),
}
}
/// 从Base64编码内容提取文本
pub fn extract_text_from_base64(&self, file_name: &str, base64_content: &str) -> Result<String, ParsingError> {
// 解码Base64内容
let bytes = general_purpose::STANDARD.decode(base64_content)?;
// 调用字节流处理方法
self.extract_text_from_bytes(file_name, bytes)
}
/// 从DOCX文件路径提取文本
fn extract_docx_from_path(&self, file_path: &str) -> Result<String, ParsingError> {
let bytes = self.read_file_safely(file_path)?;
self.extract_docx_from_bytes(bytes)
}
/// 从DOCX字节流提取文本
fn extract_docx_from_bytes(&self, bytes: Vec<u8>) -> Result<String, ParsingError> {
let docx = docx_rs::read_docx(&bytes)
.map_err(|e| ParsingError::DocxParsingError(e.to_string()))?;
Ok(self.extract_docx_text(&docx))
}
/// 从DOCX文档对象提取文本内容(优化版本)
fn extract_docx_text(&self, docx: &docx_rs::Docx) -> String {
// 预估容量以减少重新分配
let mut text_content = String::with_capacity(8192);
// 遍历文档的所有子元素
for child in &docx.document.children {
match child {
docx_rs::DocumentChild::Paragraph(para) => {
let mut has_content = false;
// 提取段落中的所有文本
for child in ¶.children {
if let docx_rs::ParagraphChild::Run(run) = child {
for run_child in &run.children {
if let docx_rs::RunChild::Text(text) = run_child {
if !text.text.trim().is_empty() {
text_content.push_str(&text.text);
has_content = true;
}
}
}
}
}
// 如果段落有内容,添加换行符
if has_content {
text_content.push('\n');
}
}
_ => {
// 处理其他类型的文档子元素,如表格等
// 这里简化处理,只处理段落
}
}
}
text_content.trim().to_string()
}
/// 从PDF文件路径提取文本
fn extract_pdf_from_path(&self, file_path: &str) -> Result<String, ParsingError> {
// 先检查文件大小
let metadata = fs::metadata(file_path)?;
let file_size = metadata.len() as usize;
self.check_file_size(file_size)?;
let text = pdf_extract::extract_text(file_path)
.map_err(|e| ParsingError::PdfParsingError(e.to_string()))?;
Ok(text.trim().to_string())
}
/// 从PDF字节流提取文本
fn extract_pdf_from_bytes(&self, bytes: Vec<u8>) -> Result<String, ParsingError> {
let text = pdf_extract::extract_text_from_mem(&bytes)
.map_err(|e| ParsingError::PdfParsingError(e.to_string()))?;
Ok(text.trim().to_string())
}
/// 从TXT文件路径提取文本
fn extract_txt_from_path(&self, file_path: &str) -> Result<String, ParsingError> {
let bytes = self.read_file_safely(file_path)?;
self.extract_txt_from_bytes(bytes)
}
/// 从TXT字节流提取文本
fn extract_txt_from_bytes(&self, bytes: Vec<u8>) -> Result<String, ParsingError> {
// 尝试UTF-8解码,先不消费bytes
match std::str::from_utf8(&bytes) {
Ok(text) => Ok(text.trim().to_string()),
Err(_) => {
// 如果UTF-8失败,使用lossy转换
let text = String::from_utf8_lossy(&bytes);
Ok(text.trim().to_string())
}
}
}
/// 从MD文件路径提取文本
fn extract_md_from_path(&self, file_path: &str) -> Result<String, ParsingError> {
let bytes = self.read_file_safely(file_path)?;
self.extract_md_from_bytes(bytes)
}
/// 从MD字节流提取文本
fn extract_md_from_bytes(&self, bytes: Vec<u8>) -> Result<String, ParsingError> {
// Markdown文件本质上也是文本文件,使用相同的处理方式
// 未来可以考虑解析Markdown语法,但目前保持简单
self.extract_txt_from_bytes(bytes)
}
}
/// 默认实例化
impl Default for DocumentParser {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_document_parser_creation() {
let parser = DocumentParser::new();
assert_eq!(std::mem::size_of_val(&parser), 0); // 零大小类型
}
#[test]
fn test_txt_support() {
let parser = DocumentParser::new();
let test_content = "Hello, World!".as_bytes().to_vec();
let result = parser.extract_text_from_bytes("test.txt", test_content);
assert!(result.is_ok());
assert_eq!(result.unwrap(), "Hello, World!");
}
#[test]
fn test_txt_with_unicode() {
let parser = DocumentParser::new();
let test_content = "中文测试 English Test 123".as_bytes().to_vec();
let result = parser.extract_text_from_bytes("test.txt", test_content);
assert!(result.is_ok());
assert_eq!(result.unwrap(), "中文测试 English Test 123");
}
#[test]
fn test_md_support() {
let parser = DocumentParser::new();
let test_content = "# 标题\n\n这是**Markdown**内容。".as_bytes().to_vec();
let result = parser.extract_text_from_bytes("test.md", test_content);
assert!(result.is_ok());
assert_eq!(result.unwrap(), "# 标题\n\n这是**Markdown**内容。");
}
#[test]
fn test_file_too_large() {
let parser = DocumentParser::new();
let large_content = vec![0u8; MAX_DOCUMENT_SIZE + 1];
let result = parser.extract_text_from_bytes("test.txt", large_content);
assert!(matches!(result, Err(ParsingError::FileTooLarge(_))));
}
#[test]
fn test_base64_decoding_error() {
let parser = DocumentParser::new();
let result = parser.extract_text_from_base64("test.docx", "invalid_base64!");
assert!(matches!(result, Err(ParsingError::Base64DecodingError(_))));
}
}
|
0015/LVGL_Joystick
| 2,798 |
README.md
|
# LVGL Joystick Library
This library provides an easy way to create virtual joysticks for use in an LVGL environment. It supports both ESP-IDF and Arduino platforms and allows you to handle joystick input with customizable styles and callbacks.
[](https://youtu.be/ZhhSd6LA1jA)
## Features
- Create virtual joysticks with customizable sizes and styles.
- Handle joystick movement with user-defined callbacks.
- Allows creation of multiple virtual joysticks, identifiable via ID.
- Supports both ESP-IDF and Arduino environments.
## Installation
### Arduino
**Install the Joystick Library**:
- Download or clone this repository.
- Copy the `LVGL_Joystick` folder to your Arduino `libraries` directory.
### ESP-IDF
**Add Joystick Library as a component**:
- Clone the LVGL Joystick repository into your `components/` directory:
```bash
mkdir -p components
cd components
git clone https://github.com/0015/LVGL_Joystick
```
## Usage
```cpp
#include <lvgl.h>
#include <joystick.h>
void joystick_position_callback(uint8_t joystick_id, int16_t x, int16_t y) {
Serial.printf("Joystick ID: %d, Position - X: %d, Y: %d\n", joystick_id, x, y);
}
void ui_init() {
lv_obj_t *screen = lv_scr_act();
create_joystick(screen, 1, LV_ALIGN_CENTER, 0, 0, 100, 25, NULL, NULL, joystick_position_callback);
}
```
**You can check more details in the example project.**
## API Reference
```cpp
void create_joystick(
lv_obj_t *parent,
uint8_t joystick_id,
lv_align_t base_align,
int base_x,
int base_y,
int base_radius,
int stick_radius,
lv_style_t *base_style,
lv_style_t *stick_style,
joystick_position_cb_t position_callback)
```
* Creates a joystick on the specified parent object.
* lv_obj_t *parent: The parent LVGL object where the joystick will be created.
* uint8_t joystick_id: A unique ID for the joystick.
* lv_align_t base_align: Alignment for the base object of the joystick.
* int base_x, int base_y: X and Y offsets for the base object's position.
* int base_radius: The radius of the base (background) circle.
* int stick_radius: The radius of the joystick (control) circle.
* lv_style_t *base_style: Pointer to a custom style for the base object (can be NULL to use the default style).
* lv_style_t *stick_style: Pointer to a custom style for the joystick object (can be NULL to use the default style).
* joystick_position_cb_t position_callback: Callback function for joystick position updates.
## Limitations
Since LVGL (the current version 9.2.0) does not support multi-touch, you cannot fire two touch events at the same time. More than two joysticks will be available as soon as LVGL is updated.
|
0015/RPI-Projects
| 1,171 |
README.md
|
<pre>
██████╗ █████╗ ███████╗██████╗ ██████╗ ███████╗██████╗ ██████╗ ██╗ ██╗ ██████╗ ██╗
██╔══██╗██╔══██╗██╔════╝██╔══██╗██╔══██╗██╔════╝██╔══██╗██╔══██╗╚██╗ ██╔╝ ██╔══██╗██║
██████╔╝███████║███████╗██████╔╝██████╔╝█████╗ ██████╔╝██████╔╝ ╚████╔╝ ██████╔╝██║
██╔══██╗██╔══██║╚════██║██╔═══╝ ██╔══██╗██╔══╝ ██╔══██╗██╔══██╗ ╚██╔╝ ██╔═══╝ ██║
██║ ██║██║ ██║███████║██║ ██████╔╝███████╗██║ ██║██║ ██║ ██║ ██║ ██║
╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝
██████╗ ██████╗ ██████╗ ██╗███████╗ ██████╗████████╗
██╔══██╗██╔══██╗██╔═══██╗ ██║██╔════╝██╔════╝╚══██╔══╝
██████╔╝██████╔╝██║ ██║ ██║█████╗ ██║ ██║
██╔═══╝ ██╔══██╗██║ ██║██ ██║██╔══╝ ██║ ██║
██║ ██║ ██║╚██████╔╝╚█████╔╝███████╗╚██████╗ ██║
╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚════╝ ╚══════╝ ╚═════╝ ╚═╝
</pre>
|
0015/LVGL_Joystick
| 5,164 |
src/lvgl_joystick.c
|
#include "lvgl_joystick.h"
#include <math.h>
#include <stdlib.h>
static void joystick_trigger_callback(joystick_data_t *data, int16_t x,
int16_t y) {
if (data->position_callback) {
data->position_callback(data->joystick_id, x, y);
}
}
static void joystick_handle_release(joystick_data_t *data,
lv_obj_t *stick_obj) {
lv_obj_set_pos(stick_obj, 0, 0);
if (data->report_mode == JOYSTICK_REPORT_MODE_ABSOLUTE) {
joystick_trigger_callback(data, 0, 0);
}
}
static void joystick_handle_pressing(joystick_data_t *data,
lv_obj_t *stick_obj) {
lv_indev_t *indev = lv_indev_active();
if (indev == NULL) return;
lv_point_t vect;
lv_indev_get_vect(indev, &vect);
int32_t x = lv_obj_get_x_aligned(stick_obj) + vect.x;
int32_t y = lv_obj_get_y_aligned(stick_obj) + vect.y;
uint8_t joystick_id = data->joystick_id;
uint8_t base_radius = data->base_radius;
uint8_t stick_radius = data->stick_radius;
float distance_from_center = sqrt(x * x + y * y);
bool should_move_stick =
distance_from_center < base_radius - (stick_radius * 1.2);
if (!should_move_stick) {
return;
}
lv_obj_set_pos(stick_obj, x, y);
if (!data->position_callback) {
return; // No callback so bail
}
if (data->report_mode == JOYSTICK_REPORT_MODE_ABSOLUTE) {
joystick_trigger_callback(data, x, y);
} else if (data->report_mode == JOYSTICK_REPORT_MODE_RELATIVE) {
joystick_trigger_callback(data, vect.x, vect.y);
}
}
// Event handler for the joystick
static void joystic_event_handler(lv_event_t *e) {
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t *obj = (lv_obj_t *)lv_event_get_target(e);
// Retrieve joystick data
joystick_data_t *joystick_data = (joystick_data_t *)lv_obj_get_user_data(obj);
if (joystick_data == NULL) {
return; // Handle error case
}
switch (code) {
case LV_EVENT_PRESSING:
joystick_handle_pressing(joystick_data, obj);
break;
case LV_EVENT_RELEASED:
joystick_handle_release(joystick_data, obj);
break;
case LV_EVENT_DELETE:
free(joystick_data);
break;
default:
break;
}
}
// Function to create a joystick with custom parameters
void create_joystick(lv_obj_t *parent, uint8_t joystick_id,
lv_align_t base_align, int base_x, int base_y,
int base_radius, int stick_radius, lv_style_t *base_style,
lv_style_t *stick_style,
joystick_position_cb_t position_callback,
joystick_report_mode_t report_mode) {
// Allocate and initialize joystick data
joystick_data_t *joystick_data =
(joystick_data_t *)malloc(sizeof(joystick_data_t));
joystick_data->joystick_id = joystick_id;
joystick_data->base_radius = base_radius;
joystick_data->stick_radius = stick_radius;
joystick_data->position_callback = position_callback;
joystick_data->report_mode = report_mode;
// Create or use provided base style
static lv_style_t default_base_style;
if (base_style == NULL) {
base_style = &default_base_style;
lv_style_init(base_style);
lv_style_set_radius(base_style, base_radius);
lv_style_set_bg_opa(base_style, LV_OPA_COVER);
lv_style_set_bg_color(base_style, lv_palette_lighten(LV_PALETTE_GREY, 1));
lv_style_set_pad_all(base_style, 0);
lv_style_set_outline_width(base_style, 2);
lv_style_set_outline_color(base_style, lv_palette_main(LV_PALETTE_BLUE));
lv_style_set_outline_pad(base_style, 8);
}
// Create the base object (joystick background)
lv_obj_t *base_obj = lv_obj_create(parent);
lv_obj_add_style(base_obj, base_style, LV_PART_MAIN);
lv_obj_clear_flag(base_obj, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_size(base_obj, base_radius * 2,
base_radius * 2); // Set size based on radius
lv_obj_align(base_obj, base_align, base_x, base_y); // Align the base_obj
// Create or use provided stick style
static lv_style_t default_stick_style;
if (stick_style == NULL) {
stick_style = &default_stick_style;
lv_style_init(stick_style);
lv_style_set_radius(stick_style, stick_radius);
lv_style_set_bg_opa(stick_style, LV_OPA_COVER);
lv_style_set_bg_color(stick_style, lv_palette_main(LV_PALETTE_BLUE));
lv_style_set_pad_all(stick_style, 0);
lv_style_set_outline_width(stick_style, 2);
lv_style_set_outline_color(stick_style, lv_palette_main(LV_PALETTE_GREEN));
lv_style_set_outline_pad(stick_style, 4);
}
// Create the stick object (control handle)
lv_obj_t *stick_obj = lv_btn_create(base_obj);
lv_obj_set_size(stick_obj, stick_radius * 2,
stick_radius * 2); // Set size based on radius
lv_obj_add_style(stick_obj, stick_style, LV_PART_MAIN);
lv_obj_center(stick_obj); // Center the stick inside the base object
// Set the joystick data as user data for the stick object
lv_obj_set_user_data(stick_obj, joystick_data);
// Set the event handler for the stick object
lv_obj_add_event_cb(stick_obj, joystic_event_handler, LV_EVENT_ALL, NULL);
}
|
0015/LVGL_Joystick
| 1,193 |
src/lvgl_joystick.h
|
#ifndef LVGL_JOYSTICK_H
#define LVGL_JOYSTICK_H
#ifdef __cplusplus
extern "C" {
#endif
#pragma once
#include <lvgl.h>
// Callback function type
typedef void (*joystick_position_cb_t)(uint8_t joystick_id, int16_t x,
int16_t y);
// Enum for how joystick reports data in the callback
typedef enum {
JOYSTICK_REPORT_MODE_ABSOLUTE, // stick position relation to center
JOYSTICK_REPORT_MODE_RELATIVE // stick change in position
} joystick_report_mode_t;
// Structure to hold joystick data
typedef struct {
uint8_t joystick_id;
uint8_t base_radius;
uint8_t stick_radius;
joystick_report_mode_t report_mode;
joystick_position_cb_t position_callback;
} joystick_data_t;
// Function prototypes
void create_joystick(lv_obj_t *parent, uint8_t joystick_id,
lv_align_t base_align, int base_x, int base_y,
int base_radius, int stick_radius, lv_style_t *base_style,
lv_style_t *stick_style,
joystick_position_cb_t position_callback,
joystick_report_mode_t report_mode);
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif // LVGL_JOYSTICK_H
|
000haoji/deep-student
| 145,648 |
src-tauri/src/database.rs
|
use std::path::{Path, PathBuf};
use std::fs;
use std::sync::Mutex;
use anyhow::{Context, Result};
use rusqlite::{Connection, params, OptionalExtension};
use chrono::{Utc, DateTime};
use crate::models::{MistakeItem, ChatMessage, Statistics, SubjectConfig, SubjectPrompts, DocumentTask, TaskStatus, AnkiCard, SubLibrary, CreateSubLibraryRequest, UpdateSubLibraryRequest, ReviewAnalysisItem};
// Re-export for external use
// pub use std::sync::MutexGuard; // Removed unused import
const CURRENT_DB_VERSION: u32 = 10;
pub struct Database {
conn: Mutex<Connection>,
db_path: PathBuf,
}
impl Database {
/// Get a reference to the underlying connection for batch operations
pub fn conn(&self) -> &Mutex<Connection> {
&self.conn
}
/// 创建新的数据库连接并初始化/迁移数据库
pub fn new(db_path: &Path) -> Result<Self> {
if let Some(parent) = db_path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("创建数据库目录失败: {:?}", parent))?;
}
let conn = Connection::open(db_path)
.with_context(|| format!("打开数据库连接失败: {:?}", db_path))?;
let db = Database { conn: Mutex::new(conn), db_path: db_path.to_path_buf() };
db.initialize_schema()?;
Ok(db)
}
fn initialize_schema(&self) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute_batch(
"BEGIN;
CREATE TABLE IF NOT EXISTS schema_version (
version INTEGER PRIMARY KEY NOT NULL
);
CREATE TABLE IF NOT EXISTS mistakes (
id TEXT PRIMARY KEY,
subject TEXT NOT NULL,
created_at TEXT NOT NULL,
question_images TEXT NOT NULL, -- JSON数组
analysis_images TEXT NOT NULL, -- JSON数组
user_question TEXT NOT NULL,
ocr_text TEXT NOT NULL,
tags TEXT NOT NULL, -- JSON数组
mistake_type TEXT NOT NULL,
status TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS chat_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
mistake_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
timestamp TEXT NOT NULL,
thinking_content TEXT, -- 可选的思维链内容
FOREIGN KEY(mistake_id) REFERENCES mistakes(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS review_analyses (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
subject TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
mistake_ids TEXT NOT NULL, -- JSON数组,关联的错题ID
consolidated_input TEXT NOT NULL, -- 合并后的输入内容
user_question TEXT NOT NULL,
status TEXT NOT NULL,
tags TEXT NOT NULL, -- JSON数组
analysis_type TEXT NOT NULL DEFAULT 'consolidated_review'
);
CREATE TABLE IF NOT EXISTS review_chat_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
review_analysis_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
timestamp TEXT NOT NULL,
thinking_content TEXT, -- 思维链内容
rag_sources TEXT, -- RAG来源信息,JSON格式
FOREIGN KEY(review_analysis_id) REFERENCES review_analyses(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS subject_configs (
id TEXT PRIMARY KEY,
subject_name TEXT NOT NULL UNIQUE,
display_name TEXT NOT NULL,
description TEXT NOT NULL,
is_enabled INTEGER NOT NULL DEFAULT 1,
prompts TEXT NOT NULL, -- JSON格式存储SubjectPrompts
mistake_types TEXT NOT NULL, -- JSON数组
default_tags TEXT NOT NULL, -- JSON数组
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS document_tasks (
id TEXT PRIMARY KEY,
document_id TEXT NOT NULL,
original_document_name TEXT NOT NULL,
segment_index INTEGER NOT NULL,
content_segment TEXT NOT NULL,
status TEXT NOT NULL CHECK(status IN ('Pending', 'Processing', 'Streaming', 'Completed', 'Failed', 'Truncated', 'Cancelled')),
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
error_message TEXT,
subject_name TEXT NOT NULL,
anki_generation_options_json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS anki_cards (
id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES document_tasks(id) ON DELETE CASCADE,
front TEXT NOT NULL,
back TEXT NOT NULL,
tags_json TEXT DEFAULT '[]',
images_json TEXT DEFAULT '[]',
is_error_card INTEGER NOT NULL DEFAULT 0,
error_content TEXT,
card_order_in_task INTEGER DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);
CREATE INDEX IF NOT EXISTS idx_document_tasks_document_id ON document_tasks(document_id);
CREATE INDEX IF NOT EXISTS idx_document_tasks_status ON document_tasks(status);
CREATE INDEX IF NOT EXISTS idx_anki_cards_task_id ON anki_cards(task_id);
CREATE INDEX IF NOT EXISTS idx_anki_cards_is_error_card ON anki_cards(is_error_card);
COMMIT;"
)?;
let current_version: u32 = conn.query_row(
"SELECT version FROM schema_version ORDER BY version DESC LIMIT 1",
[],
|row| row.get(0),
).optional()?.unwrap_or(0);
if current_version < CURRENT_DB_VERSION {
// 迁移逻辑
if current_version < 2 {
self.migrate_v1_to_v2(&conn)?;
}
if current_version < 3 {
self.migrate_v2_to_v3(&conn)?;
}
if current_version < 4 {
self.migrate_v3_to_v4(&conn)?;
}
if current_version < 5 {
self.migrate_v4_to_v5(&conn)?;
}
if current_version < 6 {
self.migrate_v5_to_v6(&conn)?;
}
if current_version < 7 {
self.migrate_v6_to_v7(&conn)?;
}
if current_version < 8 {
self.migrate_v7_to_v8(&conn)?;
}
if current_version < 9 {
self.migrate_v8_to_v9(&conn)?;
}
if current_version < 10 {
self.migrate_v9_to_v10(&conn)?;
}
conn.execute(
"INSERT OR REPLACE INTO schema_version (version) VALUES (?1)",
params![CURRENT_DB_VERSION],
)?;
}
// 调用思维链列迁移函数
self.migrate_add_thinking_column(&conn)?;
// 调用RAG来源信息列迁移函数
self.migrate_add_rag_sources_column(&conn)?;
// 调用科目配置prompts迁移函数
self.migrate_subject_config_prompts(&conn)?;
Ok(())
}
fn migrate_add_thinking_column(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> {
let mut stmt = conn.prepare("PRAGMA table_info(chat_messages);")?;
let column_exists = stmt
.query_map([], |row| row.get::<_, String>(1))?
.filter_map(Result::ok)
.any(|name| name == "thinking_content");
if !column_exists {
conn.execute(
"ALTER TABLE chat_messages ADD COLUMN thinking_content TEXT;",
[],
)?;
println!("✅ SQLite: thinking_content 列已添加");
}
Ok(())
}
fn migrate_add_rag_sources_column(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> {
let mut stmt = conn.prepare("PRAGMA table_info(chat_messages);")?;
let column_exists = stmt
.query_map([], |row| row.get::<_, String>(1))?
.filter_map(Result::ok)
.any(|name| name == "rag_sources");
if !column_exists {
conn.execute(
"ALTER TABLE chat_messages ADD COLUMN rag_sources TEXT;",
[],
)?;
println!("✅ SQLite: rag_sources 列已添加");
}
Ok(())
}
fn migrate_subject_config_prompts(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> {
// 检查是否存在subject_configs表
let table_exists = conn.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='subject_configs';")?
.query_map([], |_| Ok(()))?
.any(|_| true);
if !table_exists {
println!("⏭️ SQLite: subject_configs表不存在,跳过prompts迁移");
return Ok(());
}
// 获取所有现有的科目配置
let mut stmt = conn.prepare("SELECT id, prompts FROM subject_configs")?;
let configs: Vec<(String, String)> = stmt.query_map([], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
})?.collect::<rusqlite::Result<Vec<_>>>()?;
let mut updated_count = 0;
for (id, prompts_json) in configs {
// 尝试解析现有的prompts JSON
match serde_json::from_str::<SubjectPrompts>(&prompts_json) {
Ok(_) => {
// 如果能成功解析,说明字段已经完整,跳过
continue;
},
Err(_) => {
// 解析失败,尝试修复
println!("🔧 修复科目配置prompts: {}", id);
// 尝试解析为旧格式(没有consolidated_review_prompt字段的JSON)
let mut prompts_value: serde_json::Value = match serde_json::from_str(&prompts_json) {
Ok(v) => v,
Err(e) => {
println!("❌ 跳过无法解析的prompts JSON: {} - {}", id, e);
continue;
}
};
// 检查是否缺少consolidated_review_prompt字段
if !prompts_value.get("consolidated_review_prompt").is_some() {
// 添加默认的consolidated_review_prompt字段
prompts_value["consolidated_review_prompt"] = serde_json::Value::String(
"你是一个资深老师,请仔细阅读以下学生提交的多道错题的详细信息(包括题目原文、原始提问和历史交流)。请基于所有这些信息,对学生提出的总体回顾问题进行全面、深入的分析和解答。请注意识别错题间的关联,总结共性问题,并给出针对性的学习建议。".to_string()
);
// 更新数据库中的prompts字段
let updated_prompts_json = serde_json::to_string(&prompts_value)?;
conn.execute(
"UPDATE subject_configs SET prompts = ?1 WHERE id = ?2",
params![updated_prompts_json, id],
)?;
updated_count += 1;
println!("✅ 已修复科目配置prompts: {}", id);
}
}
}
}
if updated_count > 0 {
println!("✅ SQLite: 已修复 {} 个科目配置的prompts字段", updated_count);
} else {
println!("✅ SQLite: 所有科目配置的prompts字段都已是最新格式");
}
Ok(())
}
fn migrate_v1_to_v2(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> {
println!("🔄 数据库迁移: v1 -> v2 (添加Anki增强功能表)");
// 检查document_tasks表是否已存在
let document_tasks_exists = conn.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='document_tasks';")?
.query_map([], |_| Ok(()))?
.any(|_| true);
if !document_tasks_exists {
conn.execute(
"CREATE TABLE document_tasks (
id TEXT PRIMARY KEY,
document_id TEXT NOT NULL,
original_document_name TEXT NOT NULL,
segment_index INTEGER NOT NULL,
content_segment TEXT NOT NULL,
status TEXT NOT NULL CHECK(status IN ('Pending', 'Processing', 'Streaming', 'Completed', 'Failed', 'Truncated', 'Cancelled')),
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
error_message TEXT,
subject_name TEXT NOT NULL,
anki_generation_options_json TEXT NOT NULL
);",
[],
)?;
println!("✅ 创建document_tasks表");
}
// 检查anki_cards表是否已存在
let anki_cards_exists = conn.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='anki_cards';")?
.query_map([], |_| Ok(()))?
.any(|_| true);
if !anki_cards_exists {
conn.execute(
"CREATE TABLE anki_cards (
id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES document_tasks(id) ON DELETE CASCADE,
front TEXT NOT NULL,
back TEXT NOT NULL,
tags_json TEXT DEFAULT '[]',
images_json TEXT DEFAULT '[]',
is_error_card INTEGER NOT NULL DEFAULT 0,
error_content TEXT,
card_order_in_task INTEGER DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);",
[],
)?;
println!("✅ 创建anki_cards表");
}
// 创建索引
conn.execute("CREATE INDEX IF NOT EXISTS idx_document_tasks_document_id ON document_tasks(document_id);", [])?;
conn.execute("CREATE INDEX IF NOT EXISTS idx_document_tasks_status ON document_tasks(status);", [])?;
conn.execute("CREATE INDEX IF NOT EXISTS idx_anki_cards_task_id ON anki_cards(task_id);", [])?;
conn.execute("CREATE INDEX IF NOT EXISTS idx_anki_cards_is_error_card ON anki_cards(is_error_card);", [])?;
println!("✅ 数据库迁移完成: v1 -> v2");
Ok(())
}
fn migrate_v2_to_v3(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> {
println!("🔄 数据库迁移: v2 -> v3 (添加RAG配置表)");
// 检查rag_configurations表是否已存在
let rag_config_exists = conn.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='rag_configurations';")?
.query_map([], |_| Ok(()))?
.any(|_| true);
if !rag_config_exists {
conn.execute(
"CREATE TABLE rag_configurations (
id TEXT PRIMARY KEY,
chunk_size INTEGER NOT NULL DEFAULT 512,
chunk_overlap INTEGER NOT NULL DEFAULT 50,
chunking_strategy TEXT NOT NULL DEFAULT 'fixed_size',
min_chunk_size INTEGER NOT NULL DEFAULT 20,
default_top_k INTEGER NOT NULL DEFAULT 5,
default_rerank_enabled INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);",
[],
)?;
println!("✅ 创建rag_configurations表");
// 插入默认配置
let now = Utc::now().to_rfc3339();
conn.execute(
"INSERT INTO rag_configurations (id, chunk_size, chunk_overlap, chunking_strategy, min_chunk_size, default_top_k, default_rerank_enabled, created_at, updated_at)
VALUES ('default', 512, 50, 'fixed_size', 20, 5, 0, ?1, ?2)",
params![now, now],
)?;
println!("✅ 插入默认RAG配置");
}
println!("✅ 数据库迁移完成: v2 -> v3");
Ok(())
}
fn migrate_v3_to_v4(&self, _conn: &rusqlite::Connection) -> anyhow::Result<()> {
println!("📦 开始数据库迁移 v3 -> v4: 添加RAG来源信息支持");
// v3到v4的迁移主要通过migrate_add_rag_sources_column处理
// 这里可以添加其他v4特有的迁移逻辑
println!("✅ 数据库迁移 v3 -> v4 完成");
Ok(())
}
fn migrate_v4_to_v5(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> {
println!("📦 开始数据库迁移 v4 -> v5: 升级回顾分析表结构");
// 强制创建review_analyses和review_chat_messages表(如果不存在)
conn.execute(
"CREATE TABLE IF NOT EXISTS review_analyses (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
subject TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
mistake_ids TEXT NOT NULL,
consolidated_input TEXT NOT NULL,
user_question TEXT NOT NULL,
status TEXT NOT NULL,
tags TEXT NOT NULL,
analysis_type TEXT NOT NULL DEFAULT 'consolidated_review'
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS review_chat_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
review_analysis_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
timestamp TEXT NOT NULL,
thinking_content TEXT,
rag_sources TEXT,
FOREIGN KEY(review_analysis_id) REFERENCES review_analyses(id) ON DELETE CASCADE
)",
[],
)?;
println!("✅ 强制创建了review_analyses和review_chat_messages表");
// 迁移旧的review_sessions到新的review_analyses
self.migrate_review_sessions_to_review_analyses(conn)?;
println!("✅ 数据库迁移 v4 -> v5 完成");
Ok(())
}
fn migrate_v5_to_v6(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> {
println!("📦 开始数据库迁移 v5 -> v6: 修复回顾分析表结构");
// 强制重新创建review_analyses和review_chat_messages表,确保schema正确
conn.execute("DROP TABLE IF EXISTS review_chat_messages", [])?;
conn.execute("DROP TABLE IF EXISTS review_analyses", [])?;
conn.execute(
"CREATE TABLE review_analyses (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
subject TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
mistake_ids TEXT NOT NULL,
consolidated_input TEXT NOT NULL,
user_question TEXT NOT NULL,
status TEXT NOT NULL,
tags TEXT NOT NULL,
analysis_type TEXT NOT NULL DEFAULT 'consolidated_review'
)",
[],
)?;
conn.execute(
"CREATE TABLE review_chat_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
review_analysis_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
timestamp TEXT NOT NULL,
thinking_content TEXT,
rag_sources TEXT,
FOREIGN KEY(review_analysis_id) REFERENCES review_analyses(id) ON DELETE CASCADE
)",
[],
)?;
println!("✅ 重新创建了review_analyses和review_chat_messages表");
println!("✅ 数据库迁移 v5 -> v6 完成");
Ok(())
}
fn migrate_v6_to_v7(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> {
println!("📦 开始数据库迁移 v6 -> v7: 添加错题总结字段");
// 为mistakes表添加新的总结字段
conn.execute(
"ALTER TABLE mistakes ADD COLUMN mistake_summary TEXT",
[],
)?;
conn.execute(
"ALTER TABLE mistakes ADD COLUMN user_error_analysis TEXT",
[],
)?;
println!("✅ 已为mistakes表添加mistake_summary和user_error_analysis字段");
println!("✅ 数据库迁移 v6 -> v7 完成");
Ok(())
}
fn migrate_v7_to_v8(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> {
println!("📦 开始数据库迁移 v7 -> v8: 添加模板支持字段");
// 为anki_cards表添加扩展字段和模板ID字段
let add_extra_fields = conn.execute(
"ALTER TABLE anki_cards ADD COLUMN extra_fields_json TEXT DEFAULT '{}'",
[],
);
let add_template_id = conn.execute(
"ALTER TABLE anki_cards ADD COLUMN template_id TEXT",
[],
);
match (add_extra_fields, add_template_id) {
(Ok(_), Ok(_)) => {
println!("✅ 已为anki_cards表添加extra_fields_json和template_id字段");
}
(Err(e1), Err(e2)) => {
println!("⚠️ 添加字段时遇到错误,可能字段已存在: {} / {}", e1, e2);
}
(Ok(_), Err(e)) => {
println!("⚠️ 添加template_id字段时遇到错误,可能字段已存在: {}", e);
}
(Err(e), Ok(_)) => {
println!("⚠️ 添加extra_fields_json字段时遇到错误,可能字段已存在: {}", e);
}
}
// 创建自定义模板表
conn.execute(
"CREATE TABLE IF NOT EXISTS custom_anki_templates (
id TEXT PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
description TEXT,
author TEXT,
version TEXT NOT NULL DEFAULT '1.0.0',
preview_front TEXT NOT NULL,
preview_back TEXT NOT NULL,
note_type TEXT NOT NULL DEFAULT 'Basic',
fields_json TEXT NOT NULL DEFAULT '[]',
generation_prompt TEXT NOT NULL,
front_template TEXT NOT NULL,
back_template TEXT NOT NULL,
css_style TEXT NOT NULL,
field_extraction_rules_json TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
is_active INTEGER NOT NULL DEFAULT 1,
is_built_in INTEGER NOT NULL DEFAULT 0
);",
[],
)?;
// 创建模板表索引
conn.execute("CREATE INDEX IF NOT EXISTS idx_custom_anki_templates_is_active ON custom_anki_templates(is_active);", [])?;
conn.execute("CREATE INDEX IF NOT EXISTS idx_custom_anki_templates_is_built_in ON custom_anki_templates(is_built_in);", [])?;
println!("✅ 已创建custom_anki_templates表");
println!("✅ 数据库迁移 v7 -> v8 完成");
Ok(())
}
// 自定义模板管理方法
/// 创建自定义模板
pub fn create_custom_template(&self, request: &crate::models::CreateTemplateRequest) -> Result<String> {
let conn = self.conn.lock().unwrap();
let template_id = uuid::Uuid::new_v4().to_string();
let now = Utc::now().to_rfc3339();
conn.execute(
"INSERT INTO custom_anki_templates
(id, name, description, author, version, preview_front, preview_back, note_type,
fields_json, generation_prompt, front_template, back_template, css_style,
field_extraction_rules_json, created_at, updated_at, is_active, is_built_in)
VALUES (?1, ?2, ?3, ?4, '1.0.0', ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, 1, 0)",
params![
template_id,
request.name,
request.description,
request.author,
request.preview_front,
request.preview_back,
request.note_type,
serde_json::to_string(&request.fields)?,
request.generation_prompt,
request.front_template,
request.back_template,
request.css_style,
serde_json::to_string(&request.field_extraction_rules)?,
now.clone(),
now
]
)?;
Ok(template_id)
}
/// 获取所有自定义模板
pub fn get_all_custom_templates(&self) -> Result<Vec<crate::models::CustomAnkiTemplate>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT id, name, description, author, version, preview_front, preview_back, note_type,
fields_json, generation_prompt, front_template, back_template, css_style,
field_extraction_rules_json, created_at, updated_at, is_active, is_built_in
FROM custom_anki_templates ORDER BY created_at DESC"
)?;
let template_iter = stmt.query_map([], |row| {
let fields_json: String = row.get(8)?;
let fields: Vec<String> = serde_json::from_str(&fields_json).unwrap_or_default();
let rules_json: String = row.get(13)?;
let field_extraction_rules: std::collections::HashMap<String, crate::models::FieldExtractionRule> =
serde_json::from_str(&rules_json).unwrap_or_default();
let created_at_str: String = row.get(14)?;
let updated_at_str: String = row.get(15)?;
Ok(crate::models::CustomAnkiTemplate {
id: row.get(0)?,
name: row.get(1)?,
description: row.get(2)?,
author: row.get(3)?,
version: row.get(4)?,
preview_front: row.get(5)?,
preview_back: row.get(6)?,
note_type: row.get(7)?,
fields,
generation_prompt: row.get(9)?,
front_template: row.get(10)?,
back_template: row.get(11)?,
css_style: row.get(12)?,
field_extraction_rules,
created_at: DateTime::parse_from_rfc3339(&created_at_str).unwrap().with_timezone(&Utc),
updated_at: DateTime::parse_from_rfc3339(&updated_at_str).unwrap().with_timezone(&Utc),
is_active: row.get::<_, i32>(16)? != 0,
is_built_in: row.get::<_, i32>(17)? != 0,
})
})?;
let mut templates = Vec::new();
for template in template_iter {
templates.push(template?);
}
Ok(templates)
}
/// 获取指定ID的自定义模板
pub fn get_custom_template_by_id(&self, template_id: &str) -> Result<Option<crate::models::CustomAnkiTemplate>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT id, name, description, author, version, preview_front, preview_back, note_type,
fields_json, generation_prompt, front_template, back_template, css_style,
field_extraction_rules_json, created_at, updated_at, is_active, is_built_in
FROM custom_anki_templates WHERE id = ?1"
)?;
let result = stmt.query_row(params![template_id], |row| {
let fields_json: String = row.get(8)?;
let fields: Vec<String> = serde_json::from_str(&fields_json).unwrap_or_default();
let rules_json: String = row.get(13)?;
let field_extraction_rules: std::collections::HashMap<String, crate::models::FieldExtractionRule> =
serde_json::from_str(&rules_json).unwrap_or_default();
let created_at_str: String = row.get(14)?;
let updated_at_str: String = row.get(15)?;
Ok(crate::models::CustomAnkiTemplate {
id: row.get(0)?,
name: row.get(1)?,
description: row.get(2)?,
author: row.get(3)?,
version: row.get(4)?,
preview_front: row.get(5)?,
preview_back: row.get(6)?,
note_type: row.get(7)?,
fields,
generation_prompt: row.get(9)?,
front_template: row.get(10)?,
back_template: row.get(11)?,
css_style: row.get(12)?,
field_extraction_rules,
created_at: DateTime::parse_from_rfc3339(&created_at_str).unwrap().with_timezone(&Utc),
updated_at: DateTime::parse_from_rfc3339(&updated_at_str).unwrap().with_timezone(&Utc),
is_active: row.get::<_, i32>(16)? != 0,
is_built_in: row.get::<_, i32>(17)? != 0,
})
}).optional()?;
Ok(result)
}
/// 更新自定义模板
pub fn update_custom_template(&self, template_id: &str, request: &crate::models::UpdateTemplateRequest) -> Result<()> {
let conn = self.conn.lock().unwrap();
let now = Utc::now().to_rfc3339();
let mut query_parts = Vec::new();
let mut params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
// 将需要长期存储的值移动到这里,避免借用生命周期问题
let mut owned_fields_json = None;
let mut owned_rules_json = None;
let mut owned_active_val = None;
if let Some(name) = &request.name {
query_parts.push("name = ?".to_string());
params.push(Box::new(name.clone()));
}
if let Some(description) = &request.description {
query_parts.push("description = ?".to_string());
params.push(Box::new(description.clone()));
}
if let Some(author) = &request.author {
query_parts.push("author = ?".to_string());
params.push(Box::new(author.clone()));
}
if let Some(preview_front) = &request.preview_front {
query_parts.push("preview_front = ?".to_string());
params.push(Box::new(preview_front.clone()));
}
if let Some(preview_back) = &request.preview_back {
query_parts.push("preview_back = ?".to_string());
params.push(Box::new(preview_back.clone()));
}
if let Some(note_type) = &request.note_type {
query_parts.push("note_type = ?".to_string());
params.push(Box::new(note_type.clone()));
}
if let Some(fields) = &request.fields {
query_parts.push("fields_json = ?".to_string());
let fields_json = serde_json::to_string(fields)?;
owned_fields_json = Some(fields_json.clone());
params.push(Box::new(fields_json));
}
if let Some(generation_prompt) = &request.generation_prompt {
query_parts.push("generation_prompt = ?".to_string());
params.push(Box::new(generation_prompt.clone()));
}
if let Some(front_template) = &request.front_template {
query_parts.push("front_template = ?".to_string());
params.push(Box::new(front_template.clone()));
}
if let Some(back_template) = &request.back_template {
query_parts.push("back_template = ?".to_string());
params.push(Box::new(back_template.clone()));
}
if let Some(css_style) = &request.css_style {
query_parts.push("css_style = ?".to_string());
params.push(Box::new(css_style.clone()));
}
if let Some(field_extraction_rules) = &request.field_extraction_rules {
query_parts.push("field_extraction_rules_json = ?".to_string());
let rules_json = serde_json::to_string(field_extraction_rules)?;
owned_rules_json = Some(rules_json.clone());
params.push(Box::new(rules_json));
}
if let Some(is_active) = &request.is_active {
query_parts.push("is_active = ?".to_string());
let active_val = if *is_active { 1 } else { 0 };
owned_active_val = Some(active_val);
params.push(Box::new(active_val));
}
if query_parts.is_empty() {
return Ok(());
}
query_parts.push("updated_at = ?".to_string());
params.push(Box::new(now));
params.push(Box::new(template_id.to_string()));
let query = format!(
"UPDATE custom_anki_templates SET {} WHERE id = ?",
query_parts.join(", ")
);
conn.execute(&query, rusqlite::params_from_iter(params.iter().map(|p| p.as_ref())))?;
Ok(())
}
/// 删除自定义模板
pub fn delete_custom_template(&self, template_id: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute("DELETE FROM custom_anki_templates WHERE id = ?1 AND is_built_in = 0", params![template_id])?;
Ok(())
}
fn migrate_review_sessions_to_review_analyses(&self, conn: &rusqlite::Connection) -> anyhow::Result<()> {
// 检查旧表是否存在
let old_table_exists = conn.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='review_sessions';")?
.query_map([], |_| Ok(()))?
.any(|_| true);
if !old_table_exists {
println!("⏭️ 旧的review_sessions表不存在,跳过迁移");
return Ok(());
}
println!("🔄 迁移review_sessions数据到review_analyses");
// 创建新表(如果不存在)
conn.execute(
"CREATE TABLE IF NOT EXISTS review_analyses (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
subject TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
mistake_ids TEXT NOT NULL,
consolidated_input TEXT NOT NULL,
user_question TEXT NOT NULL,
status TEXT NOT NULL,
tags TEXT NOT NULL,
analysis_type TEXT NOT NULL DEFAULT 'consolidated_review'
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS review_chat_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
review_analysis_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
timestamp TEXT NOT NULL,
thinking_content TEXT,
rag_sources TEXT,
FOREIGN KEY(review_analysis_id) REFERENCES review_analyses(id) ON DELETE CASCADE
)",
[],
)?;
// 迁移数据
let mut stmt = conn.prepare("SELECT id, subject, mistake_ids, analysis_result, created_at FROM review_sessions")?;
let old_sessions: Vec<(String, String, String, String, String)> = stmt.query_map([], |row| {
Ok((
row.get::<_, String>(0)?, // id
row.get::<_, String>(1)?, // subject
row.get::<_, String>(2)?, // mistake_ids
row.get::<_, String>(3)?, // analysis_result
row.get::<_, String>(4)?, // created_at
))
})?.collect::<rusqlite::Result<Vec<_>>>()?;
let migration_count = old_sessions.len();
for (id, subject, mistake_ids, analysis_result, created_at) in old_sessions {
// 插入到新表
conn.execute(
"INSERT OR IGNORE INTO review_analyses
(id, name, subject, created_at, updated_at, mistake_ids, consolidated_input, user_question, status, tags, analysis_type)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
params![
id,
format!("回顾分析-{}", chrono::Utc::now().format("%Y%m%d")), // 默认名称
subject,
created_at,
chrono::Utc::now().to_rfc3339(), // updated_at
mistake_ids,
analysis_result, // 作为consolidated_input
"统一回顾分析", // 默认用户问题
"completed", // 默认状态
"[]", // 空标签数组
"consolidated_review"
]
)?;
// 迁移聊天记录
let mut chat_stmt = conn.prepare("SELECT role, content, timestamp FROM review_chat_messages WHERE review_id = ?1")?;
let chat_messages: Vec<(String, String, String)> = chat_stmt.query_map([&id], |row| {
Ok((
row.get::<_, String>(0)?, // role
row.get::<_, String>(1)?, // content
row.get::<_, String>(2)?, // timestamp
))
})?.collect::<rusqlite::Result<Vec<_>>>()?;
for (role, content, timestamp) in chat_messages {
conn.execute(
"INSERT INTO review_chat_messages
(review_analysis_id, role, content, timestamp, thinking_content, rag_sources)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![id, role, content, timestamp, None::<String>, None::<String>]
)?;
}
}
// 删除旧表(可选,为了保险起见先保留)
// conn.execute("DROP TABLE IF EXISTS review_sessions", [])?;
// conn.execute("DROP TABLE IF EXISTS review_chat_messages", [])?;
println!("✅ review_sessions迁移完成,迁移了{}条记录", migration_count);
Ok(())
}
/// 保存错题及其聊天记录
pub fn save_mistake(&self, mistake: &MistakeItem) -> Result<()> {
// 验证JSON格式以防止存储损坏的数据
self.validate_mistake_json_fields(mistake)?;
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
tx.execute(
"INSERT OR REPLACE INTO mistakes (id, subject, created_at, question_images, analysis_images, user_question, ocr_text, tags, mistake_type, status, updated_at, mistake_summary, user_error_analysis)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",
params![
mistake.id,
mistake.subject,
mistake.created_at.to_rfc3339(),
serde_json::to_string(&mistake.question_images)?,
serde_json::to_string(&mistake.analysis_images)?,
mistake.user_question,
mistake.ocr_text,
serde_json::to_string(&mistake.tags)?,
mistake.mistake_type,
mistake.status,
Utc::now().to_rfc3339(),
mistake.mistake_summary,
mistake.user_error_analysis,
],
)?;
// 删除旧的聊天记录,然后插入新的
tx.execute("DELETE FROM chat_messages WHERE mistake_id = ?1", params![mistake.id])?;
for message in &mistake.chat_history {
// 序列化RAG来源信息为JSON
let rag_sources_json = message.rag_sources.as_ref()
.map(|sources| serde_json::to_string(sources).unwrap_or_default());
tx.execute(
"INSERT INTO chat_messages (mistake_id, role, content, timestamp, thinking_content, rag_sources) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![mistake.id, message.role, message.content, message.timestamp.to_rfc3339(), message.thinking_content, rag_sources_json],
)?;
}
tx.commit()?;
Ok(())
}
/// 保存回顾分析及其聊天记录 - 复用错题分析的保存模式
pub fn save_review_analysis(&self, review: &ReviewAnalysisItem) -> Result<()> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
tx.execute(
"INSERT OR REPLACE INTO review_analyses
(id, name, subject, created_at, updated_at, mistake_ids, consolidated_input, user_question, status, tags, analysis_type)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
params![
review.id,
review.name,
review.subject,
review.created_at.to_rfc3339(),
review.updated_at.to_rfc3339(),
serde_json::to_string(&review.mistake_ids)?,
review.consolidated_input,
review.user_question,
review.status,
serde_json::to_string(&review.tags)?,
review.analysis_type,
],
)?;
// 删除旧的聊天记录,然后插入新的
tx.execute("DELETE FROM review_chat_messages WHERE review_analysis_id = ?1", params![review.id])?;
for message in &review.chat_history {
let rag_sources_json = message.rag_sources.as_ref()
.map(|sources| serde_json::to_string(sources))
.transpose()?;
tx.execute(
"INSERT INTO review_chat_messages
(review_analysis_id, role, content, timestamp, thinking_content, rag_sources)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![
review.id,
message.role,
message.content,
message.timestamp.to_rfc3339(),
message.thinking_content,
rag_sources_json,
],
)?;
}
tx.commit()?;
Ok(())
}
/// 根据ID获取错题及其聊天记录
pub fn get_mistake_by_id(&self, id: &str) -> Result<Option<MistakeItem>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT id, subject, created_at, question_images, analysis_images, user_question, ocr_text, tags, mistake_type, status, updated_at, mistake_summary, user_error_analysis FROM mistakes WHERE id = ?1"
)?;
let mistake_item = stmt.query_row(params![id], |row| {
let created_at_str: String = row.get(2)?;
let updated_at_str: String = row.get(10)?;
let question_images_str: String = row.get(3)?;
let analysis_images_str: String = row.get(4)?;
let tags_str: String = row.get(7)?;
let created_at = DateTime::parse_from_rfc3339(&created_at_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(2, "created_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(10, "updated_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
let question_images: Vec<String> = serde_json::from_str(&question_images_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(3, "question_images".to_string(), rusqlite::types::Type::Text))?;
let analysis_images: Vec<String> = serde_json::from_str(&analysis_images_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(4, "analysis_images".to_string(), rusqlite::types::Type::Text))?;
let tags: Vec<String> = serde_json::from_str(&tags_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(7, "tags".to_string(), rusqlite::types::Type::Text))?;
Ok(MistakeItem {
id: row.get(0)?,
subject: row.get(1)?,
created_at,
question_images,
analysis_images,
user_question: row.get(5)?,
ocr_text: row.get(6)?,
tags,
mistake_type: row.get(8)?,
status: row.get(9)?,
updated_at,
chat_history: vec![], // 稍后填充
mistake_summary: row.get(11)?, // 新增字段
user_error_analysis: row.get(12)?, // 新增字段
})
}).optional()?;
if let Some(mut item) = mistake_item {
let mut chat_stmt = conn.prepare(
"SELECT role, content, timestamp, thinking_content, rag_sources FROM chat_messages WHERE mistake_id = ?1 ORDER BY timestamp ASC"
)?;
let chat_iter = chat_stmt.query_map(params![id], |row| {
let timestamp_str: String = row.get(2)?;
let timestamp = DateTime::parse_from_rfc3339(×tamp_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(2, "timestamp".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
// 反序列化RAG来源信息
let rag_sources: Option<Vec<crate::models::RagSourceInfo>> =
if let Ok(Some(rag_sources_str)) = row.get::<_, Option<String>>(4) {
serde_json::from_str(&rag_sources_str).ok()
} else {
None
};
Ok(ChatMessage {
role: row.get(0)?,
content: row.get(1)?,
timestamp,
thinking_content: row.get(3)?,
rag_sources,
image_paths: None,
image_base64: None,
})
})?;
for msg_result in chat_iter {
item.chat_history.push(msg_result?);
}
Ok(Some(item))
} else {
Ok(None)
}
}
/// 根据ID获取回顾分析及其聊天记录 - 复用错题分析的查询模式
pub fn get_review_analysis_by_id(&self, id: &str) -> Result<Option<ReviewAnalysisItem>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT id, name, subject, created_at, updated_at, mistake_ids, consolidated_input, user_question, status, tags, analysis_type
FROM review_analyses WHERE id = ?1"
)?;
let review_item = stmt.query_row(params![id], |row| {
let created_at_str: String = row.get(3)?;
let updated_at_str: String = row.get(4)?;
let mistake_ids_str: String = row.get(5)?;
let tags_str: String = row.get(9)?;
let created_at = DateTime::parse_from_rfc3339(&created_at_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(3, "created_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(4, "updated_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
let mistake_ids: Vec<String> = serde_json::from_str(&mistake_ids_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(5, "mistake_ids".to_string(), rusqlite::types::Type::Text))?;
let tags: Vec<String> = serde_json::from_str(&tags_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(9, "tags".to_string(), rusqlite::types::Type::Text))?;
Ok(ReviewAnalysisItem {
id: row.get(0)?,
name: row.get(1)?,
subject: row.get(2)?,
created_at,
updated_at,
mistake_ids,
consolidated_input: row.get(6)?,
user_question: row.get(7)?,
status: row.get(8)?,
tags,
analysis_type: row.get(10)?,
chat_history: vec![], // 稍后填充
})
}).optional()?;
if let Some(mut item) = review_item {
let mut chat_stmt = conn.prepare(
"SELECT role, content, timestamp, thinking_content, rag_sources
FROM review_chat_messages WHERE review_analysis_id = ?1 ORDER BY timestamp ASC"
)?;
let chat_iter = chat_stmt.query_map(params![id], |row| {
let timestamp_str: String = row.get(2)?;
let timestamp = DateTime::parse_from_rfc3339(×tamp_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(2, "timestamp".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
// 反序列化RAG来源信息
let rag_sources: Option<Vec<crate::models::RagSourceInfo>> =
if let Ok(Some(rag_sources_str)) = row.get::<_, Option<String>>(4) {
serde_json::from_str(&rag_sources_str).ok()
} else {
None
};
Ok(ChatMessage {
role: row.get(0)?,
content: row.get(1)?,
timestamp,
thinking_content: row.get(3)?,
rag_sources,
image_paths: None,
image_base64: None,
})
})?;
for msg_result in chat_iter {
item.chat_history.push(msg_result?);
}
Ok(Some(item))
} else {
Ok(None)
}
}
/// 获取错题列表(支持筛选)
pub fn get_mistakes(
&self,
subject_filter: Option<&str>,
type_filter: Option<&str>,
tags_filter: Option<&[String]>, // 标签包含任意一个即可
) -> Result<Vec<MistakeItem>> {
let mut query = "SELECT id, subject, created_at, question_images, analysis_images, user_question, ocr_text, tags, mistake_type, status, updated_at FROM mistakes WHERE 1=1".to_string();
let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
if let Some(s) = subject_filter {
query.push_str(" AND subject = ?");
params_vec.push(Box::new(s.to_string()));
}
if let Some(t) = type_filter {
query.push_str(" AND mistake_type = ?");
params_vec.push(Box::new(t.to_string()));
}
// 注意: SQLite JSON 函数通常需要特定构建或扩展。
// 这里的标签过滤是一个简化版本,实际可能需要更复杂的查询或在应用层过滤。
// 一个更健壮的方法是使用JSON1扩展的json_each或json_extract。
// 为简单起见,如果提供了标签过滤器,我们暂时获取所有数据并在Rust中过滤。
// 或者,如果标签数量不多,可以构建 LIKE '%tag1%' OR LIKE '%tag2%' 这样的查询。
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(&query)?;
let mut rows = stmt.query(rusqlite::params_from_iter(params_vec.iter().map(|p| p.as_ref())))?;
let mut mistakes = Vec::new();
while let Some(row) = rows.next()? {
let created_at_str: String = row.get(2).map_err(|e| anyhow::anyhow!("Failed to get created_at: {}", e))?;
let updated_at_str: String = row.get(10).map_err(|e| anyhow::anyhow!("Failed to get updated_at: {}", e))?;
let tags_json: String = row.get(7).map_err(|e| anyhow::anyhow!("Failed to get tags: {}", e))?;
let current_tags: Vec<String> = serde_json::from_str(&tags_json)
.map_err(|e| anyhow::anyhow!("Failed to parse tags JSON: {}", e))?;
// 应用层标签过滤
if let Some(filter_tags) = tags_filter {
if filter_tags.is_empty() || !filter_tags.iter().any(|ft| current_tags.contains(ft)) {
if !filter_tags.is_empty() { // 如果过滤器非空但不匹配,则跳过
continue;
}
}
}
let question_images_str: String = row.get(3).map_err(|e| anyhow::anyhow!("Failed to get question_images: {}", e))?;
let analysis_images_str: String = row.get(4).map_err(|e| anyhow::anyhow!("Failed to get analysis_images: {}", e))?;
let created_at = DateTime::parse_from_rfc3339(&created_at_str)
.map_err(|e| anyhow::anyhow!("Failed to parse created_at: {}", e))?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
.map_err(|e| anyhow::anyhow!("Failed to parse updated_at: {}", e))?
.with_timezone(&Utc);
let question_images: Vec<String> = serde_json::from_str(&question_images_str)
.map_err(|e| anyhow::anyhow!("Failed to parse question_images JSON: {}", e))?;
let analysis_images: Vec<String> = serde_json::from_str(&analysis_images_str)
.map_err(|e| anyhow::anyhow!("Failed to parse analysis_images JSON: {}", e))?;
let item = MistakeItem {
id: row.get(0).map_err(|e| anyhow::anyhow!("Failed to get id: {}", e))?,
subject: row.get(1).map_err(|e| anyhow::anyhow!("Failed to get subject: {}", e))?,
created_at,
question_images,
analysis_images,
user_question: row.get(5).map_err(|e| anyhow::anyhow!("Failed to get user_question: {}", e))?,
ocr_text: row.get(6).map_err(|e| anyhow::anyhow!("Failed to get ocr_text: {}", e))?,
tags: current_tags,
mistake_type: row.get(8).map_err(|e| anyhow::anyhow!("Failed to get mistake_type: {}", e))?,
status: row.get(9).map_err(|e| anyhow::anyhow!("Failed to get status: {}", e))?,
updated_at,
chat_history: vec![], // 列表视图通常不需要完整的聊天记录
mistake_summary: None, // 列表视图不加载总结
user_error_analysis: None, // 列表视图不加载分析
};
mistakes.push(item);
}
Ok(mistakes)
}
/// 获取回顾分析列表(复用错题分析的列表模式)
pub fn get_review_analyses(
&self,
subject_filter: Option<&str>,
status_filter: Option<&str>,
) -> Result<Vec<ReviewAnalysisItem>> {
let mut query = "SELECT id, name, subject, created_at, updated_at, mistake_ids, consolidated_input, user_question, status, tags, analysis_type FROM review_analyses WHERE 1=1".to_string();
let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
if let Some(s) = subject_filter {
query.push_str(" AND subject = ?");
params_vec.push(Box::new(s.to_string()));
}
if let Some(st) = status_filter {
query.push_str(" AND status = ?");
params_vec.push(Box::new(st.to_string()));
}
query.push_str(" ORDER BY created_at DESC");
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(&query)?;
let mut rows = stmt.query(rusqlite::params_from_iter(params_vec.iter().map(|p| p.as_ref())))?;
let mut analyses = Vec::new();
while let Some(row) = rows.next()? {
let created_at_str: String = row.get(3)?;
let updated_at_str: String = row.get(4)?;
let mistake_ids_json: String = row.get(5)?;
let tags_json: String = row.get(9)?;
let created_at = DateTime::parse_from_rfc3339(&created_at_str)
.map_err(|e| anyhow::anyhow!("Failed to parse created_at: {}", e))?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
.map_err(|e| anyhow::anyhow!("Failed to parse updated_at: {}", e))?
.with_timezone(&Utc);
let mistake_ids: Vec<String> = serde_json::from_str(&mistake_ids_json)
.map_err(|e| anyhow::anyhow!("Failed to parse mistake_ids JSON: {}", e))?;
let tags: Vec<String> = serde_json::from_str(&tags_json)
.map_err(|e| anyhow::anyhow!("Failed to parse tags JSON: {}", e))?;
let item = ReviewAnalysisItem {
id: row.get(0)?,
name: row.get(1)?,
subject: row.get(2)?,
created_at,
updated_at,
mistake_ids,
consolidated_input: row.get(6)?,
user_question: row.get(7)?,
status: row.get(8)?,
tags,
analysis_type: row.get(10)?,
chat_history: vec![], // 列表视图不需要完整的聊天记录
};
analyses.push(item);
}
Ok(analyses)
}
/// 删除错题(同时删除关联的聊天记录,通过FOREIGN KEY CASCADE)
pub fn delete_mistake(&self, id: &str) -> Result<bool> {
let conn = self.conn.lock().unwrap();
let changes = conn.execute("DELETE FROM mistakes WHERE id = ?1", params![id])?;
Ok(changes > 0)
}
/// 保存设置
pub fn save_setting(&self, key: &str, value: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT OR REPLACE INTO settings (key, value, updated_at) VALUES (?1, ?2, ?3)",
params![key, value, Utc::now().to_rfc3339()],
)?;
Ok(())
}
/// 获取设置
pub fn get_setting(&self, key: &str) -> Result<Option<String>> {
let conn = self.conn.lock().unwrap();
conn.query_row(
"SELECT value FROM settings WHERE key = ?1",
params![key],
|row| row.get(0),
).optional().map_err(Into::into)
}
/// 获取统计信息
pub fn get_statistics(&self) -> Result<Statistics> {
let conn = self.conn.lock().unwrap();
// 获取错题总数
let total_mistakes: i32 = conn.query_row(
"SELECT COUNT(*) FROM mistakes",
[],
|row| row.get(0),
)?;
// 获取回顾分析总数(暂时为0,等实现回顾功能时更新)
let total_reviews: i32 = 0;
// 获取各科目统计
let mut subject_stats = std::collections::HashMap::new();
let mut stmt_subjects = conn.prepare("SELECT subject, COUNT(*) as count FROM mistakes GROUP BY subject")?;
let subject_iter = stmt_subjects.query_map([], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, i32>(1)?))
})?;
for subject_result in subject_iter {
let (subject, count) = subject_result?;
subject_stats.insert(subject, count);
}
// 获取各题目类型统计
let mut type_stats = std::collections::HashMap::new();
let mut stmt_types = conn.prepare("SELECT mistake_type, COUNT(*) as count FROM mistakes GROUP BY mistake_type")?;
let type_iter = stmt_types.query_map([], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, i32>(1)?))
})?;
for type_result in type_iter {
let (mistake_type, count) = type_result?;
type_stats.insert(mistake_type, count);
}
// 获取标签统计
let mut tag_stats = std::collections::HashMap::new();
let mut stmt_tags = conn.prepare("SELECT tags FROM mistakes WHERE tags IS NOT NULL AND tags != ''")?;
let tag_iter = stmt_tags.query_map([], |row| {
Ok(row.get::<_, String>(0)?)
})?;
for tag_result in tag_iter {
let tags_json = tag_result?;
if let Ok(tags) = serde_json::from_str::<Vec<String>>(&tags_json) {
for tag in tags {
*tag_stats.entry(tag).or_insert(0) += 1;
}
}
}
// 获取最近的错题
let mut recent_mistakes = Vec::new();
let mut stmt_recent = conn.prepare(
"SELECT id, subject, user_question, tags, created_at FROM mistakes ORDER BY created_at DESC LIMIT 5"
)?;
let recent_iter = stmt_recent.query_map([], |row| {
Ok(serde_json::json!({
"id": row.get::<_, String>(0)?,
"subject": row.get::<_, String>(1)?,
"user_question": row.get::<_, String>(2)?,
"tags": serde_json::from_str::<Vec<String>>(&row.get::<_, String>(3)?).unwrap_or_default(),
"created_at": row.get::<_, String>(4)?
}))
})?;
for recent_result in recent_iter {
recent_mistakes.push(recent_result?);
}
Ok(Statistics {
total_mistakes,
total_reviews,
subject_stats,
type_stats,
tag_stats,
recent_mistakes,
})
}
// TODO: 实现 review_sessions 和 review_chat_messages 表的相关操作
/// 保存回顾分析会话
pub fn save_review_session(&self, session: &crate::models::ReviewSession) -> Result<()> {
let conn = self.conn.lock().unwrap();
let tx = conn.unchecked_transaction()?;
// 保存会话基本信息
tx.execute(
"INSERT OR REPLACE INTO review_sessions (id, subject, mistake_ids, analysis_summary, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![
session.id,
session.subject,
serde_json::to_string(&session.mistake_ids)?,
session.analysis_summary,
session.created_at.to_rfc3339(),
session.updated_at.to_rfc3339()
],
)?;
// 删除旧的聊天记录
tx.execute("DELETE FROM review_chat_messages WHERE session_id = ?1", params![session.id])?;
// 保存聊天记录
for msg in &session.chat_history {
tx.execute(
"INSERT INTO review_chat_messages (id, session_id, role, content, timestamp) VALUES (?1, ?2, ?3, ?4, ?5)",
params![
msg.id,
msg.session_id,
msg.role,
msg.content,
msg.timestamp.to_rfc3339()
],
)?;
}
tx.commit()?;
Ok(())
}
/// 根据ID获取回顾分析会话
pub fn get_review_session_by_id(&self, id: &str) -> Result<Option<crate::models::ReviewSession>> {
let conn = self.conn.lock().unwrap();
let session_result = conn.query_row(
"SELECT id, subject, mistake_ids, analysis_summary, created_at, updated_at FROM review_sessions WHERE id = ?1",
params![id],
|row| {
let created_at_str: String = row.get(4)?;
let updated_at_str: String = row.get(5)?;
let mistake_ids_str: String = row.get(2)?;
let created_at = DateTime::parse_from_rfc3339(&created_at_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(4, "created_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(5, "updated_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
let mistake_ids: Vec<String> = serde_json::from_str(&mistake_ids_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(2, "mistake_ids".to_string(), rusqlite::types::Type::Text))?;
Ok(crate::models::ReviewSession {
id: row.get(0)?,
subject: row.get(1)?,
mistake_ids,
analysis_summary: row.get(3)?,
created_at,
updated_at,
chat_history: vec![], // 稍后填充
})
}
).optional()?;
if let Some(mut session) = session_result {
// 获取聊天记录
let mut chat_stmt = conn.prepare(
"SELECT id, session_id, role, content, timestamp FROM review_chat_messages WHERE session_id = ?1 ORDER BY timestamp ASC"
)?;
let chat_iter = chat_stmt.query_map(params![id], |row| {
let timestamp_str: String = row.get(4)?;
let timestamp = DateTime::parse_from_rfc3339(×tamp_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(4, "timestamp".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
Ok(crate::models::ReviewChatMessage {
id: row.get(0)?,
session_id: row.get(1)?,
role: row.get(2)?,
content: row.get(3)?,
timestamp,
})
})?;
for msg_result in chat_iter {
session.chat_history.push(msg_result?);
}
Ok(Some(session))
} else {
Ok(None)
}
}
/// 获取回顾分析会话列表
pub fn get_review_sessions(&self, subject_filter: Option<&str>) -> Result<Vec<crate::models::ReviewSession>> {
let conn = self.conn.lock().unwrap();
let mut query = "SELECT id, subject, mistake_ids, analysis_summary, created_at, updated_at FROM review_sessions WHERE 1=1".to_string();
let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
if let Some(subject) = subject_filter {
query.push_str(" AND subject = ?");
params_vec.push(Box::new(subject.to_string()));
}
query.push_str(" ORDER BY created_at DESC");
let mut stmt = conn.prepare(&query)?;
let mut rows = stmt.query(rusqlite::params_from_iter(params_vec.iter().map(|p| p.as_ref())))?;
let mut sessions = Vec::new();
while let Some(row) = rows.next()? {
let created_at_str: String = row.get(4)?;
let updated_at_str: String = row.get(5)?;
let mistake_ids_str: String = row.get(2)?;
let created_at = DateTime::parse_from_rfc3339(&created_at_str)
.map_err(|e| anyhow::anyhow!("Failed to parse created_at: {}", e))?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
.map_err(|e| anyhow::anyhow!("Failed to parse updated_at: {}", e))?
.with_timezone(&Utc);
let mistake_ids: Vec<String> = serde_json::from_str(&mistake_ids_str)
.map_err(|e| anyhow::anyhow!("Failed to parse mistake_ids JSON: {}", e))?;
let session = crate::models::ReviewSession {
id: row.get(0)?,
subject: row.get(1)?,
mistake_ids,
analysis_summary: row.get(3)?,
created_at,
updated_at,
chat_history: vec![], // 列表视图不需要完整聊天记录
};
sessions.push(session);
}
Ok(sessions)
}
/// 删除回顾分析会话
pub fn delete_review_session(&self, id: &str) -> Result<bool> {
let conn = self.conn.lock().unwrap();
let changes = conn.execute("DELETE FROM review_sessions WHERE id = ?1", params![id])?;
Ok(changes > 0)
}
/// 删除回顾分析(统一回顾分析功能)
pub fn delete_review_analysis(&self, id: &str) -> Result<bool> {
let conn = self.conn.lock().unwrap();
// 由于设置了 ON DELETE CASCADE,删除主记录时会自动删除关联的聊天消息
let changes = conn.execute("DELETE FROM review_analyses WHERE id = ?1", params![id])?;
Ok(changes > 0)
}
/// 添加回顾分析聊天消息
pub fn add_review_chat_message(&self, message: &crate::models::ReviewChatMessage) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO review_chat_messages (id, session_id, role, content, timestamp) VALUES (?1, ?2, ?3, ?4, ?5)",
params![
message.id,
message.session_id,
message.role,
message.content,
message.timestamp.to_rfc3339()
],
)?;
// 更新会话的更新时间
conn.execute(
"UPDATE review_sessions SET updated_at = ?1 WHERE id = ?2",
params![Utc::now().to_rfc3339(), message.session_id],
)?;
Ok(())
}
// 科目配置管理方法
/// 保存科目配置
pub fn save_subject_config(&self, config: &SubjectConfig) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT OR REPLACE INTO subject_configs (id, subject_name, display_name, description, is_enabled, prompts, mistake_types, default_tags, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
params![
config.id,
config.subject_name,
config.display_name,
config.description,
config.is_enabled as i32,
serde_json::to_string(&config.prompts)?,
serde_json::to_string(&config.mistake_types)?,
serde_json::to_string(&config.default_tags)?,
config.created_at.to_rfc3339(),
config.updated_at.to_rfc3339(),
],
)?;
Ok(())
}
/// 根据ID获取科目配置
pub fn get_subject_config_by_id(&self, id: &str) -> Result<Option<SubjectConfig>> {
let conn = self.conn.lock().unwrap();
conn.query_row(
"SELECT id, subject_name, display_name, description, is_enabled, prompts, mistake_types, default_tags, created_at, updated_at
FROM subject_configs WHERE id = ?1",
params![id],
|row| {
let created_at_str: String = row.get(8)?;
let updated_at_str: String = row.get(9)?;
let prompts_str: String = row.get(5)?;
let mistake_types_str: String = row.get(6)?;
let default_tags_str: String = row.get(7)?;
let created_at = DateTime::parse_from_rfc3339(&created_at_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(8, "created_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(9, "updated_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
let prompts: SubjectPrompts = self.parse_subject_prompts(&prompts_str)?;
let mistake_types: Vec<String> = serde_json::from_str(&mistake_types_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(6, "mistake_types".to_string(), rusqlite::types::Type::Text))?;
let default_tags: Vec<String> = serde_json::from_str(&default_tags_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(7, "default_tags".to_string(), rusqlite::types::Type::Text))?;
Ok(SubjectConfig {
id: row.get(0)?,
subject_name: row.get(1)?,
display_name: row.get(2)?,
description: row.get(3)?,
is_enabled: row.get::<_, i32>(4)? != 0,
prompts,
mistake_types,
default_tags,
created_at,
updated_at,
})
}
).optional().map_err(Into::into)
}
/// 根据科目名称获取科目配置
pub fn get_subject_config_by_name(&self, subject_name: &str) -> Result<Option<SubjectConfig>> {
let conn = self.conn.lock().unwrap();
conn.query_row(
"SELECT id, subject_name, display_name, description, is_enabled, prompts, mistake_types, default_tags, created_at, updated_at
FROM subject_configs WHERE subject_name = ?1",
params![subject_name],
|row| {
let created_at_str: String = row.get(8)?;
let updated_at_str: String = row.get(9)?;
let prompts_str: String = row.get(5)?;
let mistake_types_str: String = row.get(6)?;
let default_tags_str: String = row.get(7)?;
let created_at = DateTime::parse_from_rfc3339(&created_at_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(8, "created_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(9, "updated_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
let prompts: SubjectPrompts = self.parse_subject_prompts(&prompts_str)?;
let mistake_types: Vec<String> = serde_json::from_str(&mistake_types_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(6, "mistake_types".to_string(), rusqlite::types::Type::Text))?;
let default_tags: Vec<String> = serde_json::from_str(&default_tags_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(7, "default_tags".to_string(), rusqlite::types::Type::Text))?;
Ok(SubjectConfig {
id: row.get(0)?,
subject_name: row.get(1)?,
display_name: row.get(2)?,
description: row.get(3)?,
is_enabled: row.get::<_, i32>(4)? != 0,
prompts,
mistake_types,
default_tags,
created_at,
updated_at,
})
}
).optional().map_err(Into::into)
}
/// 获取所有科目配置
pub fn get_all_subject_configs(&self, enabled_only: bool) -> Result<Vec<SubjectConfig>> {
let conn = self.conn.lock().unwrap();
let query = if enabled_only {
"SELECT id, subject_name, display_name, description, is_enabled, prompts, mistake_types, default_tags, created_at, updated_at
FROM subject_configs WHERE is_enabled = 1 ORDER BY display_name"
} else {
"SELECT id, subject_name, display_name, description, is_enabled, prompts, mistake_types, default_tags, created_at, updated_at
FROM subject_configs ORDER BY display_name"
};
let mut stmt = conn.prepare(query)?;
let mut rows = stmt.query([])?;
let mut configs = Vec::new();
while let Some(row) = rows.next()? {
let created_at_str: String = row.get(8)?;
let updated_at_str: String = row.get(9)?;
let prompts_str: String = row.get(5)?;
let mistake_types_str: String = row.get(6)?;
let default_tags_str: String = row.get(7)?;
let created_at = DateTime::parse_from_rfc3339(&created_at_str)
.map_err(|e| anyhow::anyhow!("Failed to parse created_at: {}", e))?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
.map_err(|e| anyhow::anyhow!("Failed to parse updated_at: {}", e))?
.with_timezone(&Utc);
let prompts: SubjectPrompts = self.parse_subject_prompts(&prompts_str)
.map_err(|e| anyhow::anyhow!("Failed to parse prompts JSON: {:?}", e))?;
let mistake_types: Vec<String> = serde_json::from_str(&mistake_types_str)
.map_err(|e| anyhow::anyhow!("Failed to parse mistake_types JSON: {}", e))?;
let default_tags: Vec<String> = serde_json::from_str(&default_tags_str)
.map_err(|e| anyhow::anyhow!("Failed to parse default_tags JSON: {}", e))?;
let config = SubjectConfig {
id: row.get(0)?,
subject_name: row.get(1)?,
display_name: row.get(2)?,
description: row.get(3)?,
is_enabled: row.get::<_, i32>(4)? != 0,
prompts,
mistake_types,
default_tags,
created_at,
updated_at,
};
configs.push(config);
}
Ok(configs)
}
/// 删除科目配置
pub fn delete_subject_config(&self, id: &str) -> Result<bool> {
let conn = self.conn.lock().unwrap();
let changes = conn.execute("DELETE FROM subject_configs WHERE id = ?1", params![id])?;
Ok(changes > 0)
}
/// 初始化默认科目配置
pub fn initialize_default_subject_configs(&self) -> Result<()> {
let default_subjects = vec![
("数学", "Mathematics", "数学错题分析和讲解", self.get_math_prompts()),
("物理", "Physics", "物理概念和计算题目分析", self.get_physics_prompts()),
("化学", "Chemistry", "化学反应和实验题目分析", self.get_chemistry_prompts()),
("英语", "English", "英语语法和阅读理解分析", self.get_english_prompts()),
("语文", "Chinese", "语文阅读理解和写作分析", self.get_chinese_prompts()),
("生物", "Biology", "生物概念和实验题目分析", self.get_biology_prompts()),
("历史", "History", "历史事件和知识点分析", self.get_history_prompts()),
("地理", "Geography", "地理概念和区域分析", self.get_geography_prompts()),
("政治", "Politics", "政治理论和时事分析", self.get_politics_prompts()),
];
for (subject_name, _english_name, description, prompts) in default_subjects {
// 检查是否已存在
if self.get_subject_config_by_name(subject_name)?.is_none() {
let config = SubjectConfig {
id: uuid::Uuid::new_v4().to_string(),
subject_name: subject_name.to_string(),
display_name: subject_name.to_string(),
description: description.to_string(),
is_enabled: true,
prompts,
mistake_types: vec![
"计算错误".to_string(),
"概念理解".to_string(),
"方法应用".to_string(),
"知识遗忘".to_string(),
"审题不清".to_string(),
],
default_tags: vec![
"基础知识".to_string(),
"重点难点".to_string(),
"易错点".to_string(),
],
created_at: Utc::now(),
updated_at: Utc::now(),
};
self.save_subject_config(&config)?;
}
}
Ok(())
}
// 数学科目的专业提示词
fn get_math_prompts(&self) -> SubjectPrompts {
SubjectPrompts {
analysis_prompt: "你是一个数学教学专家。请根据提供的{subject}题目信息,详细解答学生的问题。解答要清晰、准确,包含必要的步骤和原理解释。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道错题,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要准确、详细,包含必要的公式推导和计算步骤。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,不要使用LaTeX格式\n2. 数学公式用普通文字描述,如:λ = 2 的几何重数\n3. 矩阵用文字描述,如:矩阵A减去2I等于...\n4. 避免使用\\left、\\begin{array}、\\frac等LaTeX命令\n5. 保持文本简洁易读".to_string(),
classification_prompt: "请分析这道{subject}题目的类型(如选择题、填空题、计算题、证明题等),并生成相关的{subject}标签(如代数、几何、函数、导数、概率等)。".to_string(),
consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的数学概念或公式。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案、公式或解释,tags字段应包含相关的数学知识点标签如代数、几何、函数等。".to_string(),
}
}
// 物理科目的专业提示词
fn get_physics_prompts(&self) -> SubjectPrompts {
SubjectPrompts {
analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含物理原理、公式推导和计算过程,注重物理概念的理解。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含相关的物理定律、公式应用和现象解释。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,不要使用LaTeX格式\n2. 物理公式用普通文字描述,如:F等于m乘以a\n3. 物理量用文字描述,如:速度v等于20米每秒\n4. 避免使用\\frac、\\sqrt等LaTeX命令\n5. 保持文本简洁易读".to_string(),
classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如力学、电学、光学、热学、原子物理等)。".to_string(),
consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的物理原理或定律概念。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的物理知识点标签。".to_string(),
}
}
// 化学科目的专业提示词
fn get_chemistry_prompts(&self) -> SubjectPrompts {
SubjectPrompts {
analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含化学原理、方程式和计算过程,注重化学反应机理的理解。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含相关的化学反应、化学方程式和实验原理。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,不要使用LaTeX格式\n2. 化学方程式用普通文字描述,如:2H2加O2反应生成2H2O\n3. 分子式用普通文字,如:H2O、NaCl\n4. 避免使用\\rightarrow、\\text等LaTeX命令\n5. 保持文本简洁易读".to_string(),
classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如有机化学、无机化学、物理化学、分析化学等)。".to_string(),
consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的化学反应或概念。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的化学知识点标签。".to_string(),
}
}
// 英语科目的专业提示词
fn get_english_prompts(&self) -> SubjectPrompts {
SubjectPrompts {
analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含语法解释、词汇分析和例句说明。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含语法规则、词汇用法和语言表达技巧。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,包括题目、选项、文章等\n2. 保持英文单词和句子的完整性\n3. 注意大小写和标点符号\n4. 保持段落和换行结构\n5. 保持文本简洁易读".to_string(),
classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如语法、词汇、阅读理解、写作、听力等)。".to_string(),
consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的语法规则或词汇概念。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的英语知识点标签。".to_string(),
}
}
// 语文科目的专业提示词
fn get_chinese_prompts(&self) -> SubjectPrompts {
SubjectPrompts {
analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含文本分析、语言表达和写作技巧。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含文学理解、语言运用和表达技巧。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,包括文章、诗词、题目等\n2. 保持古诗词的格式和断句\n3. 注意繁体字和异体字的识别\n4. 保持标点符号的准确性\n5. 保持文本简洁易读".to_string(),
classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如阅读理解、写作、古诗词、文言文等)。".to_string(),
consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的文学知识或语言表达概念。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的语文知识点标签。".to_string(),
}
}
// 生物科目的专业提示词
fn get_biology_prompts(&self) -> SubjectPrompts {
SubjectPrompts {
analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含生物概念、生理过程和实验原理。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含相关的生物原理、生命过程和实验方法。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,不要使用LaTeX格式\n2. 生物化学公式用普通文字描述,如:葡萄糖C6H12O6\n3. 基因型用普通文字,如:AA、Aa、aa\n4. 避免使用LaTeX命令\n5. 保持文本简洁易读".to_string(),
classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如细胞生物学、遗传学、生态学、进化论等)。".to_string(),
consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的生物概念或生命过程。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的生物知识点标签。".to_string(),
}
}
// 历史科目的专业提示词
fn get_history_prompts(&self) -> SubjectPrompts {
SubjectPrompts {
analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含历史背景、事件分析和影响评价。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含历史事件、人物分析和时代背景。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,包括题目、史料、时间等\n2. 注意历史人名和地名的准确性\n3. 保持时间表述的完整性\n4. 注意朝代和年号的正确识别\n5. 保持文本简洁易读".to_string(),
classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如古代史、近代史、现代史、政治史、经济史等)。".to_string(),
consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的历史事件或人物概念。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的历史知识点标签。".to_string(),
}
}
// 地理科目的专业提示词
fn get_geography_prompts(&self) -> SubjectPrompts {
SubjectPrompts {
analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含地理概念、空间分析和区域特征。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含地理原理、空间关系和区域分析。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,包括题目、地名、数据等\n2. 注意地名和专业术语的准确性\n3. 保持经纬度、海拔等数据的完整性\n4. 注意图表和统计数据的正确识别\n5. 保持文本简洁易读".to_string(),
classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如自然地理、人文地理、区域地理、地图分析等)。".to_string(),
consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的地理概念或区域特征。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的地理知识点标签。".to_string(),
}
}
// 政治科目的专业提示词
fn get_politics_prompts(&self) -> SubjectPrompts {
SubjectPrompts {
analysis_prompt: "你是一个{subject}教学专家。请根据提供的题目信息,详细解答学生的问题。解答要包含政治理论、政策分析和思想原理。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
review_prompt: "你是一个{subject}学习分析专家。请分析学生的多道{subject}错题,找出共同的易错点、知识盲区和学习模式,提供针对性的{subject}学习建议。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
chat_prompt: "基于这道{subject}题目,请回答学生的问题。回答要包含政治原理、政策解读和思想分析。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
ocr_prompt: "你是一个{subject}题目分析专家。请识别图片中的{subject}题目文字内容。\n\n【重要】OCR文本提取要求:\n1. 提取纯文本内容,包括题目、理论、政策等\n2. 注意政治术语和概念的准确性\n3. 保持理论表述的完整性\n4. 注意政策名称和法规条文的正确识别\n5. 保持文本简洁易读".to_string(),
classification_prompt: "请分析这道{subject}题目的类型,并生成相关的{subject}标签(如马克思主义、政治制度、经济政策、哲学原理等)。".to_string(),
consolidated_review_prompt: "你是一个{subject}回顾分析专家。请对以下多道{subject}错题进行统一分析,找出共同的易错点、知识盲区和学习模式。请提供:1. 错题间的关联性分析 2. 主要易错点总结 3. 知识点掌握情况评估 4. 针对性的学习建议和复习计划。\n\n【LaTeX 数学公式输出规范】\n1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。\n2. 行内公式使用 `$...$` 包裹,例如:`$E=mc^2$`。\n3. 独立展示的公式或方程组使用 `$$...$$` 包裹。\n4. 对于矩阵,请务必使用 `bmatrix` 环境,例如:`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$`。在 `bmatrix` 环境中,使用 `&` 分隔列元素,使用 `\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 `\\\\\\\\`) 换行。\n5. 确保所有LaTeX环境(如 `bmatrix`)和括号都正确配对和闭合。\n6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。".to_string(),
anki_generation_prompt: "请根据以下{subject}科目的学习内容,生成适合制作Anki卡片的问题和答案对。每张卡片应测试一个单一的政治理论或制度概念。请以JSON数组格式返回结果,每个对象必须包含 \"front\" (字符串), \"back\" (字符串), \"tags\" (字符串数组) 三个字段。front字段应包含问题或概念名称,back字段应包含答案或解释,tags字段应包含相关的政治知识点标签。".to_string(),
}
}
/// 保存模型分配配置
pub fn save_model_assignments(&self, assignments: &crate::models::ModelAssignments) -> Result<()> {
let assignments_json = serde_json::to_string(assignments)?;
self.save_setting("model_assignments", &assignments_json)
}
/// 获取模型分配配置
pub fn get_model_assignments(&self) -> Result<Option<crate::models::ModelAssignments>> {
match self.get_setting("model_assignments")? {
Some(json_str) => {
let assignments: crate::models::ModelAssignments = serde_json::from_str(&json_str)?;
Ok(Some(assignments))
}
None => Ok(None)
}
}
/// 保存API配置列表
pub fn save_api_configs(&self, configs: &[crate::llm_manager::ApiConfig]) -> Result<()> {
let configs_json = serde_json::to_string(configs)?;
self.save_setting("api_configs", &configs_json)
}
/// 获取API配置列表
pub fn get_api_configs(&self) -> Result<Vec<crate::llm_manager::ApiConfig>> {
match self.get_setting("api_configs")? {
Some(json_str) => {
let configs: Vec<crate::llm_manager::ApiConfig> = serde_json::from_str(&json_str)?;
Ok(configs)
}
None => Ok(Vec::new())
}
}
/// 验证错题的JSON字段格式,防止存储损坏的数据
fn validate_mistake_json_fields(&self, mistake: &MistakeItem) -> Result<()> {
// 验证question_images能够正确序列化和反序列化
let question_images_json = serde_json::to_string(&mistake.question_images)
.map_err(|e| anyhow::Error::new(e).context("序列化question_images失败"))?;
serde_json::from_str::<Vec<String>>(&question_images_json)
.map_err(|e| anyhow::Error::new(e).context("验证question_images JSON格式失败"))?;
// 验证analysis_images能够正确序列化和反序列化
let analysis_images_json = serde_json::to_string(&mistake.analysis_images)
.map_err(|e| anyhow::Error::new(e).context("序列化analysis_images失败"))?;
serde_json::from_str::<Vec<String>>(&analysis_images_json)
.map_err(|e| anyhow::Error::new(e).context("验证analysis_images JSON格式失败"))?;
// 验证tags能够正确序列化和反序列化
let tags_json = serde_json::to_string(&mistake.tags)
.map_err(|e| anyhow::Error::new(e).context("序列化tags失败"))?;
serde_json::from_str::<Vec<String>>(&tags_json)
.map_err(|e| anyhow::Error::new(e).context("验证tags JSON格式失败"))?;
// 额外验证:检查图片路径的有效性
for (i, path) in mistake.question_images.iter().enumerate() {
if path.is_empty() {
return Err(anyhow::Error::msg(format!("question_images[{}] 路径为空", i)));
}
// 基本路径格式检查
if path.contains("..") || path.starts_with('/') {
return Err(anyhow::Error::msg(format!("question_images[{}] 路径格式不安全: {}", i, path)));
}
}
for (i, path) in mistake.analysis_images.iter().enumerate() {
if path.is_empty() {
return Err(anyhow::Error::msg(format!("analysis_images[{}] 路径为空", i)));
}
// 基本路径格式检查
if path.contains("..") || path.starts_with('/') {
return Err(anyhow::Error::msg(format!("analysis_images[{}] 路径格式不安全: {}", i, path)));
}
}
println!("错题JSON字段验证通过: question_images={}, analysis_images={}, tags={}",
mistake.question_images.len(), mistake.analysis_images.len(), mistake.tags.len());
Ok(())
}
/// 解析科目提示词,自动处理缺失的anki_generation_prompt字段(向后兼容)
fn parse_subject_prompts(&self, prompts_str: &str) -> rusqlite::Result<SubjectPrompts> {
// 尝试直接解析现有格式
if let Ok(prompts) = serde_json::from_str::<SubjectPrompts>(prompts_str) {
return Ok(prompts);
}
// 如果解析失败,可能是因为缺少新字段,尝试解析为旧格式
#[derive(serde::Deserialize)]
struct LegacySubjectPrompts {
analysis_prompt: String,
review_prompt: String,
chat_prompt: String,
ocr_prompt: String,
classification_prompt: String,
consolidated_review_prompt: String,
}
match serde_json::from_str::<LegacySubjectPrompts>(prompts_str) {
Ok(legacy) => {
// 转换为新格式,添加默认的anki_generation_prompt
Ok(SubjectPrompts {
analysis_prompt: legacy.analysis_prompt,
review_prompt: legacy.review_prompt,
chat_prompt: legacy.chat_prompt,
ocr_prompt: legacy.ocr_prompt,
classification_prompt: legacy.classification_prompt,
consolidated_review_prompt: legacy.consolidated_review_prompt,
anki_generation_prompt: "请根据以下学习内容,生成适合制作Anki卡片的问题和答案对。请以JSON数组格式返回结果,每个对象必须包含 front(字符串),back(字符串),tags(字符串数组)三个字段。".to_string(),
})
},
Err(_) => {
Err(rusqlite::Error::InvalidColumnType(5, "prompts".to_string(), rusqlite::types::Type::Text))
}
}
}
// =================== Anki Enhancement Functions ===================
/// 插入文档任务
pub fn insert_document_task(&self, task: &DocumentTask) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO document_tasks
(id, document_id, original_document_name, segment_index, content_segment,
status, created_at, updated_at, error_message, subject_name, anki_generation_options_json)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
params![
task.id,
task.document_id,
task.original_document_name,
task.segment_index,
task.content_segment,
task.status.to_db_string(),
task.created_at,
task.updated_at,
task.error_message,
task.subject_name,
task.anki_generation_options_json
]
)?;
Ok(())
}
/// 更新文档任务状态
pub fn update_document_task_status(&self, task_id: &str, status: TaskStatus, error_message: Option<String>) -> Result<()> {
let conn = self.conn.lock().unwrap();
let updated_at = chrono::Utc::now().to_rfc3339();
conn.execute(
"UPDATE document_tasks SET status = ?1, error_message = ?2, updated_at = ?3 WHERE id = ?4",
params![
status.to_db_string(),
error_message,
updated_at,
task_id
]
)?;
Ok(())
}
/// 获取单个文档任务
pub fn get_document_task(&self, task_id: &str) -> Result<DocumentTask> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT id, document_id, original_document_name, segment_index, content_segment,
status, created_at, updated_at, error_message, subject_name, anki_generation_options_json
FROM document_tasks WHERE id = ?1"
)?;
let task = stmt.query_row(params![task_id], |row| {
let status_str: String = row.get(5)?;
let status: TaskStatus = serde_json::from_str(&status_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(5, "status".to_string(), rusqlite::types::Type::Text))?;
Ok(DocumentTask {
id: row.get(0)?,
document_id: row.get(1)?,
original_document_name: row.get(2)?,
segment_index: row.get(3)?,
content_segment: row.get(4)?,
status,
created_at: row.get(6)?,
updated_at: row.get(7)?,
error_message: row.get(8)?,
subject_name: row.get(9)?,
anki_generation_options_json: row.get(10)?,
})
})?;
Ok(task)
}
/// 获取指定文档的所有任务
pub fn get_tasks_for_document(&self, document_id: &str) -> Result<Vec<DocumentTask>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT id, document_id, original_document_name, segment_index, content_segment,
status, created_at, updated_at, error_message, subject_name, anki_generation_options_json
FROM document_tasks WHERE document_id = ?1 ORDER BY segment_index"
)?;
let task_iter = stmt.query_map(params![document_id], |row| {
let status_str: String = row.get(5)?;
let status: TaskStatus = serde_json::from_str(&status_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(5, "status".to_string(), rusqlite::types::Type::Text))?;
Ok(DocumentTask {
id: row.get(0)?,
document_id: row.get(1)?,
original_document_name: row.get(2)?,
segment_index: row.get(3)?,
content_segment: row.get(4)?,
status,
created_at: row.get(6)?,
updated_at: row.get(7)?,
error_message: row.get(8)?,
subject_name: row.get(9)?,
anki_generation_options_json: row.get(10)?,
})
})?;
let mut tasks = Vec::new();
for task in task_iter {
tasks.push(task?);
}
Ok(tasks)
}
/// 插入Anki卡片
pub fn insert_anki_card(&self, card: &AnkiCard) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO anki_cards
(id, task_id, front, back, text, tags_json, images_json,
is_error_card, error_content, card_order_in_task, created_at, updated_at,
extra_fields_json, template_id)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
params![
card.id,
card.task_id,
card.front,
card.back,
card.text,
serde_json::to_string(&card.tags)?,
serde_json::to_string(&card.images)?,
if card.is_error_card { 1 } else { 0 },
card.error_content,
0, // card_order_in_task will be calculated
card.created_at,
card.updated_at,
serde_json::to_string(&card.extra_fields)?,
card.template_id
]
)?;
Ok(())
}
/// 获取指定任务的所有卡片
pub fn get_cards_for_task(&self, task_id: &str) -> Result<Vec<AnkiCard>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT id, task_id, front, back, text, tags_json, images_json,
is_error_card, error_content, created_at, updated_at,
COALESCE(extra_fields_json, '{}') as extra_fields_json,
template_id
FROM anki_cards WHERE task_id = ?1 ORDER BY card_order_in_task, created_at"
)?;
let card_iter = stmt.query_map(params![task_id], |row| {
let tags_json: String = row.get(5)?;
let tags: Vec<String> = serde_json::from_str(&tags_json).unwrap_or_default();
let images_json: String = row.get(6)?;
let images: Vec<String> = serde_json::from_str(&images_json).unwrap_or_default();
let extra_fields_json: String = row.get(11)?;
let extra_fields: std::collections::HashMap<String, String> =
serde_json::from_str(&extra_fields_json).unwrap_or_default();
Ok(AnkiCard {
id: row.get(0)?,
task_id: row.get(1)?,
front: row.get(2)?,
back: row.get(3)?,
text: row.get(4)?,
tags,
images,
is_error_card: row.get::<_, i32>(7)? != 0,
error_content: row.get(8)?,
created_at: row.get(9)?,
updated_at: row.get(10)?,
extra_fields,
template_id: row.get(12)?,
})
})?;
let mut cards = Vec::new();
for card in card_iter {
cards.push(card?);
}
Ok(cards)
}
/// 获取指定文档的所有卡片
pub fn get_cards_for_document(&self, document_id: &str) -> Result<Vec<AnkiCard>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT ac.id, ac.task_id, ac.front, ac.back, ac.text, ac.tags_json, ac.images_json,
ac.is_error_card, ac.error_content, ac.created_at, ac.updated_at,
COALESCE(ac.extra_fields_json, '{}') as extra_fields_json,
ac.template_id
FROM anki_cards ac
JOIN document_tasks dt ON ac.task_id = dt.id
WHERE dt.document_id = ?1
ORDER BY dt.segment_index, ac.card_order_in_task, ac.created_at"
)?;
let card_iter = stmt.query_map(params![document_id], |row| {
let tags_json: String = row.get(5)?;
let tags: Vec<String> = serde_json::from_str(&tags_json).unwrap_or_default();
let images_json: String = row.get(6)?;
let images: Vec<String> = serde_json::from_str(&images_json).unwrap_or_default();
let extra_fields_json: String = row.get(11)?;
let extra_fields: std::collections::HashMap<String, String> =
serde_json::from_str(&extra_fields_json).unwrap_or_default();
Ok(AnkiCard {
id: row.get(0)?,
task_id: row.get(1)?,
front: row.get(2)?,
back: row.get(3)?,
text: row.get(4)?,
tags,
images,
is_error_card: row.get::<_, i32>(7)? != 0,
error_content: row.get(8)?,
created_at: row.get(9)?,
updated_at: row.get(10)?,
extra_fields,
template_id: row.get(12)?,
})
})?;
let mut cards = Vec::new();
for card in card_iter {
cards.push(card?);
}
Ok(cards)
}
/// 根据ID列表获取卡片
pub fn get_cards_by_ids(&self, card_ids: &[String]) -> Result<Vec<AnkiCard>> {
if card_ids.is_empty() {
return Ok(Vec::new());
}
let conn = self.conn.lock().unwrap();
let placeholders: Vec<&str> = card_ids.iter().map(|_| "?").collect();
let sql = format!(
"SELECT id, task_id, front, back, text, tags_json, images_json,
is_error_card, error_content, created_at, updated_at,
COALESCE(extra_fields_json, '{{}}') as extra_fields_json,
template_id
FROM anki_cards WHERE id IN ({}) ORDER BY created_at",
placeholders.join(",")
);
let mut stmt = conn.prepare(&sql)?;
let card_iter = stmt.query_map(rusqlite::params_from_iter(card_ids), |row| {
let tags_json: String = row.get(5)?;
let tags: Vec<String> = serde_json::from_str(&tags_json).unwrap_or_default();
let images_json: String = row.get(6)?;
let images: Vec<String> = serde_json::from_str(&images_json).unwrap_or_default();
let extra_fields_json: String = row.get(11)?;
let extra_fields: std::collections::HashMap<String, String> =
serde_json::from_str(&extra_fields_json).unwrap_or_default();
Ok(AnkiCard {
id: row.get(0)?,
task_id: row.get(1)?,
front: row.get(2)?,
back: row.get(3)?,
text: row.get(4)?,
tags,
images,
is_error_card: row.get::<_, i32>(7)? != 0,
error_content: row.get(8)?,
created_at: row.get(9)?,
updated_at: row.get(10)?,
extra_fields,
template_id: row.get(12)?,
})
})?;
let mut cards = Vec::new();
for card in card_iter {
cards.push(card?);
}
Ok(cards)
}
/// 更新Anki卡片
pub fn update_anki_card(&self, card: &AnkiCard) -> Result<()> {
let conn = self.conn.lock().unwrap();
let updated_at = chrono::Utc::now().to_rfc3339();
conn.execute(
"UPDATE anki_cards SET
front = ?1, back = ?2, tags_json = ?3, images_json = ?4,
is_error_card = ?5, error_content = ?6, updated_at = ?7
WHERE id = ?8",
params![
card.front,
card.back,
serde_json::to_string(&card.tags)?,
serde_json::to_string(&card.images)?,
if card.is_error_card { 1 } else { 0 },
card.error_content,
updated_at,
card.id
]
)?;
Ok(())
}
/// 删除Anki卡片
pub fn delete_anki_card(&self, card_id: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute("DELETE FROM anki_cards WHERE id = ?1", params![card_id])?;
Ok(())
}
/// 删除文档任务及其所有卡片
pub fn delete_document_task(&self, task_id: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
// 由于设置了ON DELETE CASCADE,删除任务会自动删除关联的卡片
conn.execute("DELETE FROM document_tasks WHERE id = ?1", params![task_id])?;
Ok(())
}
/// 删除整个文档会话(所有任务和卡片)
pub fn delete_document_session(&self, document_id: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
// 由于设置了ON DELETE CASCADE,删除任务会自动删除关联的卡片
conn.execute("DELETE FROM document_tasks WHERE document_id = ?1", params![document_id])?;
Ok(())
}
// ==================== RAG配置管理 ====================
/// 获取RAG配置
pub fn get_rag_configuration(&self) -> Result<Option<crate::models::RagConfiguration>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT id, chunk_size, chunk_overlap, chunking_strategy, min_chunk_size,
default_top_k, default_rerank_enabled, created_at, updated_at
FROM rag_configurations WHERE id = 'default'"
)?;
let result = stmt.query_row([], |row| {
let created_at_str: String = row.get(7)?;
let updated_at_str: String = row.get(8)?;
let created_at = DateTime::parse_from_rfc3339(&created_at_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(7, "created_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
.map_err(|_| rusqlite::Error::InvalidColumnType(8, "updated_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
Ok(crate::models::RagConfiguration {
id: row.get(0)?,
chunk_size: row.get(1)?,
chunk_overlap: row.get(2)?,
chunking_strategy: row.get(3)?,
min_chunk_size: row.get(4)?,
default_top_k: row.get(5)?,
default_rerank_enabled: row.get::<_, i32>(6)? != 0,
created_at,
updated_at,
})
}).optional()?;
Ok(result)
}
/// 更新RAG配置
pub fn update_rag_configuration(&self, config: &crate::models::RagConfigRequest) -> Result<()> {
let conn = self.conn.lock().unwrap();
let now = Utc::now().to_rfc3339();
conn.execute(
"UPDATE rag_configurations
SET chunk_size = ?1, chunk_overlap = ?2, chunking_strategy = ?3,
min_chunk_size = ?4, default_top_k = ?5, default_rerank_enabled = ?6,
updated_at = ?7
WHERE id = 'default'",
params![
config.chunk_size,
config.chunk_overlap,
config.chunking_strategy,
config.min_chunk_size,
config.default_top_k,
if config.default_rerank_enabled { 1 } else { 0 },
now
],
)?;
Ok(())
}
/// 重置RAG配置为默认值
pub fn reset_rag_configuration(&self) -> Result<()> {
let conn = self.conn.lock().unwrap();
let now = Utc::now().to_rfc3339();
conn.execute(
"UPDATE rag_configurations
SET chunk_size = 512, chunk_overlap = 50, chunking_strategy = 'fixed_size',
min_chunk_size = 20, default_top_k = 5, default_rerank_enabled = 0,
updated_at = ?1
WHERE id = 'default'",
params![now],
)?;
Ok(())
}
// ==================== RAG分库管理CRUD操作 ====================
/// 创建新的分库
pub fn create_sub_library(&self, request: &CreateSubLibraryRequest) -> Result<SubLibrary> {
let conn = self.conn.lock().unwrap();
let id = uuid::Uuid::new_v4().to_string();
let now = Utc::now();
let now_str = now.to_rfc3339();
// 检查名称是否已存在
let exists: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM rag_sub_libraries WHERE name = ?1)",
params![request.name],
|row| row.get(0)
)?;
if exists {
return Err(anyhow::anyhow!("分库名称 '{}' 已存在", request.name));
}
conn.execute(
"INSERT INTO rag_sub_libraries (id, name, description, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![id, request.name, request.description, now_str, now_str],
)?;
Ok(SubLibrary {
id,
name: request.name.clone(),
description: request.description.clone(),
created_at: now,
updated_at: now,
document_count: 0,
chunk_count: 0,
})
}
/// 获取所有分库列表
pub fn list_sub_libraries(&self) -> Result<Vec<SubLibrary>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT sl.id, sl.name, sl.description, sl.created_at, sl.updated_at,
COUNT(DISTINCT rd.id) as document_count,
COUNT(DISTINCT rdc.id) as chunk_count
FROM rag_sub_libraries sl
LEFT JOIN rag_documents rd ON sl.id = rd.sub_library_id
LEFT JOIN rag_document_chunks rdc ON rd.id = rdc.document_id
GROUP BY sl.id, sl.name, sl.description, sl.created_at, sl.updated_at
ORDER BY sl.name"
)?;
let library_iter = stmt.query_map([], |row| {
let created_at = DateTime::parse_from_rfc3339(&row.get::<_, String>(3)?)
.map_err(|_| rusqlite::Error::InvalidColumnType(3, "created_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&row.get::<_, String>(4)?)
.map_err(|_| rusqlite::Error::InvalidColumnType(4, "updated_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
Ok(SubLibrary {
id: row.get(0)?,
name: row.get(1)?,
description: row.get(2)?,
created_at,
updated_at,
document_count: row.get::<_, i64>(5)? as usize,
chunk_count: row.get::<_, i64>(6)? as usize,
})
})?;
let mut libraries = Vec::new();
for library in library_iter {
libraries.push(library?);
}
Ok(libraries)
}
/// 根据ID获取分库详情
pub fn get_sub_library_by_id(&self, id: &str) -> Result<Option<SubLibrary>> {
let conn = self.conn.lock().unwrap();
let result = conn.query_row(
"SELECT sl.id, sl.name, sl.description, sl.created_at, sl.updated_at,
COUNT(DISTINCT rd.id) as document_count,
COUNT(DISTINCT rdc.id) as chunk_count
FROM rag_sub_libraries sl
LEFT JOIN rag_documents rd ON sl.id = rd.sub_library_id
LEFT JOIN rag_document_chunks rdc ON rd.id = rdc.document_id
WHERE sl.id = ?1
GROUP BY sl.id, sl.name, sl.description, sl.created_at, sl.updated_at",
params![id],
|row| {
let created_at = DateTime::parse_from_rfc3339(&row.get::<_, String>(3)?)
.map_err(|_| rusqlite::Error::InvalidColumnType(3, "created_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&row.get::<_, String>(4)?)
.map_err(|_| rusqlite::Error::InvalidColumnType(4, "updated_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
Ok(SubLibrary {
id: row.get(0)?,
name: row.get(1)?,
description: row.get(2)?,
created_at,
updated_at,
document_count: row.get::<_, i64>(5)? as usize,
chunk_count: row.get::<_, i64>(6)? as usize,
})
}
).optional()?;
Ok(result)
}
/// 根据名称获取分库详情
pub fn get_sub_library_by_name(&self, name: &str) -> Result<Option<SubLibrary>> {
let conn = self.conn.lock().unwrap();
let result = conn.query_row(
"SELECT sl.id, sl.name, sl.description, sl.created_at, sl.updated_at,
COUNT(DISTINCT rd.id) as document_count,
COUNT(DISTINCT rdc.id) as chunk_count
FROM rag_sub_libraries sl
LEFT JOIN rag_documents rd ON sl.id = rd.sub_library_id
LEFT JOIN rag_document_chunks rdc ON rd.id = rdc.document_id
WHERE sl.name = ?1
GROUP BY sl.id, sl.name, sl.description, sl.created_at, sl.updated_at",
params![name],
|row| {
let created_at = DateTime::parse_from_rfc3339(&row.get::<_, String>(3)?)
.map_err(|_| rusqlite::Error::InvalidColumnType(3, "created_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&row.get::<_, String>(4)?)
.map_err(|_| rusqlite::Error::InvalidColumnType(4, "updated_at".to_string(), rusqlite::types::Type::Text))?
.with_timezone(&Utc);
Ok(SubLibrary {
id: row.get(0)?,
name: row.get(1)?,
description: row.get(2)?,
created_at,
updated_at,
document_count: row.get::<_, i64>(5)? as usize,
chunk_count: row.get::<_, i64>(6)? as usize,
})
}
).optional()?;
Ok(result)
}
/// 更新分库信息
pub fn update_sub_library(&self, id: &str, request: &UpdateSubLibraryRequest) -> Result<SubLibrary> {
let conn = self.conn.lock().unwrap();
let now = Utc::now().to_rfc3339();
// 检查分库是否存在
let exists: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM rag_sub_libraries WHERE id = ?1)",
params![id],
|row| row.get(0)
)?;
if !exists {
return Err(anyhow::anyhow!("分库ID '{}' 不存在", id));
}
// 如果更新名称,检查新名称是否已存在
if let Some(new_name) = &request.name {
let name_exists: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM rag_sub_libraries WHERE name = ?1 AND id != ?2)",
params![new_name, id],
|row| row.get(0)
)?;
if name_exists {
return Err(anyhow::anyhow!("分库名称 '{}' 已存在", new_name));
}
}
// 构建动态更新SQL
let mut updates = Vec::new();
let mut params_vec = Vec::new();
if let Some(name) = &request.name {
updates.push("name = ?");
params_vec.push(name.as_str());
}
if let Some(description) = &request.description {
updates.push("description = ?");
params_vec.push(description.as_str());
}
updates.push("updated_at = ?");
params_vec.push(&now);
params_vec.push(id);
let sql = format!(
"UPDATE rag_sub_libraries SET {} WHERE id = ?",
updates.join(", ")
);
conn.execute(&sql, rusqlite::params_from_iter(params_vec))?;
// 释放锁,避免递归锁导致死锁
drop(conn);
// 使用单独的只读查询获取更新后的分库信息
self.get_sub_library_by_id(id)?
.ok_or_else(|| anyhow::anyhow!("无法获取更新后的分库信息"))
}
/// 删除分库
pub fn delete_sub_library(&self, id: &str, delete_contained_documents: bool) -> Result<()> {
let conn = self.conn.lock().unwrap();
// 检查是否为默认分库
if id == "default" {
return Err(anyhow::anyhow!("不能删除默认分库"));
}
// 检查分库是否存在
let exists: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM rag_sub_libraries WHERE id = ?1)",
params![id],
|row| row.get(0)
)?;
if !exists {
return Err(anyhow::anyhow!("分库ID '{}' 不存在", id));
}
let transaction = conn.unchecked_transaction()?;
if delete_contained_documents {
// 删除分库中的所有文档及其相关数据
// 首先获取分库中的所有文档ID
let mut stmt = transaction.prepare(
"SELECT id FROM rag_documents WHERE sub_library_id = ?1"
)?;
let document_ids: Vec<String> = stmt.query_map(params![id], |row| {
Ok(row.get::<_, String>(0)?)
})?.collect::<Result<Vec<_>, _>>()?;
// 删除文档关联的向量和块
for doc_id in document_ids {
transaction.execute(
"DELETE FROM rag_document_chunks WHERE document_id = ?1",
params![doc_id],
)?;
}
// 删除分库中的所有文档
transaction.execute(
"DELETE FROM rag_documents WHERE sub_library_id = ?1",
params![id],
)?;
} else {
// 将分库中的文档移动到默认分库
transaction.execute(
"UPDATE rag_documents SET sub_library_id = 'default' WHERE sub_library_id = ?1",
params![id],
)?;
}
// 删除分库本身
transaction.execute(
"DELETE FROM rag_sub_libraries WHERE id = ?1",
params![id],
)?;
transaction.commit()?;
println!("✅ 成功删除分库: {}", id);
Ok(())
}
/// 获取指定分库中的文档列表
pub fn get_documents_by_sub_library(&self, sub_library_id: &str, page: Option<usize>, page_size: Option<usize>) -> Result<Vec<serde_json::Value>> {
let conn = self.conn.lock().unwrap();
let page = page.unwrap_or(1);
let page_size = page_size.unwrap_or(50);
let offset = (page - 1) * page_size;
let mut stmt = conn.prepare(
"SELECT id, file_name, file_path, file_size, total_chunks, sub_library_id, created_at, updated_at
FROM rag_documents
WHERE sub_library_id = ?1
ORDER BY created_at DESC
LIMIT ?2 OFFSET ?3"
)?;
let rows = stmt.query_map(params![sub_library_id, page_size, offset], |row| {
Ok(serde_json::json!({
"id": row.get::<_, String>(0)?,
"file_name": row.get::<_, String>(1)?,
"file_path": row.get::<_, Option<String>>(2)?,
"file_size": row.get::<_, Option<i64>>(3)?,
"total_chunks": row.get::<_, i32>(4)?,
"sub_library_id": row.get::<_, String>(5)?,
"created_at": row.get::<_, String>(6)?,
"updated_at": row.get::<_, String>(7)?
}))
})?;
let mut documents = Vec::new();
for row in rows {
documents.push(row?);
}
Ok(documents)
}
/// 将文档移动到指定分库
pub fn move_document_to_sub_library(&self, document_id: &str, target_sub_library_id: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
// 检查目标分库是否存在
let library_exists: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM rag_sub_libraries WHERE id = ?1)",
params![target_sub_library_id],
|row| row.get(0)
)?;
if !library_exists {
return Err(anyhow::anyhow!("目标分库ID '{}' 不存在", target_sub_library_id));
}
// 检查文档是否存在
let document_exists: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM rag_documents WHERE id = ?1)",
params![document_id],
|row| row.get(0)
)?;
if !document_exists {
return Err(anyhow::anyhow!("文档ID '{}' 不存在", document_id));
}
// 更新文档的分库归属
let updated_at = Utc::now().to_rfc3339();
conn.execute(
"UPDATE rag_documents SET sub_library_id = ?1, updated_at = ?2 WHERE id = ?3",
params![target_sub_library_id, updated_at, document_id],
)?;
println!("✅ 成功将文档 {} 移动到分库 {}", document_id, target_sub_library_id);
Ok(())
}
// =================== Migration Functions ===================
/// 版本8到版本9的数据库迁移:添加图片遮罩卡表
fn migrate_v8_to_v9(&self, conn: &rusqlite::Connection) -> Result<()> {
println!("正在迁移数据库版本8到版本9:添加图片遮罩卡支持...");
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS image_occlusion_cards (
id TEXT PRIMARY KEY,
task_id TEXT NOT NULL,
image_path TEXT NOT NULL,
image_base64 TEXT,
image_width INTEGER NOT NULL,
image_height INTEGER NOT NULL,
masks_json TEXT NOT NULL, -- JSON格式存储遮罩数组
title TEXT NOT NULL,
description TEXT,
tags_json TEXT NOT NULL DEFAULT '[]', -- JSON格式存储标签数组
subject TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);
CREATE INDEX IF NOT EXISTS idx_image_occlusion_cards_task_id ON image_occlusion_cards(task_id);
CREATE INDEX IF NOT EXISTS idx_image_occlusion_cards_subject ON image_occlusion_cards(subject);
CREATE INDEX IF NOT EXISTS idx_image_occlusion_cards_created_at ON image_occlusion_cards(created_at);"
)?;
println!("✅ 数据库版本8到版本9迁移完成");
Ok(())
}
fn migrate_v9_to_v10(&self, conn: &rusqlite::Connection) -> Result<()> {
println!("正在迁移数据库版本9到版本10:为anki_cards表添加text字段支持Cloze模板...");
// 添加text字段到anki_cards表
conn.execute(
"ALTER TABLE anki_cards ADD COLUMN text TEXT;",
[],
)?;
// 添加索引以优化查询性能
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_anki_cards_text ON anki_cards(text);",
[],
)?;
println!("✅ 数据库版本9到版本10迁移完成");
Ok(())
}
// =================== Image Occlusion Functions ===================
/// 保存图片遮罩卡到数据库
pub fn save_image_occlusion_card(&self, card: &crate::models::ImageOcclusionCard) -> Result<()> {
let conn = self.conn.lock().unwrap();
let masks_json = serde_json::to_string(&card.masks)
.map_err(|e| anyhow::anyhow!("序列化遮罩数据失败: {}", e))?;
let tags_json = serde_json::to_string(&card.tags)
.map_err(|e| anyhow::anyhow!("序列化标签数据失败: {}", e))?;
conn.execute(
"INSERT INTO image_occlusion_cards
(id, task_id, image_path, image_base64, image_width, image_height, masks_json,
title, description, tags_json, subject, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",
params![
card.id,
card.task_id,
card.image_path,
card.image_base64,
card.image_width,
card.image_height,
masks_json,
card.title,
card.description,
tags_json,
card.subject,
card.created_at,
card.updated_at
]
)?;
Ok(())
}
/// 获取所有图片遮罩卡
pub fn get_all_image_occlusion_cards(&self) -> Result<Vec<crate::models::ImageOcclusionCard>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT id, task_id, image_path, image_base64, image_width, image_height, masks_json,
title, description, tags_json, subject, created_at, updated_at
FROM image_occlusion_cards ORDER BY created_at DESC"
)?;
let card_iter = stmt.query_map([], |row| {
let masks_json: String = row.get(6)?;
let tags_json: String = row.get(9)?;
let masks: Vec<crate::models::OcclusionMask> = serde_json::from_str(&masks_json)
.map_err(|e| rusqlite::Error::InvalidColumnType(6, format!("masks_json: {}", e), rusqlite::types::Type::Text))?;
let tags: Vec<String> = serde_json::from_str(&tags_json)
.map_err(|e| rusqlite::Error::InvalidColumnType(9, format!("tags_json: {}", e), rusqlite::types::Type::Text))?;
Ok(crate::models::ImageOcclusionCard {
id: row.get(0)?,
task_id: row.get(1)?,
image_path: row.get(2)?,
image_base64: row.get(3)?,
image_width: row.get(4)?,
image_height: row.get(5)?,
masks,
title: row.get(7)?,
description: row.get(8)?,
tags,
subject: row.get(10)?,
created_at: row.get(11)?,
updated_at: row.get(12)?,
})
})?;
let mut cards = Vec::new();
for card_result in card_iter {
cards.push(card_result?);
}
Ok(cards)
}
/// 根据ID获取图片遮罩卡
pub fn get_image_occlusion_card_by_id(&self, card_id: &str) -> Result<Option<crate::models::ImageOcclusionCard>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT id, task_id, image_path, image_base64, image_width, image_height, masks_json,
title, description, tags_json, subject, created_at, updated_at
FROM image_occlusion_cards WHERE id = ?1"
)?;
let card = stmt.query_row(params![card_id], |row| {
let masks_json: String = row.get(6)?;
let tags_json: String = row.get(9)?;
let masks: Vec<crate::models::OcclusionMask> = serde_json::from_str(&masks_json)
.map_err(|e| rusqlite::Error::InvalidColumnType(6, format!("masks_json: {}", e), rusqlite::types::Type::Text))?;
let tags: Vec<String> = serde_json::from_str(&tags_json)
.map_err(|e| rusqlite::Error::InvalidColumnType(9, format!("tags_json: {}", e), rusqlite::types::Type::Text))?;
Ok(crate::models::ImageOcclusionCard {
id: row.get(0)?,
task_id: row.get(1)?,
image_path: row.get(2)?,
image_base64: row.get(3)?,
image_width: row.get(4)?,
image_height: row.get(5)?,
masks,
title: row.get(7)?,
description: row.get(8)?,
tags,
subject: row.get(10)?,
created_at: row.get(11)?,
updated_at: row.get(12)?,
})
}).optional()?;
Ok(card)
}
/// 更新图片遮罩卡
pub fn update_image_occlusion_card(&self, card: &crate::models::ImageOcclusionCard) -> Result<()> {
let conn = self.conn.lock().unwrap();
let masks_json = serde_json::to_string(&card.masks)
.map_err(|e| anyhow::anyhow!("序列化遮罩数据失败: {}", e))?;
let tags_json = serde_json::to_string(&card.tags)
.map_err(|e| anyhow::anyhow!("序列化标签数据失败: {}", e))?;
conn.execute(
"UPDATE image_occlusion_cards SET
task_id = ?2, image_path = ?3, image_base64 = ?4, image_width = ?5, image_height = ?6,
masks_json = ?7, title = ?8, description = ?9, tags_json = ?10, subject = ?11, updated_at = ?12
WHERE id = ?1",
params![
card.id,
card.task_id,
card.image_path,
card.image_base64,
card.image_width,
card.image_height,
masks_json,
card.title,
card.description,
tags_json,
card.subject,
card.updated_at
]
)?;
Ok(())
}
/// 删除图片遮罩卡
pub fn delete_image_occlusion_card(&self, card_id: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"DELETE FROM image_occlusion_cards WHERE id = ?1",
params![card_id]
)?;
Ok(())
}
/// 设置默认模板ID
pub fn set_default_template(&self, template_id: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
let now = Utc::now().to_rfc3339();
conn.execute(
"INSERT OR REPLACE INTO settings (key, value, updated_at) VALUES ('default_template_id', ?1, ?2)",
params![template_id, now]
)?;
Ok(())
}
/// 获取默认模板ID
pub fn get_default_template(&self) -> Result<Option<String>> {
let conn = self.conn.lock().unwrap();
match conn.query_row(
"SELECT value FROM settings WHERE key = 'default_template_id'",
[],
|row| row.get::<_, String>(0)
) {
Ok(template_id) => Ok(Some(template_id)),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(e) => Err(e.into()),
}
}
}
|
000haoji/deep-student
| 12,770 |
src-tauri/src/anki_connect_service.rs
|
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use crate::models::AnkiCard;
use std::net::TcpStream;
use std::time::Duration;
const ANKI_CONNECT_URL: &str = "http://127.0.0.1:8765";
#[derive(Serialize)]
struct AnkiConnectRequest {
action: String,
version: u32,
#[serde(skip_serializing_if = "Option::is_none")]
params: Option<serde_json::Value>,
}
#[derive(Deserialize)]
struct AnkiConnectResponse {
result: Option<serde_json::Value>,
error: Option<String>,
}
#[derive(Serialize)]
struct Note {
#[serde(rename = "deckName")]
deck_name: String,
#[serde(rename = "modelName")]
model_name: String,
fields: HashMap<String, String>,
tags: Vec<String>,
}
/// 检查AnkiConnect是否可用
pub async fn check_anki_connect_availability() -> Result<bool, String> {
println!("🔍 正在检查AnkiConnect连接到: {}", ANKI_CONNECT_URL);
// 首先检查端口8765是否开放
println!("🔍 第0步:检查端口8765是否开放...");
match TcpStream::connect_timeout(&"127.0.0.1:8765".parse().unwrap(), Duration::from_secs(5)) {
Ok(_) => {
println!("✅ 端口8765可访问");
}
Err(e) => {
println!("❌ 端口8765无法访问: {}", e);
return Err(format!("端口8765无法访问: {} \n\n这通常意味着:\n1. Anki桌面程序未运行\n2. AnkiConnect插件未安装或未启用\n3. 端口被其他程序占用\n\n解决方法:\n1. 启动Anki桌面程序\n2. 安装AnkiConnect插件(代码:2055492159)\n3. 重启Anki以激活插件", e));
}
}
// 首先尝试简单的GET请求检查服务是否运行
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(10))
.tcp_keepalive(Some(std::time::Duration::from_secs(30)))
.connect_timeout(std::time::Duration::from_secs(5))
.build()
.map_err(|e| format!("创建HTTP客户端失败: {}", e))?;
println!("🔍 第一步:检查AnkiConnect服务是否响应...");
match client.get(ANKI_CONNECT_URL).send().await {
Ok(response) => {
println!("✅ AnkiConnect服务响应状态: {}", response.status());
let text = response.text().await.unwrap_or_else(|_| "无法读取响应".to_string());
println!("📥 服务响应内容: {}", text);
// 检查响应内容是否包含AnkiConnect信息
if text.contains("AnkiConnect") || text.contains("apiVersion") {
println!("✅ AnkiConnect服务确认运行正常");
} else {
println!("⚠️ 服务响应异常,内容: {}", text);
}
}
Err(e) => {
println!("❌ AnkiConnect服务无响应: {}", e);
return Err(format!("AnkiConnect服务未运行或无法访问: {} \n\n请确保:\n1. Anki桌面程序正在运行\n2. AnkiConnect插件已安装(代码:2055492159)\n3. 重启Anki以激活插件\n4. 检查端口8765是否被占用", e));
}
}
// 如果基础连接成功,再尝试API请求
println!("🔍 第二步:测试AnkiConnect API...");
let request = AnkiConnectRequest {
action: "version".to_string(),
version: 6,
params: None,
};
println!("📤 发送API请求: {}", serde_json::to_string(&request).unwrap_or_else(|_| "序列化失败".to_string()));
match client
.post(ANKI_CONNECT_URL)
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("User-Agent", "ai-mistake-manager/1.0")
.json(&request)
.timeout(std::time::Duration::from_secs(15))
.send()
.await
{
Ok(response) => {
let status_code = response.status();
println!("📥 收到响应状态: {}", status_code);
if status_code.is_success() {
let response_text = response.text().await
.map_err(|e| format!("读取响应内容失败: {}", e))?;
println!("📥 响应内容: {}", response_text);
match serde_json::from_str::<AnkiConnectResponse>(&response_text) {
Ok(anki_response) => {
if anki_response.error.is_none() {
println!("✅ AnkiConnect版本检查成功");
Ok(true)
} else {
Err(format!("AnkiConnect错误: {}", anki_response.error.unwrap_or_default()))
}
}
Err(e) => Err(format!("解析AnkiConnect响应失败: {} - 响应内容: {}", e, response_text)),
}
} else {
let error_text = response.text().await.unwrap_or_else(|_| "无法读取错误内容".to_string());
Err(format!("AnkiConnect HTTP错误: {} - 内容: {}", status_code, error_text))
}
}
Err(e) => {
println!("❌ AnkiConnect连接错误详情: {:?}", e);
if e.is_timeout() {
Err("AnkiConnect连接超时(5秒),请确保Anki桌面程序正在运行并启用了AnkiConnect插件".to_string())
} else if e.is_connect() {
Err("无法连接到AnkiConnect服务器,请确保:1)Anki正在运行 2)AnkiConnect插件已安装并启用 3)端口8765未被占用".to_string())
} else if e.to_string().contains("connection closed") {
Err("连接被AnkiConnect服务器关闭,可能原因:1)AnkiConnect版本过旧 2)请求格式不兼容 3)需要重启Anki".to_string())
} else {
Err(format!("AnkiConnect连接失败: {}", e))
}
}
}
}
/// 获取所有牌组名称
pub async fn get_deck_names() -> Result<Vec<String>, String> {
let request = AnkiConnectRequest {
action: "deckNames".to_string(),
version: 6,
params: None,
};
let client = reqwest::Client::new();
match client
.post(ANKI_CONNECT_URL)
.json(&request)
.timeout(std::time::Duration::from_secs(5))
.send()
.await
{
Ok(response) => {
if response.status().is_success() {
match response.json::<AnkiConnectResponse>().await {
Ok(anki_response) => {
if let Some(error) = anki_response.error {
Err(format!("AnkiConnect错误: {}", error))
} else if let Some(result) = anki_response.result {
match serde_json::from_value::<Vec<String>>(result) {
Ok(deck_names) => Ok(deck_names),
Err(e) => Err(format!("解析牌组列表失败: {}", e)),
}
} else {
Err("AnkiConnect返回空结果".to_string())
}
}
Err(e) => Err(format!("解析AnkiConnect响应失败: {}", e)),
}
} else {
Err(format!("AnkiConnect HTTP错误: {}", response.status()))
}
}
Err(e) => Err(format!("请求牌组列表失败: {}", e)),
}
}
/// 获取所有笔记类型名称
pub async fn get_model_names() -> Result<Vec<String>, String> {
let request = AnkiConnectRequest {
action: "modelNames".to_string(),
version: 6,
params: None,
};
let client = reqwest::Client::new();
match client
.post(ANKI_CONNECT_URL)
.json(&request)
.timeout(std::time::Duration::from_secs(5))
.send()
.await
{
Ok(response) => {
if response.status().is_success() {
match response.json::<AnkiConnectResponse>().await {
Ok(anki_response) => {
if let Some(error) = anki_response.error {
Err(format!("AnkiConnect错误: {}", error))
} else if let Some(result) = anki_response.result {
match serde_json::from_value::<Vec<String>>(result) {
Ok(model_names) => Ok(model_names),
Err(e) => Err(format!("解析笔记类型列表失败: {}", e)),
}
} else {
Err("AnkiConnect返回空结果".to_string())
}
}
Err(e) => Err(format!("解析AnkiConnect响应失败: {}", e)),
}
} else {
Err(format!("AnkiConnect HTTP错误: {}", response.status()))
}
}
Err(e) => Err(format!("请求笔记类型列表失败: {}", e)),
}
}
/// 将AnkiCard列表添加到Anki
pub async fn add_notes_to_anki(
cards: Vec<AnkiCard>,
deck_name: String,
note_type: String,
) -> Result<Vec<Option<u64>>, String> {
// 首先检查AnkiConnect可用性
check_anki_connect_availability().await?;
// 构建notes数组
let notes: Vec<Note> = cards
.into_iter()
.map(|card| {
let mut fields = HashMap::new();
// 根据笔记类型决定字段映射
match note_type.as_str() {
"Basic" => {
fields.insert("Front".to_string(), card.front);
fields.insert("Back".to_string(), card.back);
}
"Basic (and reversed card)" => {
fields.insert("Front".to_string(), card.front);
fields.insert("Back".to_string(), card.back);
}
"Basic (optional reversed card)" => {
fields.insert("Front".to_string(), card.front);
fields.insert("Back".to_string(), card.back);
}
"Cloze" => {
// 对于Cloze类型,需要将front和back合并
let cloze_text = if card.back.is_empty() {
card.front
} else {
format!("{}\n\n{}", card.front, card.back)
};
fields.insert("Text".to_string(), cloze_text);
}
_ => {
// 对于其他类型,尝试使用Front/Back字段,如果失败则使用第一个和第二个字段
fields.insert("Front".to_string(), card.front);
fields.insert("Back".to_string(), card.back);
}
}
Note {
deck_name: deck_name.clone(),
model_name: note_type.clone(),
fields,
tags: card.tags,
}
})
.collect();
let params = serde_json::json!({
"notes": notes
});
let request = AnkiConnectRequest {
action: "addNotes".to_string(),
version: 6,
params: Some(params),
};
let client = reqwest::Client::new();
match client
.post(ANKI_CONNECT_URL)
.json(&request)
.timeout(std::time::Duration::from_secs(30))
.send()
.await
{
Ok(response) => {
if response.status().is_success() {
match response.json::<AnkiConnectResponse>().await {
Ok(anki_response) => {
if let Some(error) = anki_response.error {
Err(format!("AnkiConnect错误: {}", error))
} else if let Some(result) = anki_response.result {
match serde_json::from_value::<Vec<Option<u64>>>(result) {
Ok(note_ids) => Ok(note_ids),
Err(e) => Err(format!("解析笔记ID列表失败: {}", e)),
}
} else {
Err("AnkiConnect返回空结果".to_string())
}
}
Err(e) => Err(format!("解析AnkiConnect响应失败: {}", e)),
}
} else {
Err(format!("AnkiConnect HTTP错误: {}", response.status()))
}
}
Err(e) => Err(format!("添加笔记到Anki失败: {}", e)),
}
}
/// 创建牌组(如果不存在)
pub async fn create_deck_if_not_exists(deck_name: &str) -> Result<(), String> {
let params = serde_json::json!({
"deck": deck_name
});
let request = AnkiConnectRequest {
action: "createDeck".to_string(),
version: 6,
params: Some(params),
};
let client = reqwest::Client::new();
match client
.post(ANKI_CONNECT_URL)
.json(&request)
.timeout(std::time::Duration::from_secs(10))
.send()
.await
{
Ok(response) => {
if response.status().is_success() {
match response.json::<AnkiConnectResponse>().await {
Ok(anki_response) => {
if let Some(error) = anki_response.error {
// 如果牌组已存在,这不算错误
if error.contains("already exists") {
Ok(())
} else {
Err(format!("创建牌组时出错: {}", error))
}
} else {
Ok(())
}
}
Err(e) => Err(format!("解析AnkiConnect响应失败: {}", e)),
}
} else {
Err(format!("AnkiConnect HTTP错误: {}", response.status()))
}
}
Err(e) => Err(format!("创建牌组失败: {}", e)),
}
}
|
000haoji/deep-student
| 22,135 |
src-tauri/src/vector_store.rs
|
use crate::models::{
DocumentChunk, DocumentChunkWithEmbedding, RetrievedChunk, VectorStoreStats, AppError
};
use crate::database::Database;
use std::sync::Arc;
use serde_json::Value;
use rusqlite::params;
type Result<T> = std::result::Result<T, AppError>;
/// 向量存储抽象接口
pub trait VectorStore {
/// 添加文档块和对应的向量
async fn add_chunks(&self, chunks: Vec<DocumentChunkWithEmbedding>) -> Result<()>;
/// 搜索相似的文档块
async fn search_similar_chunks(&self, query_embedding: Vec<f32>, top_k: usize) -> Result<Vec<RetrievedChunk>>;
/// 在指定分库中搜索相似的文档块
async fn search_similar_chunks_in_libraries(&self, query_embedding: Vec<f32>, top_k: usize, sub_library_ids: Option<Vec<String>>) -> Result<Vec<RetrievedChunk>>;
/// 根据文档ID删除所有相关块
async fn delete_chunks_by_document_id(&self, document_id: &str) -> Result<()>;
/// 获取统计信息
async fn get_stats(&self) -> Result<VectorStoreStats>;
/// 清空所有向量数据
async fn clear_all(&self) -> Result<()>;
}
/// SQLite向量存储实现 (基础版本,使用余弦相似度)
pub struct SqliteVectorStore {
database: Arc<Database>,
}
impl SqliteVectorStore {
pub fn new(database: Arc<Database>) -> Result<Self> {
let store = Self { database };
store.initialize_tables()?;
Ok(store)
}
/// 初始化向量存储相关表
fn initialize_tables(&self) -> Result<()> {
let conn = self.database.conn().lock()
.map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?;
// 分库表
conn.execute(
"CREATE TABLE IF NOT EXISTS rag_sub_libraries (
id TEXT PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
description TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)",
[],
).map_err(|e| AppError::database(format!("创建分库表失败: {}", e)))?;
// 检查并创建默认分库
let default_library_exists: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM rag_sub_libraries WHERE name = 'default')",
[],
|row| row.get(0)
).unwrap_or(false);
if !default_library_exists {
let now = chrono::Utc::now().to_rfc3339();
conn.execute(
"INSERT INTO rag_sub_libraries (id, name, description, created_at, updated_at)
VALUES ('default', 'default', '默认知识库', ?, ?)",
params![now, now],
).map_err(|e| AppError::database(format!("创建默认分库失败: {}", e)))?;
}
// 文档表(增加分库外键)
conn.execute(
"CREATE TABLE IF NOT EXISTS rag_documents (
id TEXT PRIMARY KEY,
file_name TEXT NOT NULL,
file_path TEXT,
file_size INTEGER,
content_type TEXT,
total_chunks INTEGER DEFAULT 0,
sub_library_id TEXT NOT NULL DEFAULT 'default',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY (sub_library_id) REFERENCES rag_sub_libraries (id) ON DELETE SET DEFAULT
)",
[],
).map_err(|e| AppError::database(format!("创建文档表失败: {}", e)))?;
// 检查现有文档表是否有sub_library_id列
let has_sub_library_column: bool = conn.prepare("SELECT sub_library_id FROM rag_documents LIMIT 1")
.is_ok();
if !has_sub_library_column {
conn.execute(
"ALTER TABLE rag_documents ADD COLUMN sub_library_id TEXT NOT NULL DEFAULT 'default'",
[]
).map_err(|e| AppError::database(format!("添加分库列失败: {}", e)))?;
}
// 文档块表
conn.execute(
"CREATE TABLE IF NOT EXISTS rag_document_chunks (
id TEXT PRIMARY KEY,
document_id TEXT NOT NULL,
chunk_index INTEGER NOT NULL,
text TEXT NOT NULL,
metadata TEXT NOT NULL, -- JSON格式的元数据
created_at TEXT NOT NULL,
FOREIGN KEY (document_id) REFERENCES rag_documents (id) ON DELETE CASCADE
)",
[],
).map_err(|e| AppError::database(format!("创建文档块表失败: {}", e)))?;
// 向量表(优化版本,存储为BLOB)
conn.execute(
"CREATE TABLE IF NOT EXISTS rag_vectors (
chunk_id TEXT PRIMARY KEY,
embedding BLOB NOT NULL, -- 二进制格式的向量数据
dimension INTEGER NOT NULL,
created_at TEXT NOT NULL,
FOREIGN KEY (chunk_id) REFERENCES rag_document_chunks (id) ON DELETE CASCADE
)",
[],
).map_err(|e| AppError::database(format!("创建向量表失败: {}", e)))?;
// 创建索引以提高查询性能
let indexes = vec![
"CREATE INDEX IF NOT EXISTS idx_rag_chunks_document_id ON rag_document_chunks(document_id)",
"CREATE INDEX IF NOT EXISTS idx_rag_chunks_index ON rag_document_chunks(chunk_index)",
"CREATE INDEX IF NOT EXISTS idx_rag_vectors_dimension ON rag_vectors(dimension)",
"CREATE INDEX IF NOT EXISTS idx_rag_documents_sub_library ON rag_documents(sub_library_id)",
"CREATE INDEX IF NOT EXISTS idx_rag_sub_libraries_name ON rag_sub_libraries(name)",
];
for index_sql in indexes {
conn.execute(index_sql, [])
.map_err(|e| AppError::database(format!("创建索引失败: {}", e)))?;
}
println!("✅ RAG向量存储表初始化完成");
Ok(())
}
/// 将向量序列化为BLOB
fn serialize_vector_to_blob(vector: &[f32]) -> Result<Vec<u8>> {
let mut blob = Vec::with_capacity(vector.len() * 4);
for &value in vector {
blob.extend_from_slice(&value.to_le_bytes());
}
Ok(blob)
}
/// 从BLOB反序列化向量
fn deserialize_vector_from_blob(blob: &[u8]) -> Result<Vec<f32>> {
if blob.len() % 4 != 0 {
return Err(AppError::database("向量BLOB大小不正确".to_string()));
}
let mut vector = Vec::with_capacity(blob.len() / 4);
for chunk in blob.chunks_exact(4) {
let bytes: [u8; 4] = chunk.try_into()
.map_err(|_| AppError::database("向量BLOB格式错误".to_string()))?;
vector.push(f32::from_le_bytes(bytes));
}
Ok(vector)
}
/// 计算余弦相似度
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
if a.len() != b.len() {
return 0.0;
}
let dot_product: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
if norm_a == 0.0 || norm_b == 0.0 {
0.0
} else {
dot_product / (norm_a * norm_b)
}
}
}
impl VectorStore for SqliteVectorStore {
async fn add_chunks(&self, chunks: Vec<DocumentChunkWithEmbedding>) -> Result<()> {
let conn = self.database.conn().lock()
.map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?;
let transaction = conn.unchecked_transaction()
.map_err(|e| AppError::database(format!("开始事务失败: {}", e)))?;
let chunks_len = chunks.len();
for chunk_with_embedding in chunks {
let chunk = &chunk_with_embedding.chunk;
let embedding = &chunk_with_embedding.embedding;
// 插入文档块
let metadata_json = serde_json::to_string(&chunk.metadata)
.map_err(|e| AppError::database(format!("序列化元数据失败: {}", e)))?;
transaction.execute(
"INSERT OR REPLACE INTO rag_document_chunks
(id, document_id, chunk_index, text, metadata, created_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![
chunk.id,
chunk.document_id,
chunk.chunk_index,
chunk.text,
metadata_json,
chrono::Utc::now().to_rfc3339()
],
).map_err(|e| AppError::database(format!("插入文档块失败: {}", e)))?;
// 将向量转换为BLOB
let embedding_blob = Self::serialize_vector_to_blob(embedding)?;
// 插入向量到rag_vectors表
transaction.execute(
"INSERT OR REPLACE INTO rag_vectors
(chunk_id, embedding, dimension, created_at)
VALUES (?1, ?2, ?3, ?4)",
params![
chunk.id,
embedding_blob,
embedding.len() as i32,
chrono::Utc::now().to_rfc3339()
],
).map_err(|e| AppError::database(format!("插入向量失败: {}", e)))?;
}
transaction.commit()
.map_err(|e| AppError::database(format!("提交事务失败: {}", e)))?;
println!("✅ 成功添加 {} 个文档块到向量存储", chunks_len);
Ok(())
}
async fn search_similar_chunks(&self, query_embedding: Vec<f32>, top_k: usize) -> Result<Vec<RetrievedChunk>> {
let conn = self.database.conn().lock()
.map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?;
// 基础SQLite实现:获取所有向量,在应用层计算相似度
let mut stmt = conn.prepare(
"SELECT v.chunk_id, v.embedding, c.document_id, c.chunk_index, c.text, c.metadata
FROM rag_vectors v
JOIN rag_document_chunks c ON v.chunk_id = c.id
WHERE v.dimension = ?"
).map_err(|e| AppError::database(format!("准备查询语句失败: {}", e)))?;
let query_dim = query_embedding.len() as i32;
let rows = stmt.query_map(params![query_dim], |row| {
let chunk_id: String = row.get(0)?;
let embedding_blob: Vec<u8> = row.get(1)?;
let document_id: String = row.get(2)?;
let chunk_index: usize = row.get(3)?;
let text: String = row.get(4)?;
let metadata_json: String = row.get(5)?;
Ok((chunk_id, embedding_blob, document_id, chunk_index, text, metadata_json))
}).map_err(|e| AppError::database(format!("执行查询失败: {}", e)))?;
let mut candidates = Vec::new();
for row in rows {
let (chunk_id, embedding_blob, document_id, chunk_index, text, metadata_json) = row
.map_err(|e| AppError::database(format!("读取查询结果失败: {}", e)))?;
// 反序列化向量
let stored_embedding = Self::deserialize_vector_from_blob(&embedding_blob)?;
// 计算余弦相似度
let similarity = Self::cosine_similarity(&query_embedding, &stored_embedding);
// 解析元数据
let metadata: std::collections::HashMap<String, String> = serde_json::from_str(&metadata_json)
.map_err(|e| AppError::database(format!("解析元数据失败: {}", e)))?;
candidates.push(RetrievedChunk {
chunk: DocumentChunk {
id: chunk_id,
document_id,
chunk_index,
text,
metadata,
},
score: similarity,
});
}
// 按相似度排序并返回前top_k个结果
candidates.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
candidates.truncate(top_k);
println!("✅ 检索到 {} 个相似文档块", candidates.len());
Ok(candidates)
}
async fn search_similar_chunks_in_libraries(&self, query_embedding: Vec<f32>, top_k: usize, sub_library_ids: Option<Vec<String>>) -> Result<Vec<RetrievedChunk>> {
let conn = self.database.conn().lock()
.map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?;
// 构建SQL查询,根据是否有分库ID过滤
// 构建SQL查询,根据是否有分库ID过滤
let (sql, params): (String, Vec<rusqlite::types::Value>) = if let Some(ref library_ids) = sub_library_ids {
if library_ids.is_empty() {
return Ok(Vec::new()); // 如果提供了空的分库ID列表,返回空结果
}
let placeholders = library_ids.iter().map(|_| "?").collect::<Vec<_>>().join(",");
let sql = format!(
"SELECT v.chunk_id, v.embedding, c.document_id, c.chunk_index, c.text, c.metadata
FROM rag_vectors v
JOIN rag_document_chunks c ON v.chunk_id = c.id
JOIN rag_documents d ON c.document_id = d.id
WHERE v.dimension = ? AND d.sub_library_id IN ({})",
placeholders
);
let mut params = vec![rusqlite::types::Value::Integer(query_embedding.len() as i64)];
for lib_id in library_ids.iter() {
params.push(rusqlite::types::Value::Text(lib_id.clone()));
}
(sql, params)
} else {
// 如果没有指定分库ID,查询所有分库
let sql = "SELECT v.chunk_id, v.embedding, c.document_id, c.chunk_index, c.text, c.metadata
FROM rag_vectors v
JOIN rag_document_chunks c ON v.chunk_id = c.id
WHERE v.dimension = ?".to_string();
let params = vec![rusqlite::types::Value::Integer(query_embedding.len() as i64)];
(sql, params)
};
let mut stmt = conn.prepare(&sql)
.map_err(|e| AppError::database(format!("准备查询语句失败: {}", e)))?;
let rows = stmt.query_map(rusqlite::params_from_iter(params), |row| {
let chunk_id: String = row.get(0)?;
let embedding_blob: Vec<u8> = row.get(1)?;
let document_id: String = row.get(2)?;
let chunk_index: usize = row.get(3)?;
let text: String = row.get(4)?;
let metadata_json: String = row.get(5)?;
Ok((chunk_id, embedding_blob, document_id, chunk_index, text, metadata_json))
}).map_err(|e| AppError::database(format!("执行查询失败: {}", e)))?;
let mut candidates = Vec::new();
for row in rows {
let (chunk_id, embedding_blob, document_id, chunk_index, text, metadata_json) = row
.map_err(|e| AppError::database(format!("读取查询结果失败: {}", e)))?;
// 反序列化向量
let stored_embedding = Self::deserialize_vector_from_blob(&embedding_blob)?;
// 计算余弦相似度
let similarity = Self::cosine_similarity(&query_embedding, &stored_embedding);
// 解析元数据
let metadata: std::collections::HashMap<String, String> = serde_json::from_str(&metadata_json)
.map_err(|e| AppError::database(format!("解析元数据失败: {}", e)))?;
candidates.push(RetrievedChunk {
chunk: DocumentChunk {
id: chunk_id,
document_id,
chunk_index,
text,
metadata,
},
score: similarity,
});
}
// 按相似度排序并返回前top_k个结果
candidates.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
candidates.truncate(top_k);
let library_filter_msg = if let Some(ref lib_ids) = sub_library_ids {
format!(" (过滤分库: {:?})", lib_ids)
} else {
" (所有分库)".to_string()
};
println!("✅ 检索到 {} 个相似文档块{}", candidates.len(), library_filter_msg);
Ok(candidates)
}
async fn delete_chunks_by_document_id(&self, document_id: &str) -> Result<()> {
let conn = self.database.conn().lock()
.map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?;
let transaction = conn.unchecked_transaction()
.map_err(|e| AppError::database(format!("开始事务失败: {}", e)))?;
// VSS已移除,直接删除相关记录
// 删除向量(通过外键级联删除)
transaction.execute(
"DELETE FROM rag_document_chunks WHERE document_id = ?1",
params![document_id],
).map_err(|e| AppError::database(format!("删除文档块失败: {}", e)))?;
// 删除文档记录
transaction.execute(
"DELETE FROM rag_documents WHERE id = ?1",
params![document_id],
).map_err(|e| AppError::database(format!("删除文档记录失败: {}", e)))?;
transaction.commit()
.map_err(|e| AppError::database(format!("提交删除事务失败: {}", e)))?;
println!("✅ 成功删除文档 {} 的所有块和VSS索引", document_id);
Ok(())
}
async fn get_stats(&self) -> Result<VectorStoreStats> {
let conn = self.database.conn().lock()
.map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?;
let total_documents: usize = conn.query_row(
"SELECT COUNT(*) FROM rag_documents",
[],
|row| row.get(0),
).map_err(|e| AppError::database(format!("查询文档数失败: {}", e)))?;
let total_chunks: usize = conn.query_row(
"SELECT COUNT(*) FROM rag_document_chunks",
[],
|row| row.get(0),
).map_err(|e| AppError::database(format!("查询块数失败: {}", e)))?;
// 计算存储大小(估算)
let storage_size_bytes: u64 = conn.query_row(
"SELECT COALESCE(SUM(LENGTH(text) + LENGTH(embedding)), 0)
FROM rag_document_chunks c
LEFT JOIN rag_vectors v ON c.id = v.chunk_id",
[],
|row| row.get::<_, i64>(0).map(|s| s as u64),
).unwrap_or(0);
Ok(VectorStoreStats {
total_documents,
total_chunks,
storage_size_bytes,
})
}
async fn clear_all(&self) -> Result<()> {
let conn = self.database.conn().lock()
.map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?;
let transaction = conn.unchecked_transaction()
.map_err(|e| AppError::database(format!("开始事务失败: {}", e)))?;
// 清空VSS索引
transaction.execute("DELETE FROM vss_chunks", [])
.map_err(|e| AppError::database(format!("清空VSS索引失败: {}", e)))?;
transaction.execute("DELETE FROM rag_vectors", [])
.map_err(|e| AppError::database(format!("清空向量表失败: {}", e)))?;
transaction.execute("DELETE FROM rag_document_chunks", [])
.map_err(|e| AppError::database(format!("清空文档块表失败: {}", e)))?;
transaction.execute("DELETE FROM rag_documents", [])
.map_err(|e| AppError::database(format!("清空文档表失败: {}", e)))?;
transaction.commit()
.map_err(|e| AppError::database(format!("提交清空事务失败: {}", e)))?;
println!("✅ 成功清空所有向量存储数据和VSS索引");
Ok(())
}
}
/// 文档管理相关方法
impl SqliteVectorStore {
/// 添加文档记录
pub fn add_document_record(&self, document_id: &str, file_name: &str, file_path: Option<&str>, file_size: Option<u64>) -> Result<()> {
self.add_document_record_with_library(document_id, file_name, file_path, file_size, "default")
}
/// 添加文档记录到指定分库
pub fn add_document_record_with_library(&self, document_id: &str, file_name: &str, file_path: Option<&str>, file_size: Option<u64>, sub_library_id: &str) -> Result<()> {
let conn = self.database.conn().lock()
.map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?;
conn.execute(
"INSERT OR REPLACE INTO rag_documents
(id, file_name, file_path, file_size, sub_library_id, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
document_id,
file_name,
file_path,
file_size.map(|s| s as i64),
sub_library_id,
chrono::Utc::now().to_rfc3339(),
chrono::Utc::now().to_rfc3339()
],
).map_err(|e| AppError::database(format!("添加文档记录失败: {}", e)))?;
Ok(())
}
/// 更新文档的块数统计
pub fn update_document_chunk_count(&self, document_id: &str, chunk_count: usize) -> Result<()> {
let conn = self.database.conn().lock()
.map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?;
conn.execute(
"UPDATE rag_documents SET total_chunks = ?1, updated_at = ?2 WHERE id = ?3",
params![
chunk_count as i32,
chrono::Utc::now().to_rfc3339(),
document_id
],
).map_err(|e| AppError::database(format!("更新文档块数失败: {}", e)))?;
Ok(())
}
/// 获取所有文档列表
pub fn get_all_documents(&self) -> Result<Vec<Value>> {
let conn = self.database.conn().lock()
.map_err(|e| AppError::database(format!("获取数据库连接失败: {}", e)))?;
let mut stmt = conn.prepare(
"SELECT id, file_name, file_path, file_size, total_chunks, created_at, updated_at FROM rag_documents ORDER BY created_at DESC"
).map_err(|e| AppError::database(format!("准备查询语句失败: {}", e)))?;
let rows = stmt.query_map([], |row| {
Ok(serde_json::json!({
"id": row.get::<_, String>(0)?,
"file_name": row.get::<_, String>(1)?,
"file_path": row.get::<_, Option<String>>(2)?,
"file_size": row.get::<_, Option<i64>>(3)?,
"total_chunks": row.get::<_, i32>(4)?,
"created_at": row.get::<_, String>(5)?,
"updated_at": row.get::<_, String>(6)?
}))
}).map_err(|e| AppError::database(format!("查询文档列表失败: {}", e)))?;
let mut documents = Vec::new();
for row in rows {
documents.push(row.map_err(|e| AppError::database(format!("读取文档行失败: {}", e)))?);
}
Ok(documents)
}
}
|
000haoji/deep-student
| 16,531 |
src-tauri/src/batch_operations.rs
|
/**
* Batch Operations Module
*
* Provides efficient batch operations for database operations to improve performance
* when dealing with multiple mistakes, chat messages, or other bulk operations.
*/
use anyhow::Result;
use rusqlite::{Connection, params};
use chrono::Utc;
use crate::models::{MistakeItem, ChatMessage};
use std::collections::HashMap;
pub struct BatchOperations<'a> {
conn: &'a mut Connection,
}
impl<'a> BatchOperations<'a> {
pub fn new(conn: &'a mut Connection) -> Self {
Self { conn }
}
/// Batch save multiple mistakes with their chat histories
/// More efficient than individual saves when dealing with multiple items
pub fn batch_save_mistakes(&mut self, mistakes: &[MistakeItem]) -> Result<usize> {
if mistakes.is_empty() {
return Ok(0);
}
let tx = self.conn.transaction()?;
let mut saved_count = 0;
{
// Prepare statements for reuse in a separate scope
let mut mistake_stmt = tx.prepare(
"INSERT OR REPLACE INTO mistakes (id, subject, created_at, question_images, analysis_images, user_question, ocr_text, tags, mistake_type, status, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)"
)?;
let mut delete_messages_stmt = tx.prepare(
"DELETE FROM chat_messages WHERE mistake_id = ?1"
)?;
let mut message_stmt = tx.prepare(
"INSERT INTO chat_messages (mistake_id, role, content, timestamp, thinking_content)
VALUES (?1, ?2, ?3, ?4, ?5)"
)?;
for mistake in mistakes {
// Insert/update mistake
mistake_stmt.execute(params![
mistake.id,
mistake.subject,
mistake.created_at.to_rfc3339(),
serde_json::to_string(&mistake.question_images)?,
serde_json::to_string(&mistake.analysis_images)?,
mistake.user_question,
mistake.ocr_text,
serde_json::to_string(&mistake.tags)?,
mistake.mistake_type,
mistake.status,
Utc::now().to_rfc3339(),
])?;
// Delete old chat messages
delete_messages_stmt.execute(params![mistake.id])?;
// Insert new chat messages
for message in &mistake.chat_history {
message_stmt.execute(params![
mistake.id,
message.role,
message.content,
message.timestamp.to_rfc3339(),
message.thinking_content
])?;
}
saved_count += 1;
}
} // Statements are dropped here
tx.commit()?;
println!("✅ Batch saved {} mistakes with their chat histories", saved_count);
Ok(saved_count)
}
/// Batch delete multiple mistakes by IDs
pub fn batch_delete_mistakes(&mut self, mistake_ids: &[String]) -> Result<usize> {
if mistake_ids.is_empty() {
return Ok(0);
}
let tx = self.conn.transaction()?;
let deleted_count;
{
// Create placeholders for IN clause
let placeholders = mistake_ids.iter().map(|_| "?").collect::<Vec<_>>().join(",");
let query = format!("DELETE FROM mistakes WHERE id IN ({})", placeholders);
let mut stmt = tx.prepare(&query)?;
let params: Vec<&dyn rusqlite::ToSql> = mistake_ids.iter().map(|id| id as &dyn rusqlite::ToSql).collect();
deleted_count = stmt.execute(¶ms[..])?;
} // Statement is dropped here
tx.commit()?;
println!("✅ Batch deleted {} mistakes", deleted_count);
Ok(deleted_count)
}
/// Batch update mistake statuses
pub fn batch_update_mistake_statuses(&mut self, updates: &HashMap<String, String>) -> Result<usize> {
if updates.is_empty() {
return Ok(0);
}
let tx = self.conn.transaction()?;
let mut updated_count = 0;
{
let mut stmt = tx.prepare(
"UPDATE mistakes SET status = ?1, updated_at = ?2 WHERE id = ?3"
)?;
let now = Utc::now().to_rfc3339();
for (mistake_id, new_status) in updates {
let changes = stmt.execute(params![new_status, now, mistake_id])?;
updated_count += changes;
}
} // Statement is dropped here
tx.commit()?;
println!("✅ Batch updated {} mistake statuses", updated_count);
Ok(updated_count)
}
/// Batch add chat messages to multiple mistakes
pub fn batch_add_chat_messages(&mut self, messages_by_mistake: &HashMap<String, Vec<ChatMessage>>) -> Result<usize> {
if messages_by_mistake.is_empty() {
return Ok(0);
}
let tx = self.conn.transaction()?;
let mut added_count = 0;
{
let mut stmt = tx.prepare(
"INSERT INTO chat_messages (mistake_id, role, content, timestamp, thinking_content)
VALUES (?1, ?2, ?3, ?4, ?5)"
)?;
for (mistake_id, messages) in messages_by_mistake {
for message in messages {
stmt.execute(params![
mistake_id,
message.role,
message.content,
message.timestamp.to_rfc3339(),
message.thinking_content
])?;
added_count += 1;
}
}
} // Statement is dropped here
tx.commit()?;
println!("✅ Batch added {} chat messages", added_count);
Ok(added_count)
}
/// Batch update mistake tags
pub fn batch_update_mistake_tags(&mut self, tag_updates: &HashMap<String, Vec<String>>) -> Result<usize> {
if tag_updates.is_empty() {
return Ok(0);
}
let tx = self.conn.transaction()?;
let mut updated_count = 0;
{
let mut stmt = tx.prepare(
"UPDATE mistakes SET tags = ?1, updated_at = ?2 WHERE id = ?3"
)?;
let now = Utc::now().to_rfc3339();
for (mistake_id, new_tags) in tag_updates {
let tags_json = serde_json::to_string(new_tags)?;
let changes = stmt.execute(params![tags_json, now, mistake_id])?;
updated_count += changes;
}
} // Statement is dropped here
tx.commit()?;
println!("✅ Batch updated tags for {} mistakes", updated_count);
Ok(updated_count)
}
/// Batch operation: Archive old mistakes (change status to "archived")
pub fn batch_archive_old_mistakes(&mut self, days_old: i64) -> Result<usize> {
let tx = self.conn.transaction()?;
let cutoff_date = (Utc::now() - chrono::Duration::days(days_old)).to_rfc3339();
let updated_count = tx.execute(
"UPDATE mistakes SET status = 'archived', updated_at = ?1
WHERE created_at < ?2 AND status != 'archived'",
params![Utc::now().to_rfc3339(), cutoff_date]
)?;
tx.commit()?;
println!("✅ Batch archived {} old mistakes (older than {} days)", updated_count, days_old);
Ok(updated_count)
}
/// Batch cleanup: Remove orphaned chat messages
pub fn batch_cleanup_orphaned_messages(&mut self) -> Result<usize> {
let tx = self.conn.transaction()?;
let deleted_count = tx.execute(
"DELETE FROM chat_messages
WHERE mistake_id NOT IN (SELECT id FROM mistakes)",
[]
)?;
tx.commit()?;
println!("✅ Batch cleaned up {} orphaned chat messages", deleted_count);
Ok(deleted_count)
}
/// Batch export: Get multiple mistakes with their full data for export
pub fn batch_export_mistakes(&self, mistake_ids: &[String]) -> Result<Vec<MistakeItem>> {
if mistake_ids.is_empty() {
return Ok(Vec::new());
}
// Create placeholders for IN clause
let placeholders = mistake_ids.iter().map(|_| "?").collect::<Vec<_>>().join(",");
let query = format!(
"SELECT id, subject, created_at, question_images, analysis_images, user_question, ocr_text, tags, mistake_type, status, updated_at
FROM mistakes WHERE id IN ({})",
placeholders
);
let mut stmt = self.conn.prepare(&query)?;
let params: Vec<&dyn rusqlite::ToSql> = mistake_ids.iter().map(|id| id as &dyn rusqlite::ToSql).collect();
let mut mistakes = Vec::new();
let rows = stmt.query_map(¶ms[..], |row| {
let created_at_str: String = row.get(2)?;
let updated_at_str: String = row.get(10)?;
let question_images_str: String = row.get(3)?;
let analysis_images_str: String = row.get(4)?;
let tags_str: String = row.get(7)?;
Ok((
row.get::<_, String>(0)?, // id
row.get::<_, String>(1)?, // subject
created_at_str,
question_images_str,
analysis_images_str,
row.get::<_, String>(5)?, // user_question
row.get::<_, String>(6)?, // ocr_text
tags_str,
row.get::<_, String>(8)?, // mistake_type
row.get::<_, String>(9)?, // status
updated_at_str,
))
})?;
// Collect all mistake basic data first
let mut mistake_data = Vec::new();
for row_result in rows {
mistake_data.push(row_result?);
}
// Now fetch chat messages for all mistakes in one query
let mut chat_messages: HashMap<String, Vec<ChatMessage>> = HashMap::new();
if !mistake_ids.is_empty() {
let placeholders = mistake_ids.iter().map(|_| "?").collect::<Vec<_>>().join(",");
let chat_query = format!(
"SELECT mistake_id, role, content, timestamp, thinking_content
FROM chat_messages WHERE mistake_id IN ({}) ORDER BY mistake_id, timestamp ASC",
placeholders
);
let mut chat_stmt = self.conn.prepare(&chat_query)?;
let chat_rows = chat_stmt.query_map(¶ms[..], |row| {
Ok((
row.get::<_, String>(0)?, // mistake_id
row.get::<_, String>(1)?, // role
row.get::<_, String>(2)?, // content
row.get::<_, String>(3)?, // timestamp
row.get::<_, Option<String>>(4)?, // thinking_content
))
})?;
for chat_row_result in chat_rows {
let (mistake_id, role, content, timestamp_str, thinking_content) = chat_row_result?;
let timestamp = chrono::DateTime::parse_from_rfc3339(×tamp_str)
.map_err(|e| anyhow::anyhow!("Failed to parse timestamp: {}", e))?
.with_timezone(&Utc);
let message = ChatMessage {
role,
content,
timestamp,
thinking_content,
rag_sources: None,
image_paths: None,
image_base64: None,
};
chat_messages.entry(mistake_id).or_insert_with(Vec::new).push(message);
}
}
// Combine mistake data with chat messages
for (id, subject, created_at_str, question_images_str, analysis_images_str, user_question, ocr_text, tags_str, mistake_type, status, updated_at_str) in mistake_data {
let created_at = chrono::DateTime::parse_from_rfc3339(&created_at_str)
.map_err(|e| anyhow::anyhow!("Failed to parse created_at: {}", e))?
.with_timezone(&Utc);
let updated_at = chrono::DateTime::parse_from_rfc3339(&updated_at_str)
.map_err(|e| anyhow::anyhow!("Failed to parse updated_at: {}", e))?
.with_timezone(&Utc);
let question_images: Vec<String> = serde_json::from_str(&question_images_str)?;
let analysis_images: Vec<String> = serde_json::from_str(&analysis_images_str)?;
let tags: Vec<String> = serde_json::from_str(&tags_str)?;
let mistake = MistakeItem {
id: id.clone(),
subject,
created_at,
question_images,
analysis_images,
user_question,
ocr_text,
tags,
mistake_type,
status,
updated_at,
chat_history: chat_messages.remove(&id).unwrap_or_default(),
mistake_summary: None, // 批量操作不加载总结
user_error_analysis: None, // 批量操作不加载分析
};
mistakes.push(mistake);
}
println!("✅ Batch exported {} mistakes with full data", mistakes.len());
Ok(mistakes)
}
}
/// Extension trait for Database to add batch operations
pub trait BatchOperationExt {
fn with_batch_operations<F, R>(&self, f: F) -> Result<R>
where
F: FnOnce(&mut BatchOperations) -> Result<R>;
}
impl BatchOperationExt for crate::database::Database {
fn with_batch_operations<F, R>(&self, f: F) -> Result<R>
where
F: FnOnce(&mut BatchOperations) -> Result<R>
{
let mut conn = self.conn().lock().unwrap();
let mut batch_ops = BatchOperations::new(&mut conn);
f(&mut batch_ops)
}
}
/// Utility functions for common batch operations
pub mod batch_utils {
use super::*;
use crate::database::Database;
/// High-level function to perform bulk import of mistakes
pub fn bulk_import_mistakes(database: &Database, mistakes: &[MistakeItem]) -> Result<usize> {
database.with_batch_operations(|batch_ops| {
batch_ops.batch_save_mistakes(mistakes)
})
}
/// High-level function to perform bulk cleanup operations
pub fn bulk_cleanup(database: &Database, archive_days: Option<i64>) -> Result<(usize, usize)> {
database.with_batch_operations(|batch_ops| {
let orphaned = batch_ops.batch_cleanup_orphaned_messages()?;
let archived = if let Some(days) = archive_days {
batch_ops.batch_archive_old_mistakes(days)?
} else {
0
};
Ok((orphaned, archived))
})
}
/// High-level function to bulk update mistake properties
pub fn bulk_update_mistakes(
database: &Database,
status_updates: Option<&HashMap<String, String>>,
tag_updates: Option<&HashMap<String, Vec<String>>>,
) -> Result<(usize, usize)> {
database.with_batch_operations(|batch_ops| {
let status_count = if let Some(updates) = status_updates {
batch_ops.batch_update_mistake_statuses(updates)?
} else {
0
};
let tag_count = if let Some(updates) = tag_updates {
batch_ops.batch_update_mistake_tags(updates)?
} else {
0
};
Ok((status_count, tag_count))
})
}
/// High-level function for bulk export with progress reporting
pub fn bulk_export_mistakes(database: &Database, mistake_ids: &[String]) -> Result<Vec<MistakeItem>> {
const BATCH_SIZE: usize = 50; // Export in batches to avoid memory issues
let mut all_mistakes = Vec::new();
for chunk in mistake_ids.chunks(BATCH_SIZE) {
let mut batch_mistakes = database.with_batch_operations(|batch_ops| {
batch_ops.batch_export_mistakes(chunk)
})?;
all_mistakes.append(&mut batch_mistakes);
println!("Exported batch: {} mistakes, total so far: {}", chunk.len(), all_mistakes.len());
}
Ok(all_mistakes)
}
}
|
0015/RPI-Projects
| 1,417 |
WIFI Streaming Camera/0.RPI_Scripts/connect_cam.sh
|
#!/bin/bash
# Set the WiFi SSID and password
SSID="AMB82-Mini"
PASSWORD="Password"
# Path to the wpa_supplicant configuration file
WPA_CONF_FILE="/etc/wpa_supplicant/wpa_supplicant.conf"
# Add network configuration to wpa_supplicant configuration file
# This part needs to run with root privileges
echo "network={" >> $WPA_CONF_FILE
echo " ssid=\"$SSID\"" >> $WPA_CONF_FILE
echo " psk=\"$PASSWORD\"" >> $WPA_CONF_FILE
echo "}" >> $WPA_CONF_FILE
# Reconfigure wpa_supplicant to apply the changes
wpa_cli -i wlan0 reconfigure
# Function to check WiFi connection status and IP address
check_wifi_connection() {
# Check if the WiFi interface is associated with the specified SSID
if iwconfig wlan0 | grep -q "ESSID:\"$SSID\""; then
# Check if an IP address is assigned to wlan0
if ip addr show wlan0 | grep -q "inet "; then
return 0 # IP address assigned, connection successful
fi
fi
return 1 # Connection not successful yet
}
# Wait until WiFi connection is established and IP address is assigned
echo "Connecting to WiFi network '$SSID'..."
while ! check_wifi_connection; do
echo "WiFi connection in progress. Waiting..."
sleep 5
done
echo "WiFi connected successfully to '$SSID'."
echo "IP address assigned to wlan0: $(ip addr show wlan0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}')"
# Continue with the python script commands
python3 ./vlc_rtsp.py
|
000ylop/galgame_cn
| 4,474 |
generate_list/src/main.rs
|
use std::fs::{self, OpenOptions};
use std::io::{BufWriter, Write};
use std::path::PathBuf;
use std::time::Duration;
use playwright::Playwright;
use std::sync::Arc;
use tokio::task::JoinSet;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let Args {
sites,
output,
proxy,
} = Args::parse();
let current_list = unsafe { String::from_utf8_unchecked(fs::read(&output)?) };
let sites_list = unsafe { String::from_utf8_unchecked(fs::read(sites)?) };
let output = OpenOptions::new()
.create(false)
.append(true)
.read(false)
.open(output)?;
let mut out = BufWriter::new(output);
let pw = Playwright::initialize().await?;
pw.install_chromium()?;
let chromium = pw.chromium();
let mut launcher = chromium.launcher().headless(false);
if let Some(proxy) = proxy {
launcher = launcher.proxy(ProxySettings {
server: proxy,
bypass: None,
username: None,
password: None,
});
}
let browser = launcher.launch().await?;
let context = Arc::new(browser.context_builder().user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 GLS/100.10.9939.100").build().await?);
// bypass CF for ryuugames
context.add_cookies(&[Cookie::with_domain_path("cf_clearance", "CqCW39e7Dqzq4e74ac4NBDP_TkjJuvM6TtGCyEHqtQE-1723046672-1.0.1.1-_1Dj47lZPpDpiW6Iw6zb_lg3ZrmKgkJpxrRcxwhKWsXRtmHFy.YSBcCOYupK.I.ZSZ7tmJbfU729PlTb6K0NpQ", ".ryuugames.com", "/")]).await?;
let mut task_set: JoinSet<anyhow::Result<Option<String>>> = JoinSet::new();
if !std::fs::read_dir("res").is_ok() {
std::fs::create_dir("res")?;
}
for mut site in sites_list
.lines()
.filter(|&site| !site.is_empty())
.filter(|&site| !current_list.contains(site.split_whitespace().next().unwrap()))
.map(|s| s.to_owned())
{
let context = context.clone();
let _site = site.clone();
let split = _site.split_whitespace().collect::<Vec<_>>();
let mut caption = None;
if split.len() > 1 {
site = split[0].to_owned();
caption = Some(split[1].to_owned());
}
task_set.spawn(async move {
let page = context.new_page().await?;
let _ = page
.goto_builder(&site)
.wait_until(DocumentLoadState::Load)
.timeout(10_000.0)
.goto()
.await;
let _site = site.clone();
let screenshot_out = tokio::task::spawn_blocking(move || {
format!(
"res/{}.webp",
hex_simd::encode_to_string(md5::compute(&_site).0, hex_simd::AsciiCase::Lower)
)
})
.await?;
println!("screenshot path for {site}: {screenshot_out}");
tokio::time::sleep(Duration::from_secs(10)).await;
let title = page.title().await?;
page.screenshot_builder()
.path(screenshot_out.clone().into())
.screenshot()
.await?;
let markdown_text = tokio::task::spawn_blocking(move || match caption {
Some(caption) => format!(
r#"
<figure class="image">
<a href="{site}">
<img src="{screenshot_out}" alt="{title}"></img>
</a>
<figcaption>{caption}</figcaption>
</figure>
"#
),
None => format!("[]({site})\n\n"),
})
.await?;
Ok(Some(markdown_text))
});
}
while let Some(Ok(re)) = task_set.join_next().await {
if let Ok(Some(line)) = re {
out.write(line.as_bytes())?;
}
}
Ok(())
}
use clap::Parser;
use clap::ValueHint;
use playwright::api::{Cookie, DocumentLoadState, ProxySettings};
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
/// plain text file, contains sites to generate
#[clap(short, long, value_parser, value_hint = ValueHint::FilePath)]
sites: PathBuf,
/// result file, should exists
#[clap(short, long, value_parser, value_hint = ValueHint::FilePath)]
output: PathBuf,
/// [optional] proxy to set, for example http://127.0.0.1:8080
#[clap(short, long, value_parser)]
proxy: Option<String>,
}
|
000haoji/deep-student
| 9,124 |
src-tauri/src/analysis_service.rs
|
use crate::models::{ChatMessage, MistakeItem};
use crate::llm_manager::LLMManager;
use crate::database::Database;
use anyhow::Result;
use serde_json::json;
use std::collections::HashMap;
use std::sync::Arc;
use tauri::Window;
// 分析结果结构
#[derive(Debug, Clone)]
pub struct AnalysisResult {
pub ocr_text: String,
pub tags: Vec<String>,
pub mistake_type: String,
pub first_answer: String,
}
pub struct AnalysisService {
llm_manager: LLMManager,
// 移除重复的temp_sessions,统一使用AppState中的会话管理
}
impl AnalysisService {
pub fn new(database: Arc<Database>, file_manager: Arc<crate::file_manager::FileManager>) -> Self {
Self {
llm_manager: LLMManager::new(database, file_manager),
}
}
// 分析错题(使用统一AI接口)- 流式版本
pub async fn analyze_mistake_stream(
&self,
question_image_paths: &[String],
user_question: &str,
subject: &str,
window: Window,
stream_event: &str,
) -> Result<AnalysisResult> {
println!("开始分析错题(流式): 科目={}, 图片数量={}", subject, question_image_paths.len());
// 调用统一模型一接口进行OCR和分类(第一模型不使用流式,因为需要结构化输出)
let model1_result = self.llm_manager.call_unified_model_1(
question_image_paths.to_vec(),
user_question,
subject,
None, // 暂时不使用任务上下文
).await.map_err(|e| anyhow::anyhow!("模型一调用失败: {}", e))?;
// 构建上下文
let mut context = HashMap::new();
context.insert("ocr_text".to_string(), json!(model1_result.ocr_text));
context.insert("tags".to_string(), json!(model1_result.tags));
context.insert("mistake_type".to_string(), json!(model1_result.mistake_type));
context.insert("user_question".to_string(), json!(user_question));
// 获取模型配置以判断是否是推理模型
let model_config = self.llm_manager.get_model2_config().await
.map_err(|e| anyhow::anyhow!("获取模型配置失败: {}", e))?;
// 推理模型自动启用思维链
let enable_chain_of_thought = model_config.is_reasoning;
// 调用统一模型二接口获取首次解答(流式)
let model2_result = self.llm_manager.call_unified_model_2_stream(
&context,
&[], // 空的聊天历史
subject,
enable_chain_of_thought, // 推理模型自动启用思维链
Some(question_image_paths.to_vec()), // 🎯 修复:传入图片路径给第二模型
None, // 暂时不使用任务上下文
window,
stream_event,
).await.map_err(|e| anyhow::anyhow!("模型二调用失败: {}", e))?;
Ok(AnalysisResult {
ocr_text: model1_result.ocr_text,
tags: model1_result.tags,
mistake_type: model1_result.mistake_type,
first_answer: model2_result.assistant_message,
})
}
// 分析错题(使用统一AI接口)- 非流式版本(已废弃,统一使用流式)
pub async fn analyze_mistake(
&self,
_question_image_paths: &[String],
_user_question: &str,
_subject: &str,
) -> Result<AnalysisResult> {
println!("警告: analyze_mistake 非流式版本已废弃,请使用 analyze_mistake_stream");
// 为了兼容性,创建一个虚拟的 Window 对象
// 实际上这个函数不应该被调用
return Err(anyhow::anyhow!("非流式版本已废弃,请使用流式版本"));
}
// 继续对话(使用统一AI接口)- 流式版本
pub async fn continue_conversation_stream(
&self,
ocr_text: &str,
tags: &[String],
chat_history: &[ChatMessage],
subject: &str,
window: Window,
stream_event: &str,
) -> Result<String> {
println!("继续对话(流式): 科目={}, 聊天历史长度={}", subject, chat_history.len());
// 构建上下文
let mut context = HashMap::new();
context.insert("ocr_text".to_string(), json!(ocr_text));
context.insert("tags".to_string(), json!(tags));
context.insert("subject".to_string(), json!(subject));
// 获取模型配置以判断是否是推理模型
let model_config = self.llm_manager.get_model2_config().await
.map_err(|e| anyhow::anyhow!("获取模型配置失败: {}", e))?;
// 推理模型自动启用思维链
let enable_chain_of_thought = model_config.is_reasoning;
// 调用统一模型二接口(流式)
let model2_result = self.llm_manager.call_unified_model_2_stream(
&context,
chat_history,
subject,
enable_chain_of_thought, // 推理模型自动启用思维链
None, // 继续对话时不传入图片
None, // 暂时不使用任务上下文
window,
stream_event,
).await.map_err(|e| anyhow::anyhow!("模型二调用失败: {}", e))?;
Ok(model2_result.assistant_message)
}
// 继续对话(使用统一AI接口)- 非流式版本(已废弃,统一使用流式)
pub async fn continue_conversation(
&self,
_ocr_text: &str,
_tags: &[String],
_chat_history: &[ChatMessage],
_subject: &str,
) -> Result<String> {
println!("警告: continue_conversation 非流式版本已废弃,请使用 continue_conversation_stream");
// 为了兼容性,返回错误
return Err(anyhow::anyhow!("非流式版本已废弃,请使用流式版本"));
}
// 回顾分析(使用统一AI接口)- 流式版本
pub async fn analyze_review_session_stream(
&self,
mistakes: &[MistakeItem],
subject: &str,
window: Window,
stream_event: &str,
) -> Result<String> {
println!("开始回顾分析(流式): 科目={}, 错题数量={}", subject, mistakes.len());
// 构建回顾分析的上下文
let mut context = HashMap::new();
context.insert("subject".to_string(), json!(subject));
context.insert("mistake_count".to_string(), json!(mistakes.len()));
// 收集所有错题的信息
let mut mistake_summaries = Vec::new();
for (index, mistake) in mistakes.iter().enumerate() {
let summary = json!({
"index": index + 1,
"question": mistake.user_question,
"ocr_text": mistake.ocr_text,
"tags": mistake.tags,
"mistake_type": mistake.mistake_type,
"created_at": mistake.created_at.format("%Y-%m-%d").to_string()
});
mistake_summaries.push(summary);
}
context.insert("mistakes".to_string(), json!(mistake_summaries));
// 🎯 修复BUG-04:获取回顾分析专用模型配置
let model_assignments = self.llm_manager.get_model_assignments().await
.map_err(|e| anyhow::anyhow!("获取模型分配失败: {}", e))?;
// 优先使用回顾分析专用模型,如果未配置则回退到第二模型
let target_model_id = model_assignments.review_analysis_model_config_id
.or(model_assignments.model2_config_id)
.ok_or_else(|| anyhow::anyhow!("没有配置可用的回顾分析模型或第二模型"))?;
// 获取目标模型配置
let api_configs = self.llm_manager.get_api_configs().await
.map_err(|e| anyhow::anyhow!("获取API配置失败: {}", e))?;
let model_config = api_configs.iter()
.find(|config| config.id == target_model_id && config.enabled)
.ok_or_else(|| anyhow::anyhow!("找不到可用的回顾分析模型配置: {}", target_model_id))?;
println!("📋 回顾分析使用模型: {} ({})", model_config.name, model_config.model);
// 推理模型自动启用思维链,回顾分析特别需要深度思考
let enable_chain_of_thought = model_config.is_reasoning || true; // 回顾分析总是启用思维链
// 调用统一模型接口进行回顾分析(流式)
// 使用默认的回顾分析任务上下文(科目配置的提示词已经在 LLMManager 中处理)
let task_context = "多道错题的回顾分析和学习建议";
let model2_result = self.llm_manager.call_unified_model_stream_with_config(
model_config,
&context,
&[], // 回顾分析不需要聊天历史
subject,
enable_chain_of_thought, // 回顾分析启用思维链
None, // 回顾分析不传入图片
Some(task_context), // 使用任务上下文
window,
stream_event,
).await.map_err(|e| anyhow::anyhow!("回顾分析失败: {}", e))?;
Ok(model2_result.assistant_message)
}
// 回顾分析(使用统一AI接口)- 非流式版本(已废弃,统一使用流式)
pub async fn analyze_review_session(
&self,
_mistakes: &[MistakeItem],
_subject: &str,
) -> Result<String> {
println!("警告: analyze_review_session 非流式版本已废弃,请使用 analyze_review_session_stream");
// 为了兼容性,返回错误
return Err(anyhow::anyhow!("非流式版本已废弃,请使用流式版本"));
}
// 测试API连接
pub async fn test_connection(&self, api_key: &str, api_base: &str) -> Result<bool> {
// 使用现有的LLM管理器进行测试
self.llm_manager.test_connection(api_key, api_base).await
.map_err(|e| anyhow::anyhow!("API连接测试失败: {}", e))
}
// 获取初始解答(使用统一AI接口)
pub async fn get_initial_answer(
&self,
ocr_text: &str,
tags: &[String],
user_question: &str,
subject: &str,
) -> Result<String> {
println!("获取初始解答: 科目={}", subject);
// 构建上下文
let mut context = HashMap::new();
context.insert("ocr_text".to_string(), json!(ocr_text));
context.insert("tags".to_string(), json!(tags));
context.insert("user_question".to_string(), json!(user_question));
// 调用统一模型二接口获取首次解答
let model2_result = self.llm_manager.call_unified_model_2(
&context,
&[], // 空的聊天历史
subject,
false, // 初始解答默认不启用思维链
None, // 不传入图片
Some("提供题目的初始解答"), // 任务上下文
).await.map_err(|e| anyhow::anyhow!("获取初始解答失败: {}", e))?;
Ok(model2_result.assistant_message)
}
}
|
000haoji/deep-student
| 20,046 |
src-tauri/src/database_optimizations.rs
|
/**
* Database Optimization Module
*
* Provides optimized database query functions for better performance,
* especially for tag filtering and complex search operations.
*/
use anyhow::Result;
use rusqlite::Connection;
use chrono::{Utc, DateTime};
use crate::models::MistakeItem;
use std::collections::HashMap;
pub struct DatabaseOptimizations;
impl DatabaseOptimizations {
/// Optimized tag filtering using SQLite JSON functions
/// Much faster than application-level filtering for large datasets
pub fn get_mistakes_optimized(
conn: &Connection,
subject_filter: Option<&str>,
type_filter: Option<&str>,
tags_filter: Option<&[String]>,
limit: Option<u32>,
offset: Option<u32>,
) -> Result<Vec<MistakeItem>> {
let mut query_parts = vec![
"SELECT id, subject, created_at, question_images, analysis_images, user_question, ocr_text, tags, mistake_type, status, updated_at".to_string(),
"FROM mistakes".to_string(),
"WHERE 1=1".to_string(),
];
let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
let mut param_index = 1;
// Subject filter
if let Some(subject) = subject_filter {
query_parts.push(format!(" AND subject = ?{}", param_index));
params_vec.push(Box::new(subject.to_string()));
param_index += 1;
}
// Type filter
if let Some(mistake_type) = type_filter {
query_parts.push(format!(" AND mistake_type = ?{}", param_index));
params_vec.push(Box::new(mistake_type.to_string()));
param_index += 1;
}
// Optimized tag filter using JSON functions
if let Some(filter_tags) = tags_filter {
if !filter_tags.is_empty() {
// Use JSON_EXTRACT to check if any of the filter tags exist in the tags JSON array
let tag_conditions: Vec<String> = filter_tags.iter().enumerate().map(|(i, _)| {
let param_num = param_index + i;
// Check if the tag exists in the JSON array using json_extract and json_each
format!(
"EXISTS (SELECT 1 FROM json_each(mistakes.tags) WHERE json_each.value = ?{})",
param_num
)
}).collect();
query_parts.push(format!(" AND ({})", tag_conditions.join(" OR ")));
// Add tag parameters
for tag in filter_tags {
params_vec.push(Box::new(tag.clone()));
}
param_index += filter_tags.len();
}
}
// Add ordering for consistent results
query_parts.push(" ORDER BY created_at DESC".to_string());
// Add pagination
if let Some(limit_val) = limit {
query_parts.push(format!(" LIMIT ?{}", param_index));
params_vec.push(Box::new(limit_val));
param_index += 1;
if let Some(offset_val) = offset {
query_parts.push(format!(" OFFSET ?{}", param_index));
params_vec.push(Box::new(offset_val));
}
}
let full_query = query_parts.join("");
println!("Optimized query: {}", full_query);
let mut stmt = conn.prepare(&full_query)?;
let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();
let rows = stmt.query_map(¶ms_refs[..], |row| {
let created_at_str: String = row.get(2)?;
let updated_at_str: String = row.get(10)?;
let question_images_str: String = row.get(3)?;
let analysis_images_str: String = row.get(4)?;
let tags_str: String = row.get(7)?;
Ok((
row.get::<_, String>(0)?, // id
row.get::<_, String>(1)?, // subject
created_at_str,
question_images_str,
analysis_images_str,
row.get::<_, String>(5)?, // user_question
row.get::<_, String>(6)?, // ocr_text
tags_str,
row.get::<_, String>(8)?, // mistake_type
row.get::<_, String>(9)?, // status
updated_at_str,
))
})?;
let mut mistakes = Vec::new();
for row_result in rows {
let (id, subject, created_at_str, question_images_str, analysis_images_str,
user_question, ocr_text, tags_str, mistake_type, status, updated_at_str) = row_result?;
let created_at = DateTime::parse_from_rfc3339(&created_at_str)
.map_err(|e| anyhow::anyhow!("Failed to parse created_at: {}", e))?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
.map_err(|e| anyhow::anyhow!("Failed to parse updated_at: {}", e))?
.with_timezone(&Utc);
let question_images: Vec<String> = serde_json::from_str(&question_images_str)
.map_err(|e| anyhow::anyhow!("Failed to parse question_images JSON: {}", e))?;
let analysis_images: Vec<String> = serde_json::from_str(&analysis_images_str)
.map_err(|e| anyhow::anyhow!("Failed to parse analysis_images JSON: {}", e))?;
let tags: Vec<String> = serde_json::from_str(&tags_str)
.map_err(|e| anyhow::anyhow!("Failed to parse tags JSON: {}", e))?;
let mistake = MistakeItem {
id,
subject,
created_at,
question_images,
analysis_images,
user_question,
ocr_text,
tags,
mistake_type,
status,
updated_at,
chat_history: vec![], // Don't load chat history for list view - optimization
mistake_summary: None, // Optimization: not loaded in list view
user_error_analysis: None, // Optimization: not loaded in list view
};
mistakes.push(mistake);
}
println!("Optimized query returned {} mistakes", mistakes.len());
Ok(mistakes)
}
/// Get tag statistics with optimized JSON queries
pub fn get_tag_statistics_optimized(conn: &Connection) -> Result<HashMap<String, i32>> {
let query = r#"
SELECT json_each.value as tag, COUNT(*) as count
FROM mistakes, json_each(mistakes.tags)
WHERE json_valid(mistakes.tags) = 1
GROUP BY json_each.value
ORDER BY count DESC
"#;
let mut stmt = conn.prepare(query)?;
let rows = stmt.query_map([], |row| {
Ok((
row.get::<_, String>(0)?, // tag
row.get::<_, i32>(1)? // count
))
})?;
let mut tag_stats = HashMap::new();
for row_result in rows {
let (tag, count) = row_result?;
tag_stats.insert(tag, count);
}
Ok(tag_stats)
}
/// Full-text search across mistake content with ranking
pub fn search_mistakes_fulltext(
conn: &Connection,
search_term: &str,
subject_filter: Option<&str>,
limit: Option<u32>,
) -> Result<Vec<MistakeItem>> {
let mut query = r#"
SELECT id, subject, created_at, question_images, analysis_images, user_question, ocr_text, tags, mistake_type, status, updated_at,
-- Calculate relevance score
(CASE WHEN user_question LIKE ? THEN 3 ELSE 0 END +
CASE WHEN ocr_text LIKE ? THEN 2 ELSE 0 END +
CASE WHEN mistake_type LIKE ? THEN 1 ELSE 0 END) as relevance
FROM mistakes
WHERE (user_question LIKE ? OR ocr_text LIKE ? OR mistake_type LIKE ?)
"#.to_string();
let search_pattern = format!("%{}%", search_term);
let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = vec![
Box::new(search_pattern.clone()), // user_question scoring
Box::new(search_pattern.clone()), // ocr_text scoring
Box::new(search_pattern.clone()), // mistake_type scoring
Box::new(search_pattern.clone()), // user_question filter
Box::new(search_pattern.clone()), // ocr_text filter
Box::new(search_pattern.clone()), // mistake_type filter
];
if let Some(subject) = subject_filter {
query.push_str(" AND subject = ?");
params_vec.push(Box::new(subject.to_string()));
}
query.push_str(" ORDER BY relevance DESC, created_at DESC");
if let Some(limit_val) = limit {
query.push_str(" LIMIT ?");
params_vec.push(Box::new(limit_val));
}
let mut stmt = conn.prepare(&query)?;
let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();
let rows = stmt.query_map(¶ms_refs[..], |row| {
let created_at_str: String = row.get(2)?;
let updated_at_str: String = row.get(10)?;
let question_images_str: String = row.get(3)?;
let analysis_images_str: String = row.get(4)?;
let tags_str: String = row.get(7)?;
let relevance: i32 = row.get(11)?;
Ok((
row.get::<_, String>(0)?, // id
row.get::<_, String>(1)?, // subject
created_at_str,
question_images_str,
analysis_images_str,
row.get::<_, String>(5)?, // user_question
row.get::<_, String>(6)?, // ocr_text
tags_str,
row.get::<_, String>(8)?, // mistake_type
row.get::<_, String>(9)?, // status
updated_at_str,
relevance,
))
})?;
let mut mistakes = Vec::new();
for row_result in rows {
let (id, subject, created_at_str, question_images_str, analysis_images_str,
user_question, ocr_text, tags_str, mistake_type, status, updated_at_str, _relevance) = row_result?;
let created_at = DateTime::parse_from_rfc3339(&created_at_str)
.map_err(|e| anyhow::anyhow!("Failed to parse created_at: {}", e))?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
.map_err(|e| anyhow::anyhow!("Failed to parse updated_at: {}", e))?
.with_timezone(&Utc);
let question_images: Vec<String> = serde_json::from_str(&question_images_str)?;
let analysis_images: Vec<String> = serde_json::from_str(&analysis_images_str)?;
let tags: Vec<String> = serde_json::from_str(&tags_str)?;
let mistake = MistakeItem {
id,
subject,
created_at,
question_images,
analysis_images,
user_question,
ocr_text,
tags,
mistake_type,
status,
updated_at,
chat_history: vec![],
mistake_summary: None, // Search doesn't need summary
user_error_analysis: None, // Search doesn't need analysis
};
mistakes.push(mistake);
}
println!("Full-text search returned {} mistakes for term: '{}'", mistakes.len(), search_term);
Ok(mistakes)
}
/// Get mistakes by date range with optimized indexing
pub fn get_mistakes_by_date_range(
conn: &Connection,
start_date: &str, // RFC3339 format
end_date: &str, // RFC3339 format
subject_filter: Option<&str>,
) -> Result<Vec<MistakeItem>> {
let mut query = r#"
SELECT id, subject, created_at, question_images, analysis_images, user_question, ocr_text, tags, mistake_type, status, updated_at
FROM mistakes
WHERE created_at >= ? AND created_at <= ?
"#.to_string();
let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = vec![
Box::new(start_date.to_string()),
Box::new(end_date.to_string()),
];
if let Some(subject) = subject_filter {
query.push_str(" AND subject = ?");
params_vec.push(Box::new(subject.to_string()));
}
query.push_str(" ORDER BY created_at DESC");
let mut stmt = conn.prepare(&query)?;
let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();
let rows = stmt.query_map(¶ms_refs[..], |row| {
let created_at_str: String = row.get(2)?;
let updated_at_str: String = row.get(10)?;
let question_images_str: String = row.get(3)?;
let analysis_images_str: String = row.get(4)?;
let tags_str: String = row.get(7)?;
Ok((
row.get::<_, String>(0)?, // id
row.get::<_, String>(1)?, // subject
created_at_str,
question_images_str,
analysis_images_str,
row.get::<_, String>(5)?, // user_question
row.get::<_, String>(6)?, // ocr_text
tags_str,
row.get::<_, String>(8)?, // mistake_type
row.get::<_, String>(9)?, // status
updated_at_str,
))
})?;
let mut mistakes = Vec::new();
for row_result in rows {
let (id, subject, created_at_str, question_images_str, analysis_images_str,
user_question, ocr_text, tags_str, mistake_type, status, updated_at_str) = row_result?;
let created_at = DateTime::parse_from_rfc3339(&created_at_str)?
.with_timezone(&Utc);
let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)?
.with_timezone(&Utc);
let question_images: Vec<String> = serde_json::from_str(&question_images_str)?;
let analysis_images: Vec<String> = serde_json::from_str(&analysis_images_str)?;
let tags: Vec<String> = serde_json::from_str(&tags_str)?;
let mistake = MistakeItem {
id,
subject,
created_at,
question_images,
analysis_images,
user_question,
ocr_text,
tags,
mistake_type,
status,
updated_at,
chat_history: vec![],
mistake_summary: None, // Search doesn't need summary
user_error_analysis: None, // Search doesn't need analysis
};
mistakes.push(mistake);
}
Ok(mistakes)
}
/// Create database indexes for better performance
pub fn create_performance_indexes(conn: &Connection) -> Result<()> {
let indexes = vec![
// Index on created_at for date-based queries
"CREATE INDEX IF NOT EXISTS idx_mistakes_created_at ON mistakes(created_at)",
// Index on subject for subject filtering
"CREATE INDEX IF NOT EXISTS idx_mistakes_subject ON mistakes(subject)",
// Index on mistake_type for type filtering
"CREATE INDEX IF NOT EXISTS idx_mistakes_type ON mistakes(mistake_type)",
// Index on status for status filtering
"CREATE INDEX IF NOT EXISTS idx_mistakes_status ON mistakes(status)",
// Composite index for common filtering combinations
"CREATE INDEX IF NOT EXISTS idx_mistakes_subject_type ON mistakes(subject, mistake_type)",
// Index on chat_messages for faster joins
"CREATE INDEX IF NOT EXISTS idx_chat_messages_mistake_id ON chat_messages(mistake_id)",
"CREATE INDEX IF NOT EXISTS idx_chat_messages_timestamp ON chat_messages(timestamp)",
];
for index_sql in indexes {
conn.execute(index_sql, [])?;
println!("Created index: {}", index_sql);
}
Ok(())
}
/// Analyze query performance and suggest optimizations
pub fn analyze_query_performance(conn: &Connection, query: &str) -> Result<String> {
let explain_query = format!("EXPLAIN QUERY PLAN {}", query);
let mut stmt = conn.prepare(&explain_query)?;
let rows = stmt.query_map([], |row| {
Ok(format!(
"Level {}: {} - {}",
row.get::<_, i32>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?
))
})?;
let mut analysis = Vec::new();
for row_result in rows {
analysis.push(row_result?);
}
Ok(analysis.join("\n"))
}
}
/// Extension trait to add optimized methods to Database
pub trait DatabaseOptimizationExt {
fn get_mistakes_optimized(
&self,
subject_filter: Option<&str>,
type_filter: Option<&str>,
tags_filter: Option<&[String]>,
limit: Option<u32>,
offset: Option<u32>,
) -> Result<Vec<MistakeItem>>;
fn get_tag_statistics_optimized(&self) -> Result<HashMap<String, i32>>;
fn search_mistakes_fulltext(
&self,
search_term: &str,
subject_filter: Option<&str>,
limit: Option<u32>,
) -> Result<Vec<MistakeItem>>;
fn get_mistakes_by_date_range(
&self,
start_date: &str,
end_date: &str,
subject_filter: Option<&str>,
) -> Result<Vec<MistakeItem>>;
fn create_performance_indexes(&self) -> Result<()>;
fn analyze_query_performance(&self, query: &str) -> Result<String>;
}
impl DatabaseOptimizationExt for crate::database::Database {
fn get_mistakes_optimized(
&self,
subject_filter: Option<&str>,
type_filter: Option<&str>,
tags_filter: Option<&[String]>,
limit: Option<u32>,
offset: Option<u32>,
) -> Result<Vec<MistakeItem>> {
let conn = self.conn().lock().unwrap();
DatabaseOptimizations::get_mistakes_optimized(
&conn,
subject_filter,
type_filter,
tags_filter,
limit,
offset,
)
}
fn get_tag_statistics_optimized(&self) -> Result<HashMap<String, i32>> {
let conn = self.conn().lock().unwrap();
DatabaseOptimizations::get_tag_statistics_optimized(&conn)
}
fn search_mistakes_fulltext(
&self,
search_term: &str,
subject_filter: Option<&str>,
limit: Option<u32>,
) -> Result<Vec<MistakeItem>> {
let conn = self.conn().lock().unwrap();
DatabaseOptimizations::search_mistakes_fulltext(&conn, search_term, subject_filter, limit)
}
fn get_mistakes_by_date_range(
&self,
start_date: &str,
end_date: &str,
subject_filter: Option<&str>,
) -> Result<Vec<MistakeItem>> {
let conn = self.conn().lock().unwrap();
DatabaseOptimizations::get_mistakes_by_date_range(&conn, start_date, end_date, subject_filter)
}
fn create_performance_indexes(&self) -> Result<()> {
let conn = self.conn().lock().unwrap();
DatabaseOptimizations::create_performance_indexes(&conn)
}
fn analyze_query_performance(&self, query: &str) -> Result<String> {
let conn = self.conn().lock().unwrap();
DatabaseOptimizations::analyze_query_performance(&conn, query)
}
}
|
0015/RPI-Projects
| 2,946 |
WIFI Streaming Camera/1.AMB82_RTSP_APMode/1.AMB82_RTSP_APMode.ino
|
/////////////////////////////////////////////////////////////////
/*
WiFi Streaming Camera for AMB32-Mini
For More Information: https://youtu.be/FEs1RIjfO3Y
Created by Eric N. (ThatProject)
*/
/////////////////////////////////////////////////////////////////
#include "WiFi.h"
#include "StreamIO.h"
#include "VideoStream.h"
#include "AudioStream.h"
#include "AudioEncoder.h"
#include "RTSP.h"
#define CHANNEL 1
VideoSetting configV(CHANNEL);
AudioSetting configA(0);
Audio audio;
AAC aac;
RTSP rtsp;
StreamIO audioStreamer(1, 1); // 1 Input Audio -> 1 Output AAC
StreamIO avMixStreamer(2, 1); // 2 Input Video + Audio -> 1 Output RTSP
char ssid[] = "AMB82-Mini"; // your network SSID (name)
char pass[] = "Password"; // your network password
int status = WL_IDLE_STATUS;
char channel[] = "1"; // Set the AP channel
int ssid_status = 0;
void setup() {
Serial.begin(115200);
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to start AP with SSID: ");
Serial.println(ssid);
status = WiFi.apbegin(ssid, pass, channel, ssid_status);
// wait 2 seconds for connection:
delay(2000);
}
// Configure camera video channel with video format information
// Adjust the bitrate based on your WiFi network quality
configV.setBitrate(2 * 1024 * 1024); // Recommend to use 2Mbps for RTSP streaming to prevent network congestion
Camera.configVideoChannel(CHANNEL, configV);
Camera.videoInit();
// Configure audio peripheral for audio data output
audio.configAudio(configA);
audio.begin();
// Configure AAC audio encoder
aac.configAudio(configA);
aac.begin();
// Configure RTSP with identical video format information and enable audio streaming
rtsp.configVideo(configV);
rtsp.configAudio(configA, CODEC_AAC);
rtsp.begin();
// Configure StreamIO object to stream data from audio channel to AAC encoder
audioStreamer.registerInput(audio);
audioStreamer.registerOutput(aac);
if (audioStreamer.begin() != 0) {
Serial.println("StreamIO link start failed");
}
// Configure StreamIO object to stream data from video channel and AAC encoder to rtsp output
avMixStreamer.registerInput1(Camera.getStream(CHANNEL));
avMixStreamer.registerInput2(aac);
avMixStreamer.registerOutput(rtsp);
if (avMixStreamer.begin() != 0) {
Serial.println("StreamIO link start failed");
}
// Start data stream from video channel
Camera.channelBegin(CHANNEL);
delay(1000);
printInfo();
}
void loop() {
// Do nothing
}
void printInfo(void) {
Serial.println("------------------------------");
Serial.println("- Summary of Streaming -");
Serial.println("------------------------------");
Camera.printInfo();
IPAddress ip = WiFi.localIP();
Serial.println("- RTSP -");
Serial.print("rtsp://");
Serial.print(ip);
Serial.print(":");
rtsp.printInfo();
Serial.println("- Audio -");
audio.printInfo();
}
|
0015/LVGL_Joystick
| 77,022 |
examples/espidf_example/sdkconfig
|
#
# Automatically generated file. DO NOT EDIT.
# Espressif IoT Development Framework (ESP-IDF) 5.3.0 Project Configuration
#
CONFIG_SOC_MPU_MIN_REGION_SIZE=0x20000000
CONFIG_SOC_MPU_REGIONS_MAX_NUM=8
CONFIG_SOC_ADC_SUPPORTED=y
CONFIG_SOC_UART_SUPPORTED=y
CONFIG_SOC_PCNT_SUPPORTED=y
CONFIG_SOC_PHY_SUPPORTED=y
CONFIG_SOC_WIFI_SUPPORTED=y
CONFIG_SOC_TWAI_SUPPORTED=y
CONFIG_SOC_GDMA_SUPPORTED=y
CONFIG_SOC_AHB_GDMA_SUPPORTED=y
CONFIG_SOC_GPTIMER_SUPPORTED=y
CONFIG_SOC_LCDCAM_SUPPORTED=y
CONFIG_SOC_MCPWM_SUPPORTED=y
CONFIG_SOC_DEDICATED_GPIO_SUPPORTED=y
CONFIG_SOC_CACHE_SUPPORT_WRAP=y
CONFIG_SOC_ULP_SUPPORTED=y
CONFIG_SOC_ULP_FSM_SUPPORTED=y
CONFIG_SOC_RISCV_COPROC_SUPPORTED=y
CONFIG_SOC_BT_SUPPORTED=y
CONFIG_SOC_USB_OTG_SUPPORTED=y
CONFIG_SOC_USB_SERIAL_JTAG_SUPPORTED=y
CONFIG_SOC_CCOMP_TIMER_SUPPORTED=y
CONFIG_SOC_ASYNC_MEMCPY_SUPPORTED=y
CONFIG_SOC_SUPPORTS_SECURE_DL_MODE=y
CONFIG_SOC_EFUSE_KEY_PURPOSE_FIELD=y
CONFIG_SOC_EFUSE_SUPPORTED=y
CONFIG_SOC_SDMMC_HOST_SUPPORTED=y
CONFIG_SOC_RTC_FAST_MEM_SUPPORTED=y
CONFIG_SOC_RTC_SLOW_MEM_SUPPORTED=y
CONFIG_SOC_RTC_MEM_SUPPORTED=y
CONFIG_SOC_PSRAM_DMA_CAPABLE=y
CONFIG_SOC_XT_WDT_SUPPORTED=y
CONFIG_SOC_I2S_SUPPORTED=y
CONFIG_SOC_RMT_SUPPORTED=y
CONFIG_SOC_SDM_SUPPORTED=y
CONFIG_SOC_GPSPI_SUPPORTED=y
CONFIG_SOC_LEDC_SUPPORTED=y
CONFIG_SOC_I2C_SUPPORTED=y
CONFIG_SOC_SYSTIMER_SUPPORTED=y
CONFIG_SOC_SUPPORT_COEXISTENCE=y
CONFIG_SOC_TEMP_SENSOR_SUPPORTED=y
CONFIG_SOC_AES_SUPPORTED=y
CONFIG_SOC_MPI_SUPPORTED=y
CONFIG_SOC_SHA_SUPPORTED=y
CONFIG_SOC_HMAC_SUPPORTED=y
CONFIG_SOC_DIG_SIGN_SUPPORTED=y
CONFIG_SOC_FLASH_ENC_SUPPORTED=y
CONFIG_SOC_SECURE_BOOT_SUPPORTED=y
CONFIG_SOC_MEMPROT_SUPPORTED=y
CONFIG_SOC_TOUCH_SENSOR_SUPPORTED=y
CONFIG_SOC_BOD_SUPPORTED=y
CONFIG_SOC_CLK_TREE_SUPPORTED=y
CONFIG_SOC_MPU_SUPPORTED=y
CONFIG_SOC_WDT_SUPPORTED=y
CONFIG_SOC_SPI_FLASH_SUPPORTED=y
CONFIG_SOC_RNG_SUPPORTED=y
CONFIG_SOC_LIGHT_SLEEP_SUPPORTED=y
CONFIG_SOC_DEEP_SLEEP_SUPPORTED=y
CONFIG_SOC_LP_PERIPH_SHARE_INTERRUPT=y
CONFIG_SOC_PM_SUPPORTED=y
CONFIG_SOC_XTAL_SUPPORT_40M=y
CONFIG_SOC_APPCPU_HAS_CLOCK_GATING_BUG=y
CONFIG_SOC_ADC_RTC_CTRL_SUPPORTED=y
CONFIG_SOC_ADC_DIG_CTRL_SUPPORTED=y
CONFIG_SOC_ADC_ARBITER_SUPPORTED=y
CONFIG_SOC_ADC_DIG_IIR_FILTER_SUPPORTED=y
CONFIG_SOC_ADC_MONITOR_SUPPORTED=y
CONFIG_SOC_ADC_DMA_SUPPORTED=y
CONFIG_SOC_ADC_PERIPH_NUM=2
CONFIG_SOC_ADC_MAX_CHANNEL_NUM=10
CONFIG_SOC_ADC_ATTEN_NUM=4
CONFIG_SOC_ADC_DIGI_CONTROLLER_NUM=2
CONFIG_SOC_ADC_PATT_LEN_MAX=24
CONFIG_SOC_ADC_DIGI_MIN_BITWIDTH=12
CONFIG_SOC_ADC_DIGI_MAX_BITWIDTH=12
CONFIG_SOC_ADC_DIGI_RESULT_BYTES=4
CONFIG_SOC_ADC_DIGI_DATA_BYTES_PER_CONV=4
CONFIG_SOC_ADC_DIGI_IIR_FILTER_NUM=2
CONFIG_SOC_ADC_DIGI_MONITOR_NUM=2
CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_HIGH=83333
CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_LOW=611
CONFIG_SOC_ADC_RTC_MIN_BITWIDTH=12
CONFIG_SOC_ADC_RTC_MAX_BITWIDTH=12
CONFIG_SOC_ADC_CALIBRATION_V1_SUPPORTED=y
CONFIG_SOC_ADC_SELF_HW_CALI_SUPPORTED=y
CONFIG_SOC_ADC_SHARED_POWER=y
CONFIG_SOC_APB_BACKUP_DMA=y
CONFIG_SOC_BROWNOUT_RESET_SUPPORTED=y
CONFIG_SOC_CACHE_WRITEBACK_SUPPORTED=y
CONFIG_SOC_CACHE_FREEZE_SUPPORTED=y
CONFIG_SOC_CPU_CORES_NUM=2
CONFIG_SOC_CPU_INTR_NUM=32
CONFIG_SOC_CPU_HAS_FPU=y
CONFIG_SOC_HP_CPU_HAS_MULTIPLE_CORES=y
CONFIG_SOC_CPU_BREAKPOINTS_NUM=2
CONFIG_SOC_CPU_WATCHPOINTS_NUM=2
CONFIG_SOC_CPU_WATCHPOINT_MAX_REGION_SIZE=64
CONFIG_SOC_DS_SIGNATURE_MAX_BIT_LEN=4096
CONFIG_SOC_DS_KEY_PARAM_MD_IV_LENGTH=16
CONFIG_SOC_DS_KEY_CHECK_MAX_WAIT_US=1100
CONFIG_SOC_AHB_GDMA_VERSION=1
CONFIG_SOC_GDMA_NUM_GROUPS_MAX=1
CONFIG_SOC_GDMA_PAIRS_PER_GROUP=5
CONFIG_SOC_GDMA_PAIRS_PER_GROUP_MAX=5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y
CONFIG_SOC_I2S_SUPPORTS_PDM=y
CONFIG_SOC_I2S_SUPPORTS_PDM_TX=y
CONFIG_SOC_I2S_PDM_MAX_TX_LINES=2
CONFIG_SOC_I2S_SUPPORTS_PDM_RX=y
CONFIG_SOC_I2S_PDM_MAX_RX_LINES=4
CONFIG_SOC_I2S_SUPPORTS_TDM=y
CONFIG_SOC_LEDC_SUPPORT_APB_CLOCK=y
CONFIG_SOC_LEDC_SUPPORT_XTAL_CLOCK=y
CONFIG_SOC_LEDC_CHANNEL_NUM=8
CONFIG_SOC_LEDC_TIMER_BIT_WIDTH=14
CONFIG_SOC_LEDC_SUPPORT_FADE_STOP=y
CONFIG_SOC_MCPWM_GROUPS=2
CONFIG_SOC_MCPWM_TIMERS_PER_GROUP=3
CONFIG_SOC_MCPWM_OPERATORS_PER_GROUP=3
CONFIG_SOC_MCPWM_COMPARATORS_PER_OPERATOR=2
CONFIG_SOC_MCPWM_GENERATORS_PER_OPERATOR=2
CONFIG_SOC_MCPWM_TRIGGERS_PER_OPERATOR=2
CONFIG_SOC_MCPWM_GPIO_FAULTS_PER_GROUP=3
CONFIG_SOC_MCPWM_CAPTURE_TIMERS_PER_GROUP=y
CONFIG_SOC_MCPWM_CAPTURE_CHANNELS_PER_TIMER=3
CONFIG_SOC_MCPWM_GPIO_SYNCHROS_PER_GROUP=3
CONFIG_SOC_MCPWM_SWSYNC_CAN_PROPAGATE=y
CONFIG_SOC_MMU_LINEAR_ADDRESS_REGION_NUM=1
CONFIG_SOC_MMU_PERIPH_NUM=1
CONFIG_SOC_PCNT_GROUPS=1
CONFIG_SOC_PCNT_UNITS_PER_GROUP=4
CONFIG_SOC_PCNT_CHANNELS_PER_UNIT=2
CONFIG_SOC_PCNT_THRES_POINT_PER_UNIT=2
CONFIG_SOC_RMT_GROUPS=1
CONFIG_SOC_RMT_TX_CANDIDATES_PER_GROUP=4
CONFIG_SOC_RMT_RX_CANDIDATES_PER_GROUP=4
CONFIG_SOC_RMT_CHANNELS_PER_GROUP=8
CONFIG_SOC_RMT_MEM_WORDS_PER_CHANNEL=48
CONFIG_SOC_RMT_SUPPORT_RX_PINGPONG=y
CONFIG_SOC_RMT_SUPPORT_RX_DEMODULATION=y
CONFIG_SOC_RMT_SUPPORT_TX_ASYNC_STOP=y
CONFIG_SOC_RMT_SUPPORT_TX_LOOP_COUNT=y
CONFIG_SOC_RMT_SUPPORT_TX_LOOP_AUTO_STOP=y
CONFIG_SOC_RMT_SUPPORT_TX_SYNCHRO=y
CONFIG_SOC_RMT_SUPPORT_TX_CARRIER_DATA_ONLY=y
CONFIG_SOC_RMT_SUPPORT_XTAL=y
CONFIG_SOC_RMT_SUPPORT_RC_FAST=y
CONFIG_SOC_RMT_SUPPORT_APB=y
CONFIG_SOC_RMT_SUPPORT_DMA=y
CONFIG_SOC_LCD_I80_SUPPORTED=y
CONFIG_SOC_LCD_RGB_SUPPORTED=y
CONFIG_SOC_LCD_I80_BUSES=1
CONFIG_SOC_LCD_RGB_PANELS=1
CONFIG_SOC_LCD_I80_BUS_WIDTH=16
CONFIG_SOC_LCD_RGB_DATA_WIDTH=16
CONFIG_SOC_LCD_SUPPORT_RGB_YUV_CONV=y
CONFIG_SOC_RTC_CNTL_CPU_PD_DMA_BUS_WIDTH=128
CONFIG_SOC_RTC_CNTL_CPU_PD_REG_FILE_NUM=549
CONFIG_SOC_RTC_CNTL_TAGMEM_PD_DMA_BUS_WIDTH=128
CONFIG_SOC_RTCIO_PIN_COUNT=22
CONFIG_SOC_RTCIO_INPUT_OUTPUT_SUPPORTED=y
CONFIG_SOC_RTCIO_HOLD_SUPPORTED=y
CONFIG_SOC_RTCIO_WAKE_SUPPORTED=y
CONFIG_SOC_SDM_GROUPS=y
CONFIG_SOC_SDM_CHANNELS_PER_GROUP=8
CONFIG_SOC_SDM_CLK_SUPPORT_APB=y
CONFIG_SOC_SPI_PERIPH_NUM=3
CONFIG_SOC_SPI_MAX_CS_NUM=6
CONFIG_SOC_SPI_MAXIMUM_BUFFER_SIZE=64
CONFIG_SOC_SPI_SUPPORT_DDRCLK=y
CONFIG_SOC_SPI_SLAVE_SUPPORT_SEG_TRANS=y
CONFIG_SOC_SPI_SUPPORT_CD_SIG=y
CONFIG_SOC_SPI_SUPPORT_CONTINUOUS_TRANS=y
CONFIG_SOC_SPI_SUPPORT_SLAVE_HD_VER2=y
CONFIG_SOC_SPI_SUPPORT_CLK_APB=y
CONFIG_SOC_SPI_SUPPORT_CLK_XTAL=y
CONFIG_SOC_SPI_PERIPH_SUPPORT_CONTROL_DUMMY_OUT=y
CONFIG_SOC_MEMSPI_IS_INDEPENDENT=y
CONFIG_SOC_SPI_MAX_PRE_DIVIDER=16
CONFIG_SOC_SPI_SUPPORT_OCT=y
CONFIG_SOC_SPI_SCT_SUPPORTED=y
CONFIG_SOC_SPI_SCT_REG_NUM=14
CONFIG_SOC_SPI_SCT_BUFFER_NUM_MAX=y
CONFIG_SOC_SPI_SCT_CONF_BITLEN_MAX=0x3FFFA
CONFIG_SOC_MEMSPI_SRC_FREQ_120M=y
CONFIG_SOC_MEMSPI_SRC_FREQ_80M_SUPPORTED=y
CONFIG_SOC_MEMSPI_SRC_FREQ_40M_SUPPORTED=y
CONFIG_SOC_MEMSPI_SRC_FREQ_20M_SUPPORTED=y
CONFIG_SOC_SPIRAM_SUPPORTED=y
CONFIG_SOC_SPIRAM_XIP_SUPPORTED=y
CONFIG_SOC_SYSTIMER_COUNTER_NUM=2
CONFIG_SOC_SYSTIMER_ALARM_NUM=3
CONFIG_SOC_SYSTIMER_BIT_WIDTH_LO=32
CONFIG_SOC_SYSTIMER_BIT_WIDTH_HI=20
CONFIG_SOC_SYSTIMER_FIXED_DIVIDER=y
CONFIG_SOC_SYSTIMER_INT_LEVEL=y
CONFIG_SOC_SYSTIMER_ALARM_MISS_COMPENSATE=y
CONFIG_SOC_TIMER_GROUPS=2
CONFIG_SOC_TIMER_GROUP_TIMERS_PER_GROUP=2
CONFIG_SOC_TIMER_GROUP_COUNTER_BIT_WIDTH=54
CONFIG_SOC_TIMER_GROUP_SUPPORT_XTAL=y
CONFIG_SOC_TIMER_GROUP_SUPPORT_APB=y
CONFIG_SOC_TIMER_GROUP_TOTAL_TIMERS=4
CONFIG_SOC_TOUCH_SENSOR_VERSION=2
CONFIG_SOC_TOUCH_SENSOR_NUM=15
CONFIG_SOC_TOUCH_PROXIMITY_CHANNEL_NUM=3
CONFIG_SOC_TOUCH_PROXIMITY_MEAS_DONE_SUPPORTED=y
CONFIG_SOC_TOUCH_SAMPLER_NUM=1
CONFIG_SOC_TWAI_CONTROLLER_NUM=1
CONFIG_SOC_TWAI_CLK_SUPPORT_APB=y
CONFIG_SOC_TWAI_BRP_MIN=2
CONFIG_SOC_TWAI_BRP_MAX=16384
CONFIG_SOC_TWAI_SUPPORTS_RX_STATUS=y
CONFIG_SOC_UART_NUM=3
CONFIG_SOC_UART_HP_NUM=3
CONFIG_SOC_UART_FIFO_LEN=128
CONFIG_SOC_UART_BITRATE_MAX=5000000
CONFIG_SOC_UART_SUPPORT_FSM_TX_WAIT_SEND=y
CONFIG_SOC_UART_SUPPORT_WAKEUP_INT=y
CONFIG_SOC_UART_SUPPORT_APB_CLK=y
CONFIG_SOC_UART_SUPPORT_RTC_CLK=y
CONFIG_SOC_UART_SUPPORT_XTAL_CLK=y
CONFIG_SOC_USB_OTG_PERIPH_NUM=1
CONFIG_SOC_SHA_DMA_MAX_BUFFER_SIZE=3968
CONFIG_SOC_SHA_SUPPORT_DMA=y
CONFIG_SOC_SHA_SUPPORT_RESUME=y
CONFIG_SOC_SHA_GDMA=y
CONFIG_SOC_SHA_SUPPORT_SHA1=y
CONFIG_SOC_SHA_SUPPORT_SHA224=y
CONFIG_SOC_SHA_SUPPORT_SHA256=y
CONFIG_SOC_SHA_SUPPORT_SHA384=y
CONFIG_SOC_SHA_SUPPORT_SHA512=y
CONFIG_SOC_SHA_SUPPORT_SHA512_224=y
CONFIG_SOC_SHA_SUPPORT_SHA512_256=y
CONFIG_SOC_SHA_SUPPORT_SHA512_T=y
CONFIG_SOC_MPI_MEM_BLOCKS_NUM=4
CONFIG_SOC_MPI_OPERATIONS_NUM=3
CONFIG_SOC_RSA_MAX_BIT_LEN=4096
CONFIG_SOC_AES_SUPPORT_DMA=y
CONFIG_SOC_AES_GDMA=y
CONFIG_SOC_AES_SUPPORT_AES_128=y
CONFIG_SOC_AES_SUPPORT_AES_256=y
CONFIG_SOC_PM_SUPPORT_EXT0_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_EXT1_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_EXT_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_WIFI_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_BT_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_CPU_PD=y
CONFIG_SOC_PM_SUPPORT_TAGMEM_PD=y
CONFIG_SOC_PM_SUPPORT_RTC_PERIPH_PD=y
CONFIG_SOC_PM_SUPPORT_RC_FAST_PD=y
CONFIG_SOC_PM_SUPPORT_VDDSDIO_PD=y
CONFIG_SOC_PM_SUPPORT_MAC_BB_PD=y
CONFIG_SOC_PM_SUPPORT_MODEM_PD=y
CONFIG_SOC_CONFIGURABLE_VDDSDIO_SUPPORTED=y
CONFIG_SOC_PM_SUPPORT_DEEPSLEEP_CHECK_STUB_ONLY=y
CONFIG_SOC_PM_CPU_RETENTION_BY_RTCCNTL=y
CONFIG_SOC_PM_MODEM_RETENTION_BY_BACKUPDMA=y
CONFIG_SOC_CLK_RC_FAST_D256_SUPPORTED=y
CONFIG_SOC_RTC_SLOW_CLK_SUPPORT_RC_FAST_D256=y
CONFIG_SOC_CLK_RC_FAST_SUPPORT_CALIBRATION=y
CONFIG_SOC_CLK_XTAL32K_SUPPORTED=y
CONFIG_SOC_EFUSE_DIS_DOWNLOAD_ICACHE=y
CONFIG_SOC_EFUSE_DIS_DOWNLOAD_DCACHE=y
CONFIG_SOC_EFUSE_HARD_DIS_JTAG=y
CONFIG_SOC_EFUSE_DIS_USB_JTAG=y
CONFIG_SOC_EFUSE_SOFT_DIS_JTAG=y
CONFIG_SOC_EFUSE_DIS_DIRECT_BOOT=y
CONFIG_SOC_EFUSE_DIS_ICACHE=y
CONFIG_SOC_EFUSE_BLOCK9_KEY_PURPOSE_QUIRK=y
CONFIG_SOC_SECURE_BOOT_V2_RSA=y
CONFIG_SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS=3
CONFIG_SOC_EFUSE_REVOKE_BOOT_KEY_DIGESTS=y
CONFIG_SOC_SUPPORT_SECURE_BOOT_REVOKE_KEY=y
CONFIG_SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX=64
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES=y
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_OPTIONS=y
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_128=y
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_256=y
CONFIG_SOC_MEMPROT_CPU_PREFETCH_PAD_SIZE=16
CONFIG_SOC_MEMPROT_MEM_ALIGN_SIZE=256
CONFIG_SOC_PHY_DIG_REGS_MEM_SIZE=21
CONFIG_SOC_MAC_BB_PD_MEM_SIZE=192
CONFIG_SOC_WIFI_LIGHT_SLEEP_CLK_WIDTH=12
CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_WAIT_IDLE=y
CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_SUSPEND=y
CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_RESUME=y
CONFIG_SOC_SPI_MEM_SUPPORT_SW_SUSPEND=y
CONFIG_SOC_SPI_MEM_SUPPORT_OPI_MODE=y
CONFIG_SOC_SPI_MEM_SUPPORT_TIMING_TUNING=y
CONFIG_SOC_SPI_MEM_SUPPORT_CONFIG_GPIO_BY_EFUSE=y
CONFIG_SOC_SPI_MEM_SUPPORT_WRAP=y
CONFIG_SOC_MEMSPI_TIMING_TUNING_BY_MSPI_DELAY=y
CONFIG_SOC_MEMSPI_CORE_CLK_SHARED_WITH_PSRAM=y
CONFIG_SOC_COEX_HW_PTI=y
CONFIG_SOC_EXTERNAL_COEX_LEADER_TX_LINE=y
CONFIG_SOC_SDMMC_USE_GPIO_MATRIX=y
CONFIG_SOC_SDMMC_NUM_SLOTS=2
CONFIG_SOC_SDMMC_SUPPORT_XTAL_CLOCK=y
CONFIG_SOC_SDMMC_DELAY_PHASE_NUM=4
CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_FAST_RC=y
CONFIG_SOC_WIFI_HW_TSF=y
CONFIG_SOC_WIFI_FTM_SUPPORT=y
CONFIG_SOC_WIFI_GCMP_SUPPORT=y
CONFIG_SOC_WIFI_WAPI_SUPPORT=y
CONFIG_SOC_WIFI_CSI_SUPPORT=y
CONFIG_SOC_WIFI_MESH_SUPPORT=y
CONFIG_SOC_WIFI_SUPPORT_VARIABLE_BEACON_WINDOW=y
CONFIG_SOC_WIFI_PHY_NEEDS_USB_WORKAROUND=y
CONFIG_SOC_BLE_SUPPORTED=y
CONFIG_SOC_BLE_MESH_SUPPORTED=y
CONFIG_SOC_BLE_50_SUPPORTED=y
CONFIG_SOC_BLE_DEVICE_PRIVACY_SUPPORTED=y
CONFIG_SOC_BLUFI_SUPPORTED=y
CONFIG_SOC_ULP_HAS_ADC=y
CONFIG_SOC_PHY_COMBO_MODULE=y
CONFIG_IDF_CMAKE=y
CONFIG_IDF_TOOLCHAIN="gcc"
CONFIG_IDF_TARGET_ARCH_XTENSA=y
CONFIG_IDF_TARGET_ARCH="xtensa"
CONFIG_IDF_TARGET="esp32s3"
CONFIG_IDF_INIT_VERSION="5.3.0"
CONFIG_IDF_TARGET_ESP32S3=y
CONFIG_IDF_FIRMWARE_CHIP_ID=0x0009
#
# Build type
#
CONFIG_APP_BUILD_TYPE_APP_2NDBOOT=y
# CONFIG_APP_BUILD_TYPE_RAM is not set
CONFIG_APP_BUILD_GENERATE_BINARIES=y
CONFIG_APP_BUILD_BOOTLOADER=y
CONFIG_APP_BUILD_USE_FLASH_SECTIONS=y
# CONFIG_APP_REPRODUCIBLE_BUILD is not set
# CONFIG_APP_NO_BLOBS is not set
# end of Build type
#
# Bootloader config
#
#
# Bootloader manager
#
CONFIG_BOOTLOADER_COMPILE_TIME_DATE=y
CONFIG_BOOTLOADER_PROJECT_VER=1
# end of Bootloader manager
CONFIG_BOOTLOADER_OFFSET_IN_FLASH=0x0
CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y
# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG is not set
# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_PERF is not set
# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_NONE is not set
# CONFIG_BOOTLOADER_LOG_LEVEL_NONE is not set
# CONFIG_BOOTLOADER_LOG_LEVEL_ERROR is not set
# CONFIG_BOOTLOADER_LOG_LEVEL_WARN is not set
CONFIG_BOOTLOADER_LOG_LEVEL_INFO=y
# CONFIG_BOOTLOADER_LOG_LEVEL_DEBUG is not set
# CONFIG_BOOTLOADER_LOG_LEVEL_VERBOSE is not set
CONFIG_BOOTLOADER_LOG_LEVEL=3
#
# Serial Flash Configurations
#
# CONFIG_BOOTLOADER_FLASH_DC_AWARE is not set
CONFIG_BOOTLOADER_FLASH_XMC_SUPPORT=y
# end of Serial Flash Configurations
CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_9V=y
# CONFIG_BOOTLOADER_FACTORY_RESET is not set
# CONFIG_BOOTLOADER_APP_TEST is not set
CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE=y
CONFIG_BOOTLOADER_WDT_ENABLE=y
# CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE is not set
CONFIG_BOOTLOADER_WDT_TIME_MS=9000
# CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE is not set
# CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP is not set
# CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON is not set
# CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS is not set
CONFIG_BOOTLOADER_RESERVE_RTC_SIZE=0
# CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC is not set
# end of Bootloader config
#
# Security features
#
CONFIG_SECURE_BOOT_V2_RSA_SUPPORTED=y
CONFIG_SECURE_BOOT_V2_PREFERRED=y
# CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT is not set
# CONFIG_SECURE_BOOT is not set
# CONFIG_SECURE_FLASH_ENC_ENABLED is not set
CONFIG_SECURE_ROM_DL_MODE_ENABLED=y
# end of Security features
#
# Application manager
#
CONFIG_APP_COMPILE_TIME_DATE=y
# CONFIG_APP_EXCLUDE_PROJECT_VER_VAR is not set
# CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR is not set
# CONFIG_APP_PROJECT_VER_FROM_CONFIG is not set
CONFIG_APP_RETRIEVE_LEN_ELF_SHA=9
# end of Application manager
CONFIG_ESP_ROM_HAS_CRC_LE=y
CONFIG_ESP_ROM_HAS_CRC_BE=y
CONFIG_ESP_ROM_HAS_MZ_CRC32=y
CONFIG_ESP_ROM_HAS_JPEG_DECODE=y
CONFIG_ESP_ROM_UART_CLK_IS_XTAL=y
CONFIG_ESP_ROM_HAS_RETARGETABLE_LOCKING=y
CONFIG_ESP_ROM_USB_OTG_NUM=3
CONFIG_ESP_ROM_USB_SERIAL_DEVICE_NUM=4
CONFIG_ESP_ROM_HAS_ERASE_0_REGION_BUG=y
CONFIG_ESP_ROM_HAS_ENCRYPTED_WRITES_USING_LEGACY_DRV=y
CONFIG_ESP_ROM_GET_CLK_FREQ=y
CONFIG_ESP_ROM_HAS_HAL_WDT=y
CONFIG_ESP_ROM_NEEDS_SWSETUP_WORKAROUND=y
CONFIG_ESP_ROM_HAS_LAYOUT_TABLE=y
CONFIG_ESP_ROM_HAS_SPI_FLASH=y
CONFIG_ESP_ROM_HAS_ETS_PRINTF_BUG=y
CONFIG_ESP_ROM_HAS_NEWLIB=y
CONFIG_ESP_ROM_HAS_NEWLIB_NANO_FORMAT=y
CONFIG_ESP_ROM_HAS_NEWLIB_32BIT_TIME=y
CONFIG_ESP_ROM_NEEDS_SET_CACHE_MMU_SIZE=y
CONFIG_ESP_ROM_RAM_APP_NEEDS_MMU_INIT=y
CONFIG_ESP_ROM_HAS_FLASH_COUNT_PAGES_BUG=y
CONFIG_ESP_ROM_HAS_CACHE_SUSPEND_WAITI_BUG=y
CONFIG_ESP_ROM_HAS_CACHE_WRITEBACK_BUG=y
CONFIG_ESP_ROM_HAS_SW_FLOAT=y
CONFIG_ESP_ROM_HAS_VERSION=y
CONFIG_ESP_ROM_SUPPORT_DEEP_SLEEP_WAKEUP_STUB=y
#
# Boot ROM Behavior
#
CONFIG_BOOT_ROM_LOG_ALWAYS_ON=y
# CONFIG_BOOT_ROM_LOG_ALWAYS_OFF is not set
# CONFIG_BOOT_ROM_LOG_ON_GPIO_HIGH is not set
# CONFIG_BOOT_ROM_LOG_ON_GPIO_LOW is not set
# end of Boot ROM Behavior
#
# Serial flasher config
#
# CONFIG_ESPTOOLPY_NO_STUB is not set
# CONFIG_ESPTOOLPY_OCT_FLASH is not set
CONFIG_ESPTOOLPY_FLASH_MODE_AUTO_DETECT=y
# CONFIG_ESPTOOLPY_FLASHMODE_QIO is not set
# CONFIG_ESPTOOLPY_FLASHMODE_QOUT is not set
CONFIG_ESPTOOLPY_FLASHMODE_DIO=y
# CONFIG_ESPTOOLPY_FLASHMODE_DOUT is not set
CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_STR=y
CONFIG_ESPTOOLPY_FLASHMODE="dio"
# CONFIG_ESPTOOLPY_FLASHFREQ_120M is not set
CONFIG_ESPTOOLPY_FLASHFREQ_80M=y
# CONFIG_ESPTOOLPY_FLASHFREQ_40M is not set
# CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set
CONFIG_ESPTOOLPY_FLASHFREQ_80M_DEFAULT=y
CONFIG_ESPTOOLPY_FLASHFREQ="80m"
# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE_2MB=y
# CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE="2MB"
# CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set
CONFIG_ESPTOOLPY_BEFORE_RESET=y
# CONFIG_ESPTOOLPY_BEFORE_NORESET is not set
CONFIG_ESPTOOLPY_BEFORE="default_reset"
CONFIG_ESPTOOLPY_AFTER_RESET=y
# CONFIG_ESPTOOLPY_AFTER_NORESET is not set
CONFIG_ESPTOOLPY_AFTER="hard_reset"
CONFIG_ESPTOOLPY_MONITOR_BAUD=115200
# end of Serial flasher config
#
# Partition Table
#
CONFIG_PARTITION_TABLE_SINGLE_APP=y
# CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set
# CONFIG_PARTITION_TABLE_TWO_OTA is not set
# CONFIG_PARTITION_TABLE_CUSTOM is not set
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions_singleapp.csv"
CONFIG_PARTITION_TABLE_OFFSET=0x8000
CONFIG_PARTITION_TABLE_MD5=y
# end of Partition Table
#
# Compiler options
#
CONFIG_COMPILER_OPTIMIZATION_DEBUG=y
# CONFIG_COMPILER_OPTIMIZATION_SIZE is not set
# CONFIG_COMPILER_OPTIMIZATION_PERF is not set
# CONFIG_COMPILER_OPTIMIZATION_NONE is not set
CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE=y
# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT is not set
# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE is not set
CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB=y
CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL=2
# CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT is not set
CONFIG_COMPILER_HIDE_PATHS_MACROS=y
# CONFIG_COMPILER_CXX_EXCEPTIONS is not set
# CONFIG_COMPILER_CXX_RTTI is not set
CONFIG_COMPILER_STACK_CHECK_MODE_NONE=y
# CONFIG_COMPILER_STACK_CHECK_MODE_NORM is not set
# CONFIG_COMPILER_STACK_CHECK_MODE_STRONG is not set
# CONFIG_COMPILER_STACK_CHECK_MODE_ALL is not set
# CONFIG_COMPILER_WARN_WRITE_STRINGS is not set
# CONFIG_COMPILER_DISABLE_GCC12_WARNINGS is not set
# CONFIG_COMPILER_DISABLE_GCC13_WARNINGS is not set
# CONFIG_COMPILER_DUMP_RTL_FILES is not set
CONFIG_COMPILER_RT_LIB_GCCLIB=y
CONFIG_COMPILER_RT_LIB_NAME="gcc"
# CONFIG_COMPILER_ORPHAN_SECTIONS_WARNING is not set
CONFIG_COMPILER_ORPHAN_SECTIONS_PLACE=y
# end of Compiler options
#
# Component config
#
#
# Application Level Tracing
#
# CONFIG_APPTRACE_DEST_JTAG is not set
CONFIG_APPTRACE_DEST_NONE=y
# CONFIG_APPTRACE_DEST_UART1 is not set
# CONFIG_APPTRACE_DEST_UART2 is not set
# CONFIG_APPTRACE_DEST_USB_CDC is not set
CONFIG_APPTRACE_DEST_UART_NONE=y
CONFIG_APPTRACE_UART_TASK_PRIO=1
CONFIG_APPTRACE_LOCK_ENABLE=y
# end of Application Level Tracing
#
# Bluetooth
#
# CONFIG_BT_ENABLED is not set
CONFIG_BT_ALARM_MAX_NUM=50
# end of Bluetooth
#
# Console Library
#
# CONFIG_CONSOLE_SORTED_HELP is not set
# end of Console Library
#
# Driver Configurations
#
#
# TWAI Configuration
#
# CONFIG_TWAI_ISR_IN_IRAM is not set
CONFIG_TWAI_ERRATA_FIX_LISTEN_ONLY_DOM=y
# end of TWAI Configuration
#
# Legacy ADC Driver Configuration
#
# CONFIG_ADC_SUPPRESS_DEPRECATE_WARN is not set
#
# Legacy ADC Calibration Configuration
#
# CONFIG_ADC_CALI_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy ADC Calibration Configuration
# end of Legacy ADC Driver Configuration
#
# Legacy MCPWM Driver Configurations
#
# CONFIG_MCPWM_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy MCPWM Driver Configurations
#
# Legacy Timer Group Driver Configurations
#
# CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy Timer Group Driver Configurations
#
# Legacy RMT Driver Configurations
#
# CONFIG_RMT_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy RMT Driver Configurations
#
# Legacy I2S Driver Configurations
#
# CONFIG_I2S_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy I2S Driver Configurations
#
# Legacy PCNT Driver Configurations
#
# CONFIG_PCNT_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy PCNT Driver Configurations
#
# Legacy SDM Driver Configurations
#
# CONFIG_SDM_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy SDM Driver Configurations
#
# Legacy Temperature Sensor Driver Configurations
#
# CONFIG_TEMP_SENSOR_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy Temperature Sensor Driver Configurations
# end of Driver Configurations
#
# eFuse Bit Manager
#
# CONFIG_EFUSE_CUSTOM_TABLE is not set
# CONFIG_EFUSE_VIRTUAL is not set
CONFIG_EFUSE_MAX_BLK_LEN=256
# end of eFuse Bit Manager
#
# ESP-TLS
#
CONFIG_ESP_TLS_USING_MBEDTLS=y
CONFIG_ESP_TLS_USE_DS_PERIPHERAL=y
# CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is not set
# CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is not set
# CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK is not set
# CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL is not set
# CONFIG_ESP_TLS_PSK_VERIFICATION is not set
# CONFIG_ESP_TLS_INSECURE is not set
# end of ESP-TLS
#
# ADC and ADC Calibration
#
# CONFIG_ADC_ONESHOT_CTRL_FUNC_IN_IRAM is not set
# CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is not set
# CONFIG_ADC_CONTINUOUS_FORCE_USE_ADC2_ON_C3_S3 is not set
# CONFIG_ADC_ENABLE_DEBUG_LOG is not set
# end of ADC and ADC Calibration
#
# Wireless Coexistence
#
CONFIG_ESP_COEX_ENABLED=y
# CONFIG_ESP_COEX_EXTERNAL_COEXIST_ENABLE is not set
# end of Wireless Coexistence
#
# Common ESP-related
#
CONFIG_ESP_ERR_TO_NAME_LOOKUP=y
# end of Common ESP-related
#
# ESP-Driver:GPIO Configurations
#
# CONFIG_GPIO_CTRL_FUNC_IN_IRAM is not set
# end of ESP-Driver:GPIO Configurations
#
# ESP-Driver:GPTimer Configurations
#
CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y
# CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is not set
# CONFIG_GPTIMER_ISR_IRAM_SAFE is not set
# CONFIG_GPTIMER_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:GPTimer Configurations
#
# ESP-Driver:I2C Configurations
#
# CONFIG_I2C_ISR_IRAM_SAFE is not set
# CONFIG_I2C_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:I2C Configurations
#
# ESP-Driver:I2S Configurations
#
# CONFIG_I2S_ISR_IRAM_SAFE is not set
# CONFIG_I2S_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:I2S Configurations
#
# ESP-Driver:LEDC Configurations
#
# CONFIG_LEDC_CTRL_FUNC_IN_IRAM is not set
# end of ESP-Driver:LEDC Configurations
#
# ESP-Driver:MCPWM Configurations
#
# CONFIG_MCPWM_ISR_IRAM_SAFE is not set
# CONFIG_MCPWM_CTRL_FUNC_IN_IRAM is not set
# CONFIG_MCPWM_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:MCPWM Configurations
#
# ESP-Driver:PCNT Configurations
#
# CONFIG_PCNT_CTRL_FUNC_IN_IRAM is not set
# CONFIG_PCNT_ISR_IRAM_SAFE is not set
# CONFIG_PCNT_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:PCNT Configurations
#
# ESP-Driver:RMT Configurations
#
# CONFIG_RMT_ISR_IRAM_SAFE is not set
# CONFIG_RMT_RECV_FUNC_IN_IRAM is not set
# CONFIG_RMT_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:RMT Configurations
#
# ESP-Driver:Sigma Delta Modulator Configurations
#
# CONFIG_SDM_CTRL_FUNC_IN_IRAM is not set
# CONFIG_SDM_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:Sigma Delta Modulator Configurations
#
# ESP-Driver:SPI Configurations
#
# CONFIG_SPI_MASTER_IN_IRAM is not set
CONFIG_SPI_MASTER_ISR_IN_IRAM=y
# CONFIG_SPI_SLAVE_IN_IRAM is not set
CONFIG_SPI_SLAVE_ISR_IN_IRAM=y
# end of ESP-Driver:SPI Configurations
#
# ESP-Driver:Temperature Sensor Configurations
#
# CONFIG_TEMP_SENSOR_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:Temperature Sensor Configurations
#
# ESP-Driver:UART Configurations
#
# CONFIG_UART_ISR_IN_IRAM is not set
# end of ESP-Driver:UART Configurations
#
# ESP-Driver:USB Serial/JTAG Configuration
#
CONFIG_USJ_ENABLE_USB_SERIAL_JTAG=y
# end of ESP-Driver:USB Serial/JTAG Configuration
#
# Ethernet
#
CONFIG_ETH_ENABLED=y
CONFIG_ETH_USE_SPI_ETHERNET=y
# CONFIG_ETH_SPI_ETHERNET_DM9051 is not set
# CONFIG_ETH_SPI_ETHERNET_W5500 is not set
# CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL is not set
# CONFIG_ETH_USE_OPENETH is not set
# CONFIG_ETH_TRANSMIT_MUTEX is not set
# end of Ethernet
#
# Event Loop Library
#
# CONFIG_ESP_EVENT_LOOP_PROFILING is not set
CONFIG_ESP_EVENT_POST_FROM_ISR=y
CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR=y
# end of Event Loop Library
#
# GDB Stub
#
CONFIG_ESP_GDBSTUB_ENABLED=y
# CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME is not set
CONFIG_ESP_GDBSTUB_SUPPORT_TASKS=y
CONFIG_ESP_GDBSTUB_MAX_TASKS=32
# end of GDB Stub
#
# ESP HTTP client
#
CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y
# CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH is not set
# CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH is not set
# CONFIG_ESP_HTTP_CLIENT_ENABLE_CUSTOM_TRANSPORT is not set
# end of ESP HTTP client
#
# HTTP Server
#
CONFIG_HTTPD_MAX_REQ_HDR_LEN=512
CONFIG_HTTPD_MAX_URI_LEN=512
CONFIG_HTTPD_ERR_RESP_NO_DELAY=y
CONFIG_HTTPD_PURGE_BUF_LEN=32
# CONFIG_HTTPD_LOG_PURGE_DATA is not set
# CONFIG_HTTPD_WS_SUPPORT is not set
# CONFIG_HTTPD_QUEUE_WORK_BLOCKING is not set
# end of HTTP Server
#
# ESP HTTPS OTA
#
# CONFIG_ESP_HTTPS_OTA_DECRYPT_CB is not set
# CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP is not set
# end of ESP HTTPS OTA
#
# ESP HTTPS server
#
# CONFIG_ESP_HTTPS_SERVER_ENABLE is not set
# end of ESP HTTPS server
#
# Hardware Settings
#
#
# Chip revision
#
CONFIG_ESP32S3_REV_MIN_0=y
# CONFIG_ESP32S3_REV_MIN_1 is not set
# CONFIG_ESP32S3_REV_MIN_2 is not set
CONFIG_ESP32S3_REV_MIN_FULL=0
CONFIG_ESP_REV_MIN_FULL=0
#
# Maximum Supported ESP32-S3 Revision (Rev v0.99)
#
CONFIG_ESP32S3_REV_MAX_FULL=99
CONFIG_ESP_REV_MAX_FULL=99
# end of Chip revision
#
# MAC Config
#
CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_STA=y
CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_AP=y
CONFIG_ESP_MAC_ADDR_UNIVERSE_BT=y
CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH=y
CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES_FOUR=y
CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES=4
# CONFIG_ESP32S3_UNIVERSAL_MAC_ADDRESSES_TWO is not set
CONFIG_ESP32S3_UNIVERSAL_MAC_ADDRESSES_FOUR=y
CONFIG_ESP32S3_UNIVERSAL_MAC_ADDRESSES=4
# CONFIG_ESP_MAC_USE_CUSTOM_MAC_AS_BASE_MAC is not set
# end of MAC Config
#
# Sleep Config
#
CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND=y
CONFIG_ESP_SLEEP_PSRAM_LEAKAGE_WORKAROUND=y
CONFIG_ESP_SLEEP_MSPI_NEED_ALL_IO_PU=y
CONFIG_ESP_SLEEP_RTC_BUS_ISO_WORKAROUND=y
CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND=y
CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY=2000
# CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION is not set
# CONFIG_ESP_SLEEP_DEBUG is not set
CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS=y
# end of Sleep Config
#
# RTC Clock Config
#
CONFIG_RTC_CLK_SRC_INT_RC=y
# CONFIG_RTC_CLK_SRC_EXT_CRYS is not set
# CONFIG_RTC_CLK_SRC_EXT_OSC is not set
# CONFIG_RTC_CLK_SRC_INT_8MD256 is not set
CONFIG_RTC_CLK_CAL_CYCLES=1024
# end of RTC Clock Config
#
# Peripheral Control
#
CONFIG_PERIPH_CTRL_FUNC_IN_IRAM=y
# end of Peripheral Control
#
# GDMA Configurations
#
CONFIG_GDMA_CTRL_FUNC_IN_IRAM=y
# CONFIG_GDMA_ISR_IRAM_SAFE is not set
# CONFIG_GDMA_ENABLE_DEBUG_LOG is not set
# end of GDMA Configurations
#
# Main XTAL Config
#
CONFIG_XTAL_FREQ_40=y
CONFIG_XTAL_FREQ=40
# end of Main XTAL Config
CONFIG_ESP_SPI_BUS_LOCK_ISR_FUNCS_IN_IRAM=y
# end of Hardware Settings
#
# LCD and Touch Panel
#
#
# LCD Touch Drivers are maintained in the IDF Component Registry
#
#
# LCD Peripheral Configuration
#
CONFIG_LCD_PANEL_IO_FORMAT_BUF_SIZE=32
# CONFIG_LCD_ENABLE_DEBUG_LOG is not set
# CONFIG_LCD_RGB_ISR_IRAM_SAFE is not set
# CONFIG_LCD_RGB_RESTART_IN_VSYNC is not set
# end of LCD Peripheral Configuration
# end of LCD and Touch Panel
#
# ESP NETIF Adapter
#
CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL=120
CONFIG_ESP_NETIF_TCPIP_LWIP=y
# CONFIG_ESP_NETIF_LOOPBACK is not set
CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y
# CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS is not set
# CONFIG_ESP_NETIF_L2_TAP is not set
# CONFIG_ESP_NETIF_BRIDGE_EN is not set
# end of ESP NETIF Adapter
#
# Partition API Configuration
#
# end of Partition API Configuration
#
# PHY
#
CONFIG_ESP_PHY_ENABLED=y
CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE=y
# CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION is not set
CONFIG_ESP_PHY_MAX_WIFI_TX_POWER=20
CONFIG_ESP_PHY_MAX_TX_POWER=20
# CONFIG_ESP_PHY_REDUCE_TX_POWER is not set
CONFIG_ESP_PHY_ENABLE_USB=y
# CONFIG_ESP_PHY_ENABLE_CERT_TEST is not set
CONFIG_ESP_PHY_RF_CAL_PARTIAL=y
# CONFIG_ESP_PHY_RF_CAL_NONE is not set
# CONFIG_ESP_PHY_RF_CAL_FULL is not set
CONFIG_ESP_PHY_CALIBRATION_MODE=0
# CONFIG_ESP_PHY_PLL_TRACK_DEBUG is not set
# end of PHY
#
# Power Management
#
# CONFIG_PM_ENABLE is not set
CONFIG_PM_POWER_DOWN_CPU_IN_LIGHT_SLEEP=y
CONFIG_PM_RESTORE_CACHE_TAGMEM_AFTER_LIGHT_SLEEP=y
# end of Power Management
#
# ESP PSRAM
#
CONFIG_SPIRAM=y
#
# SPI RAM config
#
CONFIG_SPIRAM_MODE_QUAD=y
# CONFIG_SPIRAM_MODE_OCT is not set
CONFIG_SPIRAM_TYPE_AUTO=y
# CONFIG_SPIRAM_TYPE_ESPPSRAM16 is not set
# CONFIG_SPIRAM_TYPE_ESPPSRAM32 is not set
# CONFIG_SPIRAM_TYPE_ESPPSRAM64 is not set
CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY=y
CONFIG_SPIRAM_CLK_IO=30
CONFIG_SPIRAM_CS_IO=26
# CONFIG_SPIRAM_XIP_FROM_PSRAM is not set
# CONFIG_SPIRAM_FETCH_INSTRUCTIONS is not set
# CONFIG_SPIRAM_RODATA is not set
# CONFIG_SPIRAM_SPEED_120M is not set
# CONFIG_SPIRAM_SPEED_80M is not set
CONFIG_SPIRAM_SPEED_40M=y
CONFIG_SPIRAM_SPEED=40
CONFIG_SPIRAM_BOOT_INIT=y
# CONFIG_SPIRAM_IGNORE_NOTFOUND is not set
# CONFIG_SPIRAM_USE_MEMMAP is not set
# CONFIG_SPIRAM_USE_CAPS_ALLOC is not set
CONFIG_SPIRAM_USE_MALLOC=y
CONFIG_SPIRAM_MEMTEST=y
CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=16384
# CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP is not set
CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL=32768
# CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY is not set
# end of SPI RAM config
# end of ESP PSRAM
#
# ESP Ringbuf
#
# CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH is not set
# end of ESP Ringbuf
#
# ESP System Settings
#
# CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_80 is not set
# CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160 is not set
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240=y
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=240
#
# Cache config
#
CONFIG_ESP32S3_INSTRUCTION_CACHE_16KB=y
# CONFIG_ESP32S3_INSTRUCTION_CACHE_32KB is not set
CONFIG_ESP32S3_INSTRUCTION_CACHE_SIZE=0x4000
# CONFIG_ESP32S3_INSTRUCTION_CACHE_4WAYS is not set
CONFIG_ESP32S3_INSTRUCTION_CACHE_8WAYS=y
CONFIG_ESP32S3_ICACHE_ASSOCIATED_WAYS=8
# CONFIG_ESP32S3_INSTRUCTION_CACHE_LINE_16B is not set
CONFIG_ESP32S3_INSTRUCTION_CACHE_LINE_32B=y
CONFIG_ESP32S3_INSTRUCTION_CACHE_LINE_SIZE=32
# CONFIG_ESP32S3_DATA_CACHE_16KB is not set
CONFIG_ESP32S3_DATA_CACHE_32KB=y
# CONFIG_ESP32S3_DATA_CACHE_64KB is not set
CONFIG_ESP32S3_DATA_CACHE_SIZE=0x8000
# CONFIG_ESP32S3_DATA_CACHE_4WAYS is not set
CONFIG_ESP32S3_DATA_CACHE_8WAYS=y
CONFIG_ESP32S3_DCACHE_ASSOCIATED_WAYS=8
# CONFIG_ESP32S3_DATA_CACHE_LINE_16B is not set
CONFIG_ESP32S3_DATA_CACHE_LINE_32B=y
# CONFIG_ESP32S3_DATA_CACHE_LINE_64B is not set
CONFIG_ESP32S3_DATA_CACHE_LINE_SIZE=32
# end of Cache config
#
# Memory
#
# CONFIG_ESP32S3_RTCDATA_IN_FAST_MEM is not set
# CONFIG_ESP32S3_USE_FIXED_STATIC_RAM_SIZE is not set
# end of Memory
#
# Trace memory
#
# CONFIG_ESP32S3_TRAX is not set
CONFIG_ESP32S3_TRACEMEM_RESERVE_DRAM=0x0
# end of Trace memory
# CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT is not set
CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT=y
# CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT is not set
# CONFIG_ESP_SYSTEM_PANIC_GDBSTUB is not set
CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS=0
CONFIG_ESP_SYSTEM_RTC_FAST_MEM_AS_HEAP_DEPCHECK=y
CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP=y
#
# Memory protection
#
CONFIG_ESP_SYSTEM_MEMPROT_FEATURE=y
CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_LOCK=y
# end of Memory protection
CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE=32
CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=2304
CONFIG_ESP_MAIN_TASK_STACK_SIZE=3584
CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0=y
# CONFIG_ESP_MAIN_TASK_AFFINITY_CPU1 is not set
# CONFIG_ESP_MAIN_TASK_AFFINITY_NO_AFFINITY is not set
CONFIG_ESP_MAIN_TASK_AFFINITY=0x0
CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE=2048
CONFIG_ESP_CONSOLE_UART_DEFAULT=y
# CONFIG_ESP_CONSOLE_USB_CDC is not set
# CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG is not set
# CONFIG_ESP_CONSOLE_UART_CUSTOM is not set
# CONFIG_ESP_CONSOLE_NONE is not set
# CONFIG_ESP_CONSOLE_SECONDARY_NONE is not set
CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED=y
CONFIG_ESP_CONSOLE_UART=y
CONFIG_ESP_CONSOLE_UART_NUM=0
CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=0
CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200
CONFIG_ESP_INT_WDT=y
CONFIG_ESP_INT_WDT_TIMEOUT_MS=300
CONFIG_ESP_INT_WDT_CHECK_CPU1=y
CONFIG_ESP_TASK_WDT_EN=y
CONFIG_ESP_TASK_WDT_INIT=y
# CONFIG_ESP_TASK_WDT_PANIC is not set
CONFIG_ESP_TASK_WDT_TIMEOUT_S=5
CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0=y
CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1=y
# CONFIG_ESP_PANIC_HANDLER_IRAM is not set
# CONFIG_ESP_DEBUG_STUBS_ENABLE is not set
CONFIG_ESP_DEBUG_OCDAWARE=y
CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4=y
#
# Brownout Detector
#
CONFIG_ESP_BROWNOUT_DET=y
CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7=y
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6 is not set
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5 is not set
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_4 is not set
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_3 is not set
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_2 is not set
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_1 is not set
CONFIG_ESP_BROWNOUT_DET_LVL=7
# end of Brownout Detector
CONFIG_ESP_SYSTEM_BROWNOUT_INTR=y
CONFIG_ESP_SYSTEM_BBPLL_RECALIB=y
# end of ESP System Settings
#
# IPC (Inter-Processor Call)
#
CONFIG_ESP_IPC_TASK_STACK_SIZE=1280
CONFIG_ESP_IPC_USES_CALLERS_PRIORITY=y
CONFIG_ESP_IPC_ISR_ENABLE=y
# end of IPC (Inter-Processor Call)
#
# ESP Timer (High Resolution Timer)
#
# CONFIG_ESP_TIMER_PROFILING is not set
CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER=y
CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER=y
CONFIG_ESP_TIMER_TASK_STACK_SIZE=3584
CONFIG_ESP_TIMER_INTERRUPT_LEVEL=1
# CONFIG_ESP_TIMER_SHOW_EXPERIMENTAL is not set
CONFIG_ESP_TIMER_TASK_AFFINITY=0x0
CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0=y
CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0=y
# CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD is not set
CONFIG_ESP_TIMER_IMPL_SYSTIMER=y
# end of ESP Timer (High Resolution Timer)
#
# Wi-Fi
#
CONFIG_ESP_WIFI_ENABLED=y
CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=10
CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=32
CONFIG_ESP_WIFI_STATIC_TX_BUFFER=y
CONFIG_ESP_WIFI_TX_BUFFER_TYPE=0
CONFIG_ESP_WIFI_STATIC_TX_BUFFER_NUM=16
CONFIG_ESP_WIFI_CACHE_TX_BUFFER_NUM=32
CONFIG_ESP_WIFI_STATIC_RX_MGMT_BUFFER=y
# CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUFFER is not set
CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUF=0
CONFIG_ESP_WIFI_RX_MGMT_BUF_NUM_DEF=5
# CONFIG_ESP_WIFI_CSI_ENABLED is not set
CONFIG_ESP_WIFI_AMPDU_TX_ENABLED=y
CONFIG_ESP_WIFI_TX_BA_WIN=6
CONFIG_ESP_WIFI_AMPDU_RX_ENABLED=y
CONFIG_ESP_WIFI_RX_BA_WIN=6
# CONFIG_ESP_WIFI_AMSDU_TX_ENABLED is not set
CONFIG_ESP_WIFI_NVS_ENABLED=y
CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0=y
# CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_1 is not set
CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN=752
CONFIG_ESP_WIFI_MGMT_SBUF_NUM=32
CONFIG_ESP_WIFI_IRAM_OPT=y
# CONFIG_ESP_WIFI_EXTRA_IRAM_OPT is not set
CONFIG_ESP_WIFI_RX_IRAM_OPT=y
CONFIG_ESP_WIFI_ENABLE_WPA3_SAE=y
CONFIG_ESP_WIFI_ENABLE_SAE_PK=y
CONFIG_ESP_WIFI_SOFTAP_SAE_SUPPORT=y
CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA=y
# CONFIG_ESP_WIFI_SLP_IRAM_OPT is not set
CONFIG_ESP_WIFI_SLP_DEFAULT_MIN_ACTIVE_TIME=50
CONFIG_ESP_WIFI_SLP_DEFAULT_MAX_ACTIVE_TIME=10
CONFIG_ESP_WIFI_SLP_DEFAULT_WAIT_BROADCAST_DATA_TIME=15
# CONFIG_ESP_WIFI_FTM_ENABLE is not set
CONFIG_ESP_WIFI_STA_DISCONNECTED_PM_ENABLE=y
# CONFIG_ESP_WIFI_GCMP_SUPPORT is not set
CONFIG_ESP_WIFI_GMAC_SUPPORT=y
CONFIG_ESP_WIFI_SOFTAP_SUPPORT=y
# CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT is not set
CONFIG_ESP_WIFI_ESPNOW_MAX_ENCRYPT_NUM=7
CONFIG_ESP_WIFI_MBEDTLS_CRYPTO=y
CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT=y
# CONFIG_ESP_WIFI_WAPI_PSK is not set
# CONFIG_ESP_WIFI_SUITE_B_192 is not set
# CONFIG_ESP_WIFI_11KV_SUPPORT is not set
# CONFIG_ESP_WIFI_MBO_SUPPORT is not set
# CONFIG_ESP_WIFI_DPP_SUPPORT is not set
# CONFIG_ESP_WIFI_11R_SUPPORT is not set
# CONFIG_ESP_WIFI_WPS_SOFTAP_REGISTRAR is not set
#
# WPS Configuration Options
#
# CONFIG_ESP_WIFI_WPS_STRICT is not set
# CONFIG_ESP_WIFI_WPS_PASSPHRASE is not set
# end of WPS Configuration Options
# CONFIG_ESP_WIFI_DEBUG_PRINT is not set
# CONFIG_ESP_WIFI_TESTING_OPTIONS is not set
CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT=y
# CONFIG_ESP_WIFI_ENT_FREE_DYNAMIC_BUFFER is not set
# end of Wi-Fi
#
# Core dump
#
# CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH is not set
# CONFIG_ESP_COREDUMP_ENABLE_TO_UART is not set
CONFIG_ESP_COREDUMP_ENABLE_TO_NONE=y
# end of Core dump
#
# FAT Filesystem support
#
CONFIG_FATFS_VOLUME_COUNT=2
CONFIG_FATFS_LFN_NONE=y
# CONFIG_FATFS_LFN_HEAP is not set
# CONFIG_FATFS_LFN_STACK is not set
# CONFIG_FATFS_SECTOR_512 is not set
CONFIG_FATFS_SECTOR_4096=y
# CONFIG_FATFS_CODEPAGE_DYNAMIC is not set
CONFIG_FATFS_CODEPAGE_437=y
# CONFIG_FATFS_CODEPAGE_720 is not set
# CONFIG_FATFS_CODEPAGE_737 is not set
# CONFIG_FATFS_CODEPAGE_771 is not set
# CONFIG_FATFS_CODEPAGE_775 is not set
# CONFIG_FATFS_CODEPAGE_850 is not set
# CONFIG_FATFS_CODEPAGE_852 is not set
# CONFIG_FATFS_CODEPAGE_855 is not set
# CONFIG_FATFS_CODEPAGE_857 is not set
# CONFIG_FATFS_CODEPAGE_860 is not set
# CONFIG_FATFS_CODEPAGE_861 is not set
# CONFIG_FATFS_CODEPAGE_862 is not set
# CONFIG_FATFS_CODEPAGE_863 is not set
# CONFIG_FATFS_CODEPAGE_864 is not set
# CONFIG_FATFS_CODEPAGE_865 is not set
# CONFIG_FATFS_CODEPAGE_866 is not set
# CONFIG_FATFS_CODEPAGE_869 is not set
# CONFIG_FATFS_CODEPAGE_932 is not set
# CONFIG_FATFS_CODEPAGE_936 is not set
# CONFIG_FATFS_CODEPAGE_949 is not set
# CONFIG_FATFS_CODEPAGE_950 is not set
CONFIG_FATFS_CODEPAGE=437
CONFIG_FATFS_FS_LOCK=0
CONFIG_FATFS_TIMEOUT_MS=10000
CONFIG_FATFS_PER_FILE_CACHE=y
CONFIG_FATFS_ALLOC_PREFER_EXTRAM=y
# CONFIG_FATFS_USE_FASTSEEK is not set
CONFIG_FATFS_VFS_FSTAT_BLKSIZE=0
# CONFIG_FATFS_IMMEDIATE_FSYNC is not set
# CONFIG_FATFS_USE_LABEL is not set
CONFIG_FATFS_LINK_LOCK=y
# end of FAT Filesystem support
#
# FreeRTOS
#
#
# Kernel
#
# CONFIG_FREERTOS_SMP is not set
# CONFIG_FREERTOS_UNICORE is not set
CONFIG_FREERTOS_HZ=100
# CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE is not set
# CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL is not set
CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY=y
CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS=1
CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=1536
# CONFIG_FREERTOS_USE_IDLE_HOOK is not set
# CONFIG_FREERTOS_USE_TICK_HOOK is not set
CONFIG_FREERTOS_MAX_TASK_NAME_LEN=16
# CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY is not set
CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME="Tmr Svc"
# CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU0 is not set
# CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU1 is not set
CONFIG_FREERTOS_TIMER_TASK_NO_AFFINITY=y
CONFIG_FREERTOS_TIMER_SERVICE_TASK_CORE_AFFINITY=0x7FFFFFFF
CONFIG_FREERTOS_TIMER_TASK_PRIORITY=1
CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=2048
CONFIG_FREERTOS_TIMER_QUEUE_LENGTH=10
CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE=0
CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES=1
# CONFIG_FREERTOS_USE_TRACE_FACILITY is not set
# CONFIG_FREERTOS_USE_LIST_DATA_INTEGRITY_CHECK_BYTES is not set
# CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS is not set
# CONFIG_FREERTOS_USE_APPLICATION_TASK_TAG is not set
# end of Kernel
#
# Port
#
CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER=y
# CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK is not set
CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS=y
# CONFIG_FREERTOS_TASK_PRE_DELETION_HOOK is not set
# CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP is not set
CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER=y
CONFIG_FREERTOS_ISR_STACKSIZE=1536
CONFIG_FREERTOS_INTERRUPT_BACKTRACE=y
CONFIG_FREERTOS_TICK_SUPPORT_SYSTIMER=y
CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL1=y
# CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL3 is not set
CONFIG_FREERTOS_SYSTICK_USES_SYSTIMER=y
# CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH is not set
# CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE is not set
# end of Port
CONFIG_FREERTOS_PORT=y
CONFIG_FREERTOS_NO_AFFINITY=0x7FFFFFFF
CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION=y
CONFIG_FREERTOS_DEBUG_OCDAWARE=y
CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT=y
CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH=y
CONFIG_FREERTOS_NUMBER_OF_CORES=2
# end of FreeRTOS
#
# Hardware Abstraction Layer (HAL) and Low Level (LL)
#
CONFIG_HAL_ASSERTION_EQUALS_SYSTEM=y
# CONFIG_HAL_ASSERTION_DISABLE is not set
# CONFIG_HAL_ASSERTION_SILENT is not set
# CONFIG_HAL_ASSERTION_ENABLE is not set
CONFIG_HAL_DEFAULT_ASSERTION_LEVEL=2
CONFIG_HAL_WDT_USE_ROM_IMPL=y
CONFIG_HAL_SPI_MASTER_FUNC_IN_IRAM=y
CONFIG_HAL_SPI_SLAVE_FUNC_IN_IRAM=y
# end of Hardware Abstraction Layer (HAL) and Low Level (LL)
#
# Heap memory debugging
#
CONFIG_HEAP_POISONING_DISABLED=y
# CONFIG_HEAP_POISONING_LIGHT is not set
# CONFIG_HEAP_POISONING_COMPREHENSIVE is not set
CONFIG_HEAP_TRACING_OFF=y
# CONFIG_HEAP_TRACING_STANDALONE is not set
# CONFIG_HEAP_TRACING_TOHOST is not set
# CONFIG_HEAP_USE_HOOKS is not set
# CONFIG_HEAP_TASK_TRACKING is not set
# CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS is not set
# CONFIG_HEAP_PLACE_FUNCTION_INTO_FLASH is not set
# end of Heap memory debugging
#
# Log output
#
# CONFIG_LOG_DEFAULT_LEVEL_NONE is not set
# CONFIG_LOG_DEFAULT_LEVEL_ERROR is not set
# CONFIG_LOG_DEFAULT_LEVEL_WARN is not set
CONFIG_LOG_DEFAULT_LEVEL_INFO=y
# CONFIG_LOG_DEFAULT_LEVEL_DEBUG is not set
# CONFIG_LOG_DEFAULT_LEVEL_VERBOSE is not set
CONFIG_LOG_DEFAULT_LEVEL=3
CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT=y
# CONFIG_LOG_MAXIMUM_LEVEL_DEBUG is not set
# CONFIG_LOG_MAXIMUM_LEVEL_VERBOSE is not set
CONFIG_LOG_MAXIMUM_LEVEL=3
# CONFIG_LOG_MASTER_LEVEL is not set
CONFIG_LOG_COLORS=y
CONFIG_LOG_TIMESTAMP_SOURCE_RTOS=y
# CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM is not set
# end of Log output
#
# LWIP
#
CONFIG_LWIP_ENABLE=y
CONFIG_LWIP_LOCAL_HOSTNAME="espressif"
# CONFIG_LWIP_NETIF_API is not set
CONFIG_LWIP_TCPIP_TASK_PRIO=18
# CONFIG_LWIP_TCPIP_CORE_LOCKING is not set
# CONFIG_LWIP_CHECK_THREAD_SAFETY is not set
CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y
# CONFIG_LWIP_L2_TO_L3_COPY is not set
# CONFIG_LWIP_IRAM_OPTIMIZATION is not set
# CONFIG_LWIP_EXTRA_IRAM_OPTIMIZATION is not set
CONFIG_LWIP_TIMERS_ONDEMAND=y
CONFIG_LWIP_ND6=y
# CONFIG_LWIP_FORCE_ROUTER_FORWARDING is not set
CONFIG_LWIP_MAX_SOCKETS=10
# CONFIG_LWIP_USE_ONLY_LWIP_SELECT is not set
# CONFIG_LWIP_SO_LINGER is not set
CONFIG_LWIP_SO_REUSE=y
CONFIG_LWIP_SO_REUSE_RXTOALL=y
# CONFIG_LWIP_SO_RCVBUF is not set
# CONFIG_LWIP_NETBUF_RECVINFO is not set
CONFIG_LWIP_IP_DEFAULT_TTL=64
CONFIG_LWIP_IP4_FRAG=y
CONFIG_LWIP_IP6_FRAG=y
# CONFIG_LWIP_IP4_REASSEMBLY is not set
# CONFIG_LWIP_IP6_REASSEMBLY is not set
CONFIG_LWIP_IP_REASS_MAX_PBUFS=10
# CONFIG_LWIP_IP_FORWARD is not set
# CONFIG_LWIP_STATS is not set
CONFIG_LWIP_ESP_GRATUITOUS_ARP=y
CONFIG_LWIP_GARP_TMR_INTERVAL=60
CONFIG_LWIP_ESP_MLDV6_REPORT=y
CONFIG_LWIP_MLDV6_TMR_INTERVAL=40
CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32
CONFIG_LWIP_DHCP_DOES_ARP_CHECK=y
# CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID is not set
CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID=y
# CONFIG_LWIP_DHCP_RESTORE_LAST_IP is not set
CONFIG_LWIP_DHCP_OPTIONS_LEN=68
CONFIG_LWIP_NUM_NETIF_CLIENT_DATA=0
CONFIG_LWIP_DHCP_COARSE_TIMER_SECS=1
#
# DHCP server
#
CONFIG_LWIP_DHCPS=y
CONFIG_LWIP_DHCPS_LEASE_UNIT=60
CONFIG_LWIP_DHCPS_MAX_STATION_NUM=8
CONFIG_LWIP_DHCPS_STATIC_ENTRIES=y
# end of DHCP server
# CONFIG_LWIP_AUTOIP is not set
CONFIG_LWIP_IPV4=y
CONFIG_LWIP_IPV6=y
# CONFIG_LWIP_IPV6_AUTOCONFIG is not set
CONFIG_LWIP_IPV6_NUM_ADDRESSES=3
# CONFIG_LWIP_IPV6_FORWARD is not set
# CONFIG_LWIP_NETIF_STATUS_CALLBACK is not set
CONFIG_LWIP_NETIF_LOOPBACK=y
CONFIG_LWIP_LOOPBACK_MAX_PBUFS=8
#
# TCP
#
CONFIG_LWIP_MAX_ACTIVE_TCP=16
CONFIG_LWIP_MAX_LISTENING_TCP=16
CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION=y
CONFIG_LWIP_TCP_MAXRTX=12
CONFIG_LWIP_TCP_SYNMAXRTX=12
CONFIG_LWIP_TCP_MSS=1440
CONFIG_LWIP_TCP_TMR_INTERVAL=250
CONFIG_LWIP_TCP_MSL=60000
CONFIG_LWIP_TCP_FIN_WAIT_TIMEOUT=20000
CONFIG_LWIP_TCP_SND_BUF_DEFAULT=5760
CONFIG_LWIP_TCP_WND_DEFAULT=5760
CONFIG_LWIP_TCP_RECVMBOX_SIZE=6
CONFIG_LWIP_TCP_ACCEPTMBOX_SIZE=6
CONFIG_LWIP_TCP_QUEUE_OOSEQ=y
CONFIG_LWIP_TCP_OOSEQ_TIMEOUT=6
CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS=4
# CONFIG_LWIP_TCP_SACK_OUT is not set
CONFIG_LWIP_TCP_OVERSIZE_MSS=y
# CONFIG_LWIP_TCP_OVERSIZE_QUARTER_MSS is not set
# CONFIG_LWIP_TCP_OVERSIZE_DISABLE is not set
CONFIG_LWIP_TCP_RTO_TIME=1500
# end of TCP
#
# UDP
#
CONFIG_LWIP_MAX_UDP_PCBS=16
CONFIG_LWIP_UDP_RECVMBOX_SIZE=6
# end of UDP
#
# Checksums
#
# CONFIG_LWIP_CHECKSUM_CHECK_IP is not set
# CONFIG_LWIP_CHECKSUM_CHECK_UDP is not set
CONFIG_LWIP_CHECKSUM_CHECK_ICMP=y
# end of Checksums
CONFIG_LWIP_TCPIP_TASK_STACK_SIZE=3072
CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY=y
# CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0 is not set
# CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU1 is not set
CONFIG_LWIP_TCPIP_TASK_AFFINITY=0x7FFFFFFF
# CONFIG_LWIP_PPP_SUPPORT is not set
CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE=3
CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS=5
# CONFIG_LWIP_SLIP_SUPPORT is not set
#
# ICMP
#
CONFIG_LWIP_ICMP=y
# CONFIG_LWIP_MULTICAST_PING is not set
# CONFIG_LWIP_BROADCAST_PING is not set
# end of ICMP
#
# LWIP RAW API
#
CONFIG_LWIP_MAX_RAW_PCBS=16
# end of LWIP RAW API
#
# SNTP
#
CONFIG_LWIP_SNTP_MAX_SERVERS=1
# CONFIG_LWIP_DHCP_GET_NTP_SRV is not set
CONFIG_LWIP_SNTP_UPDATE_DELAY=3600000
CONFIG_LWIP_SNTP_STARTUP_DELAY=y
CONFIG_LWIP_SNTP_MAXIMUM_STARTUP_DELAY=5000
# end of SNTP
#
# DNS
#
CONFIG_LWIP_DNS_MAX_SERVERS=3
# CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT is not set
# end of DNS
CONFIG_LWIP_BRIDGEIF_MAX_PORTS=7
CONFIG_LWIP_ESP_LWIP_ASSERT=y
#
# Hooks
#
# CONFIG_LWIP_HOOK_TCP_ISN_NONE is not set
CONFIG_LWIP_HOOK_TCP_ISN_DEFAULT=y
# CONFIG_LWIP_HOOK_TCP_ISN_CUSTOM is not set
CONFIG_LWIP_HOOK_IP6_ROUTE_NONE=y
# CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT is not set
# CONFIG_LWIP_HOOK_IP6_ROUTE_CUSTOM is not set
CONFIG_LWIP_HOOK_ND6_GET_GW_NONE=y
# CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT is not set
# CONFIG_LWIP_HOOK_ND6_GET_GW_CUSTOM is not set
CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE=y
# CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_DEFAULT is not set
# CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_CUSTOM is not set
CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE=y
# CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_DEFAULT is not set
# CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM is not set
CONFIG_LWIP_HOOK_IP6_INPUT_NONE=y
# CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT is not set
# CONFIG_LWIP_HOOK_IP6_INPUT_CUSTOM is not set
# end of Hooks
# CONFIG_LWIP_DEBUG is not set
# end of LWIP
#
# mbedTLS
#
CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y
# CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC is not set
# CONFIG_MBEDTLS_DEFAULT_MEM_ALLOC is not set
# CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC is not set
CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y
CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=16384
CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096
# CONFIG_MBEDTLS_DYNAMIC_BUFFER is not set
# CONFIG_MBEDTLS_DEBUG is not set
#
# mbedTLS v3.x related
#
# CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 is not set
# CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH is not set
# CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK is not set
# CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set
CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y
CONFIG_MBEDTLS_PKCS7_C=y
# end of mbedTLS v3.x related
#
# Certificate Bundle
#
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL=y
# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN is not set
# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE is not set
# CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE is not set
# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEPRECATED_LIST is not set
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS=200
# end of Certificate Bundle
# CONFIG_MBEDTLS_ECP_RESTARTABLE is not set
CONFIG_MBEDTLS_CMAC_C=y
CONFIG_MBEDTLS_HARDWARE_AES=y
CONFIG_MBEDTLS_AES_USE_INTERRUPT=y
CONFIG_MBEDTLS_AES_INTERRUPT_LEVEL=0
CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER=y
CONFIG_MBEDTLS_HARDWARE_MPI=y
# CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI is not set
CONFIG_MBEDTLS_MPI_USE_INTERRUPT=y
CONFIG_MBEDTLS_MPI_INTERRUPT_LEVEL=0
CONFIG_MBEDTLS_HARDWARE_SHA=y
CONFIG_MBEDTLS_ROM_MD5=y
# CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set
# CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set
CONFIG_MBEDTLS_HAVE_TIME=y
# CONFIG_MBEDTLS_PLATFORM_TIME_ALT is not set
# CONFIG_MBEDTLS_HAVE_TIME_DATE is not set
CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y
CONFIG_MBEDTLS_SHA512_C=y
CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT=y
# CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set
# CONFIG_MBEDTLS_TLS_CLIENT_ONLY is not set
# CONFIG_MBEDTLS_TLS_DISABLED is not set
CONFIG_MBEDTLS_TLS_SERVER=y
CONFIG_MBEDTLS_TLS_CLIENT=y
CONFIG_MBEDTLS_TLS_ENABLED=y
#
# TLS Key Exchange Methods
#
# CONFIG_MBEDTLS_PSK_MODES is not set
CONFIG_MBEDTLS_KEY_EXCHANGE_RSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA=y
# end of TLS Key Exchange Methods
CONFIG_MBEDTLS_SSL_RENEGOTIATION=y
CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y
# CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set
# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set
CONFIG_MBEDTLS_SSL_ALPN=y
CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS=y
CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS=y
#
# Symmetric Ciphers
#
CONFIG_MBEDTLS_AES_C=y
# CONFIG_MBEDTLS_CAMELLIA_C is not set
# CONFIG_MBEDTLS_DES_C is not set
# CONFIG_MBEDTLS_BLOWFISH_C is not set
# CONFIG_MBEDTLS_XTEA_C is not set
CONFIG_MBEDTLS_CCM_C=y
CONFIG_MBEDTLS_GCM_C=y
# CONFIG_MBEDTLS_NIST_KW_C is not set
# end of Symmetric Ciphers
# CONFIG_MBEDTLS_RIPEMD160_C is not set
#
# Certificates
#
CONFIG_MBEDTLS_PEM_PARSE_C=y
CONFIG_MBEDTLS_PEM_WRITE_C=y
CONFIG_MBEDTLS_X509_CRL_PARSE_C=y
CONFIG_MBEDTLS_X509_CSR_PARSE_C=y
# end of Certificates
CONFIG_MBEDTLS_ECP_C=y
# CONFIG_MBEDTLS_DHM_C is not set
CONFIG_MBEDTLS_ECDH_C=y
CONFIG_MBEDTLS_ECDSA_C=y
# CONFIG_MBEDTLS_ECJPAKE_C is not set
CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED=y
CONFIG_MBEDTLS_ECP_NIST_OPTIM=y
CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM=y
# CONFIG_MBEDTLS_POLY1305_C is not set
# CONFIG_MBEDTLS_CHACHA20_C is not set
# CONFIG_MBEDTLS_HKDF_C is not set
# CONFIG_MBEDTLS_THREADING_C is not set
CONFIG_MBEDTLS_ERROR_STRINGS=y
# end of mbedTLS
#
# ESP-MQTT Configurations
#
CONFIG_MQTT_PROTOCOL_311=y
# CONFIG_MQTT_PROTOCOL_5 is not set
CONFIG_MQTT_TRANSPORT_SSL=y
CONFIG_MQTT_TRANSPORT_WEBSOCKET=y
CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y
# CONFIG_MQTT_MSG_ID_INCREMENTAL is not set
# CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED is not set
# CONFIG_MQTT_REPORT_DELETED_MESSAGES is not set
# CONFIG_MQTT_USE_CUSTOM_CONFIG is not set
# CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED is not set
# CONFIG_MQTT_CUSTOM_OUTBOX is not set
# end of ESP-MQTT Configurations
#
# Newlib
#
CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF=y
# CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF is not set
# CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR is not set
# CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF is not set
# CONFIG_NEWLIB_STDIN_LINE_ENDING_LF is not set
CONFIG_NEWLIB_STDIN_LINE_ENDING_CR=y
# CONFIG_NEWLIB_NANO_FORMAT is not set
CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y
# CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC is not set
# CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT is not set
# CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE is not set
# end of Newlib
CONFIG_STDATOMIC_S32C1I_SPIRAM_WORKAROUND=y
#
# NVS
#
# CONFIG_NVS_ENCRYPTION is not set
# CONFIG_NVS_ASSERT_ERROR_CHECK is not set
# CONFIG_NVS_LEGACY_DUP_KEYS_COMPATIBILITY is not set
# end of NVS
#
# OpenThread
#
# CONFIG_OPENTHREAD_ENABLED is not set
#
# Thread Operational Dataset
#
CONFIG_OPENTHREAD_NETWORK_NAME="OpenThread-ESP"
CONFIG_OPENTHREAD_MESH_LOCAL_PREFIX="fd00:db8:a0:0::/64"
CONFIG_OPENTHREAD_NETWORK_CHANNEL=15
CONFIG_OPENTHREAD_NETWORK_PANID=0x1234
CONFIG_OPENTHREAD_NETWORK_EXTPANID="dead00beef00cafe"
CONFIG_OPENTHREAD_NETWORK_MASTERKEY="00112233445566778899aabbccddeeff"
CONFIG_OPENTHREAD_NETWORK_PSKC="104810e2315100afd6bc9215a6bfac53"
# end of Thread Operational Dataset
CONFIG_OPENTHREAD_XTAL_ACCURACY=130
# CONFIG_OPENTHREAD_SPINEL_ONLY is not set
CONFIG_OPENTHREAD_RX_ON_WHEN_IDLE=y
#
# Thread Address Query Config
#
# end of Thread Address Query Config
# end of OpenThread
#
# Protocomm
#
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0=y
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1=y
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2=y
# end of Protocomm
#
# PThreads
#
CONFIG_PTHREAD_TASK_PRIO_DEFAULT=5
CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072
CONFIG_PTHREAD_STACK_MIN=768
CONFIG_PTHREAD_DEFAULT_CORE_NO_AFFINITY=y
# CONFIG_PTHREAD_DEFAULT_CORE_0 is not set
# CONFIG_PTHREAD_DEFAULT_CORE_1 is not set
CONFIG_PTHREAD_TASK_CORE_DEFAULT=-1
CONFIG_PTHREAD_TASK_NAME_DEFAULT="pthread"
# end of PThreads
#
# MMU Config
#
CONFIG_MMU_PAGE_SIZE_64KB=y
CONFIG_MMU_PAGE_MODE="64KB"
CONFIG_MMU_PAGE_SIZE=0x10000
# end of MMU Config
#
# Main Flash configuration
#
#
# SPI Flash behavior when brownout
#
CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC=y
CONFIG_SPI_FLASH_BROWNOUT_RESET=y
# end of SPI Flash behavior when brownout
#
# Optional and Experimental Features (READ DOCS FIRST)
#
#
# Features here require specific hardware (READ DOCS FIRST!)
#
# CONFIG_SPI_FLASH_HPM_ENA is not set
CONFIG_SPI_FLASH_HPM_AUTO=y
# CONFIG_SPI_FLASH_HPM_DIS is not set
CONFIG_SPI_FLASH_HPM_ON=y
CONFIG_SPI_FLASH_HPM_DC_AUTO=y
# CONFIG_SPI_FLASH_HPM_DC_DISABLE is not set
CONFIG_SPI_FLASH_SUSPEND_QVL_SUPPORTED=y
# CONFIG_SPI_FLASH_AUTO_SUSPEND is not set
CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US=50
# end of Optional and Experimental Features (READ DOCS FIRST)
# end of Main Flash configuration
#
# SPI Flash driver
#
# CONFIG_SPI_FLASH_VERIFY_WRITE is not set
# CONFIG_SPI_FLASH_ENABLE_COUNTERS is not set
CONFIG_SPI_FLASH_ROM_DRIVER_PATCH=y
# CONFIG_SPI_FLASH_ROM_IMPL is not set
CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS=y
# CONFIG_SPI_FLASH_DANGEROUS_WRITE_FAILS is not set
# CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED is not set
# CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE is not set
CONFIG_SPI_FLASH_YIELD_DURING_ERASE=y
CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS=20
CONFIG_SPI_FLASH_ERASE_YIELD_TICKS=1
CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE=8192
# CONFIG_SPI_FLASH_SIZE_OVERRIDE is not set
# CONFIG_SPI_FLASH_CHECK_ERASE_TIMEOUT_DISABLED is not set
# CONFIG_SPI_FLASH_OVERRIDE_CHIP_DRIVER_LIST is not set
#
# Auto-detect flash chips
#
CONFIG_SPI_FLASH_VENDOR_XMC_SUPPORTED=y
CONFIG_SPI_FLASH_VENDOR_GD_SUPPORTED=y
CONFIG_SPI_FLASH_VENDOR_ISSI_SUPPORTED=y
CONFIG_SPI_FLASH_VENDOR_MXIC_SUPPORTED=y
CONFIG_SPI_FLASH_VENDOR_WINBOND_SUPPORTED=y
CONFIG_SPI_FLASH_VENDOR_BOYA_SUPPORTED=y
CONFIG_SPI_FLASH_VENDOR_TH_SUPPORTED=y
CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP=y
CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP=y
CONFIG_SPI_FLASH_SUPPORT_GD_CHIP=y
CONFIG_SPI_FLASH_SUPPORT_WINBOND_CHIP=y
CONFIG_SPI_FLASH_SUPPORT_BOYA_CHIP=y
CONFIG_SPI_FLASH_SUPPORT_TH_CHIP=y
CONFIG_SPI_FLASH_SUPPORT_MXIC_OPI_CHIP=y
# end of Auto-detect flash chips
CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE=y
# end of SPI Flash driver
#
# SPIFFS Configuration
#
CONFIG_SPIFFS_MAX_PARTITIONS=3
#
# SPIFFS Cache Configuration
#
CONFIG_SPIFFS_CACHE=y
CONFIG_SPIFFS_CACHE_WR=y
# CONFIG_SPIFFS_CACHE_STATS is not set
# end of SPIFFS Cache Configuration
CONFIG_SPIFFS_PAGE_CHECK=y
CONFIG_SPIFFS_GC_MAX_RUNS=10
# CONFIG_SPIFFS_GC_STATS is not set
CONFIG_SPIFFS_PAGE_SIZE=256
CONFIG_SPIFFS_OBJ_NAME_LEN=32
# CONFIG_SPIFFS_FOLLOW_SYMLINKS is not set
CONFIG_SPIFFS_USE_MAGIC=y
CONFIG_SPIFFS_USE_MAGIC_LENGTH=y
CONFIG_SPIFFS_META_LENGTH=4
CONFIG_SPIFFS_USE_MTIME=y
#
# Debug Configuration
#
# CONFIG_SPIFFS_DBG is not set
# CONFIG_SPIFFS_API_DBG is not set
# CONFIG_SPIFFS_GC_DBG is not set
# CONFIG_SPIFFS_CACHE_DBG is not set
# CONFIG_SPIFFS_CHECK_DBG is not set
# CONFIG_SPIFFS_TEST_VISUALISATION is not set
# end of Debug Configuration
# end of SPIFFS Configuration
#
# TCP Transport
#
#
# Websocket
#
CONFIG_WS_TRANSPORT=y
CONFIG_WS_BUFFER_SIZE=1024
# CONFIG_WS_DYNAMIC_BUFFER is not set
# end of Websocket
# end of TCP Transport
#
# Ultra Low Power (ULP) Co-processor
#
# CONFIG_ULP_COPROC_ENABLED is not set
#
# ULP Debugging Options
#
# end of ULP Debugging Options
# end of Ultra Low Power (ULP) Co-processor
#
# Unity unit testing library
#
CONFIG_UNITY_ENABLE_FLOAT=y
CONFIG_UNITY_ENABLE_DOUBLE=y
# CONFIG_UNITY_ENABLE_64BIT is not set
# CONFIG_UNITY_ENABLE_COLOR is not set
CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER=y
# CONFIG_UNITY_ENABLE_FIXTURE is not set
# CONFIG_UNITY_ENABLE_BACKTRACE_ON_FAIL is not set
# end of Unity unit testing library
#
# USB-OTG
#
CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE=256
CONFIG_USB_HOST_HW_BUFFER_BIAS_BALANCED=y
# CONFIG_USB_HOST_HW_BUFFER_BIAS_IN is not set
# CONFIG_USB_HOST_HW_BUFFER_BIAS_PERIODIC_OUT is not set
#
# Root Hub configuration
#
CONFIG_USB_HOST_DEBOUNCE_DELAY_MS=250
CONFIG_USB_HOST_RESET_HOLD_MS=30
CONFIG_USB_HOST_RESET_RECOVERY_MS=30
CONFIG_USB_HOST_SET_ADDR_RECOVERY_MS=10
# end of Root Hub configuration
# CONFIG_USB_HOST_ENABLE_ENUM_FILTER_CALLBACK is not set
CONFIG_USB_OTG_SUPPORTED=y
# end of USB-OTG
#
# Virtual file system
#
CONFIG_VFS_SUPPORT_IO=y
CONFIG_VFS_SUPPORT_DIR=y
CONFIG_VFS_SUPPORT_SELECT=y
CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT=y
# CONFIG_VFS_SELECT_IN_RAM is not set
CONFIG_VFS_SUPPORT_TERMIOS=y
CONFIG_VFS_MAX_COUNT=8
#
# Host File System I/O (Semihosting)
#
CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS=1
# end of Host File System I/O (Semihosting)
# end of Virtual file system
#
# Wear Levelling
#
# CONFIG_WL_SECTOR_SIZE_512 is not set
CONFIG_WL_SECTOR_SIZE_4096=y
CONFIG_WL_SECTOR_SIZE=4096
# end of Wear Levelling
#
# Wi-Fi Provisioning Manager
#
CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES=16
CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT=30
# CONFIG_WIFI_PROV_BLE_FORCE_ENCRYPTION is not set
CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y
# CONFIG_WIFI_PROV_STA_FAST_SCAN is not set
# end of Wi-Fi Provisioning Manager
#
# CMake Utilities
#
# CONFIG_CU_RELINKER_ENABLE is not set
# CONFIG_CU_DIAGNOSTICS_COLOR_NEVER is not set
CONFIG_CU_DIAGNOSTICS_COLOR_ALWAYS=y
# CONFIG_CU_DIAGNOSTICS_COLOR_AUTO is not set
# CONFIG_CU_GCC_LTO_ENABLE is not set
# CONFIG_CU_GCC_STRING_1BYTE_ALIGN is not set
# end of CMake Utilities
#
# ESP LCD TOUCH
#
CONFIG_ESP_LCD_TOUCH_MAX_POINTS=5
CONFIG_ESP_LCD_TOUCH_MAX_BUTTONS=1
# end of ESP LCD TOUCH
#
# LVGL configuration
#
CONFIG_LV_CONF_SKIP=y
# CONFIG_LV_CONF_MINIMAL is not set
#
# Color Settings
#
# CONFIG_LV_COLOR_DEPTH_32 is not set
# CONFIG_LV_COLOR_DEPTH_24 is not set
CONFIG_LV_COLOR_DEPTH_16=y
# CONFIG_LV_COLOR_DEPTH_8 is not set
# CONFIG_LV_COLOR_DEPTH_1 is not set
CONFIG_LV_COLOR_DEPTH=16
# end of Color Settings
#
# Memory Settings
#
CONFIG_LV_USE_BUILTIN_MALLOC=y
# CONFIG_LV_USE_CLIB_MALLOC is not set
# CONFIG_LV_USE_MICROPYTHON_MALLOC is not set
# CONFIG_LV_USE_RTTHREAD_MALLOC is not set
# CONFIG_LV_USE_CUSTOM_MALLOC is not set
CONFIG_LV_USE_BUILTIN_STRING=y
# CONFIG_LV_USE_CLIB_STRING is not set
# CONFIG_LV_USE_CUSTOM_STRING is not set
CONFIG_LV_USE_BUILTIN_SPRINTF=y
# CONFIG_LV_USE_CLIB_SPRINTF is not set
# CONFIG_LV_USE_CUSTOM_SPRINTF is not set
CONFIG_LV_MEM_SIZE_KILOBYTES=64
CONFIG_LV_MEM_POOL_EXPAND_SIZE_KILOBYTES=0
CONFIG_LV_MEM_ADR=0x0
# end of Memory Settings
#
# HAL Settings
#
CONFIG_LV_DEF_REFR_PERIOD=33
CONFIG_LV_DPI_DEF=130
# end of HAL Settings
#
# Operating System (OS)
#
CONFIG_LV_OS_NONE=y
# CONFIG_LV_OS_PTHREAD is not set
# CONFIG_LV_OS_FREERTOS is not set
# CONFIG_LV_OS_CMSIS_RTOS2 is not set
# CONFIG_LV_OS_RTTHREAD is not set
# CONFIG_LV_OS_WINDOWS is not set
# CONFIG_LV_OS_MQX is not set
# CONFIG_LV_OS_CUSTOM is not set
CONFIG_LV_USE_OS=0
# end of Operating System (OS)
#
# Rendering Configuration
#
CONFIG_LV_DRAW_BUF_STRIDE_ALIGN=1
CONFIG_LV_DRAW_BUF_ALIGN=4
CONFIG_LV_DRAW_LAYER_SIMPLE_BUF_SIZE=24576
CONFIG_LV_USE_DRAW_SW=y
CONFIG_LV_DRAW_SW_SUPPORT_RGB565=y
CONFIG_LV_DRAW_SW_SUPPORT_RGB565A8=y
CONFIG_LV_DRAW_SW_SUPPORT_RGB888=y
CONFIG_LV_DRAW_SW_SUPPORT_XRGB8888=y
CONFIG_LV_DRAW_SW_SUPPORT_ARGB8888=y
CONFIG_LV_DRAW_SW_SUPPORT_L8=y
CONFIG_LV_DRAW_SW_SUPPORT_AL88=y
CONFIG_LV_DRAW_SW_SUPPORT_A8=y
CONFIG_LV_DRAW_SW_SUPPORT_I1=y
CONFIG_LV_DRAW_SW_DRAW_UNIT_CNT=1
# CONFIG_LV_USE_DRAW_ARM2D_SYNC is not set
# CONFIG_LV_USE_NATIVE_HELIUM_ASM is not set
CONFIG_LV_DRAW_SW_COMPLEX=y
# CONFIG_LV_USE_DRAW_SW_COMPLEX_GRADIENTS is not set
CONFIG_LV_DRAW_SW_SHADOW_CACHE_SIZE=0
CONFIG_LV_DRAW_SW_CIRCLE_CACHE_SIZE=4
CONFIG_LV_DRAW_SW_ASM_NONE=y
# CONFIG_LV_DRAW_SW_ASM_NEON is not set
# CONFIG_LV_DRAW_SW_ASM_HELIUM is not set
# CONFIG_LV_DRAW_SW_ASM_CUSTOM is not set
CONFIG_LV_USE_DRAW_SW_ASM=0
# CONFIG_LV_USE_DRAW_VGLITE is not set
# CONFIG_LV_USE_DRAW_PXP is not set
# CONFIG_LV_USE_DRAW_DAVE2D is not set
# CONFIG_LV_USE_DRAW_SDL is not set
# CONFIG_LV_USE_DRAW_VG_LITE is not set
# CONFIG_LV_USE_VECTOR_GRAPHIC is not set
# end of Rendering Configuration
#
# Feature Configuration
#
#
# Logging
#
# CONFIG_LV_USE_LOG is not set
# end of Logging
#
# Asserts
#
CONFIG_LV_USE_ASSERT_NULL=y
CONFIG_LV_USE_ASSERT_MALLOC=y
# CONFIG_LV_USE_ASSERT_STYLE is not set
# CONFIG_LV_USE_ASSERT_MEM_INTEGRITY is not set
# CONFIG_LV_USE_ASSERT_OBJ is not set
CONFIG_LV_ASSERT_HANDLER_INCLUDE="assert.h"
# end of Asserts
#
# Debug
#
# CONFIG_LV_USE_REFR_DEBUG is not set
# CONFIG_LV_USE_LAYER_DEBUG is not set
# CONFIG_LV_USE_PARALLEL_DRAW_DEBUG is not set
# end of Debug
#
# Others
#
# CONFIG_LV_ENABLE_GLOBAL_CUSTOM is not set
CONFIG_LV_CACHE_DEF_SIZE=0
CONFIG_LV_IMAGE_HEADER_CACHE_DEF_CNT=0
CONFIG_LV_GRADIENT_MAX_STOPS=2
CONFIG_LV_COLOR_MIX_ROUND_OFS=128
# CONFIG_LV_OBJ_STYLE_CACHE is not set
# CONFIG_LV_USE_OBJ_ID is not set
# CONFIG_LV_USE_OBJ_PROPERTY is not set
# end of Others
# end of Feature Configuration
#
# Compiler Settings
#
# CONFIG_LV_BIG_ENDIAN_SYSTEM is not set
CONFIG_LV_ATTRIBUTE_MEM_ALIGN_SIZE=1
# CONFIG_LV_ATTRIBUTE_FAST_MEM_USE_IRAM is not set
# CONFIG_LV_USE_FLOAT is not set
# CONFIG_LV_USE_MATRIX is not set
# CONFIG_LV_USE_PRIVATE_API is not set
# end of Compiler Settings
#
# Font Usage
#
#
# Enable built-in fonts
#
# CONFIG_LV_FONT_MONTSERRAT_8 is not set
# CONFIG_LV_FONT_MONTSERRAT_10 is not set
# CONFIG_LV_FONT_MONTSERRAT_12 is not set
CONFIG_LV_FONT_MONTSERRAT_14=y
# CONFIG_LV_FONT_MONTSERRAT_16 is not set
# CONFIG_LV_FONT_MONTSERRAT_18 is not set
# CONFIG_LV_FONT_MONTSERRAT_20 is not set
# CONFIG_LV_FONT_MONTSERRAT_22 is not set
# CONFIG_LV_FONT_MONTSERRAT_24 is not set
# CONFIG_LV_FONT_MONTSERRAT_26 is not set
# CONFIG_LV_FONT_MONTSERRAT_28 is not set
# CONFIG_LV_FONT_MONTSERRAT_30 is not set
# CONFIG_LV_FONT_MONTSERRAT_32 is not set
# CONFIG_LV_FONT_MONTSERRAT_34 is not set
# CONFIG_LV_FONT_MONTSERRAT_36 is not set
# CONFIG_LV_FONT_MONTSERRAT_38 is not set
# CONFIG_LV_FONT_MONTSERRAT_40 is not set
# CONFIG_LV_FONT_MONTSERRAT_42 is not set
# CONFIG_LV_FONT_MONTSERRAT_44 is not set
# CONFIG_LV_FONT_MONTSERRAT_46 is not set
# CONFIG_LV_FONT_MONTSERRAT_48 is not set
# CONFIG_LV_FONT_MONTSERRAT_28_COMPRESSED is not set
# CONFIG_LV_FONT_DEJAVU_16_PERSIAN_HEBREW is not set
# CONFIG_LV_FONT_SIMSUN_14_CJK is not set
# CONFIG_LV_FONT_SIMSUN_16_CJK is not set
# CONFIG_LV_FONT_UNSCII_8 is not set
# CONFIG_LV_FONT_UNSCII_16 is not set
# end of Enable built-in fonts
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_8 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_10 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_12 is not set
CONFIG_LV_FONT_DEFAULT_MONTSERRAT_14=y
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_16 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_18 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_20 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_22 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_24 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_26 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_30 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_32 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_34 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_36 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_38 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_40 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_42 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_44 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_46 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_48 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28_COMPRESSED is not set
# CONFIG_LV_FONT_DEFAULT_DEJAVU_16_PERSIAN_HEBREW is not set
# CONFIG_LV_FONT_DEFAULT_SIMSUN_14_CJK is not set
# CONFIG_LV_FONT_DEFAULT_SIMSUN_16_CJK is not set
# CONFIG_LV_FONT_DEFAULT_UNSCII_8 is not set
# CONFIG_LV_FONT_DEFAULT_UNSCII_16 is not set
# CONFIG_LV_FONT_FMT_TXT_LARGE is not set
# CONFIG_LV_USE_FONT_COMPRESSED is not set
CONFIG_LV_USE_FONT_PLACEHOLDER=y
# end of Font Usage
#
# Text Settings
#
CONFIG_LV_TXT_ENC_UTF8=y
# CONFIG_LV_TXT_ENC_ASCII is not set
CONFIG_LV_TXT_BREAK_CHARS=" ,.;:-_)}"
CONFIG_LV_TXT_LINE_BREAK_LONG_LEN=0
# CONFIG_LV_USE_BIDI is not set
# CONFIG_LV_USE_ARABIC_PERSIAN_CHARS is not set
# end of Text Settings
#
# Widget Usage
#
CONFIG_LV_WIDGETS_HAS_DEFAULT_VALUE=y
CONFIG_LV_USE_ANIMIMG=y
CONFIG_LV_USE_ARC=y
CONFIG_LV_USE_BAR=y
CONFIG_LV_USE_BUTTON=y
CONFIG_LV_USE_BUTTONMATRIX=y
CONFIG_LV_USE_CALENDAR=y
# CONFIG_LV_CALENDAR_WEEK_STARTS_MONDAY is not set
CONFIG_LV_USE_CALENDAR_HEADER_ARROW=y
CONFIG_LV_USE_CALENDAR_HEADER_DROPDOWN=y
# CONFIG_LV_USE_CALENDAR_CHINESE is not set
CONFIG_LV_USE_CANVAS=y
CONFIG_LV_USE_CHART=y
CONFIG_LV_USE_CHECKBOX=y
CONFIG_LV_USE_DROPDOWN=y
CONFIG_LV_USE_IMAGE=y
CONFIG_LV_USE_IMAGEBUTTON=y
CONFIG_LV_USE_KEYBOARD=y
CONFIG_LV_USE_LABEL=y
CONFIG_LV_LABEL_TEXT_SELECTION=y
CONFIG_LV_LABEL_LONG_TXT_HINT=y
CONFIG_LV_LABEL_WAIT_CHAR_COUNT=3
CONFIG_LV_USE_LED=y
CONFIG_LV_USE_LINE=y
CONFIG_LV_USE_LIST=y
CONFIG_LV_USE_MENU=y
CONFIG_LV_USE_MSGBOX=y
CONFIG_LV_USE_ROLLER=y
CONFIG_LV_USE_SCALE=y
CONFIG_LV_USE_SLIDER=y
CONFIG_LV_USE_SPAN=y
CONFIG_LV_SPAN_SNIPPET_STACK_SIZE=64
CONFIG_LV_USE_SPINBOX=y
CONFIG_LV_USE_SPINNER=y
CONFIG_LV_USE_SWITCH=y
CONFIG_LV_USE_TEXTAREA=y
CONFIG_LV_TEXTAREA_DEF_PWD_SHOW_TIME=1500
CONFIG_LV_USE_TABLE=y
CONFIG_LV_USE_TABVIEW=y
CONFIG_LV_USE_TILEVIEW=y
CONFIG_LV_USE_WIN=y
# end of Widget Usage
#
# Themes
#
CONFIG_LV_USE_THEME_DEFAULT=y
# CONFIG_LV_THEME_DEFAULT_DARK is not set
CONFIG_LV_THEME_DEFAULT_GROW=y
CONFIG_LV_THEME_DEFAULT_TRANSITION_TIME=80
CONFIG_LV_USE_THEME_SIMPLE=y
# CONFIG_LV_USE_THEME_MONO is not set
# end of Themes
#
# Layouts
#
CONFIG_LV_USE_FLEX=y
CONFIG_LV_USE_GRID=y
# end of Layouts
#
# 3rd Party Libraries
#
CONFIG_LV_FS_DEFAULT_DRIVE_LETTER=0
# CONFIG_LV_USE_FS_STDIO is not set
# CONFIG_LV_USE_FS_POSIX is not set
# CONFIG_LV_USE_FS_WIN32 is not set
# CONFIG_LV_USE_FS_FATFS is not set
# CONFIG_LV_USE_FS_MEMFS is not set
# CONFIG_LV_USE_FS_LITTLEFS is not set
# CONFIG_LV_USE_FS_ARDUINO_ESP_LITTLEFS is not set
# CONFIG_LV_USE_FS_ARDUINO_SD is not set
# CONFIG_LV_USE_LODEPNG is not set
# CONFIG_LV_USE_LIBPNG is not set
# CONFIG_LV_USE_BMP is not set
# CONFIG_LV_USE_TJPGD is not set
# CONFIG_LV_USE_LIBJPEG_TURBO is not set
# CONFIG_LV_USE_GIF is not set
# CONFIG_LV_BIN_DECODER_RAM_LOAD is not set
# CONFIG_LV_USE_RLE is not set
# CONFIG_LV_USE_QRCODE is not set
# CONFIG_LV_USE_BARCODE is not set
# CONFIG_LV_USE_FREETYPE is not set
# CONFIG_LV_USE_TINY_TTF is not set
# CONFIG_LV_USE_RLOTTIE is not set
# CONFIG_LV_USE_THORVG is not set
# CONFIG_LV_USE_LZ4 is not set
# CONFIG_LV_USE_FFMPEG is not set
# end of 3rd Party Libraries
#
# Others
#
# CONFIG_LV_USE_SNAPSHOT is not set
# CONFIG_LV_USE_SYSMON is not set
# CONFIG_LV_USE_PROFILER is not set
# CONFIG_LV_USE_MONKEY is not set
# CONFIG_LV_USE_GRIDNAV is not set
# CONFIG_LV_USE_FRAGMENT is not set
# CONFIG_LV_USE_IMGFONT is not set
CONFIG_LV_USE_OBSERVER=y
# CONFIG_LV_USE_IME_PINYIN is not set
# CONFIG_LV_USE_FILE_EXPLORER is not set
# end of Others
#
# Devices
#
# CONFIG_LV_USE_SDL is not set
# CONFIG_LV_USE_X11 is not set
# CONFIG_LV_USE_WAYLAND is not set
# CONFIG_LV_USE_LINUX_FBDEV is not set
# CONFIG_LV_USE_NUTTX is not set
# CONFIG_LV_USE_LINUX_DRM is not set
# CONFIG_LV_USE_TFT_ESPI is not set
# CONFIG_LV_USE_EVDEV is not set
# CONFIG_LV_USE_LIBINPUT is not set
# CONFIG_LV_USE_ST7735 is not set
# CONFIG_LV_USE_ST7789 is not set
# CONFIG_LV_USE_ST7796 is not set
# CONFIG_LV_USE_ILI9341 is not set
# CONFIG_LV_USE_GENERIC_MIPI is not set
# CONFIG_LV_USE_RENESAS_GLCDC is not set
# CONFIG_LV_USE_OPENGLES is not set
# CONFIG_LV_USE_QNX is not set
# end of Devices
#
# Examples
#
CONFIG_LV_BUILD_EXAMPLES=y
# end of Examples
#
# Demos
#
# CONFIG_LV_USE_DEMO_WIDGETS is not set
# CONFIG_LV_USE_DEMO_KEYPAD_AND_ENCODER is not set
# CONFIG_LV_USE_DEMO_RENDER is not set
# CONFIG_LV_USE_DEMO_SCROLL is not set
# CONFIG_LV_USE_DEMO_STRESS is not set
# CONFIG_LV_USE_DEMO_MUSIC is not set
# CONFIG_LV_USE_DEMO_FLEX_LAYOUT is not set
# CONFIG_LV_USE_DEMO_MULTILANG is not set
# end of Demos
# end of LVGL configuration
# end of Component config
# CONFIG_IDF_EXPERIMENTAL_FEATURES is not set
# Deprecated options for backward compatibility
# CONFIG_APP_BUILD_TYPE_ELF_RAM is not set
# CONFIG_NO_BLOBS is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_NONE is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_ERROR is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_WARN is not set
CONFIG_LOG_BOOTLOADER_LEVEL_INFO=y
# CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE is not set
CONFIG_LOG_BOOTLOADER_LEVEL=3
# CONFIG_APP_ROLLBACK_ENABLE is not set
# CONFIG_FLASH_ENCRYPTION_ENABLED is not set
# CONFIG_FLASHMODE_QIO is not set
# CONFIG_FLASHMODE_QOUT is not set
CONFIG_FLASHMODE_DIO=y
# CONFIG_FLASHMODE_DOUT is not set
CONFIG_MONITOR_BAUD=115200
CONFIG_OPTIMIZATION_LEVEL_DEBUG=y
CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG=y
CONFIG_COMPILER_OPTIMIZATION_DEFAULT=y
# CONFIG_OPTIMIZATION_LEVEL_RELEASE is not set
# CONFIG_COMPILER_OPTIMIZATION_LEVEL_RELEASE is not set
CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED=y
# CONFIG_OPTIMIZATION_ASSERTIONS_SILENT is not set
# CONFIG_OPTIMIZATION_ASSERTIONS_DISABLED is not set
CONFIG_OPTIMIZATION_ASSERTION_LEVEL=2
# CONFIG_CXX_EXCEPTIONS is not set
CONFIG_STACK_CHECK_NONE=y
# CONFIG_STACK_CHECK_NORM is not set
# CONFIG_STACK_CHECK_STRONG is not set
# CONFIG_STACK_CHECK_ALL is not set
# CONFIG_WARN_WRITE_STRINGS is not set
# CONFIG_ESP32_APPTRACE_DEST_TRAX is not set
CONFIG_ESP32_APPTRACE_DEST_NONE=y
CONFIG_ESP32_APPTRACE_LOCK_ENABLE=y
# CONFIG_EXTERNAL_COEX_ENABLE is not set
# CONFIG_ESP_WIFI_EXTERNAL_COEXIST_ENABLE is not set
# CONFIG_MCPWM_ISR_IN_IRAM is not set
# CONFIG_EVENT_LOOP_PROFILING is not set
CONFIG_POST_EVENTS_FROM_ISR=y
CONFIG_POST_EVENTS_FROM_IRAM_ISR=y
CONFIG_GDBSTUB_SUPPORT_TASKS=y
CONFIG_GDBSTUB_MAX_TASKS=32
# CONFIG_OTA_ALLOW_HTTP is not set
CONFIG_ESP32S3_DEEP_SLEEP_WAKEUP_DELAY=2000
CONFIG_ESP_SLEEP_DEEP_SLEEP_WAKEUP_DELAY=2000
CONFIG_ESP32S3_RTC_CLK_SRC_INT_RC=y
# CONFIG_ESP32S3_RTC_CLK_SRC_EXT_CRYS is not set
# CONFIG_ESP32S3_RTC_CLK_SRC_EXT_OSC is not set
# CONFIG_ESP32S3_RTC_CLK_SRC_INT_8MD256 is not set
CONFIG_ESP32S3_RTC_CLK_CAL_CYCLES=1024
CONFIG_ESP32_PHY_CALIBRATION_AND_DATA_STORAGE=y
# CONFIG_ESP32_PHY_INIT_DATA_IN_PARTITION is not set
CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER=20
CONFIG_ESP32_PHY_MAX_TX_POWER=20
# CONFIG_REDUCE_PHY_TX_POWER is not set
# CONFIG_ESP32_REDUCE_PHY_TX_POWER is not set
CONFIG_ESP_SYSTEM_PM_POWER_DOWN_CPU=y
CONFIG_PM_POWER_DOWN_TAGMEM_IN_LIGHT_SLEEP=y
CONFIG_ESP32S3_SPIRAM_SUPPORT=y
CONFIG_DEFAULT_PSRAM_CLK_IO=30
CONFIG_DEFAULT_PSRAM_CS_IO=26
# CONFIG_ESP32S3_DEFAULT_CPU_FREQ_80 is not set
# CONFIG_ESP32S3_DEFAULT_CPU_FREQ_160 is not set
CONFIG_ESP32S3_DEFAULT_CPU_FREQ_240=y
CONFIG_ESP32S3_DEFAULT_CPU_FREQ_MHZ=240
CONFIG_SYSTEM_EVENT_QUEUE_SIZE=32
CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE=2304
CONFIG_MAIN_TASK_STACK_SIZE=3584
CONFIG_CONSOLE_UART_DEFAULT=y
# CONFIG_CONSOLE_UART_CUSTOM is not set
# CONFIG_CONSOLE_UART_NONE is not set
# CONFIG_ESP_CONSOLE_UART_NONE is not set
CONFIG_CONSOLE_UART=y
CONFIG_CONSOLE_UART_NUM=0
CONFIG_CONSOLE_UART_BAUDRATE=115200
CONFIG_INT_WDT=y
CONFIG_INT_WDT_TIMEOUT_MS=300
CONFIG_INT_WDT_CHECK_CPU1=y
CONFIG_TASK_WDT=y
CONFIG_ESP_TASK_WDT=y
# CONFIG_TASK_WDT_PANIC is not set
CONFIG_TASK_WDT_TIMEOUT_S=5
CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0=y
CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1=y
# CONFIG_ESP32_DEBUG_STUBS_ENABLE is not set
CONFIG_ESP32S3_DEBUG_OCDAWARE=y
CONFIG_BROWNOUT_DET=y
CONFIG_ESP32S3_BROWNOUT_DET=y
CONFIG_ESP32S3_BROWNOUT_DET=y
CONFIG_BROWNOUT_DET_LVL_SEL_7=y
CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_7=y
# CONFIG_BROWNOUT_DET_LVL_SEL_6 is not set
# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_6 is not set
# CONFIG_BROWNOUT_DET_LVL_SEL_5 is not set
# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_5 is not set
# CONFIG_BROWNOUT_DET_LVL_SEL_4 is not set
# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_4 is not set
# CONFIG_BROWNOUT_DET_LVL_SEL_3 is not set
# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_3 is not set
# CONFIG_BROWNOUT_DET_LVL_SEL_2 is not set
# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_2 is not set
# CONFIG_BROWNOUT_DET_LVL_SEL_1 is not set
# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_1 is not set
CONFIG_BROWNOUT_DET_LVL=7
CONFIG_ESP32S3_BROWNOUT_DET_LVL=7
CONFIG_IPC_TASK_STACK_SIZE=1280
CONFIG_TIMER_TASK_STACK_SIZE=3584
CONFIG_ESP32_WIFI_ENABLED=y
CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM=10
CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=32
CONFIG_ESP32_WIFI_STATIC_TX_BUFFER=y
CONFIG_ESP32_WIFI_TX_BUFFER_TYPE=0
CONFIG_ESP32_WIFI_STATIC_TX_BUFFER_NUM=16
CONFIG_ESP32_WIFI_CACHE_TX_BUFFER_NUM=32
# CONFIG_ESP32_WIFI_CSI_ENABLED is not set
CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED=y
CONFIG_ESP32_WIFI_TX_BA_WIN=6
CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y
CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y
CONFIG_ESP32_WIFI_RX_BA_WIN=6
CONFIG_ESP32_WIFI_RX_BA_WIN=6
# CONFIG_ESP32_WIFI_AMSDU_TX_ENABLED is not set
CONFIG_ESP32_WIFI_NVS_ENABLED=y
CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0=y
# CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1 is not set
CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN=752
CONFIG_ESP32_WIFI_MGMT_SBUF_NUM=32
CONFIG_ESP32_WIFI_IRAM_OPT=y
CONFIG_ESP32_WIFI_RX_IRAM_OPT=y
CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE=y
CONFIG_ESP32_WIFI_ENABLE_WPA3_OWE_STA=y
CONFIG_WPA_MBEDTLS_CRYPTO=y
CONFIG_WPA_MBEDTLS_TLS_CLIENT=y
# CONFIG_WPA_WAPI_PSK is not set
# CONFIG_WPA_SUITE_B_192 is not set
# CONFIG_WPA_11KV_SUPPORT is not set
# CONFIG_WPA_MBO_SUPPORT is not set
# CONFIG_WPA_DPP_SUPPORT is not set
# CONFIG_WPA_11R_SUPPORT is not set
# CONFIG_WPA_WPS_SOFTAP_REGISTRAR is not set
# CONFIG_WPA_WPS_STRICT is not set
# CONFIG_WPA_DEBUG_PRINT is not set
# CONFIG_WPA_TESTING_OPTIONS is not set
# CONFIG_ESP32_ENABLE_COREDUMP_TO_FLASH is not set
# CONFIG_ESP32_ENABLE_COREDUMP_TO_UART is not set
CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE=y
CONFIG_TIMER_TASK_PRIORITY=1
CONFIG_TIMER_TASK_STACK_DEPTH=2048
CONFIG_TIMER_QUEUE_LENGTH=10
# CONFIG_ENABLE_STATIC_TASK_CLEAN_UP_HOOK is not set
# CONFIG_HAL_ASSERTION_SILIENT is not set
# CONFIG_L2_TO_L3_COPY is not set
CONFIG_ESP_GRATUITOUS_ARP=y
CONFIG_GARP_TMR_INTERVAL=60
CONFIG_TCPIP_RECVMBOX_SIZE=32
CONFIG_TCP_MAXRTX=12
CONFIG_TCP_SYNMAXRTX=12
CONFIG_TCP_MSS=1440
CONFIG_TCP_MSL=60000
CONFIG_TCP_SND_BUF_DEFAULT=5760
CONFIG_TCP_WND_DEFAULT=5760
CONFIG_TCP_RECVMBOX_SIZE=6
CONFIG_TCP_QUEUE_OOSEQ=y
CONFIG_TCP_OVERSIZE_MSS=y
# CONFIG_TCP_OVERSIZE_QUARTER_MSS is not set
# CONFIG_TCP_OVERSIZE_DISABLE is not set
CONFIG_UDP_RECVMBOX_SIZE=6
CONFIG_TCPIP_TASK_STACK_SIZE=3072
CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY=y
# CONFIG_TCPIP_TASK_AFFINITY_CPU0 is not set
# CONFIG_TCPIP_TASK_AFFINITY_CPU1 is not set
CONFIG_TCPIP_TASK_AFFINITY=0x7FFFFFFF
# CONFIG_PPP_SUPPORT is not set
CONFIG_ESP32S3_TIME_SYSCALL_USE_RTC_SYSTIMER=y
CONFIG_ESP32S3_TIME_SYSCALL_USE_RTC_FRC1=y
# CONFIG_ESP32S3_TIME_SYSCALL_USE_RTC is not set
# CONFIG_ESP32S3_TIME_SYSCALL_USE_SYSTIMER is not set
# CONFIG_ESP32S3_TIME_SYSCALL_USE_FRC1 is not set
# CONFIG_ESP32S3_TIME_SYSCALL_USE_NONE is not set
CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT=5
CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072
CONFIG_ESP32_PTHREAD_STACK_MIN=768
CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY=y
# CONFIG_ESP32_DEFAULT_PTHREAD_CORE_0 is not set
# CONFIG_ESP32_DEFAULT_PTHREAD_CORE_1 is not set
CONFIG_ESP32_PTHREAD_TASK_CORE_DEFAULT=-1
CONFIG_ESP32_PTHREAD_TASK_NAME_DEFAULT="pthread"
CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS=y
# CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_FAILS is not set
# CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED is not set
CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT=y
CONFIG_SUPPORT_TERMIOS=y
CONFIG_SEMIHOSTFS_MAX_MOUNT_POINTS=1
# End of deprecated options
|
0015/LVGL_Joystick
| 77,022 |
examples/espidf_example/sdkconfig.wt32sc01plus
|
#
# Automatically generated file. DO NOT EDIT.
# Espressif IoT Development Framework (ESP-IDF) 5.3.0 Project Configuration
#
CONFIG_SOC_MPU_MIN_REGION_SIZE=0x20000000
CONFIG_SOC_MPU_REGIONS_MAX_NUM=8
CONFIG_SOC_ADC_SUPPORTED=y
CONFIG_SOC_UART_SUPPORTED=y
CONFIG_SOC_PCNT_SUPPORTED=y
CONFIG_SOC_PHY_SUPPORTED=y
CONFIG_SOC_WIFI_SUPPORTED=y
CONFIG_SOC_TWAI_SUPPORTED=y
CONFIG_SOC_GDMA_SUPPORTED=y
CONFIG_SOC_AHB_GDMA_SUPPORTED=y
CONFIG_SOC_GPTIMER_SUPPORTED=y
CONFIG_SOC_LCDCAM_SUPPORTED=y
CONFIG_SOC_MCPWM_SUPPORTED=y
CONFIG_SOC_DEDICATED_GPIO_SUPPORTED=y
CONFIG_SOC_CACHE_SUPPORT_WRAP=y
CONFIG_SOC_ULP_SUPPORTED=y
CONFIG_SOC_ULP_FSM_SUPPORTED=y
CONFIG_SOC_RISCV_COPROC_SUPPORTED=y
CONFIG_SOC_BT_SUPPORTED=y
CONFIG_SOC_USB_OTG_SUPPORTED=y
CONFIG_SOC_USB_SERIAL_JTAG_SUPPORTED=y
CONFIG_SOC_CCOMP_TIMER_SUPPORTED=y
CONFIG_SOC_ASYNC_MEMCPY_SUPPORTED=y
CONFIG_SOC_SUPPORTS_SECURE_DL_MODE=y
CONFIG_SOC_EFUSE_KEY_PURPOSE_FIELD=y
CONFIG_SOC_EFUSE_SUPPORTED=y
CONFIG_SOC_SDMMC_HOST_SUPPORTED=y
CONFIG_SOC_RTC_FAST_MEM_SUPPORTED=y
CONFIG_SOC_RTC_SLOW_MEM_SUPPORTED=y
CONFIG_SOC_RTC_MEM_SUPPORTED=y
CONFIG_SOC_PSRAM_DMA_CAPABLE=y
CONFIG_SOC_XT_WDT_SUPPORTED=y
CONFIG_SOC_I2S_SUPPORTED=y
CONFIG_SOC_RMT_SUPPORTED=y
CONFIG_SOC_SDM_SUPPORTED=y
CONFIG_SOC_GPSPI_SUPPORTED=y
CONFIG_SOC_LEDC_SUPPORTED=y
CONFIG_SOC_I2C_SUPPORTED=y
CONFIG_SOC_SYSTIMER_SUPPORTED=y
CONFIG_SOC_SUPPORT_COEXISTENCE=y
CONFIG_SOC_TEMP_SENSOR_SUPPORTED=y
CONFIG_SOC_AES_SUPPORTED=y
CONFIG_SOC_MPI_SUPPORTED=y
CONFIG_SOC_SHA_SUPPORTED=y
CONFIG_SOC_HMAC_SUPPORTED=y
CONFIG_SOC_DIG_SIGN_SUPPORTED=y
CONFIG_SOC_FLASH_ENC_SUPPORTED=y
CONFIG_SOC_SECURE_BOOT_SUPPORTED=y
CONFIG_SOC_MEMPROT_SUPPORTED=y
CONFIG_SOC_TOUCH_SENSOR_SUPPORTED=y
CONFIG_SOC_BOD_SUPPORTED=y
CONFIG_SOC_CLK_TREE_SUPPORTED=y
CONFIG_SOC_MPU_SUPPORTED=y
CONFIG_SOC_WDT_SUPPORTED=y
CONFIG_SOC_SPI_FLASH_SUPPORTED=y
CONFIG_SOC_RNG_SUPPORTED=y
CONFIG_SOC_LIGHT_SLEEP_SUPPORTED=y
CONFIG_SOC_DEEP_SLEEP_SUPPORTED=y
CONFIG_SOC_LP_PERIPH_SHARE_INTERRUPT=y
CONFIG_SOC_PM_SUPPORTED=y
CONFIG_SOC_XTAL_SUPPORT_40M=y
CONFIG_SOC_APPCPU_HAS_CLOCK_GATING_BUG=y
CONFIG_SOC_ADC_RTC_CTRL_SUPPORTED=y
CONFIG_SOC_ADC_DIG_CTRL_SUPPORTED=y
CONFIG_SOC_ADC_ARBITER_SUPPORTED=y
CONFIG_SOC_ADC_DIG_IIR_FILTER_SUPPORTED=y
CONFIG_SOC_ADC_MONITOR_SUPPORTED=y
CONFIG_SOC_ADC_DMA_SUPPORTED=y
CONFIG_SOC_ADC_PERIPH_NUM=2
CONFIG_SOC_ADC_MAX_CHANNEL_NUM=10
CONFIG_SOC_ADC_ATTEN_NUM=4
CONFIG_SOC_ADC_DIGI_CONTROLLER_NUM=2
CONFIG_SOC_ADC_PATT_LEN_MAX=24
CONFIG_SOC_ADC_DIGI_MIN_BITWIDTH=12
CONFIG_SOC_ADC_DIGI_MAX_BITWIDTH=12
CONFIG_SOC_ADC_DIGI_RESULT_BYTES=4
CONFIG_SOC_ADC_DIGI_DATA_BYTES_PER_CONV=4
CONFIG_SOC_ADC_DIGI_IIR_FILTER_NUM=2
CONFIG_SOC_ADC_DIGI_MONITOR_NUM=2
CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_HIGH=83333
CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_LOW=611
CONFIG_SOC_ADC_RTC_MIN_BITWIDTH=12
CONFIG_SOC_ADC_RTC_MAX_BITWIDTH=12
CONFIG_SOC_ADC_CALIBRATION_V1_SUPPORTED=y
CONFIG_SOC_ADC_SELF_HW_CALI_SUPPORTED=y
CONFIG_SOC_ADC_SHARED_POWER=y
CONFIG_SOC_APB_BACKUP_DMA=y
CONFIG_SOC_BROWNOUT_RESET_SUPPORTED=y
CONFIG_SOC_CACHE_WRITEBACK_SUPPORTED=y
CONFIG_SOC_CACHE_FREEZE_SUPPORTED=y
CONFIG_SOC_CPU_CORES_NUM=2
CONFIG_SOC_CPU_INTR_NUM=32
CONFIG_SOC_CPU_HAS_FPU=y
CONFIG_SOC_HP_CPU_HAS_MULTIPLE_CORES=y
CONFIG_SOC_CPU_BREAKPOINTS_NUM=2
CONFIG_SOC_CPU_WATCHPOINTS_NUM=2
CONFIG_SOC_CPU_WATCHPOINT_MAX_REGION_SIZE=64
CONFIG_SOC_DS_SIGNATURE_MAX_BIT_LEN=4096
CONFIG_SOC_DS_KEY_PARAM_MD_IV_LENGTH=16
CONFIG_SOC_DS_KEY_CHECK_MAX_WAIT_US=1100
CONFIG_SOC_AHB_GDMA_VERSION=1
CONFIG_SOC_GDMA_NUM_GROUPS_MAX=1
CONFIG_SOC_GDMA_PAIRS_PER_GROUP=5
CONFIG_SOC_GDMA_PAIRS_PER_GROUP_MAX=5
CONFIG_SOC_AHB_GDMA_SUPPORT_PSRAM=y
CONFIG_SOC_GPIO_PORT=1
CONFIG_SOC_GPIO_PIN_COUNT=49
CONFIG_SOC_GPIO_SU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OC_I2S_SUPPORTS_PDM_RX=y
CONFIG_SOC_I2S_PDM_MAX_RX_LINES=4
CONFIG_SOC_I2S_SUPPORTS_TDM=y
CONFIG_SOC_LEDC_SUPPORT_APB_CLOCK=y
CONFIG_SOC_LEDC_SUPPORT_XTAL_CLOCK=y
CONFIG_SOC_LEDC_CHANNEL_NUM=8
CONFIG_SOC_LEDC_TIMER_BIT_WIDTH=14
CONFIG_SOC_LEDC_SUPPORT_FADE_STOP=y
CONFIG_SOC_MCPWM_GROUPS=2
CONFIG_SOC_MCPWM_TIMERS_PER_GROUP=3
CONFIG_SOC_MCPWM_OPERATORS_PER_GROUP=3
CONFIG_SOC_MCPWM_COMPARATORS_PER_OPERATOR=2
CONFIG_SOC_MCPWM_GENERATORS_PER_OPERATOR=2
CONFIG_SOC_MCPWM_TRIGGERS_PER_OPERATOR=2
CONFIG_SOC_MCPWM_GPIO_FAULTS_PER_GROUP=3
CONFIG_SOC_MCPWM_CAPTURE_TIMERS_PER_GROUP=y
CONFIG_SOC_MCPWM_CAPTURE_CHANNELS_PER_TIMER=3
CONFIG_SOC_MCPWM_GPIO_SYNCHROS_PER_GROUP=3
CONFIG_SOC_MCPWM_SWSYNC_CAN_PROPAGATE=y
CONFIG_SOC_MMU_LINEAR_ADDRESS_REGION_NUM=1
CONFIG_SOC_MMU_PERIPH_NUM=1
CONFIG_SOC_PCNT_GROUPS=1
CONFIG_SOC_PCNT_UNITS_PER_GROUP=4
CONFIG_SOC_PCNT_CHANNELS_PER_UNIT=2
CONFIG_SOC_PCNT_THRES_POINT_PER_UNIT=2
CONFIG_SOC_RMT_GROUPS=1
CONFIG_SOC_RMT_TX_CANDIDATES_PER_GROUP=4
CONFIG_SOC_RMT_RX_CANDIDATES_PER_GROUP=4
CONFIG_SOC_RMT_CHANNELS_PER_GROUP=8
CONFIG_SOC_RMT_MEM_WORDS_PER_CHANNEL=48
CONFIG_SOC_RMT_SUPPORT_RX_PINGPONG=y
CONFIG_SOC_RMT_SUPPORT_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_SIG=y
CONFIG_SOC_SPI_SUPPORT_CONTINUOUS_TRANS=y
CONFIG_SOC_SPI_SUPPORT_SLAVE_HD_VER2=y
CONFIG_SOC_SPI_SUPPORT_CLK_APB=y
CONFIG_SOC_SPI_SUPPORT_CLK_XTAL=y
CONFIG_SOC_SPI_PERIPH_SUPPORT_CONTROL_DUMMY_OUT=y
CONFIG_SOC_MEMSPI_IS_INDEPENDENT=y
CONFIG_SOC_SPI_MAX_PRE_DIVIDER=16
CONFIG_SOC_SPI_SUPPORT_OCT=y
CONFIG_SOC_SPI_SCT_SUPPORTED=y
CONFIG_SOC_SPI_SCT_REG_NUM=14
CONFIG_SOC_SPI_SCT_BUFFER_NUM_MAX=y
CONFIG_SOC_SPI_SCT_CONF_BITLEN_MAX=0x3FFFA
CONFIG_SOC_MEMSPI_SRC_FREQ_120M=y
CONFIG_SOC_MEMSPI_SRC_FREQ_80M_SUPPORTED=y
CONFIG_SOC_MEMSPI_SRC_FREQ_40M_SUPPORTED=y
CONFIG_SOC_MEMSPI_SRC_FREQ_20M_SUPPORTED=y
CONFIG_SOC_SPIRAM_SUPPORTED=y
CONFIG_SOC_SPIRAM_XIP_SUPPORTED=y
CONFIG_SOC_SYSTIMER_COUNTER_NUM=2
CONFIG_SOC_SYSTIMER_ALARM_NUM=3
CONFIG_SOC_SYSTIMER_BIT_WIDTH_LO=32
CONFIG_SOC_SYSTIMER_BIT_WIDTH_HI=20
CONFIG_SOC_SYSTIMER_FIXED_DIVIDER=y
CONFIG_SOC_SYSTIMER_INT_LEVEL=y
CONFIG_SOC_SYSTIMER_ALARM_MISS_COMPENSATE=y
CONFIG_SOC_TIMER_GROUPS=2
CONFIG_SOC_TIMER_GROUP_TIMERS_PER_GROUP=2
CONFIG_SOC_TIMER_GROUP_COUNTER_BIT_WIDTH=54
CONFIG_SOC_TIMER_GROUP_SUPPORT_XTAL=y
CONFIG_SOC_TIMER_GROUP_SUPPORT_APB=y
CONFIG_SOC_TIMER_GROUP_TOTAL_TIMERS=4
CONFIG_SOC_TOUCH_SENSOR_VERSION=2
CONFIG_SOC_TOUCH_SENSOR_NUM=15
CONFIG_SOC_TOUCH_PROXIMITY_CHANNEL_NUM=3
CONFIG_SOC_TOUCH_PROXIMITY_MEAS_DONE_SUPPORTED=y
CONFIG_SOC_TOUCH_SAMPLER_NUM=1
CONFIG_SOC_TWAI_CONTROLLER_NUM=1
CONFIG_SOC_TWAI_CLK_SUPPORT_APB=y
CONFIG_SOC_TWAI_BRP_MIN=2
CONFIG_SOC_TWAI_BRP_MAX=16384
CONFIG_SOC_TWAI_SUPPORTS_RX_STATUS=y
CONFIG_SOC_UART_NUM=3
CONFIG_SOC_UART_HP_NUM=3
CONFIG_SOC_UART_FIFO_LEN=128
CONFIG_SOC_UART_BITRATE_MAX=5000000
CONFIG_SOC_UART_SUPPORT_FSM_TX_WAIT_SEND=y
CONFIG_SOC_UART_SUPPORT_WAKEUP_INT=y
CONFIG_SOC_UART_SUPPORT_APB_CLK=y
CONFIG_SOC_UART_SUPPORT_RTC_CLK=y
CONFIG_SOC_UART_SUPPORT_XTAL_CLK=y
CONFIG_SOC_USB_OTG_PERIPH_NUM=1
CONFIG_SOC_SHA_DMA_MAX_BUFFER_SIZE=3968
CONFIG_SOC_SHA_SUPPORT_DMA=y
CONFIG_SOC_SHA_SUPPORT_RESUME=y
CONFIG_SOC_SHA_GDMA=y
CONFIG_SOC_SHA_SUPPORT_SHA1=y
CONFIG_SOC_SHA_SUPPORT_SHA224=y
CONFIG_SOC_SHA_SUPPORT_SHA256=y
CONFIG_SOC_SHA_SUPPORT_SHA384=y
CONFIG_SOC_SHA_SUPPORT_SHA512=y
CONFIG_SOC_SHA_SUPPORT_SHA512_224=y
CONFIG_SOC_SHA_SUPPORT_SHA512_256=y
CONFIG_SOC_SHA_SUPPORT_SHA512_T=y
CONFIG_SOC_MPI_MEM_BLOCKS_NUM=4
CONFIG_SOC_MPI_OPERATIONS_NUM=3
CONFIG_SOC_RSA_MAX_BIT_LEN=4096
CONFIG_SOC_AES_SUPPORT_DMA=y
CONFIG_SOC_AES_GDMA=y
CONFIG_SOC_AES_SUPPORT_AES_128=y
CONFIG_SOC_AES_SUPPORT_AES_256=y
CONFIG_SOC_PM_SUPPORT_EXT0_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_EXT1_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_EXT_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_WIFI_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_BT_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_CPU_PD=y
CONFIG_SOC_PM_SUPPORT_TAGMEM_PD=y
CONFIG_SOC_PM_SUPPORT_RTC_PERIPH_PD=y
CONFIG_SOC_PM_SUPPORT_RC_FAST_PD=y
CONFIG_SOC_PM_SUPPORT_VDDSDIO_PD=y
CONFIG_SOC_PM_SUPPORT_MAC_BB_PD=y
CONFIG_SOC_PM_SUPPORT_MODEM_PD=y
CONFIG_SOC_CONFIGURABLE_VDDSDIO_SUPPORTED=y
CONFIG_SOC_PM_SUPPORT_DEEPSLEEP_CHECK_STUB_ONLY=y
CONFIG_SOC_PM_CPU_RETENTION_BY_RTCCNTL=y
CONFIG_SOC_PM_MODEM_RETENTION_BY_BACKUPDMA=y
CONFIG_SOC_CLK_RC_FAST_D256_SUPPORTED=y
CONFIG_SOC_RTC_SLOW_CLK_SUPPORT_RC_FAST_D256=y
CONFIG_SOC_CLK_RC_FAST_SUPPORT_CALIBRATION=y
CONFIG_SOC_CLK_XTAL32K_SUPPORTED=y
CONFIG_SOC_EFUSE_DIS_DOWNLOAD_ICACHE=y
CONFIG_SOC_EFUSE_DIS_DOWNLOAD_DCACHE=y
CONFIG_SOC_EFUSE_HARD_DIS_JTAG=y
CONFIG_SOC_EFUSE_DIS_USB_JTAG=y
CONFIG_SOC_EFUSE_SOFT_DIS_JTAG=y
CONFIG_SOC_EFUSE_DIS_DIRECT_BOOT=y
CONFIG_SOC_EFUSE_DIS_ICACHE=y
CONFIG_SOC_EFUSE_BLOCK9_KEY_PURPOSE_QUIRK=y
CONFIG_SOC_SECURE_BOOT_V2_RSA=y
CONFIG_SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS=3
CONFIG_SOC_EFUSE_REVOKE_BOOT_KEY_DIGESTS=y
CONFIG_SOC_SUPPORT_SECURE_BOOT_REVOKE_KEY=y
CONFIG_SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX=64
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES=y
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_OPTIONS=y
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_128=y
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_256=y
CONFIG_SOC_MEMPROT_CPU_PREFETCH_PAD_SIZE=16
CONFIG_SOC_MEMPROT_MEM_ALIGN_SIZE=256
CONFIG_SOC_PHY_DIG_REGS_MEM_SIZE=21
CONFIG_SOC_MAC_BB_PD_MEM_SIZE=192
CONFIG_SOC_WIFI_LIGHT_SLEEP_CLK_WIDTH=12
CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_WAIT_IDLE=y
CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_SUSPEND=y
CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_RESUME=y
CONFIG_SOC_SPI_MEM_SUPPORT_SW_SUSPEND=y
CONFIG_SOC_SPI_MEM_SUPPORT_OPI_MODE=y
CONFIG_SOC_SPI_MEM_SUPPORT_TIMING_TUNING=y
CONFIG_SOC_SPI_MEM_SUPPORT_CONFIG_GPIO_BY_EFUSE=y
CONFIG_SOC_SPI_MEM_SUPPORT_WRAP=y
CONFIG_SOC_MEMSPI_TIMING_TUNING_BY_MSPI_DELAY=y
CONFIG_SOC_MEMSPI_CORE_CLK_SHARED_WITH_PSRAM=y
CONFIG_SOC_COEX_HW_PTI=y
CONFIG_SOC_EXTERNAL_COEX_LEADER_TX_LINE=y
CONFIG_SOC_SDMMC_USE_GPIO_MATRIX=y
CONFIG_SOC_SDMMC_NUM_SLOTS=2
CONFIG_SOC_SDMMC_SUPPORT_XTAL_CLOCK=y
CONFIG_SOC_SDMMC_DELAY_PHASE_NUM=4
CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_FAST_RC=y
CONFIG_SOC_WIFI_HW_TSF=y
CONFIG_SOC_WIFI_FTM_SUPPORT=y
CONFIG_SOC_WIFI_GCMP_SUPPORT=y
CONFIG_SOC_WIFI_WAPI_SUPPORT=y
CONFIG_SOC_WIFI_CSI_SUPPORT=y
CONFIG_SOC_WIFI_MESH_SUPPORT=y
CONFIG_SOC_WIFI_SUPPORT_VARIABLE_BEACON_WINDOW=y
CONFIG_SOC_WIFI_PHY_NEEDS_USB_WORKAROUND=y
CONFIG_SOC_BLE_SUPPORTED=y
CONFIG_SOC_BLE_MESH_SUPPORTED=y
CONFIG_SOC_BLE_50_SUPPORTED=y
CONFIG_SOC_BLE_DEVICE_PRIVACY_SUPPORTED=y
CONFIG_SOC_BLUFI_SUPPORTED=y
CONFIG_SOC_ULP_HAS_ADC=y
CONFIG_SOC_PHY_COMBO_MODULE=y
CONFIG_IDF_CMAKE=y
CONFIG_IDF_TOOLCHAIN="gcc"
CONFIG_IDF_TARGET_ARCH_XTENSA=y
CONFIG_IDF_TARGET_ARCH="xtensa"
CONFIG_IDF_TARGET="esp32s3"
CONFIG_IDF_INIT_VERSION="5.3.0"
CONFIG_IDF_TARGET_ESP32S3=y
CONFIG_IDF_FIRMWARE_CHIP_ID=0x0009
#
# Build type
#
CONFIG_APP_BUILD_TYPE_APP_2NDBOOT=y
# CONFIG_APP_BUILD_TYPE_RAM is not set
CONFIG_APP_BUILD_GENERATE_BINARIES=y
CONFIG_APP_BUILD_BOOTLOADER=y
CONFIG_APP_BUILD_USE_FLASH_SECTIONS=y
# CONFIG_APP_REPRODUCIBLE_BUILD is not set
# CONFIG_APP_NO_BLOBS is not set
# end of Build type
#
# Bootloader config
#
#
# Bootloader manager
#
CONFIG_BOOTLOADER_COMPILE_TIME_DATE=y
CONFIG_BOOTLOADER_PROJECT_VER=1
# end of Bootloader manager
CONFIG_BOOTLOADER_OFFSET_IN_FLASH=0x0
CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y
# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG is not set
# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_PERF is not set
# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_NONE is not set
# CONFIG_BOOTLOADER_LOG_LEVEL_NONE is not set
# CONFIG_BOOTLOADER_LOG_LEVEL_ERROR is not set
# CONFIG_BOOTLOADER_LOG_LEVEL_WARN is not set
CONFIG_BOOTLOADER_LOG_LEVEL_INFO=y
# CONFIG_BOOTLOADER_LOG_LEVEL_DEBUG is not set
# CONFIG_BOOTLOADER_LOG_LEVEL_VERBOSE is not set
CONFIG_BOOTLOADER_LOG_LEVEL=3
#
# Serial Flash Configurations
#
# CONFIG_BOOTLOADER_FLASH_DC_AWARE is not set
CONFIG_BOOTLOADER_FLASH_XMC_SUPPORT=y
# end of Serial Flash Configurations
CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_9V=y
# CONFIG_BOOTLOADER_FACTORY_RESET is not set
# CONFIG_BOOTLOADER_APP_TEST is not set
CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE=y
CONFIG_BOOTLOADER_WDT_ENABLE=y
# CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE is not set
CONFIG_BOOTLOADER_WDT_TIME_MS=9000
# CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE is not set
# CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP is not set
# CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON is not set
# CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS is not set
CONFIG_BOOTLOADER_RESERVE_RTC_SIZE=0
# CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC is not set
# end of Bootloader config
#
# Security features
#
CONFIG_SECURE_BOOT_V2_RSA_SUPPORTED=y
CONFIG_SECURE_BOOT_V2_PREFERRED=y
# CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT is not set
# CONFIG_SECURE_BOOT is not set
# CONFIG_SECURE_FLASH_ENC_ENABLED is not set
CONFIG_SECURE_ROM_DL_MODE_ENABLED=y
# end of Security features
#
# Application manager
#
CONFIG_APP_COMPILE_TIME_DATE=y
# CONFIG_APP_EXCLUDE_PROJECT_VER_VAR is not set
# CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR is not set
# CONFIG_APP_PROJECT_VER_FROM_CONFIG is not set
CONFIG_APP_RETRIEVE_LEN_ELF_SHA=9
# end of Application manager
CONFIG_ESP_ROM_HAS_CRC_LE=y
CONFIG_ESP_ROM_HAS_CRC_BE=y
CONFIG_ESP_ROM_HAS_MZ_CRC32=y
CONFIG_ESP_ROM_HAS_JPEG_DECODE=y
CONFIG_ESP_ROM_UART_CLK_IS_XTAL=y
CONFIG_ESP_ROM_HAS_RETARGETABLE_LOCKING=y
CONFIG_ESP_ROM_USB_OTG_NUM=3
CONFIG_ESP_ROM_USB_SERIAL_DEVICE_NUM=4
CONFIG_ESP_ROM_HAS_ERASE_0_REGION_BUG=y
CONFIG_ESP_ROM_HAS_ENCRYPTED_WRITES_USING_LEGACY_DRV=y
CONFIG_ESP_ROM_GET_CLK_FREQ=y
CONFIG_ESP_ROM_HAS_HAL_WDT=y
CONFIG_ESP_ROM_NEEDS_SWSETUP_WORKAROUND=y
CONFIG_ESP_ROM_HAS_LAYOUT_TABLE=y
CONFIG_ESP_ROM_HAS_SPI_FLASH=y
CONFIG_ESP_ROM_HAS_ETS_PRINTF_BUG=y
CONFIG_ESP_ROM_HAS_NEWLIB=y
CONFIG_ESP_ROM_HAS_NEWLIB_NANO_FORMAT=y
CONFIG_ESP_ROM_HAS_NEWLIB_32BIT_TIME=y
CONFIG_ESP_ROM_NEEDS_SET_CACHE_MMU_SIZE=y
CONFIG_ESP_ROM_RAM_APP_NEEDS_MMU_INIT=y
CONFIG_ESP_ROM_HAS_FLASH_COUNT_PAGES_BUG=y
CONFIG_ESP_ROM_HAS_CACHE_SUSPEND_WAITI_BUG=y
CONFIG_ESP_ROM_HAS_CACHE_WRITEBACK_BUG=y
CONFIG_ESP_ROM_HAS_SW_FLOAT=y
CONFIG_ESP_ROM_HAS_VERSION=y
CONFIG_ESP_ROM_SUPPORT_DEEP_SLEEP_WAKEUP_STUB=y
#
# Boot ROM Behavior
#
CONFIG_BOOT_ROM_LOG_ALWAYS_ON=y
# CONFIG_BOOT_ROM_LOG_ALWAYS_OFF is not set
# CONFIG_BOOT_ROM_LOG_ON_GPIO_HIGH is not set
# CONFIG_BOOT_ROM_LOG_ON_GPIO_LOW is not set
# end of Boot ROM Behavior
#
# Serial flasher config
#
# CONFIG_ESPTOOLPY_NO_STUB is not set
# CONFIG_ESPTOOLPY_OCT_FLASH is not set
CONFIG_ESPTOOLPY_FLASH_MODE_AUTO_DETECT=y
# CONFIG_ESPTOOLPY_FLASHMODE_QIO is not set
# CONFIG_ESPTOOLPY_FLASHMODE_QOUT is not set
CONFIG_ESPTOOLPY_FLASHMODE_DIO=y
# CONFIG_ESPTOOLPY_FLASHMODE_DOUT is not set
CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_STR=y
CONFIG_ESPTOOLPY_FLASHMODE="dio"
# CONFIG_ESPTOOLPY_FLASHFREQ_120M is not set
CONFIG_ESPTOOLPY_FLASHFREQ_80M=y
# CONFIG_ESPTOOLPY_FLASHFREQ_40M is not set
# CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set
CONFIG_ESPTOOLPY_FLASHFREQ_80M_DEFAULT=y
CONFIG_ESPTOOLPY_FLASHFREQ="80m"
# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE_2MB=y
# CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE="2MB"
# CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set
CONFIG_ESPTOOLPY_BEFORE_RESET=y
# CONFIG_ESPTOOLPY_BEFORE_NORESET is not set
CONFIG_ESPTOOLPY_BEFORE="default_reset"
CONFIG_ESPTOOLPY_AFTER_RESET=y
# CONFIG_ESPTOOLPY_AFTER_NORESET is not set
CONFIG_ESPTOOLPY_AFTER="hard_reset"
CONFIG_ESPTOOLPY_MONITOR_BAUD=115200
# end of Serial flasher config
#
# Partition Table
#
CONFIG_PARTITION_TABLE_SINGLE_APP=y
# CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set
# CONFIG_PARTITION_TABLE_TWO_OTA is not set
# CONFIG_PARTITION_TABLE_CUSTOM is not set
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions_singleapp.csv"
CONFIG_PARTITION_TABLE_OFFSET=0x8000
CONFIG_PARTITION_TABLE_MD5=y
# end of Partition Table
#
# Compiler options
#
CONFIG_COMPILER_OPTIMIZATION_DEBUG=y
# CONFIG_COMPILER_OPTIMIZATION_SIZE is not set
# CONFIG_COMPILER_OPTIMIZATION_PERF is not set
# CONFIG_COMPILER_OPTIMIZATION_NONE is not set
CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE=y
# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT is not set
# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE is not set
CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB=y
CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL=2
# CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT is not set
CONFIG_COMPILER_HIDE_PATHS_MACROS=y
# CONFIG_COMPILER_CXX_EXCEPTIONS is not set
# CONFIG_COMPILER_CXX_RTTI is not set
CONFIG_COMPILER_STACK_CHECK_MODE_NONE=y
# CONFIG_COMPILER_STACK_CHECK_MODE_NORM is not set
# CONFIG_COMPILER_STACK_CHECK_MODE_STRONG is not set
# CONFIG_COMPILER_STACK_CHECK_MODE_ALL is not set
# CONFIG_COMPILER_WARN_WRITE_STRINGS is not set
# CONFIG_COMPILER_DISABLE_GCC12_WARNINGS is not set
# CONFIG_COMPILER_DISABLE_GCC13_WARNINGS is not set
# CONFIG_COMPILER_DUMP_RTL_FILES is not set
CONFIG_COMPILER_RT_LIB_GCCLIB=y
CONFIG_COMPILER_RT_LIB_NAME="gcc"
# CONFIG_COMPILER_ORPHAN_SECTIONS_WARNING is not set
CONFIG_COMPILER_ORPHAN_SECTIONS_PLACE=y
# end of Compiler options
#
# Component config
#
#
# Application Level Tracing
#
# CONFIG_APPTRACE_DEST_JTAG is not set
CONFIG_APPTRACE_DEST_NONE=y
# CONFIG_APPTRACE_DEST_UART1 is not set
# CONFIG_APPTRACE_DEST_UART2 is not set
# CONFIG_APPTRACE_DEST_USB_CDC is not set
CONFIG_APPTRACE_DEST_UART_NONE=y
CONFIG_APPTRACE_UART_TASK_PRIO=1
CONFIG_APPTRACE_LOCK_ENABLE=y
# end of Application Level Tracing
#
# Bluetooth
#
# CONFIG_BT_ENABLED is not set
CONFIG_BT_ALARM_MAX_NUM=50
# end of Bluetooth
#
# Console Library
#
# CONFIG_CONSOLE_SORTED_HELP is not set
# end of Console Library
#
# Driver Configurations
#
#
# TWAI Configuration
#
# CONFIG_TWAI_ISR_IN_IRAM is not set
CONFIG_TWAI_ERRATA_FIX_LISTEN_ONLY_DOM=y
# end of TWAI Configuration
#
# Legacy ADC Driver Configuration
#
# CONFIG_ADC_SUPPRESS_DEPRECATE_WARN is not set
#
# Legacy ADC Calibration Configuration
#
# CONFIG_ADC_CALI_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy ADC Calibration Configuration
# end of Legacy ADC Driver Configuration
#
# Legacy MCPWM Driver Configurations
#
# CONFIG_MCPWM_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy MCPWM Driver Configurations
#
# Legacy Timer Group Driver Configurations
#
# CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy Timer Group Driver Configurations
#
# Legacy RMT Driver Configurations
#
# CONFIG_RMT_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy RMT Driver Configurations
#
# Legacy I2S Driver Configurations
#
# CONFIG_I2S_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy I2S Driver Configurations
#
# Legacy PCNT Driver Configurations
#
# CONFIG_PCNT_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy PCNT Driver Configurations
#
# Legacy SDM Driver Configurations
#
# CONFIG_SDM_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy SDM Driver Configurations
#
# Legacy Temperature Sensor Driver Configurations
#
# CONFIG_TEMP_SENSOR_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy Temperature Sensor Driver Configurations
# end of Driver Configurations
#
# eFuse Bit Manager
#
# CONFIG_EFUSE_CUSTOM_TABLE is not set
# CONFIG_EFUSE_VIRTUAL is not set
CONFIG_EFUSE_MAX_BLK_LEN=256
# end of eFuse Bit Manager
#
# ESP-TLS
#
CONFIG_ESP_TLS_USING_MBEDTLS=y
CONFIG_ESP_TLS_USE_DS_PERIPHERAL=y
# CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is not set
# CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is not set
# CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK is not set
# CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL is not set
# CONFIG_ESP_TLS_PSK_VERIFICATION is not set
# CONFIG_ESP_TLS_INSECURE is not set
# end of ESP-TLS
#
# ADC and ADC Calibration
#
# CONFIG_ADC_ONESHOT_CTRL_FUNC_IN_IRAM is not set
# CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is not set
# CONFIG_ADC_CONTINUOUS_FORCE_USE_ADC2_ON_C3_S3 is not set
# CONFIG_ADC_ENABLE_DEBUG_LOG is not set
# end of ADC and ADC Calibration
#
# Wireless Coexistence
#
CONFIG_ESP_COEX_ENABLED=y
# CONFIG_ESP_COEX_EXTERNAL_COEXIST_ENABLE is not set
# end of Wireless Coexistence
#
# Common ESP-related
#
CONFIG_ESP_ERR_TO_NAME_LOOKUP=y
# end of Common ESP-related
#
# ESP-Driver:GPIO Configurations
#
# CONFIG_GPIO_CTRL_FUNC_IN_IRAM is not set
# end of ESP-Driver:GPIO Configurations
#
# ESP-Driver:GPTimer Configurations
#
CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y
# CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is not set
# CONFIG_GPTIMER_ISR_IRAM_SAFE is not set
# CONFIG_GPTIMER_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:GPTimer Configurations
#
# ESP-Driver:I2C Configurations
#
# CONFIG_I2C_ISR_IRAM_SAFE is not set
# CONFIG_I2C_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:I2C Configurations
#
# ESP-Driver:I2S Configurations
#
# CONFIG_I2S_ISR_IRAM_SAFE is not set
# CONFIG_I2S_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:I2S Configurations
#
# ESP-Driver:LEDC Configurations
#
# CONFIG_LEDC_CTRL_FUNC_IN_IRAM is not set
# end of ESP-Driver:LEDC Configurations
#
# ESP-Driver:MCPWM Configurations
#
# CONFIG_MCPWM_ISR_IRAM_SAFE is not set
# CONFIG_MCPWM_CTRL_FUNC_IN_IRAM is not set
# CONFIG_MCPWM_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:MCPWM Configurations
#
# ESP-Driver:PCNT Configurations
#
# CONFIG_PCNT_CTRL_FUNC_IN_IRAM is not set
# CONFIG_PCNT_ISR_IRAM_SAFE is not set
# CONFIG_PCNT_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:PCNT Configurations
#
# ESP-Driver:RMT Configurations
#
# CONFIG_RMT_ISR_IRAM_SAFE is not set
# CONFIG_RMT_RECV_FUNC_IN_IRAM is not set
# CONFIG_RMT_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:RMT Configurations
#
# ESP-Driver:Sigma Delta Modulator Configurations
#
# CONFIG_SDM_CTRL_FUNC_IN_IRAM is not set
# CONFIG_SDM_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:Sigma Delta Modulator Configurations
#
# ESP-Driver:SPI Configurations
#
# CONFIG_SPI_MASTER_IN_IRAM is not set
CONFIG_SPI_MASTER_ISR_IN_IRAM=y
# CONFIG_SPI_SLAVE_IN_IRAM is not set
CONFIG_SPI_SLAVE_ISR_IN_IRAM=y
# end of ESP-Driver:SPI Configurations
#
# ESP-Driver:Temperature Sensor Configurations
#
# CONFIG_TEMP_SENSOR_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:Temperature Sensor Configurations
#
# ESP-Driver:UART Configurations
#
# CONFIG_UART_ISR_IN_IRAM is not set
# end of ESP-Driver:UART Configurations
#
# ESP-Driver:USB Serial/JTAG Configuration
#
CONFIG_USJ_ENABLE_USB_SERIAL_JTAG=y
# end of ESP-Driver:USB Serial/JTAG Configuration
#
# Ethernet
#
CONFIG_ETH_ENABLED=y
CONFIG_ETH_USE_SPI_ETHERNET=y
# CONFIG_ETH_SPI_ETHERNET_DM9051 is not set
# CONFIG_ETH_SPI_ETHERNET_W5500 is not set
# CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL is not set
# CONFIG_ETH_USE_OPENETH is not set
# CONFIG_ETH_TRANSMIT_MUTEX is not set
# end of Ethernet
#
# Event Loop Library
#
# CONFIG_ESP_EVENT_LOOP_PROFILING is not set
CONFIG_ESP_EVENT_POST_FROM_ISR=y
CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR=y
# end of Event Loop Library
#
# GDB Stub
#
CONFIG_ESP_GDBSTUB_ENABLED=y
# CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME is not set
CONFIG_ESP_GDBSTUB_SUPPORT_TASKS=y
CONFIG_ESP_GDBSTUB_MAX_TASKS=32
# end of GDB Stub
#
# ESP HTTP client
#
CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y
# CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH is not set
# CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH is not set
# CONFIG_ESP_HTTP_CLIENT_ENABLE_CUSTOM_TRANSPORT is not set
# end of ESP HTTP client
#
# HTTP Server
#
CONFIG_HTTPD_MAX_REQ_HDR_LEN=512
CONFIG_HTTPD_MAX_URI_LEN=512
CONFIG_HTTPD_ERR_RESP_NO_DELAY=y
CONFIG_HTTPD_PURGE_BUF_LEN=32
# CONFIG_HTTPD_LOG_PURGE_DATA is not set
# CONFIG_HTTPD_WS_SUPPORT is not set
# CONFIG_HTTPD_QUEUE_WORK_BLOCKING is not set
# end of HTTP Server
#
# ESP HTTPS OTA
#
# CONFIG_ESP_HTTPS_OTA_DECRYPT_CB is not set
# CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP is not set
# end of ESP HTTPS OTA
#
# ESP HTTPS server
#
# CONFIG_ESP_HTTPS_SERVER_ENABLE is not set
# end of ESP HTTPS server
#
# Hardware Settings
#
#
# Chip revision
#
CONFIG_ESP32S3_REV_MIN_0=y
# CONFIG_ESP32S3_REV_MIN_1 is not set
# CONFIG_ESP32S3_REV_MIN_2 is not set
CONFIG_ESP32S3_REV_MIN_FULL=0
CONFIG_ESP_REV_MIN_FULL=0
#
# Maximum Supported ESP32-S3 Revision (Rev v0.99)
#
CONFIG_ESP32S3_REV_MAX_FULL=99
CONFIG_ESP_REV_MAX_FULL=99
# end of Chip revision
#
# MAC Config
#
CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_STA=y
CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_AP=y
CONFIG_ESP_MAC_ADDR_UNIVERSE_BT=y
CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH=y
CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES_FOUR=y
CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES=4
# CONFIG_ESP32S3_UNIVERSAL_MAC_ADDRESSES_TWO is not set
CONFIG_ESP32S3_UNIVERSAL_MAC_ADDRESSES_FOUR=y
CONFIG_ESP32S3_UNIVERSAL_MAC_ADDRESSES=4
# CONFIG_ESP_MAC_USE_CUSTOM_MAC_AS_BASE_MAC is not set
# end of MAC Config
#
# Sleep Config
#
CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND=y
CONFIG_ESP_SLEEP_PSRAM_LEAKAGE_WORKAROUND=y
CONFIG_ESP_SLEEP_MSPI_NEED_ALL_IO_PU=y
CONFIG_ESP_SLEEP_RTC_BUS_ISO_WORKAROUND=y
CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND=y
CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY=2000
# CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION is not set
# CONFIG_ESP_SLEEP_DEBUG is not set
CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS=y
# end of Sleep Config
#
# RTC Clock Config
#
CONFIG_RTC_CLK_SRC_INT_RC=y
# CONFIG_RTC_CLK_SRC_EXT_CRYS is not set
# CONFIG_RTC_CLK_SRC_EXT_OSC is not set
# CONFIG_RTC_CLK_SRC_INT_8MD256 is not set
CONFIG_RTC_CLK_CAL_CYCLES=1024
# end of RTC Clock Config
#
# Peripheral Control
#
CONFIG_PERIPH_CTRL_FUNC_IN_IRAM=y
# end of Peripheral Control
#
# GDMA Configurations
#
CONFIG_GDMA_CTRL_FUNC_IN_IRAM=y
# CONFIG_GDMA_ISR_IRAM_SAFE is not set
# CONFIG_GDMA_ENABLE_DEBUG_LOG is not set
# end of GDMA Configurations
#
# Main XTAL Config
#
CONFIG_XTAL_FREQ_40=y
CONFIG_XTAL_FREQ=40
# end of Main XTAL Config
CONFIG_ESP_SPI_BUS_LOCK_ISR_FUNCS_IN_IRAM=y
# end of Hardware Settings
#
# LCD and Touch Panel
#
#
# LCD Touch Drivers are maintained in the IDF Component Registry
#
#
# LCD Peripheral Configuration
#
CONFIG_LCD_PANEL_IO_FORMAT_BUF_SIZE=32
# CONFIG_LCD_ENABLE_DEBUG_LOG is not set
# CONFIG_LCD_RGB_ISR_IRAM_SAFE is not set
# CONFIG_LCD_RGB_RESTART_IN_VSYNC is not set
# end of LCD Peripheral Configuration
# end of LCD and Touch Panel
#
# ESP NETIF Adapter
#
CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL=120
CONFIG_ESP_NETIF_TCPIP_LWIP=y
# CONFIG_ESP_NETIF_LOOPBACK is not set
CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y
# CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS is not set
# CONFIG_ESP_NETIF_L2_TAP is not set
# CONFIG_ESP_NETIF_BRIDGE_EN is not set
# end of ESP NETIF Adapter
#
# Partition API Configuration
#
# end of Partition API Configuration
#
# PHY
#
CONFIG_ESP_PHY_ENABLED=y
CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE=y
# CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION is not set
CONFIG_ESP_PHY_MAX_WIFI_TX_POWER=20
CONFIG_ESP_PHY_MAX_TX_POWER=20
# CONFIG_ESP_PHY_REDUCE_TX_POWER is not set
CONFIG_ESP_PHY_ENABLE_USB=y
# CONFIG_ESP_PHY_ENABLE_CERT_TEST is not set
CONFIG_ESP_PHY_RF_CAL_PARTIAL=y
# CONFIG_ESP_PHY_RF_CAL_NONE is not set
# CONFIG_ESP_PHY_RF_CAL_FULL is not set
CONFIG_ESP_PHY_CALIBRATION_MODE=0
# CONFIG_ESP_PHY_PLL_TRACK_DEBUG is not set
# end of PHY
#
# Power Management
#
# CONFIG_PM_ENABLE is not set
CONFIG_PM_POWER_DOWN_CPU_IN_LIGHT_SLEEP=y
CONFIG_PM_RESTORE_CACHE_TAGMEM_AFTER_LIGHT_SLEEP=y
# end of Power Management
#
# ESP PSRAM
#
CONFIG_SPIRAM=y
#
# SPI RAM config
#
CONFIG_SPIRAM_MODE_QUAD=y
# CONFIG_SPIRAM_MODE_OCT is not set
CONFIG_SPIRAM_TYPE_AUTO=y
# CONFIG_SPIRAM_TYPE_ESPPSRAM16 is not set
# CONFIG_SPIRAM_TYPE_ESPPSRAM32 is not set
# CONFIG_SPIRAM_TYPE_ESPPSRAM64 is not set
CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY=y
CONFIG_SPIRAM_CLK_IO=30
CONFIG_SPIRAM_CS_IO=26
# CONFIG_SPIRAM_XIP_FROM_PSRAM is not set
# CONFIG_SPIRAM_FETCH_INSTRUCTIONS is not set
# CONFIG_SPIRAM_RODATA is not set
# CONFIG_SPIRAM_SPEED_120M is not set
# CONFIG_SPIRAM_SPEED_80M is not set
CONFIG_SPIRAM_SPEED_40M=y
CONFIG_SPIRAM_SPEED=40
CONFIG_SPIRAM_BOOT_INIT=y
# CONFIG_SPIRAM_IGNORE_NOTFOUND is not set
# CONFIG_SPIRAM_USE_MEMMAP is not set
# CONFIG_SPIRAM_USE_CAPS_ALLOC is not set
CONFIG_SPIRAM_USE_MALLOC=y
CONFIG_SPIRAM_MEMTEST=y
CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=16384
# CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP is not set
CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL=32768
# CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY is not set
# end of SPI RAM config
# end of ESP PSRAM
#
# ESP Ringbuf
#
# CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH is not set
# end of ESP Ringbuf
#
# ESP System Settings
#
# CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_80 is not set
# CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160 is not set
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240=y
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=240
#
# Cache config
#
CONFIG_ESP32S3_INSTRUCTION_CACHE_16KB=y
# CONFIG_ESP32S3_INSTRUCTION_CACHE_32KB is not set
CONFIG_ESP32S3_INSTRUCTION_CACHE_SIZE=0x4000
# CONFIG_ESP32S3_INSTRUCTION_CACHE_4WAYS is not set
CONFIG_ESP32S3_INSTRUCTION_CACHE_8WAYS=y
CONFIG_ESP32S3_ICACHE_ASSOCIATED_WAYS=8
# CONFIG_ESP32S3_INSTRUCTION_CACHE_LINE_16B is not set
CONFIG_ESP32S3_INSTRUCTION_CACHE_LINE_32B=y
CONFIG_ESP32S3_INSTRUCTION_CACHE_LINE_SIZE=32
# CONFIG_ESP32S3_DATA_CACHE_16KB is not set
CONFIG_ESP32S3_DATA_CACHE_32KB=y
# CONFIG_ESP32S3_DATA_CACHE_64KB is not set
CONFIG_ESP32S3_DATA_CACHE_SIZE=0x8000
# CONFIG_ESP32S3_DATA_CACHE_4WAYS is not set
CONFIG_ESP32S3_DATA_CACHE_8WAYS=y
CONFIG_ESP32S3_DCACHE_ASSOCIATED_WAYS=8
# CONFIG_ESP32S3_DATA_CACHE_LINE_16B is not set
CONFIG_ESP32S3_DATA_CACHE_LINE_32B=y
# CONFIG_ESP32S3_DATA_CACHE_LINE_64B is not set
CONFIG_ESP32S3_DATA_CACHE_LINE_SIZE=32
# end of Cache config
#
# Memory
#
# CONFIG_ESP32S3_RTCDATA_IN_FAST_MEM is not set
# CONFIG_ESP32S3_USE_FIXED_STATIC_RAM_SIZE is not set
# end of Memory
#
# Trace memory
#
# CONFIG_ESP32S3_TRAX is not set
CONFIG_ESP32S3_TRACEMEM_RESERVE_DRAM=0x0
# end of Trace memory
# CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT is not set
CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT=y
# CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT is not set
# CONFIG_ESP_SYSTEM_PANIC_GDBSTUB is not set
CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS=0
CONFIG_ESP_SYSTEM_RTC_FAST_MEM_AS_HEAP_DEPCHECK=y
CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP=y
#
# Memory protection
#
CONFIG_ESP_SYSTEM_MEMPROT_FEATURE=y
CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_LOCK=y
# end of Memory protection
CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE=32
CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=2304
CONFIG_ESP_MAIN_TASK_STACK_SIZE=3584
CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0=y
# CONFIG_ESP_MAIN_TASK_AFFINITY_CPU1 is not set
# CONFIG_ESP_MAIN_TASK_AFFINITY_NO_AFFINITY is not set
CONFIG_ESP_MAIN_TASK_AFFINITY=0x0
CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE=2048
CONFIG_ESP_CONSOLE_UART_DEFAULT=y
# CONFIG_ESP_CONSOLE_USB_CDC is not set
# CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG is not set
# CONFIG_ESP_CONSOLE_UART_CUSTOM is not set
# CONFIG_ESP_CONSOLE_NONE is not set
# CONFIG_ESP_CONSOLE_SECONDARY_NONE is not set
CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED=y
CONFIG_ESP_CONSOLE_UART=y
CONFIG_ESP_CONSOLE_UART_NUM=0
CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=0
CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200
CONFIG_ESP_INT_WDT=y
CONFIG_ESP_INT_WDT_TIMEOUT_MS=300
CONFIG_ESP_INT_WDT_CHECK_CPU1=y
CONFIG_ESP_TASK_WDT_EN=y
CONFIG_ESP_TASK_WDT_INIT=y
# CONFIG_ESP_TASK_WDT_PANIC is not set
CONFIG_ESP_TASK_WDT_TIMEOUT_S=5
CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0=y
CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1=y
# CONFIG_ESP_PANIC_HANDLER_IRAM is not set
# CONFIG_ESP_DEBUG_STUBS_ENABLE is not set
CONFIG_ESP_DEBUG_OCDAWARE=y
CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4=y
#
# Brownout Detector
#
CONFIG_ESP_BROWNOUT_DET=y
CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7=y
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6 is not set
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5 is not set
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_4 is not set
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_3 is not set
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_2 is not set
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_1 is not set
CONFIG_ESP_BROWNOUT_DET_LVL=7
# end of Brownout Detector
CONFIG_ESP_SYSTEM_BROWNOUT_INTR=y
CONFIG_ESP_SYSTEM_BBPLL_RECALIB=y
# end of ESP System Settings
#
# IPC (Inter-Processor Call)
#
CONFIG_ESP_IPC_TASK_STACK_SIZE=1280
CONFIG_ESP_IPC_USES_CALLERS_PRIORITY=y
CONFIG_ESP_IPC_ISR_ENABLE=y
# end of IPC (Inter-Processor Call)
#
# ESP Timer (High Resolution Timer)
#
# CONFIG_ESP_TIMER_PROFILING is not set
CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER=y
CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER=y
CONFIG_ESP_TIMER_TASK_STACK_SIZE=3584
CONFIG_ESP_TIMER_INTERRUPT_LEVEL=1
# CONFIG_ESP_TIMER_SHOW_EXPERIMENTAL is not set
CONFIG_ESP_TIMER_TASK_AFFINITY=0x0
CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0=y
CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0=y
# CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD is not set
CONFIG_ESP_TIMER_IMPL_SYSTIMER=y
# end of ESP Timer (High Resolution Timer)
#
# Wi-Fi
#
CONFIG_ESP_WIFI_ENABLED=y
CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=10
CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=32
CONFIG_ESP_WIFI_STATIC_TX_BUFFER=y
CONFIG_ESP_WIFI_TX_BUFFER_TYPE=0
CONFIG_ESP_WIFI_STATIC_TX_BUFFER_NUM=16
CONFIG_ESP_WIFI_CACHE_TX_BUFFER_NUM=32
CONFIG_ESP_WIFI_STATIC_RX_MGMT_BUFFER=y
# CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUFFER is not set
CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUF=0
CONFIG_ESP_WIFI_RX_MGMT_BUF_NUM_DEF=5
# CONFIG_ESP_WIFI_CSI_ENABLED is not set
CONFIG_ESP_WIFI_AMPDU_TX_ENABLED=y
CONFIG_ESP_WIFI_TX_BA_WIN=6
CONFIG_ESP_WIFI_AMPDU_RX_ENABLED=y
CONFIG_ESP_WIFI_RX_BA_WIN=6
# CONFIG_ESP_WIFI_AMSDU_TX_ENABLED is not set
CONFIG_ESP_WIFI_NVS_ENABLED=y
CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0=y
# CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_1 is not set
CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN=752
CONFIG_ESP_WIFI_MGMT_SBUF_NUM=32
CONFIG_ESP_WIFI_IRAM_OPT=y
# CONFIG_ESP_WIFI_EXTRA_IRAM_OPT is not set
CONFIG_ESP_WIFI_RX_IRAM_OPT=y
CONFIG_ESP_WIFI_ENABLE_WPA3_SAE=y
CONFIG_ESP_WIFI_ENABLE_SAE_PK=y
CONFIG_ESP_WIFI_SOFTAP_SAE_SUPPORT=y
CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA=y
# CONFIG_ESP_WIFI_SLP_IRAM_OPT is not set
CONFIG_ESP_WIFI_SLP_DEFAULT_MIN_ACTIVE_TIME=50
CONFIG_ESP_WIFI_SLP_DEFAULT_MAX_ACTIVE_TIME=10
CONFIG_ESP_WIFI_SLP_DEFAULT_WAIT_BROADCAST_DATA_TIME=15
# CONFIG_ESP_WIFI_FTM_ENABLE is not set
CONFIG_ESP_WIFI_STA_DISCONNECTED_PM_ENABLE=y
# CONFIG_ESP_WIFI_GCMP_SUPPORT is not set
CONFIG_ESP_WIFI_GMAC_SUPPORT=y
CONFIG_ESP_WIFI_SOFTAP_SUPPORT=y
# CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT is not set
CONFIG_ESP_WIFI_ESPNOW_MAX_ENCRYPT_NUM=7
CONFIG_ESP_WIFI_MBEDTLS_CRYPTO=y
CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT=y
# CONFIG_ESP_WIFI_WAPI_PSK is not set
# CONFIG_ESP_WIFI_SUITE_B_192 is not set
# CONFIG_ESP_WIFI_11KV_SUPPORT is not set
# CONFIG_ESP_WIFI_MBO_SUPPORT is not set
# CONFIG_ESP_WIFI_DPP_SUPPORT is not set
# CONFIG_ESP_WIFI_11R_SUPPORT is not set
# CONFIG_ESP_WIFI_WPS_SOFTAP_REGISTRAR is not set
#
# WPS Configuration Options
#
# CONFIG_ESP_WIFI_WPS_STRICT is not set
# CONFIG_ESP_WIFI_WPS_PASSPHRASE is not set
# end of WPS Configuration Options
# CONFIG_ESP_WIFI_DEBUG_PRINT is not set
# CONFIG_ESP_WIFI_TESTING_OPTIONS is not set
CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT=y
# CONFIG_ESP_WIFI_ENT_FREE_DYNAMIC_BUFFER is not set
# end of Wi-Fi
#
# Core dump
#
# CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH is not set
# CONFIG_ESP_COREDUMP_ENABLE_TO_UART is not set
CONFIG_ESP_COREDUMP_ENABLE_TO_NONE=y
# end of Core dump
#
# FAT Filesystem support
#
CONFIG_FATFS_VOLUME_COUNT=2
CONFIG_FATFS_LFN_NONE=y
# CONFIG_FATFS_LFN_HEAP is not set
# CONFIG_FATFS_LFN_STACK is not set
# CONFIG_FATFS_SECTOR_512 is not set
CONFIG_FATFS_SECTOR_4096=y
# CONFIG_FATFS_CODEPAGE_DYNAMIC is not set
CONFIG_FATFS_CODEPAGE_437=y
# CONFIG_FATFS_CODEPAGE_720 is not set
# CONFIG_FATFS_CODEPAGE_737 is not set
# CONFIG_FATFS_CODEPAGE_771 is not set
# CONFIG_FATFS_CODEPAGE_775 is not set
# CONFIG_FATFS_CODEPAGE_850 is not set
# CONFIG_FATFS_CODEPAGE_852 is not set
# CONFIG_FATFS_CODEPAGE_855 is not set
# CONFIG_FATFS_CODEPAGE_857 is not set
# CONFIG_FATFS_CODEPAGE_860 is not set
# CONFIG_FATFS_CODEPAGE_861 is not set
# CONFIG_FATFS_CODEPAGE_862 is not set
# CONFIG_FATFS_CODEPAGE_863 is not set
# CONFIG_FATFS_CODEPAGE_864 is not set
# CONFIG_FATFS_CODEPAGE_865 is not set
# CONFIG_FATFS_CODEPAGE_866 is not set
# CONFIG_FATFS_CODEPAGE_869 is not set
# CONFIG_FATFS_CODEPAGE_932 is not set
# CONFIG_FATFS_CODEPAGE_936 is not set
# CONFIG_FATFS_CODEPAGE_949 is not set
# CONFIG_FATFS_CODEPAGE_950 is not set
CONFIG_FATFS_CODEPAGE=437
CONFIG_FATFS_FS_LOCK=0
CONFIG_FATFS_TIMEOUT_MS=10000
CONFIG_FATFS_PER_FILE_CACHE=y
CONFIG_FATFS_ALLOC_PREFER_EXTRAM=y
# CONFIG_FATFS_USE_FASTSEEK is not set
CONFIG_FATFS_VFS_FSTAT_BLKSIZE=0
# CONFIG_FATFS_IMMEDIATE_FSYNC is not set
# CONFIG_FATFS_USE_LABEL is not set
CONFIG_FATFS_LINK_LOCK=y
# end of FAT Filesystem support
#
# FreeRTOS
#
#
# Kernel
#
# CONFIG_FREERTOS_SMP is not set
# CONFIG_FREERTOS_UNICORE is not set
CONFIG_FREERTOS_HZ=100
# CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE is not set
# CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL is not set
CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY=y
CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS=1
CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=1536
# CONFIG_FREERTOS_USE_IDLE_HOOK is not set
# CONFIG_FREERTOS_USE_TICK_HOOK is not set
CONFIG_FREERTOS_MAX_TASK_NAME_LEN=16
# CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY is not set
CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME="Tmr Svc"
# CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU0 is not set
# CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU1 is not set
CONFIG_FREERTOS_TIMER_TASK_NO_AFFINITY=y
CONFIG_FREERTOS_TIMER_SERVICE_TASK_CORE_AFFINITY=0x7FFFFFFF
CONFIG_FREERTOS_TIMER_TASK_PRIORITY=1
CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=2048
CONFIG_FREERTOS_TIMER_QUEUE_LENGTH=10
CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE=0
CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES=1
# CONFIG_FREERTOS_USE_TRACE_FACILITY is not set
# CONFIG_FREERTOS_USE_LIST_DATA_INTEGRITY_CHECK_BYTES is not set
# CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS is not set
# CONFIG_FREERTOS_USE_APPLICATION_TASK_TAG is not set
# end of Kernel
#
# Port
#
CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER=y
# CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK is not set
CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS=y
# CONFIG_FREERTOS_TASK_PRE_DELETION_HOOK is not set
# CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP is not set
CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER=y
CONFIG_FREERTOS_ISR_STACKSIZE=1536
CONFIG_FREERTOS_INTERRUPT_BACKTRACE=y
CONFIG_FREERTOS_TICK_SUPPORT_SYSTIMER=y
CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL1=y
# CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL3 is not set
CONFIG_FREERTOS_SYSTICK_USES_SYSTIMER=y
# CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH is not set
# CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE is not set
# end of Port
CONFIG_FREERTOS_PORT=y
CONFIG_FREERTOS_NO_AFFINITY=0x7FFFFFFF
CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION=y
CONFIG_FREERTOS_DEBUG_OCDAWARE=y
CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT=y
CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH=y
CONFIG_FREERTOS_NUMBER_OF_CORES=2
# end of FreeRTOS
#
# Hardware Abstraction Layer (HAL) and Low Level (LL)
#
CONFIG_HAL_ASSERTION_EQUALS_SYSTEM=y
# CONFIG_HAL_ASSERTION_DISABLE is not set
# CONFIG_HAL_ASSERTION_SILENT is not set
# CONFIG_HAL_ASSERTION_ENABLE is not set
CONFIG_HAL_DEFAULT_ASSERTION_LEVEL=2
CONFIG_HAL_WDT_USE_ROM_IMPL=y
CONFIG_HAL_SPI_MASTER_FUNC_IN_IRAM=y
CONFIG_HAL_SPI_SLAVE_FUNC_IN_IRAM=y
# end of Hardware Abstraction Layer (HAL) and Low Level (LL)
#
# Heap memory debugging
#
CONFIG_HEAP_POISONING_DISABLED=y
# CONFIG_HEAP_POISONING_LIGHT is not set
# CONFIG_HEAP_POISONING_COMPREHENSIVE is not set
CONFIG_HEAP_TRACING_OFF=y
# CONFIG_HEAP_TRACING_STANDALONE is not set
# CONFIG_HEAP_TRACING_TOHOST is not set
# CONFIG_HEAP_USE_HOOKS is not set
# CONFIG_HEAP_TASK_TRACKING is not set
# CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS is not set
# CONFIG_HEAP_PLACE_FUNCTION_INTO_FLASH is not set
# end of Heap memory debugging
#
# Log output
#
# CONFIG_LOG_DEFAULT_LEVEL_NONE is not set
# CONFIG_LOG_DEFAULT_LEVEL_ERROR is not set
# CONFIG_LOG_DEFAULT_LEVEL_WARN is not set
CONFIG_LOG_DEFAULT_LEVEL_INFO=y
# CONFIG_LOG_DEFAULT_LEVEL_DEBUG is not set
# CONFIG_LOG_DEFAULT_LEVEL_VERBOSE is not set
CONFIG_LOG_DEFAULT_LEVEL=3
CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT=y
# CONFIG_LOG_MAXIMUM_LEVEL_DEBUG is not set
# CONFIG_LOG_MAXIMUM_LEVEL_VERBOSE is not set
CONFIG_LOG_MAXIMUM_LEVEL=3
# CONFIG_LOG_MASTER_LEVEL is not set
CONFIG_LOG_COLORS=y
CONFIG_LOG_TIMESTAMP_SOURCE_RTOS=y
# CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM is not set
# end of Log output
#
# LWIP
#
CONFIG_LWIP_ENABLE=y
CONFIG_LWIP_LOCAL_HOSTNAME="espressif"
# CONFIG_LWIP_NETIF_API is not set
CONFIG_LWIP_TCPIP_TASK_PRIO=18
# CONFIG_LWIP_TCPIP_CORE_LOCKING is not set
# CONFIG_LWIP_CHECK_THREAD_SAFETY is not set
CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y
# CONFIG_LWIP_L2_TO_L3_COPY is not set
# CONFIG_LWIP_IRAM_OPTIMIZATION is not set
# CONFIG_LWIP_EXTRA_IRAM_OPTIMIZATION is not set
CONFIG_LWIP_TIMERS_ONDEMAND=y
CONFIG_LWIP_ND6=y
# CONFIG_LWIP_FORCE_ROUTER_FORWARDING is not set
CONFIG_LWIP_MAX_SOCKETS=10
# CONFIG_LWIP_USE_ONLY_LWIP_SELECT is not set
# CONFIG_LWIP_SO_LINGER is not set
CONFIG_LWIP_SO_REUSE=y
CONFIG_LWIP_SO_REUSE_RXTOALL=y
# CONFIG_LWIP_SO_RCVBUF is not set
# CONFIG_LWIP_NETBUF_RECVINFO is not set
CONFIG_LWIP_IP_DEFAULT_TTL=64
CONFIG_LWIP_IP4_FRAG=y
CONFIG_LWIP_IP6_FRAG=y
# CONFIG_LWIP_IP4_REASSEMBLY is not set
# CONFIG_LWIP_IP6_REASSEMBLY is not set
CONFIG_LWIP_IP_REASS_MAX_PBUFS=10
# CONFIG_LWIP_IP_FORWARD is not set
# CONFIG_LWIP_STATS is not set
CONFIG_LWIP_ESP_GRATUITOUS_ARP=y
CONFIG_LWIP_GARP_TMR_INTERVAL=60
CONFIG_LWIP_ESP_MLDV6_REPORT=y
CONFIG_LWIP_MLDV6_TMR_INTERVAL=40
CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32
CONFIG_LWIP_DHCP_DOES_ARP_CHECK=y
# CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID is not set
CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID=y
# CONFIG_LWIP_DHCP_RESTORE_LAST_IP is not set
CONFIG_LWIP_DHCP_OPTIONS_LEN=68
CONFIG_LWIP_NUM_NETIF_CLIENT_DATA=0
CONFIG_LWIP_DHCP_COARSE_TIMER_SECS=1
#
# DHCP server
#
CONFIG_LWIP_DHCPS=y
CONFIG_LWIP_DHCPS_LEASE_UNIT=60
CONFIG_LWIP_DHCPS_MAX_STATION_NUM=8
CONFIG_LWIP_DHCPS_STATIC_ENTRIES=y
# end of DHCP server
# CONFIG_LWIP_AUTOIP is not set
CONFIG_LWIP_IPV4=y
CONFIG_LWIP_IPV6=y
# CONFIG_LWIP_IPV6_AUTOCONFIG is not set
CONFIG_LWIP_IPV6_NUM_ADDRESSES=3
# CONFIG_LWIP_IPV6_FORWARD is not set
# CONFIG_LWIP_NETIF_STATUS_CALLBACK is not set
CONFIG_LWIP_NETIF_LOOPBACK=y
CONFIG_LWIP_LOOPBACK_MAX_PBUFS=8
#
# TCP
#
CONFIG_LWIP_MAX_ACTIVE_TCP=16
CONFIG_LWIP_MAX_LISTENING_TCP=16
CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION=y
CONFIG_LWIP_TCP_MAXRTX=12
CONFIG_LWIP_TCP_SYNMAXRTX=12
CONFIG_LWIP_TCP_MSS=1440
CONFIG_LWIP_TCP_TMR_INTERVAL=250
CONFIG_LWIP_TCP_MSL=60000
CONFIG_LWIP_TCP_FIN_WAIT_TIMEOUT=20000
CONFIG_LWIP_TCP_SND_BUF_DEFAULT=5760
CONFIG_LWIP_TCP_WND_DEFAULT=5760
CONFIG_LWIP_TCP_RECVMBOX_SIZE=6
CONFIG_LWIP_TCP_ACCEPTMBOX_SIZE=6
CONFIG_LWIP_TCP_QUEUE_OOSEQ=y
CONFIG_LWIP_TCP_OOSEQ_TIMEOUT=6
CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS=4
# CONFIG_LWIP_TCP_SACK_OUT is not set
CONFIG_LWIP_TCP_OVERSIZE_MSS=y
# CONFIG_LWIP_TCP_OVERSIZE_QUARTER_MSS is not set
# CONFIG_LWIP_TCP_OVERSIZE_DISABLE is not set
CONFIG_LWIP_TCP_RTO_TIME=1500
# end of TCP
#
# UDP
#
CONFIG_LWIP_MAX_UDP_PCBS=16
CONFIG_LWIP_UDP_RECVMBOX_SIZE=6
# end of UDP
#
# Checksums
#
# CONFIG_LWIP_CHECKSUM_CHECK_IP is not set
# CONFIG_LWIP_CHECKSUM_CHECK_UDP is not set
CONFIG_LWIP_CHECKSUM_CHECK_ICMP=y
# end of Checksums
CONFIG_LWIP_TCPIP_TASK_STACK_SIZE=3072
CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY=y
# CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0 is not set
# CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU1 is not set
CONFIG_LWIP_TCPIP_TASK_AFFINITY=0x7FFFFFFF
# CONFIG_LWIP_PPP_SUPPORT is not set
CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE=3
CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS=5
# CONFIG_LWIP_SLIP_SUPPORT is not set
#
# ICMP
#
CONFIG_LWIP_ICMP=y
# CONFIG_LWIP_MULTICAST_PING is not set
# CONFIG_LWIP_BROADCAST_PING is not set
# end of ICMP
#
# LWIP RAW API
#
CONFIG_LWIP_MAX_RAW_PCBS=16
# end of LWIP RAW API
#
# SNTP
#
CONFIG_LWIP_SNTP_MAX_SERVERS=1
# CONFIG_LWIP_DHCP_GET_NTP_SRV is not set
CONFIG_LWIP_SNTP_UPDATE_DELAY=3600000
CONFIG_LWIP_SNTP_STARTUP_DELAY=y
CONFIG_LWIP_SNTP_MAXIMUM_STARTUP_DELAY=5000
# end of SNTP
#
# DNS
#
CONFIG_LWIP_DNS_MAX_SERVERS=3
# CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT is not set
# end of DNS
CONFIG_LWIP_BRIDGEIF_MAX_PORTS=7
CONFIG_LWIP_ESP_LWIP_ASSERT=y
#
# Hooks
#
# CONFIG_LWIP_HOOK_TCP_ISN_NONE is not set
CONFIG_LWIP_HOOK_TCP_ISN_DEFAULT=y
# CONFIG_LWIP_HOOK_TCP_ISN_CUSTOM is not set
CONFIG_LWIP_HOOK_IP6_ROUTE_NONE=y
# CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT is not set
# CONFIG_LWIP_HOOK_IP6_ROUTE_CUSTOM is not set
CONFIG_LWIP_HOOK_ND6_GET_GW_NONE=y
# CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT is not set
# CONFIG_LWIP_HOOK_ND6_GET_GW_CUSTOM is not set
CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE=y
# CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_DEFAULT is not set
# CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_CUSTOM is not set
CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE=y
# CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_DEFAULT is not set
# CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM is not set
CONFIG_LWIP_HOOK_IP6_INPUT_NONE=y
# CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT is not set
# CONFIG_LWIP_HOOK_IP6_INPUT_CUSTOM is not set
# end of Hooks
# CONFIG_LWIP_DEBUG is not set
# end of LWIP
#
# mbedTLS
#
CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y
# CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC is not set
# CONFIG_MBEDTLS_DEFAULT_MEM_ALLOC is not set
# CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC is not set
CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y
CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=16384
CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096
# CONFIG_MBEDTLS_DYNAMIC_BUFFER is not set
# CONFIG_MBEDTLS_DEBUG is not set
#
# mbedTLS v3.x related
#
# CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 is not set
# CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH is not set
# CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK is not set
# CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set
CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y
CONFIG_MBEDTLS_PKCS7_C=y
# end of mbedTLS v3.x related
#
# Certificate Bundle
#
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL=y
# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN is not set
# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE is not set
# CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE is not set
# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEPRECATED_LIST is not set
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS=200
# end of Certificate Bundle
# CONFIG_MBEDTLS_ECP_RESTARTABLE is not set
CONFIG_MBEDTLS_CMAC_C=y
CONFIG_MBEDTLS_HARDWARE_AES=y
CONFIG_MBEDTLS_AES_USE_INTERRUPT=y
CONFIG_MBEDTLS_AES_INTERRUPT_LEVEL=0
CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER=y
CONFIG_MBEDTLS_HARDWARE_MPI=y
# CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI is not set
CONFIG_MBEDTLS_MPI_USE_INTERRUPT=y
CONFIG_MBEDTLS_MPI_INTERRUPT_LEVEL=0
CONFIG_MBEDTLS_HARDWARE_SHA=y
CONFIG_MBEDTLS_ROM_MD5=y
# CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set
# CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set
CONFIG_MBEDTLS_HAVE_TIME=y
# CONFIG_MBEDTLS_PLATFORM_TIME_ALT is not set
# CONFIG_MBEDTLS_HAVE_TIME_DATE is not set
CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y
CONFIG_MBEDTLS_SHA512_C=y
CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT=y
# CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set
# CONFIG_MBEDTLS_TLS_CLIENT_ONLY is not set
# CONFIG_MBEDTLS_TLS_DISABLED is not set
CONFIG_MBEDTLS_TLS_SERVER=y
CONFIG_MBEDTLS_TLS_CLIENT=y
CONFIG_MBEDTLS_TLS_ENABLED=y
#
# TLS Key Exchange Methods
#
# CONFIG_MBEDTLS_PSK_MODES is not set
CONFIG_MBEDTLS_KEY_EXCHANGE_RSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA=y
# end of TLS Key Exchange Methods
CONFIG_MBEDTLS_SSL_RENEGOTIATION=y
CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y
# CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set
# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set
CONFIG_MBEDTLS_SSL_ALPN=y
CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS=y
CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS=y
#
# Symmetric Ciphers
#
CONFIG_MBEDTLS_AES_C=y
# CONFIG_MBEDTLS_CAMELLIA_C is not set
# CONFIG_MBEDTLS_DES_C is not set
# CONFIG_MBEDTLS_BLOWFISH_C is not set
# CONFIG_MBEDTLS_XTEA_C is not set
CONFIG_MBEDTLS_CCM_C=y
CONFIG_MBEDTLS_GCM_C=y
# CONFIG_MBEDTLS_NIST_KW_C is not set
# end of Symmetric Ciphers
# CONFIG_MBEDTLS_RIPEMD160_C is not set
#
# Certificates
#
CONFIG_MBEDTLS_PEM_PARSE_C=y
CONFIG_MBEDTLS_PEM_WRITE_C=y
CONFIG_MBEDTLS_X509_CRL_PARSE_C=y
CONFIG_MBEDTLS_X509_CSR_PARSE_C=y
# end of Certificates
CONFIG_MBEDTLS_ECP_C=y
# CONFIG_MBEDTLS_DHM_C is not set
CONFIG_MBEDTLS_ECDH_C=y
CONFIG_MBEDTLS_ECDSA_C=y
# CONFIG_MBEDTLS_ECJPAKE_C is not set
CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED=y
CONFIG_MBEDTLS_ECP_NIST_OPTIM=y
CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM=y
# CONFIG_MBEDTLS_POLY1305_C is not set
# CONFIG_MBEDTLS_CHACHA20_C is not set
# CONFIG_MBEDTLS_HKDF_C is not set
# CONFIG_MBEDTLS_THREADING_C is not set
CONFIG_MBEDTLS_ERROR_STRINGS=y
# end of mbedTLS
#
# ESP-MQTT Configurations
#
CONFIG_MQTT_PROTOCOL_311=y
# CONFIG_MQTT_PROTOCOL_5 is not set
CONFIG_MQTT_TRANSPORT_SSL=y
CONFIG_MQTT_TRANSPORT_WEBSOCKET=y
CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y
# CONFIG_MQTT_MSG_ID_INCREMENTAL is not set
# CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED is not set
# CONFIG_MQTT_REPORT_DELETED_MESSAGES is not set
# CONFIG_MQTT_USE_CUSTOM_CONFIG is not set
# CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED is not set
# CONFIG_MQTT_CUSTOM_OUTBOX is not set
# end of ESP-MQTT Configurations
#
# Newlib
#
CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF=y
# CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF is not set
# CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR is not set
# CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF is not set
# CONFIG_NEWLIB_STDIN_LINE_ENDING_LF is not set
CONFIG_NEWLIB_STDIN_LINE_ENDING_CR=y
# CONFIG_NEWLIB_NANO_FORMAT is not set
CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y
# CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC is not set
# CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT is not set
# CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE is not set
# end of Newlib
CONFIG_STDATOMIC_S32C1I_SPIRAM_WORKAROUND=y
#
# NVS
#
# CONFIG_NVS_ENCRYPTION is not set
# CONFIG_NVS_ASSERT_ERROR_CHECK is not set
# CONFIG_NVS_LEGACY_DUP_KEYS_COMPATIBILITY is not set
# end of NVS
#
# OpenThread
#
# CONFIG_OPENTHREAD_ENABLED is not set
#
# Thread Operational Dataset
#
CONFIG_OPENTHREAD_NETWORK_NAME="OpenThread-ESP"
CONFIG_OPENTHREAD_MESH_LOCAL_PREFIX="fd00:db8:a0:0::/64"
CONFIG_OPENTHREAD_NETWORK_CHANNEL=15
CONFIG_OPENTHREAD_NETWORK_PANID=0x1234
CONFIG_OPENTHREAD_NETWORK_EXTPANID="dead00beef00cafe"
CONFIG_OPENTHREAD_NETWORK_MASTERKEY="00112233445566778899aabbccddeeff"
CONFIG_OPENTHREAD_NETWORK_PSKC="104810e2315100afd6bc9215a6bfac53"
# end of Thread Operational Dataset
CONFIG_OPENTHREAD_XTAL_ACCURACY=130
# CONFIG_OPENTHREAD_SPINEL_ONLY is not set
CONFIG_OPENTHREAD_RX_ON_WHEN_IDLE=y
#
# Thread Address Query Config
#
# end of Thread Address Query Config
# end of OpenThread
#
# Protocomm
#
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0=y
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1=y
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2=y
# end of Protocomm
#
# PThreads
#
CONFIG_PTHREAD_TASK_PRIO_DEFAULT=5
CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072
CONFIG_PTHREAD_STACK_MIN=768
CONFIG_PTHREAD_DEFAULT_CORE_NO_AFFINITY=y
# CONFIG_PTHREAD_DEFAULT_CORE_0 is not set
# CONFIG_PTHREAD_DEFAULT_CORE_1 is not set
CONFIG_PTHREAD_TASK_CORE_DEFAULT=-1
CONFIG_PTHREAD_TASK_NAME_DEFAULT="pthread"
# end of PThreads
#
# MMU Config
#
CONFIG_MMU_PAGE_SIZE_64KB=y
CONFIG_MMU_PAGE_MODE="64KB"
CONFIG_MMU_PAGE_SIZE=0x10000
# end of MMU Config
#
# Main Flash configuration
#
#
# SPI Flash behavior when brownout
#
CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC=y
CONFIG_SPI_FLASH_BROWNOUT_RESET=y
# end of SPI Flash behavior when brownout
#
# Optional and Experimental Features (READ DOCS FIRST)
#
#
# Features here require specific hardware (READ DOCS FIRST!)
#
# CONFIG_SPI_FLASH_HPM_ENA is not set
CONFIG_SPI_FLASH_HPM_AUTO=y
# CONFIG_SPI_FLASH_HPM_DIS is not set
CONFIG_SPI_FLASH_HPM_ON=y
CONFIG_SPI_FLASH_HPM_DC_AUTO=y
# CONFIG_SPI_FLASH_HPM_DC_DISABLE is not set
CONFIG_SPI_FLASH_SUSPEND_QVL_SUPPORTED=y
# CONFIG_SPI_FLASH_AUTO_SUSPEND is not set
CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US=50
# end of Optional and Experimental Features (READ DOCS FIRST)
# end of Main Flash configuration
#
# SPI Flash driver
#
# CONFIG_SPI_FLASH_VERIFY_WRITE is not set
# CONFIG_SPI_FLASH_ENABLE_COUNTERS is not set
CONFIG_SPI_FLASH_ROM_DRIVER_PATCH=y
# CONFIG_SPI_FLASH_ROM_IMPL is not set
CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS=y
# CONFIG_SPI_FLASH_DANGEROUS_WRITE_FAILS is not set
# CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED is not set
# CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE is not set
CONFIG_SPI_FLASH_YIELD_DURING_ERASE=y
CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS=20
CONFIG_SPI_FLASH_ERASE_YIELD_TICKS=1
CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE=8192
# CONFIG_SPI_FLASH_SIZE_OVERRIDE is not set
# CONFIG_SPI_FLASH_CHECK_ERASE_TIMEOUT_DISABLED is not set
# CONFIG_SPI_FLASH_OVERRIDE_CHIP_DRIVER_LIST is not set
#
# Auto-detect flash chips
#
CONFIG_SPI_FLASH_VENDOR_XMC_SUPPORTED=y
CONFIG_SPI_FLASH_VENDOR_GD_SUPPORTED=y
CONFIG_SPI_FLASH_VENDOR_ISSI_SUPPORTED=y
CONFIG_SPI_FLASH_VENDOR_MXIC_SUPPORTED=y
CONFIG_SPI_FLASH_VENDOR_WINBOND_SUPPORTED=y
CONFIG_SPI_FLASH_VENDOR_BOYA_SUPPORTED=y
CONFIG_SPI_FLASH_VENDOR_TH_SUPPORTED=y
CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP=y
CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP=y
CONFIG_SPI_FLASH_SUPPORT_GD_CHIP=y
CONFIG_SPI_FLASH_SUPPORT_WINBOND_CHIP=y
CONFIG_SPI_FLASH_SUPPORT_BOYA_CHIP=y
CONFIG_SPI_FLASH_SUPPORT_TH_CHIP=y
CONFIG_SPI_FLASH_SUPPORT_MXIC_OPI_CHIP=y
# end of Auto-detect flash chips
CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE=y
# end of SPI Flash driver
#
# SPIFFS Configuration
#
CONFIG_SPIFFS_MAX_PARTITIONS=3
#
# SPIFFS Cache Configuration
#
CONFIG_SPIFFS_CACHE=y
CONFIG_SPIFFS_CACHE_WR=y
# CONFIG_SPIFFS_CACHE_STATS is not set
# end of SPIFFS Cache Configuration
CONFIG_SPIFFS_PAGE_CHECK=y
CONFIG_SPIFFS_GC_MAX_RUNS=10
# CONFIG_SPIFFS_GC_STATS is not set
CONFIG_SPIFFS_PAGE_SIZE=256
CONFIG_SPIFFS_OBJ_NAME_LEN=32
# CONFIG_SPIFFS_FOLLOW_SYMLINKS is not set
CONFIG_SPIFFS_USE_MAGIC=y
CONFIG_SPIFFS_USE_MAGIC_LENGTH=y
CONFIG_SPIFFS_META_LENGTH=4
CONFIG_SPIFFS_USE_MTIME=y
#
# Debug Configuration
#
# CONFIG_SPIFFS_DBG is not set
# CONFIG_SPIFFS_API_DBG is not set
# CONFIG_SPIFFS_GC_DBG is not set
# CONFIG_SPIFFS_CACHE_DBG is not set
# CONFIG_SPIFFS_CHECK_DBG is not set
# CONFIG_SPIFFS_TEST_VISUALISATION is not set
# end of Debug Configuration
# end of SPIFFS Configuration
#
# TCP Transport
#
#
# Websocket
#
CONFIG_WS_TRANSPORT=y
CONFIG_WS_BUFFER_SIZE=1024
# CONFIG_WS_DYNAMIC_BUFFER is not set
# end of Websocket
# end of TCP Transport
#
# Ultra Low Power (ULP) Co-processor
#
# CONFIG_ULP_COPROC_ENABLED is not set
#
# ULP Debugging Options
#
# end of ULP Debugging Options
# end of Ultra Low Power (ULP) Co-processor
#
# Unity unit testing library
#
CONFIG_UNITY_ENABLE_FLOAT=y
CONFIG_UNITY_ENABLE_DOUBLE=y
# CONFIG_UNITY_ENABLE_64BIT is not set
# CONFIG_UNITY_ENABLE_COLOR is not set
CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER=y
# CONFIG_UNITY_ENABLE_FIXTURE is not set
# CONFIG_UNITY_ENABLE_BACKTRACE_ON_FAIL is not set
# end of Unity unit testing library
#
# USB-OTG
#
CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE=256
CONFIG_USB_HOST_HW_BUFFER_BIAS_BALANCED=y
# CONFIG_USB_HOST_HW_BUFFER_BIAS_IN is not set
# CONFIG_USB_HOST_HW_BUFFER_BIAS_PERIODIC_OUT is not set
#
# Root Hub configuration
#
CONFIG_USB_HOST_DEBOUNCE_DELAY_MS=250
CONFIG_USB_HOST_RESET_HOLD_MS=30
CONFIG_USB_HOST_RESET_RECOVERY_MS=30
CONFIG_USB_HOST_SET_ADDR_RECOVERY_MS=10
# end of Root Hub configuration
# CONFIG_USB_HOST_ENABLE_ENUM_FILTER_CALLBACK is not set
CONFIG_USB_OTG_SUPPORTED=y
# end of USB-OTG
#
# Virtual file system
#
CONFIG_VFS_SUPPORT_IO=y
CONFIG_VFS_SUPPORT_DIR=y
CONFIG_VFS_SUPPORT_SELECT=y
CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT=y
# CONFIG_VFS_SELECT_IN_RAM is not set
CONFIG_VFS_SUPPORT_TERMIOS=y
CONFIG_VFS_MAX_COUNT=8
#
# Host File System I/O (Semihosting)
#
CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS=1
# end of Host File System I/O (Semihosting)
# end of Virtual file system
#
# Wear Levelling
#
# CONFIG_WL_SECTOR_SIZE_512 is not set
CONFIG_WL_SECTOR_SIZE_4096=y
CONFIG_WL_SECTOR_SIZE=4096
# end of Wear Levelling
#
# Wi-Fi Provisioning Manager
#
CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES=16
CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT=30
# CONFIG_WIFI_PROV_BLE_FORCE_ENCRYPTION is not set
CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y
# CONFIG_WIFI_PROV_STA_FAST_SCAN is not set
# end of Wi-Fi Provisioning Manager
#
# CMake Utilities
#
# CONFIG_CU_RELINKER_ENABLE is not set
# CONFIG_CU_DIAGNOSTICS_COLOR_NEVER is not set
CONFIG_CU_DIAGNOSTICS_COLOR_ALWAYS=y
# CONFIG_CU_DIAGNOSTICS_COLOR_AUTO is not set
# CONFIG_CU_GCC_LTO_ENABLE is not set
# CONFIG_CU_GCC_STRING_1BYTE_ALIGN is not set
# end of CMake Utilities
#
# ESP LCD TOUCH
#
CONFIG_ESP_LCD_TOUCH_MAX_POINTS=5
CONFIG_ESP_LCD_TOUCH_MAX_BUTTONS=1
# end of ESP LCD TOUCH
#
# LVGL configuration
#
CONFIG_LV_CONF_SKIP=y
# CONFIG_LV_CONF_MINIMAL is not set
#
# Color Settings
#
# CONFIG_LV_COLOR_DEPTH_32 is not set
# CONFIG_LV_COLOR_DEPTH_24 is not set
CONFIG_LV_COLOR_DEPTH_16=y
# CONFIG_LV_COLOR_DEPTH_8 is not set
# CONFIG_LV_COLOR_DEPTH_1 is not set
CONFIG_LV_COLOR_DEPTH=16
# end of Color Settings
#
# Memory Settings
#
CONFIG_LV_USE_BUILTIN_MALLOC=y
# CONFIG_LV_USE_CLIB_MALLOC is not set
# CONFIG_LV_USE_MICROPYTHON_MALLOC is not set
# CONFIG_LV_USE_RTTHREAD_MALLOC is not set
# CONFIG_LV_USE_CUSTOM_MALLOC is not set
CONFIG_LV_USE_BUILTIN_STRING=y
# CONFIG_LV_USE_CLIB_STRING is not set
# CONFIG_LV_USE_CUSTOM_STRING is not set
CONFIG_LV_USE_BUILTIN_SPRINTF=y
# CONFIG_LV_USE_CLIB_SPRINTF is not set
# CONFIG_LV_USE_CUSTOM_SPRINTF is not set
CONFIG_LV_MEM_SIZE_KILOBYTES=64
CONFIG_LV_MEM_POOL_EXPAND_SIZE_KILOBYTES=0
CONFIG_LV_MEM_ADR=0x0
# end of Memory Settings
#
# HAL Settings
#
CONFIG_LV_DEF_REFR_PERIOD=33
CONFIG_LV_DPI_DEF=130
# end of HAL Settings
#
# Operating System (OS)
#
CONFIG_LV_OS_NONE=y
# CONFIG_LV_OS_PTHREAD is not set
# CONFIG_LV_OS_FREERTOS is not set
# CONFIG_LV_OS_CMSIS_RTOS2 is not set
# CONFIG_LV_OS_RTTHREAD is not set
# CONFIG_LV_OS_WINDOWS is not set
# CONFIG_LV_OS_MQX is not set
# CONFIG_LV_OS_CUSTOM is not set
CONFIG_LV_USE_OS=0
# end of Operating System (OS)
#
# Rendering Configuration
#
CONFIG_LV_DRAW_BUF_STRIDE_ALIGN=1
CONFIG_LV_DRAW_BUF_ALIGN=4
CONFIG_LV_DRAW_LAYER_SIMPLE_BUF_SIZE=24576
CONFIG_LV_USE_DRAW_SW=y
CONFIG_LV_DRAW_SW_SUPPORT_RGB565=y
CONFIG_LV_DRAW_SW_SUPPORT_RGB565A8=y
CONFIG_LV_DRAW_SW_SUPPORT_RGB888=y
CONFIG_LV_DRAW_SW_SUPPORT_XRGB8888=y
CONFIG_LV_DRAW_SW_SUPPORT_ARGB8888=y
CONFIG_LV_DRAW_SW_SUPPORT_L8=y
CONFIG_LV_DRAW_SW_SUPPORT_AL88=y
CONFIG_LV_DRAW_SW_SUPPORT_A8=y
CONFIG_LV_DRAW_SW_SUPPORT_I1=y
CONFIG_LV_DRAW_SW_DRAW_UNIT_CNT=1
# CONFIG_LV_USE_DRAW_ARM2D_SYNC is not set
# CONFIG_LV_USE_NATIVE_HELIUM_ASM is not set
CONFIG_LV_DRAW_SW_COMPLEX=y
# CONFIG_LV_USE_DRAW_SW_COMPLEX_GRADIENTS is not set
CONFIG_LV_DRAW_SW_SHADOW_CACHE_SIZE=0
CONFIG_LV_DRAW_SW_CIRCLE_CACHE_SIZE=4
CONFIG_LV_DRAW_SW_ASM_NONE=y
# CONFIG_LV_DRAW_SW_ASM_NEON is not set
# CONFIG_LV_DRAW_SW_ASM_HELIUM is not set
# CONFIG_LV_DRAW_SW_ASM_CUSTOM is not set
CONFIG_LV_USE_DRAW_SW_ASM=0
# CONFIG_LV_USE_DRAW_VGLITE is not set
# CONFIG_LV_USE_DRAW_PXP is not set
# CONFIG_LV_USE_DRAW_DAVE2D is not set
# CONFIG_LV_USE_DRAW_SDL is not set
# CONFIG_LV_USE_DRAW_VG_LITE is not set
# CONFIG_LV_USE_VECTOR_GRAPHIC is not set
# end of Rendering Configuration
#
# Feature Configuration
#
#
# Logging
#
# CONFIG_LV_USE_LOG is not set
# end of Logging
#
# Asserts
#
CONFIG_LV_USE_ASSERT_NULL=y
CONFIG_LV_USE_ASSERT_MALLOC=y
# CONFIG_LV_USE_ASSERT_STYLE is not set
# CONFIG_LV_USE_ASSERT_MEM_INTEGRITY is not set
# CONFIG_LV_USE_ASSERT_OBJ is not set
CONFIG_LV_ASSERT_HANDLER_INCLUDE="assert.h"
# end of Asserts
#
# Debug
#
# CONFIG_LV_USE_REFR_DEBUG is not set
# CONFIG_LV_USE_LAYER_DEBUG is not set
# CONFIG_LV_USE_PARALLEL_DRAW_DEBUG is not set
# end of Debug
#
# Others
#
# CONFIG_LV_ENABLE_GLOBAL_CUSTOM is not set
CONFIG_LV_CACHE_DEF_SIZE=0
CONFIG_LV_IMAGE_HEADER_CACHE_DEF_CNT=0
CONFIG_LV_GRADIENT_MAX_STOPS=2
CONFIG_LV_COLOR_MIX_ROUND_OFS=128
# CONFIG_LV_OBJ_STYLE_CACHE is not set
# CONFIG_LV_USE_OBJ_ID is not set
# CONFIG_LV_USE_OBJ_PROPERTY is not set
# end of Others
# end of Feature Configuration
#
# Compiler Settings
#
# CONFIG_LV_BIG_ENDIAN_SYSTEM is not set
CONFIG_LV_ATTRIBUTE_MEM_ALIGN_SIZE=1
# CONFIG_LV_ATTRIBUTE_FAST_MEM_USE_IRAM is not set
# CONFIG_LV_USE_FLOAT is not set
# CONFIG_LV_USE_MATRIX is not set
# CONFIG_LV_USE_PRIVATE_API is not set
# end of Compiler Settings
#
# Font Usage
#
#
# Enable built-in fonts
#
# CONFIG_LV_FONT_MONTSERRAT_8 is not set
# CONFIG_LV_FONT_MONTSERRAT_10 is not set
# CONFIG_LV_FONT_MONTSERRAT_12 is not set
CONFIG_LV_FONT_MONTSERRAT_14=y
# CONFIG_LV_FONT_MONTSERRAT_16 is not set
# CONFIG_LV_FONT_MONTSERRAT_18 is not set
# CONFIG_LV_FONT_MONTSERRAT_20 is not set
# CONFIG_LV_FONT_MONTSERRAT_22 is not set
# CONFIG_LV_FONT_MONTSERRAT_24 is not set
# CONFIG_LV_FONT_MONTSERRAT_26 is not set
# CONFIG_LV_FONT_MONTSERRAT_28 is not set
# CONFIG_LV_FONT_MONTSERRAT_30 is not set
# CONFIG_LV_FONT_MONTSERRAT_32 is not set
# CONFIG_LV_FONT_MONTSERRAT_34 is not set
# CONFIG_LV_FONT_MONTSERRAT_36 is not set
# CONFIG_LV_FONT_MONTSERRAT_38 is not set
# CONFIG_LV_FONT_MONTSERRAT_40 is not set
# CONFIG_LV_FONT_MONTSERRAT_42 is not set
# CONFIG_LV_FONT_MONTSERRAT_44 is not set
# CONFIG_LV_FONT_MONTSERRAT_46 is not set
# CONFIG_LV_FONT_MONTSERRAT_48 is not set
# CONFIG_LV_FONT_MONTSERRAT_28_COMPRESSED is not set
# CONFIG_LV_FONT_DEJAVU_16_PERSIAN_HEBREW is not set
# CONFIG_LV_FONT_SIMSUN_14_CJK is not set
# CONFIG_LV_FONT_SIMSUN_16_CJK is not set
# CONFIG_LV_FONT_UNSCII_8 is not set
# CONFIG_LV_FONT_UNSCII_16 is not set
# end of Enable built-in fonts
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_8 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_10 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_12 is not set
CONFIG_LV_FONT_DEFAULT_MONTSERRAT_14=y
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_16 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_18 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_20 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_22 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_24 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_26 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_30 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_32 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_34 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_36 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_38 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_40 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_42 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_44 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_46 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_48 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28_COMPRESSED is not set
# CONFIG_LV_FONT_DEFAULT_DEJAVU_16_PERSIAN_HEBREW is not set
# CONFIG_LV_FONT_DEFAULT_SIMSUN_14_CJK is not set
# CONFIG_LV_FONT_DEFAULT_SIMSUN_16_CJK is not set
# CONFIG_LV_FONT_DEFAULT_UNSCII_8 is not set
# CONFIG_LV_FONT_DEFAULT_UNSCII_16 is not set
# CONFIG_LV_FONT_FMT_TXT_LARGE is not set
# CONFIG_LV_USE_FONT_COMPRESSED is not set
CONFIG_LV_USE_FONT_PLACEHOLDER=y
# end of Font Usage
#
# Text Settings
#
CONFIG_LV_TXT_ENC_UTF8=y
# CONFIG_LV_TXT_ENC_ASCII is not set
CONFIG_LV_TXT_BREAK_CHARS=" ,.;:-_)}"
CONFIG_LV_TXT_LINE_BREAK_LONG_LEN=0
# CONFIG_LV_USE_BIDI is not set
# CONFIG_LV_USE_ARABIC_PERSIAN_CHARS is not set
# end of Text Settings
#
# Widget Usage
#
CONFIG_LV_WIDGETS_HAS_DEFAULT_VALUE=y
CONFIG_LV_USE_ANIMIMG=y
CONFIG_LV_USE_ARC=y
CONFIG_LV_USE_BAR=y
CONFIG_LV_USE_BUTTON=y
CONFIG_LV_USE_BUTTONMATRIX=y
CONFIG_LV_USE_CALENDAR=y
# CONFIG_LV_CALENDAR_WEEK_STARTS_MONDAY is not set
CONFIG_LV_USE_CALENDAR_HEADER_ARROW=y
CONFIG_LV_USE_CALENDAR_HEADER_DROPDOWN=y
# CONFIG_LV_USE_CALENDAR_CHINESE is not set
CONFIG_LV_USE_CANVAS=y
CONFIG_LV_USE_CHART=y
CONFIG_LV_USE_CHECKBOX=y
CONFIG_LV_USE_DROPDOWN=y
CONFIG_LV_USE_IMAGE=y
CONFIG_LV_USE_IMAGEBUTTON=y
CONFIG_LV_USE_KEYBOARD=y
CONFIG_LV_USE_LABEL=y
CONFIG_LV_LABEL_TEXT_SELECTION=y
CONFIG_LV_LABEL_LONG_TXT_HINT=y
CONFIG_LV_LABEL_WAIT_CHAR_COUNT=3
CONFIG_LV_USE_LED=y
CONFIG_LV_USE_LINE=y
CONFIG_LV_USE_LIST=y
CONFIG_LV_USE_MENU=y
CONFIG_LV_USE_MSGBOX=y
CONFIG_LV_USE_ROLLER=y
CONFIG_LV_USE_SCALE=y
CONFIG_LV_USE_SLIDER=y
CONFIG_LV_USE_SPAN=y
CONFIG_LV_SPAN_SNIPPET_STACK_SIZE=64
CONFIG_LV_USE_SPINBOX=y
CONFIG_LV_USE_SPINNER=y
CONFIG_LV_USE_SWITCH=y
CONFIG_LV_USE_TEXTAREA=y
CONFIG_LV_TEXTAREA_DEF_PWD_SHOW_TIME=1500
CONFIG_LV_USE_TABLE=y
CONFIG_LV_USE_TABVIEW=y
CONFIG_LV_USE_TILEVIEW=y
CONFIG_LV_USE_WIN=y
# end of Widget Usage
#
# Themes
#
CONFIG_LV_USE_THEME_DEFAULT=y
# CONFIG_LV_THEME_DEFAULT_DARK is not set
CONFIG_LV_THEME_DEFAULT_GROW=y
CONFIG_LV_THEME_DEFAULT_TRANSITION_TIME=80
CONFIG_LV_USE_THEME_SIMPLE=y
# CONFIG_LV_USE_THEME_MONO is not set
# end of Themes
#
# Layouts
#
CONFIG_LV_USE_FLEX=y
CONFIG_LV_USE_GRID=y
# end of Layouts
#
# 3rd Party Libraries
#
CONFIG_LV_FS_DEFAULT_DRIVE_LETTER=0
# CONFIG_LV_USE_FS_STDIO is not set
# CONFIG_LV_USE_FS_POSIX is not set
# CONFIG_LV_USE_FS_WIN32 is not set
# CONFIG_LV_USE_FS_FATFS is not set
# CONFIG_LV_USE_FS_MEMFS is not set
# CONFIG_LV_USE_FS_LITTLEFS is not set
# CONFIG_LV_USE_FS_ARDUINO_ESP_LITTLEFS is not set
# CONFIG_LV_USE_FS_ARDUINO_SD is not set
# CONFIG_LV_USE_LODEPNG is not set
# CONFIG_LV_USE_LIBPNG is not set
# CONFIG_LV_USE_BMP is not set
# CONFIG_LV_USE_TJPGD is not set
# CONFIG_LV_USE_LIBJPEG_TURBO is not set
# CONFIG_LV_USE_GIF is not set
# CONFIG_LV_BIN_DECODER_RAM_LOAD is not set
# CONFIG_LV_USE_RLE is not set
# CONFIG_LV_USE_QRCODE is not set
# CONFIG_LV_USE_BARCODE is not set
# CONFIG_LV_USE_FREETYPE is not set
# CONFIG_LV_USE_TINY_TTF is not set
# CONFIG_LV_USE_RLOTTIE is not set
# CONFIG_LV_USE_THORVG is not set
# CONFIG_LV_USE_LZ4 is not set
# CONFIG_LV_USE_FFMPEG is not set
# end of 3rd Party Libraries
#
# Others
#
# CONFIG_LV_USE_SNAPSHOT is not set
# CONFIG_LV_USE_SYSMON is not set
# CONFIG_LV_USE_PROFILER is not set
# CONFIG_LV_USE_MONKEY is not set
# CONFIG_LV_USE_GRIDNAV is not set
# CONFIG_LV_USE_FRAGMENT is not set
# CONFIG_LV_USE_IMGFONT is not set
CONFIG_LV_USE_OBSERVER=y
# CONFIG_LV_USE_IME_PINYIN is not set
# CONFIG_LV_USE_FILE_EXPLORER is not set
# end of Others
#
# Devices
#
# CONFIG_LV_USE_SDL is not set
# CONFIG_LV_USE_X11 is not set
# CONFIG_LV_USE_WAYLAND is not set
# CONFIG_LV_USE_LINUX_FBDEV is not set
# CONFIG_LV_USE_NUTTX is not set
# CONFIG_LV_USE_LINUX_DRM is not set
# CONFIG_LV_USE_TFT_ESPI is not set
# CONFIG_LV_USE_EVDEV is not set
# CONFIG_LV_USE_LIBINPUT is not set
# CONFIG_LV_USE_ST7735 is not set
# CONFIG_LV_USE_ST7789 is not set
# CONFIG_LV_USE_ST7796 is not set
# CONFIG_LV_USE_ILI9341 is not set
# CONFIG_LV_USE_GENERIC_MIPI is not set
# CONFIG_LV_USE_RENESAS_GLCDC is not set
# CONFIG_LV_USE_OPENGLES is not set
# CONFIG_LV_USE_QNX is not set
# end of Devices
#
# Examples
#
CONFIG_LV_BUILD_EXAMPLES=y
# end of Examples
#
# Demos
#
# CONFIG_LV_USE_DEMO_WIDGETS is not set
# CONFIG_LV_USE_DEMO_KEYPAD_AND_ENCODER is not set
# CONFIG_LV_USE_DEMO_RENDER is not set
# CONFIG_LV_USE_DEMO_SCROLL is not set
# CONFIG_LV_USE_DEMO_STRESS is not set
# CONFIG_LV_USE_DEMO_MUSIC is not set
# CONFIG_LV_USE_DEMO_FLEX_LAYOUT is not set
# CONFIG_LV_USE_DEMO_MULTILANG is not set
# end of Demos
# end of LVGL configuration
# end of Component config
# CONFIG_IDF_EXPERIMENTAL_FEATURES is not set
# Deprecated options for backward compatibility
# CONFIG_APP_BUILD_TYPE_ELF_RAM is not set
# CONFIG_NO_BLOBS is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_NONE is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_ERROR is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_WARN is not set
CONFIG_LOG_BOOTLOADER_LEVEL_INFO=y
# CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE is not set
CONFIG_LOG_BOOTLOADER_LEVEL=3
# CONFIG_APP_ROLLBACK_ENABLE is not set
# CONFIG_FLASH_ENCRYPTION_ENABLED is not set
# CONFIG_FLASHMODE_QIO is not set
# CONFIG_FLASHMODE_QOUT is not set
CONFIG_FLASHMODE_DIO=y
# CONFIG_FLASHMODE_DOUT is not set
CONFIG_MONITOR_BAUD=115200
CONFIG_OPTIMIZATION_LEVEL_DEBUG=y
CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG=y
CONFIG_COMPILER_OPTIMIZATION_DEFAULT=y
# CONFIG_OPTIMIZATION_LEVEL_RELEASE is not set
# CONFIG_COMPILER_OPTIMIZATION_LEVEL_RELEASE is not set
CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED=y
# CONFIG_OPTIMIZATION_ASSERTIONS_SILENT is not set
# CONFIG_OPTIMIZATION_ASSERTIONS_DISABLED is not set
CONFIG_OPTIMIZATION_ASSERTION_LEVEL=2
# CONFIG_CXX_EXCEPTIONS is not set
CONFIG_STACK_CHECK_NONE=y
# CONFIG_STACK_CHECK_NORM is not set
# CONFIG_STACK_CHECK_STRONG is not set
# CONFIG_STACK_CHECK_ALL is not set
# CONFIG_WARN_WRITE_STRINGS is not set
# CONFIG_ESP32_APPTRACE_DEST_TRAX is not set
CONFIG_ESP32_APPTRACE_DEST_NONE=y
CONFIG_ESP32_APPTRACE_LOCK_ENABLE=y
# CONFIG_EXTERNAL_COEX_ENABLE is not set
# CONFIG_ESP_WIFI_EXTERNAL_COEXIST_ENABLE is not set
# CONFIG_MCPWM_ISR_IN_IRAM is not set
# CONFIG_EVENT_LOOP_PROFILING is not set
CONFIG_POST_EVENTS_FROM_ISR=y
CONFIG_POST_EVENTS_FROM_IRAM_ISR=y
CONFIG_GDBSTUB_SUPPORT_TASKS=y
CONFIG_GDBSTUB_MAX_TASKS=32
# CONFIG_OTA_ALLOW_HTTP is not set
CONFIG_ESP32S3_DEEP_SLEEP_WAKEUP_DELAY=2000
CONFIG_ESP_SLEEP_DEEP_SLEEP_WAKEUP_DELAY=2000
CONFIG_ESP32S3_RTC_CLK_SRC_INT_RC=y
# CONFIG_ESP32S3_RTC_CLK_SRC_EXT_CRYS is not set
# CONFIG_ESP32S3_RTC_CLK_SRC_EXT_OSC is not set
# CONFIG_ESP32S3_RTC_CLK_SRC_INT_8MD256 is not set
CONFIG_ESP32S3_RTC_CLK_CAL_CYCLES=1024
CONFIG_ESP32_PHY_CALIBRATION_AND_DATA_STORAGE=y
# CONFIG_ESP32_PHY_INIT_DATA_IN_PARTITION is not set
CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER=20
CONFIG_ESP32_PHY_MAX_TX_POWER=20
# CONFIG_REDUCE_PHY_TX_POWER is not set
# CONFIG_ESP32_REDUCE_PHY_TX_POWER is not set
CONFIG_ESP_SYSTEM_PM_POWER_DOWN_CPU=y
CONFIG_PM_POWER_DOWN_TAGMEM_IN_LIGHT_SLEEP=y
CONFIG_ESP32S3_SPIRAM_SUPPORT=y
CONFIG_DEFAULT_PSRAM_CLK_IO=30
CONFIG_DEFAULT_PSRAM_CS_IO=26
# CONFIG_ESP32S3_DEFAULT_CPU_FREQ_80 is not set
# CONFIG_ESP32S3_DEFAULT_CPU_FREQ_160 is not set
CONFIG_ESP32S3_DEFAULT_CPU_FREQ_240=y
CONFIG_ESP32S3_DEFAULT_CPU_FREQ_MHZ=240
CONFIG_SYSTEM_EVENT_QUEUE_SIZE=32
CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE=2304
CONFIG_MAIN_TASK_STACK_SIZE=3584
CONFIG_CONSOLE_UART_DEFAULT=y
# CONFIG_CONSOLE_UART_CUSTOM is not set
# CONFIG_CONSOLE_UART_NONE is not set
# CONFIG_ESP_CONSOLE_UART_NONE is not set
CONFIG_CONSOLE_UART=y
CONFIG_CONSOLE_UART_NUM=0
CONFIG_CONSOLE_UART_BAUDRATE=115200
CONFIG_INT_WDT=y
CONFIG_INT_WDT_TIMEOUT_MS=300
CONFIG_INT_WDT_CHECK_CPU1=y
CONFIG_TASK_WDT=y
CONFIG_ESP_TASK_WDT=y
# CONFIG_TASK_WDT_PANIC is not set
CONFIG_TASK_WDT_TIMEOUT_S=5
CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0=y
CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1=y
# CONFIG_ESP32_DEBUG_STUBS_ENABLE is not set
CONFIG_ESP32S3_DEBUG_OCDAWARE=y
CONFIG_BROWNOUT_DET=y
CONFIG_ESP32S3_BROWNOUT_DET=y
CONFIG_ESP32S3_BROWNOUT_DET=y
CONFIG_BROWNOUT_DET_LVL_SEL_7=y
CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_7=y
# CONFIG_BROWNOUT_DET_LVL_SEL_6 is not set
# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_6 is not set
# CONFIG_BROWNOUT_DET_LVL_SEL_5 is not set
# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_5 is not set
# CONFIG_BROWNOUT_DET_LVL_SEL_4 is not set
# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_4 is not set
# CONFIG_BROWNOUT_DET_LVL_SEL_3 is not set
# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_3 is not set
# CONFIG_BROWNOUT_DET_LVL_SEL_2 is not set
# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_2 is not set
# CONFIG_BROWNOUT_DET_LVL_SEL_1 is not set
# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_1 is not set
CONFIG_BROWNOUT_DET_LVL=7
CONFIG_ESP32S3_BROWNOUT_DET_LVL=7
CONFIG_IPC_TASK_STACK_SIZE=1280
CONFIG_TIMER_TASK_STACK_SIZE=3584
CONFIG_ESP32_WIFI_ENABLED=y
CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM=10
CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=32
CONFIG_ESP32_WIFI_STATIC_TX_BUFFER=y
CONFIG_ESP32_WIFI_TX_BUFFER_TYPE=0
CONFIG_ESP32_WIFI_STATIC_TX_BUFFER_NUM=16
CONFIG_ESP32_WIFI_CACHE_TX_BUFFER_NUM=32
# CONFIG_ESP32_WIFI_CSI_ENABLED is not set
CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED=y
CONFIG_ESP32_WIFI_TX_BA_WIN=6
CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y
CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y
CONFIG_ESP32_WIFI_RX_BA_WIN=6
CONFIG_ESP32_WIFI_RX_BA_WIN=6
# CONFIG_ESP32_WIFI_AMSDU_TX_ENABLED is not set
CONFIG_ESP32_WIFI_NVS_ENABLED=y
CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0=y
# CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1 is not set
CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN=752
CONFIG_ESP32_WIFI_MGMT_SBUF_NUM=32
CONFIG_ESP32_WIFI_IRAM_OPT=y
CONFIG_ESP32_WIFI_RX_IRAM_OPT=y
CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE=y
CONFIG_ESP32_WIFI_ENABLE_WPA3_OWE_STA=y
CONFIG_WPA_MBEDTLS_CRYPTO=y
CONFIG_WPA_MBEDTLS_TLS_CLIENT=y
# CONFIG_WPA_WAPI_PSK is not set
# CONFIG_WPA_SUITE_B_192 is not set
# CONFIG_WPA_11KV_SUPPORT is not set
# CONFIG_WPA_MBO_SUPPORT is not set
# CONFIG_WPA_DPP_SUPPORT is not set
# CONFIG_WPA_11R_SUPPORT is not set
# CONFIG_WPA_WPS_SOFTAP_REGISTRAR is not set
# CONFIG_WPA_WPS_STRICT is not set
# CONFIG_WPA_DEBUG_PRINT is not set
# CONFIG_WPA_TESTING_OPTIONS is not set
# CONFIG_ESP32_ENABLE_COREDUMP_TO_FLASH is not set
# CONFIG_ESP32_ENABLE_COREDUMP_TO_UART is not set
CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE=y
CONFIG_TIMER_TASK_PRIORITY=1
CONFIG_TIMER_TASK_STACK_DEPTH=2048
CONFIG_TIMER_QUEUE_LENGTH=10
# CONFIG_ENABLE_STATIC_TASK_CLEAN_UP_HOOK is not set
# CONFIG_HAL_ASSERTION_SILIENT is not set
# CONFIG_L2_TO_L3_COPY is not set
CONFIG_ESP_GRATUITOUS_ARP=y
CONFIG_GARP_TMR_INTERVAL=60
CONFIG_TCPIP_RECVMBOX_SIZE=32
CONFIG_TCP_MAXRTX=12
CONFIG_TCP_SYNMAXRTX=12
CONFIG_TCP_MSS=1440
CONFIG_TCP_MSL=60000
CONFIG_TCP_SND_BUF_DEFAULT=5760
CONFIG_TCP_WND_DEFAULT=5760
CONFIG_TCP_RECVMBOX_SIZE=6
CONFIG_TCP_QUEUE_OOSEQ=y
CONFIG_TCP_OVERSIZE_MSS=y
# CONFIG_TCP_OVERSIZE_QUARTER_MSS is not set
# CONFIG_TCP_OVERSIZE_DISABLE is not set
CONFIG_UDP_RECVMBOX_SIZE=6
CONFIG_TCPIP_TASK_STACK_SIZE=3072
CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY=y
# CONFIG_TCPIP_TASK_AFFINITY_CPU0 is not set
# CONFIG_TCPIP_TASK_AFFINITY_CPU1 is not set
CONFIG_TCPIP_TASK_AFFINITY=0x7FFFFFFF
# CONFIG_PPP_SUPPORT is not set
CONFIG_ESP32S3_TIME_SYSCALL_USE_RTC_SYSTIMER=y
CONFIG_ESP32S3_TIME_SYSCALL_USE_RTC_FRC1=y
# CONFIG_ESP32S3_TIME_SYSCALL_USE_RTC is not set
# CONFIG_ESP32S3_TIME_SYSCALL_USE_SYSTIMER is not set
# CONFIG_ESP32S3_TIME_SYSCALL_USE_FRC1 is not set
# CONFIG_ESP32S3_TIME_SYSCALL_USE_NONE is not set
CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT=5
CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072
CONFIG_ESP32_PTHREAD_STACK_MIN=768
CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY=y
# CONFIG_ESP32_DEFAULT_PTHREAD_CORE_0 is not set
# CONFIG_ESP32_DEFAULT_PTHREAD_CORE_1 is not set
CONFIG_ESP32_PTHREAD_TASK_CORE_DEFAULT=-1
CONFIG_ESP32_PTHREAD_TASK_NAME_DEFAULT="pthread"
CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS=y
# CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_FAILS is not set
# CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED is not set
CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT=y
CONFIG_SUPPORT_TERMIOS=y
CONFIG_SEMIHOSTFS_MAX_MOUNT_POINTS=1
# End of deprecated options
|
0015/LVGL_Joystick
| 1,870 |
examples/arduino_example/LGFX_WT32-SC01-Plus.h
|
#define LGFX_USE_V1
#include <LovyanGFX.hpp>
class LGFX : public lgfx::LGFX_Device {
lgfx::Panel_ST7796 _panel_instance;
lgfx::Bus_Parallel8 _bus_instance;
lgfx::Light_PWM _light_instance;
lgfx::Touch_FT5x06 _touch_instance;
public:
LGFX(void) {
{
auto cfg = _bus_instance.config();
cfg.freq_write = 60000000;
cfg.pin_wr = 47;
cfg.pin_rd = -1;
cfg.pin_rs = 0;
cfg.pin_d0 = 9;
cfg.pin_d1 = 46;
cfg.pin_d2 = 3;
cfg.pin_d3 = 8;
cfg.pin_d4 = 18;
cfg.pin_d5 = 17;
cfg.pin_d6 = 16;
cfg.pin_d7 = 15;
_bus_instance.config(cfg);
_panel_instance.setBus(&_bus_instance);
}
{
auto cfg = _panel_instance.config();
cfg.pin_cs = -1;
cfg.pin_rst = 4;
cfg.pin_busy = -1;
cfg.memory_width = 320;
cfg.memory_height = 480;
cfg.panel_width = 320;
cfg.panel_height = 480;
cfg.offset_x = 0;
cfg.offset_y = 0;
cfg.offset_rotation = 0;
cfg.dummy_read_pixel = 8;
cfg.dummy_read_bits = 1;
cfg.readable = true;
cfg.invert = true;
cfg.rgb_order = false;
cfg.dlen_16bit = false;
cfg.bus_shared = true;
_panel_instance.config(cfg);
}
{
auto cfg = _light_instance.config();
cfg.pin_bl = 45;
cfg.invert = false;
cfg.freq = 44100;
cfg.pwm_channel = 7;
_light_instance.config(cfg);
_panel_instance.setLight(&_light_instance);
}
{
auto cfg = _touch_instance.config();
cfg.i2c_port = 1;
cfg.i2c_addr = 0x38;
cfg.pin_sda = 6;
cfg.pin_scl = 5;
cfg.freq = 400000;
cfg.x_min = 0;
cfg.x_max = 320;
cfg.y_min = 0;
cfg.y_max = 480;
_touch_instance.config(cfg);
_panel_instance.setTouch(&_touch_instance);
}
setPanel(&_panel_instance);
}
};
|
000haoji/deep-student
| 40,367 |
src-tauri/src/streaming_anki_service.rs
|
use crate::models::{
DocumentTask, TaskStatus, AnkiCard, AnkiGenerationOptions, AppError, StreamedCardPayload,
StreamEvent, SubjectConfig, FieldType, FieldExtractionRule
};
use crate::llm_manager::ApiConfig;
use crate::database::Database;
use crate::llm_manager::LLMManager;
use std::sync::Arc;
use uuid::Uuid;
use chrono::Utc;
use reqwest::Client;
use serde_json::{json, Value};
use futures_util::StreamExt;
use tauri::{Window, Emitter};
use std::time::Duration;
use tokio::time::timeout;
#[derive(Clone)]
pub struct StreamingAnkiService {
db: Arc<Database>,
llm_manager: Arc<LLMManager>,
client: Client,
}
impl StreamingAnkiService {
pub fn new(db: Arc<Database>, llm_manager: Arc<LLMManager>) -> Self {
let client = Client::builder()
.timeout(Duration::from_secs(600)) // 10分钟超时,适合流式处理
.build()
.expect("创建HTTP客户端失败");
Self {
db,
llm_manager,
client,
}
}
/// 处理任务并流式生成卡片
pub async fn process_task_and_generate_cards_stream(
&self,
task: DocumentTask,
window: Window,
) -> Result<(), AppError> {
let task_id = task.id.clone();
// 更新任务状态为处理中
self.update_task_status(&task_id, TaskStatus::Processing, None, Some(task.segment_index), &window).await?;
// 获取配置
let (api_config, subject_config) = self.get_configurations(&task.subject_name).await?;
// 解析生成选项
let options: AnkiGenerationOptions = serde_json::from_str(&task.anki_generation_options_json)
.map_err(|e| AppError::validation(format!("解析生成选项失败: {}", e)))?;
// 构建prompt
let prompt = self.build_prompt(subject_config.as_ref(), &task.content_segment, &options)?;
// 确定API参数
let max_tokens = options.max_output_tokens_override
.or(options.max_tokens.map(|t| t as u32))
.unwrap_or(api_config.max_output_tokens);
let temperature = options.temperature_override
.or(options.temperature)
.unwrap_or(api_config.temperature);
// 开始流式处理
self.update_task_status(&task_id, TaskStatus::Streaming, None, Some(task.segment_index), &window).await?;
let result = self.stream_cards_from_ai(
&api_config,
&prompt,
max_tokens,
temperature,
&task_id,
&window,
&options,
).await;
match result {
Ok(card_count) => {
self.complete_task_successfully(&task_id, card_count, &window).await?;
}
Err(e) => {
self.handle_task_error(&task_id, &e, &window).await?;
}
}
Ok(())
}
/// 获取API配置和科目配置(科目配置可选)
async fn get_configurations(&self, subject_name: &str) -> Result<(ApiConfig, Option<SubjectConfig>), AppError> {
// 获取模型分配
let model_assignments = self.llm_manager.get_model_assignments().await
.map_err(|e| AppError::configuration(format!("获取模型分配失败: {}", e)))?;
// 获取Anki制卡模型配置
let anki_model_id = model_assignments.anki_card_model_config_id
.ok_or_else(|| AppError::configuration("Anki制卡模型在模型分配中未配置 (anki_card_model_config_id is None)"))?;
println!("[ANKI_CONFIG_DEBUG] Anki Model ID from assignments: {}", anki_model_id);
let api_configs = self.llm_manager.get_api_configs().await
.map_err(|e| AppError::configuration(format!("获取API配置失败: {}", e)))?;
let config_count = api_configs.len();
let api_config = api_configs.into_iter()
.find(|config| config.id == anki_model_id && config.enabled)
.ok_or_else(|| AppError::configuration(format!("找不到有效的Anki制卡模型配置. Tried to find ID: {} in {} available configs.", anki_model_id, config_count)))?;
println!("[ANKI_CONFIG_DEBUG] Found ApiConfig for ANKI: ID='{}', Name='{}', BaseURL='{}', Model='{}', Enabled='{}'",
api_config.id,
api_config.name.as_str(), // Assuming name is String, not Option<String>
api_config.base_url,
api_config.model,
api_config.enabled
);
// 尝试获取科目配置,但不再要求必须存在
let subject_config = match self.db.get_subject_config_by_name(subject_name) {
Ok(Some(config)) => {
println!("✅ 找到科目配置: {}", subject_name);
Some(config)
}
Ok(None) => {
println!("ℹ️ 未找到科目配置: {},将使用默认配置", subject_name);
None
}
Err(e) => {
println!("⚠️ 获取科目配置失败,将使用默认配置: {}", e);
None
}
};
Ok((api_config, subject_config))
}
/// 构建AI提示词
fn build_prompt(
&self,
subject_config: Option<&SubjectConfig>,
content: &str,
options: &AnkiGenerationOptions,
) -> Result<String, AppError> {
// 优先级:用户自定义system_prompt > 模板prompt > 科目配置prompt > 默认prompt
let base_prompt = if let Some(system_prompt) = &options.system_prompt {
if !system_prompt.trim().is_empty() {
system_prompt.clone()
} else {
// 如果system_prompt为空,则继续使用原有逻辑
if let Some(custom_prompt) = &options.custom_anki_prompt {
custom_prompt.clone()
} else if let Some(config) = subject_config {
config.prompts.anki_generation_prompt.replace("{subject}", &config.subject_name)
} else {
// 默认ANKI制卡prompt
"你是一个专业的ANKI学习卡片制作助手。请根据提供的学习内容,生成高质量的ANKI学习卡片。\n\n要求:\n1. 卡片应该有助于记忆和理解\n2. 问题要简洁明确\n3. 答案要准确完整\n4. 适当添加相关标签\n5. 确保卡片的逻辑性和实用性".to_string()
}
}
} else {
// 如果没有设置system_prompt,使用原有逻辑
if let Some(custom_prompt) = &options.custom_anki_prompt {
custom_prompt.clone()
} else if let Some(config) = subject_config {
config.prompts.anki_generation_prompt.replace("{subject}", &config.subject_name)
} else {
// 默认ANKI制卡prompt
"你是一个专业的ANKI学习卡片制作助手。请根据提供的学习内容,生成高质量的ANKI学习卡片。\n\n要求:\n1. 卡片应该有助于记忆和理解\n2. 问题要简洁明确\n3. 答案要准确完整\n4. 适当添加相关标签\n5. 确保卡片的逻辑性和实用性".to_string()
}
};
// 获取模板字段,默认为基础字段
let template_fields = options.template_fields.as_ref()
.map(|fields| fields.clone())
.unwrap_or_else(|| vec!["front".to_string(), "back".to_string(), "tags".to_string()]);
// 动态构建字段要求
let fields_requirement = template_fields.iter()
.map(|field| {
match field.as_str() {
"front" => "front(字符串):问题或概念".to_string(),
"back" => "back(字符串):答案或解释".to_string(),
"tags" => "tags(字符串数组):相关标签".to_string(),
"example" => "example(字符串,可选):具体示例".to_string(),
"source" => "source(字符串,可选):来源信息".to_string(),
"code" => "code(字符串,可选):代码示例".to_string(),
"notes" => "notes(字符串,可选):补充注释".to_string(),
_ => format!("{}(字符串,可选):{}", field, field),
}
})
.collect::<Vec<_>>()
.join("、");
// 构建示例JSON
let example_json = {
let mut example_fields = vec![];
for field in &template_fields {
match field.as_str() {
"front" => example_fields.push("\"front\": \"问题内容\"".to_string()),
"back" => example_fields.push("\"back\": \"答案内容\"".to_string()),
"tags" => example_fields.push("\"tags\": [\"标签1\", \"标签2\"]".to_string()),
"example" => example_fields.push("\"example\": \"示例内容\"".to_string()),
"source" => example_fields.push("\"source\": \"来源信息\"".to_string()),
"code" => example_fields.push("\"code\": \"代码示例\"".to_string()),
"notes" => example_fields.push("\"notes\": \"注释内容\"".to_string()),
_ => example_fields.push(format!("\"{}\": \"{}内容\"", field, field)),
}
}
format!("{{{}}}", example_fields.join(", "))
};
// 添加自定义要求部分
let custom_requirements_text = if let Some(requirements) = &options.custom_requirements {
if !requirements.trim().is_empty() {
format!("\n\n📋 特殊制卡要求:\n{}\n请严格按照以上要求进行制卡。", requirements.trim())
} else {
String::new()
}
} else {
String::new()
};
// 构建卡片数量要求
let card_count_instruction = if options.max_cards_per_mistake > 0 {
format!("🎯 重要提醒:你必须根据提供内容的具体情况来生成卡片:\n\
- 如果内容是选择题格式:请为每一道选择题生成一张对应的卡片,绝不要遗漏任何题目\n\
- 如果内容是其他格式:建议生成{}张高质量卡片,充分覆盖所有知识点\n\
\n\
❗ 特别强调:不要只生成几张卡片就停止,要确保充分利用提供的内容!\n\n", options.max_cards_per_mistake)
} else {
"🎯 重要提醒:你必须根据提供内容的具体情况来生成卡片:\n\
- 如果内容是选择题格式:请为每一道选择题生成一张对应的卡片,绝不要遗漏任何题目\n\
- 如果内容是其他格式:请生成尽可能多的高质量Anki卡片,充分覆盖所有知识点\n\
\n\
❗ 特别强调:不要只生成几张卡片就停止,要确保充分利用提供的内容!\n\n".to_string()
};
// 增强prompt以支持流式输出和动态字段
let enhanced_prompt = format!(
"{}{}\n\n{}\
重要指令:\n\
1. 请逐个生成卡片,每个卡片必须是完整的JSON格式\n\
2. 每生成一个完整的卡片JSON后,立即输出分隔符:<<<ANKI_CARD_JSON_END>>>\n\
3. JSON格式必须包含以下字段:{}\n\
4. 不要使用Markdown代码块,直接输出JSON\n\
5. 示例输出格式:\n\
{}\n\
<<<ANKI_CARD_JSON_END>>>\n\n\
请根据以下内容生成Anki卡片:\n\n{}",
base_prompt, custom_requirements_text, card_count_instruction, fields_requirement, example_json, content
);
Ok(enhanced_prompt)
}
/// 流式处理AI响应并生成卡片
async fn stream_cards_from_ai(
&self,
api_config: &ApiConfig,
prompt: &str,
max_tokens: u32,
temperature: f32,
task_id: &str,
window: &Window,
options: &AnkiGenerationOptions,
) -> Result<u32, AppError> {
let request_body = json!({
"model": api_config.model,
"messages": [
{
"role": "user",
"content": prompt
}
],
"max_tokens": max_tokens,
"temperature": temperature,
"stream": true
});
let request_url = format!("{}/chat/completions", api_config.base_url.trim_end_matches('/'));
println!("[ANKI_REQUEST_DEBUG] Attempting to POST to URL: {}", request_url);
println!("[ANKI_REQUEST_DEBUG] Request Body Model: {}", api_config.model);
println!("[ANKI_REQUEST_DEBUG] Prompt length: {}", prompt.len());
println!("[ANKI_REQUEST_DEBUG] Max Tokens: {}, Temperature: {}", max_tokens, temperature);
println!("[ANKI_REQUEST_DEBUG] Max Cards Per Mistake: {}", options.max_cards_per_mistake);
println!("[ANKI_REQUEST_DEBUG] System Prompt: {}",
if let Some(sp) = &options.system_prompt {
if sp.trim().is_empty() { "未设置" } else { "已自定义" }
} else { "使用默认" });
// 输出完整的 prompt 内容
println!("[ANKI_PROMPT_DEBUG] ==> 完整Prompt内容开始 <==");
println!("{}", prompt);
println!("[ANKI_PROMPT_DEBUG] ==> 完整Prompt内容结束 <==");
// 输出完整的请求体
println!("[ANKI_REQUEST_DEBUG] ==> 完整请求体开始 <==");
println!("{}", serde_json::to_string_pretty(&request_body).unwrap_or_default());
println!("[ANKI_REQUEST_DEBUG] ==> 完整请求体结束 <==");
let response = self.client
.post(&request_url)
.header("Authorization", format!("Bearer {}", api_config.api_key))
.header("Content-Type", "application/json")
.json(&request_body)
.send()
.await
.map_err(|e| AppError::network(format!("AI请求失败: {}", e)))?;
if !response.status().is_success() {
let error_text = response.text().await.unwrap_or_default();
return Err(AppError::llm(format!("AI API错误: {}", error_text)));
}
let mut stream = response.bytes_stream();
let mut buffer = String::new();
let mut card_count = 0u32;
let mut _last_activity = std::time::Instant::now(); // Prefixed to silence warning
const IDLE_TIMEOUT: Duration = Duration::from_secs(30); // 30秒无响应超时
let mut all_received_content = String::new(); // 用于记录所有接收到的内容
while let Some(chunk_result) = timeout(IDLE_TIMEOUT, stream.next()).await
.map_err(|_| AppError::network("AI响应超时"))?
{
let chunk = chunk_result
.map_err(|e| AppError::network(format!("读取AI响应流失败: {}", e)))?;
_last_activity = std::time::Instant::now(); // Prefixed to silence warning
let chunk_str = String::from_utf8_lossy(&chunk);
// 处理SSE格式
for line in chunk_str.lines() {
if line.starts_with("data: ") {
let data = &line[6..]; // 去掉 "data: " 前缀
if data == "[DONE]" {
break;
}
// 解析SSE数据
if let Ok(json_data) = serde_json::from_str::<Value>(data) {
if let Some(content) = json_data["choices"][0]["delta"]["content"].as_str() {
buffer.push_str(content);
all_received_content.push_str(content); // 记录所有内容
// 检查是否有完整的卡片
while let Some(card_result) = self.extract_card_from_buffer(&mut buffer) {
match card_result {
Ok(card_json) => {
match self.parse_and_save_card(&card_json, task_id, options.template_id.as_deref(), &options.field_extraction_rules).await {
Ok(card) => {
card_count += 1;
println!("[ANKI_CARD_DEBUG] 已生成第{}张卡片 (目标: {}张)", card_count, options.max_cards_per_mistake);
self.emit_new_card(card, window).await;
}
Err(e) => {
println!("解析卡片失败: {} - 原始JSON: {}", e, card_json);
// 继续处理,不中断整个流程
}
}
}
Err(truncated_content) => {
// 处理截断内容
if let Ok(error_card) = self.create_error_card(&truncated_content, task_id).await {
self.emit_error_card(error_card, window).await;
}
}
}
}
}
}
}
}
}
// 处理剩余缓冲区内容
if !buffer.trim().is_empty() {
if let Ok(error_card) = self.create_error_card(&buffer, task_id).await {
self.emit_error_card(error_card, window).await;
}
}
// 输出完整的AI响应内容
println!("[ANKI_RESPONSE_DEBUG] ==> 完整AI响应内容开始 <==");
println!("{}", all_received_content);
println!("[ANKI_RESPONSE_DEBUG] ==> 完整AI响应内容结束 <==");
println!("[ANKI_RESPONSE_DEBUG] 总共生成卡片数量: {}", card_count);
println!("[ANKI_RESPONSE_DEBUG] 剩余缓冲区内容: '{}'", buffer);
Ok(card_count)
}
/// 从缓冲区提取卡片
fn extract_card_from_buffer(&self, buffer: &mut String) -> Option<Result<String, String>> {
const DELIMITER: &str = "<<<ANKI_CARD_JSON_END>>>";
if let Some(delimiter_pos) = buffer.find(DELIMITER) {
let card_content = buffer[..delimiter_pos].trim().to_string();
let remaining = buffer[delimiter_pos + DELIMITER.len()..].to_string();
*buffer = remaining;
if !card_content.is_empty() {
Some(Ok(card_content))
} else {
None
}
} else if buffer.len() > 10000 { // 如果缓冲区过大,可能是截断
let truncated = buffer.clone();
buffer.clear();
Some(Err(truncated))
} else {
None
}
}
/// 解析并保存卡片 - 支持动态字段提取规则
async fn parse_and_save_card(&self, card_json: &str, task_id: &str, template_id: Option<&str>, extraction_rules: &Option<std::collections::HashMap<String, FieldExtractionRule>>) -> Result<AnkiCard, AppError> {
// 清理JSON字符串
let cleaned_json = self.clean_json_string(card_json);
// 解析JSON
let json_value: Value = serde_json::from_str(&cleaned_json)
.map_err(|e| AppError::validation(format!("JSON解析失败: {} - 原始内容: {}", e, card_json)))?;
// 动态字段提取 - 使用模板的字段提取规则
let (front, back, tags, extra_fields) = if let Some(rules) = extraction_rules {
self.extract_fields_with_rules(&json_value, rules)?
} else {
// 回退到旧的硬编码逻辑
self.extract_fields_legacy(&json_value)?
};
// 清理所有字段中的模板占位符
let cleaned_front = self.clean_template_placeholders(&front);
let cleaned_back = self.clean_template_placeholders(&back);
let cleaned_tags: Vec<String> = tags.iter()
.map(|tag| self.clean_template_placeholders(tag))
.filter(|tag| !tag.is_empty())
.collect();
let cleaned_extra_fields: std::collections::HashMap<String, String> = extra_fields.iter()
.map(|(k, v)| (k.clone(), self.clean_template_placeholders(v)))
.collect();
// 创建卡片
let now = Utc::now().to_rfc3339();
let card = AnkiCard {
id: Uuid::new_v4().to_string(),
task_id: task_id.to_string(),
front: cleaned_front,
back: cleaned_back,
text: cleaned_extra_fields.get("text").cloned(), // 从清理后的extra_fields中提取text字段
tags: cleaned_tags,
images: Vec::new(),
is_error_card: false,
error_content: None,
created_at: now.clone(),
updated_at: now,
extra_fields: cleaned_extra_fields,
template_id: template_id.map(|id| id.to_string()),
};
// 检查是否存在重复卡片 - 支持不同卡片类型的重复检测
if let Ok(existing_cards) = self.db.get_cards_for_task(task_id) {
let is_duplicate = existing_cards.iter().any(|existing| {
// 对于Cloze类型,比较text字段;对于其他类型,比较front和back字段
if card.text.is_some() && existing.text.is_some() {
// 两张卡片都有text字段,按Cloze类型处理
card.text == existing.text && card.text.as_ref().unwrap().len() > 0
} else {
// 按传统方式比较front和back字段
existing.front == card.front && existing.back == card.back
}
});
if is_duplicate {
let preview = card.text.as_ref().unwrap_or(&card.front).chars().take(50).collect::<String>();
println!("⚠️ 发现重复卡片,跳过保存: {}", preview);
return Err(AppError::validation("重复卡片已跳过".to_string()));
}
}
// 保存到数据库
self.db.insert_anki_card(&card)
.map_err(|e| AppError::database(format!("保存卡片失败: {}", e)))?;
Ok(card)
}
/// 清理JSON字符串
fn clean_json_string(&self, json_str: &str) -> String {
let mut cleaned = json_str.trim();
// 移除Markdown代码块标记
if cleaned.starts_with("```json") {
cleaned = &cleaned[7..];
}
if cleaned.starts_with("```") {
cleaned = &cleaned[3..];
}
if cleaned.ends_with("```") {
cleaned = &cleaned[..cleaned.len() - 3];
}
cleaned.trim().to_string()
}
/// 清理模板占位符
fn clean_template_placeholders(&self, content: &str) -> String {
let mut cleaned = content.to_string();
// 移除各种可能的占位符
cleaned = cleaned.replace("{{.}}", "");
cleaned = cleaned.replace("{{/}}", "");
cleaned = cleaned.replace("{{#}}", "");
cleaned = cleaned.replace("{{}}", "");
// 移除空的Mustache标签 {{}}
while cleaned.contains("{{}}") {
cleaned = cleaned.replace("{{}}", "");
}
// 移除可能的空白标签
cleaned = cleaned.replace("{{ }}", "");
cleaned = cleaned.replace("{{ }}", "");
// 清理多余的空白和换行
cleaned.trim().to_string()
}
/// 使用模板字段提取规则动态解析字段
fn extract_fields_with_rules(
&self,
json_value: &Value,
rules: &std::collections::HashMap<String, FieldExtractionRule>
) -> Result<(String, String, Vec<String>, std::collections::HashMap<String, String>), AppError> {
let mut front = String::new();
let mut back = String::new();
let mut tags = Vec::new();
let mut extra_fields = std::collections::HashMap::new();
// 遍历所有定义的字段规则
for (field_name, rule) in rules {
let field_value = self.extract_field_value(json_value, field_name);
match (field_value, rule.is_required) {
(Some(value), _) => {
// 字段存在,根据类型和字段名称处理
match field_name.to_lowercase().as_str() {
"front" => {
front = self.process_field_value(&value, &rule.field_type)?;
}
"back" => {
back = self.process_field_value(&value, &rule.field_type)?;
}
"tags" => {
tags = self.process_tags_field(&value, &rule.field_type)?;
}
"explanation" => {
// 选择题的答案需要组合多个字段
let explanation_text = self.process_field_value(&value, &rule.field_type)?;
// 先保存explanation,稍后组合完整答案
extra_fields.insert("explanation".to_string(), explanation_text);
}
// 填空题模板字段映射
"text" => {
// 对于填空题,Text字段应该保存到extra_fields中,用于Cloze模板
let processed_value = self.process_field_value(&value, &rule.field_type)?;
extra_fields.insert("text".to_string(), processed_value.clone());
// 同时设置front字段以确保基础验证通过
front = processed_value.clone();
back = format!("填空题:{}", processed_value); // 为back字段提供有意义的内容
}
_ => {
// 扩展字段
let processed_value = self.process_field_value(&value, &rule.field_type)?;
extra_fields.insert(field_name.to_lowercase(), processed_value);
}
}
}
(None, true) => {
// 必需字段缺失
if let Some(default) = &rule.default_value {
match field_name.to_lowercase().as_str() {
"front" => front = default.clone(),
"back" => back = default.clone(),
"tags" => tags = serde_json::from_str(default).unwrap_or_default(),
_ => {
extra_fields.insert(field_name.to_lowercase(), default.clone());
}
}
} else {
return Err(AppError::validation(format!("缺少必需字段: {}", field_name)));
}
}
(None, false) => {
// 可选字段缺失,使用默认值
if let Some(default) = &rule.default_value {
match field_name.to_lowercase().as_str() {
"front" => front = default.clone(),
"back" => back = default.clone(),
"tags" => tags = serde_json::from_str(default).unwrap_or_default(),
_ => {
extra_fields.insert(field_name.to_lowercase(), default.clone());
}
}
}
// 如果没有默认值,就不设置该字段
}
}
}
// 特殊处理选择题模板的back字段组合
if extra_fields.contains_key("optiona") {
// 这是选择题模板,需要组合答案
let mut choice_back = String::new();
// 添加选项
if let Some(option_a) = extra_fields.get("optiona") {
choice_back.push_str(&format!("A. {}\n", option_a));
}
if let Some(option_b) = extra_fields.get("optionb") {
choice_back.push_str(&format!("B. {}\n", option_b));
}
if let Some(option_c) = extra_fields.get("optionc") {
choice_back.push_str(&format!("C. {}\n", option_c));
}
if let Some(option_d) = extra_fields.get("optiond") {
choice_back.push_str(&format!("D. {}\n", option_d));
}
// 添加正确答案
if let Some(correct) = extra_fields.get("correct") {
choice_back.push_str(&format!("\n正确答案:{}\n", correct));
}
// 添加解析
if let Some(explanation) = extra_fields.get("explanation") {
choice_back.push_str(&format!("\n解析:{}", explanation));
}
back = choice_back;
}
// 确保front和back字段有值
if front.is_empty() {
return Err(AppError::validation(format!("front字段不能为空 - 原始JSON: {}", serde_json::to_string(&json_value).unwrap_or_default())));
}
if back.is_empty() {
// 尝试为选择题自动生成back内容
if json_value.get("optiona").and_then(|v| v.as_str()).is_some() {
let mut choice_back = String::new();
// 添加选项并保存到extra_fields
if let Some(option_a) = json_value.get("optiona").and_then(|v| v.as_str()) {
choice_back.push_str(&format!("A. {}\n", option_a));
extra_fields.insert("optiona".to_string(), option_a.to_string());
}
if let Some(option_b) = json_value.get("optionb").and_then(|v| v.as_str()) {
choice_back.push_str(&format!("B. {}\n", option_b));
extra_fields.insert("optionb".to_string(), option_b.to_string());
}
if let Some(option_c) = json_value.get("optionc").and_then(|v| v.as_str()) {
choice_back.push_str(&format!("C. {}\n", option_c));
extra_fields.insert("optionc".to_string(), option_c.to_string());
}
if let Some(option_d) = json_value.get("optiond").and_then(|v| v.as_str()) {
choice_back.push_str(&format!("D. {}\n", option_d));
extra_fields.insert("optiond".to_string(), option_d.to_string());
}
// 添加正确答案并保存到extra_fields
if let Some(correct) = json_value.get("correct").and_then(|v| v.as_str()) {
choice_back.push_str(&format!("\n正确答案:{}\n", correct));
extra_fields.insert("correct".to_string(), correct.to_string());
}
// 添加解析并保存到extra_fields
if let Some(explanation) = json_value.get("explanation").and_then(|v| v.as_str()) {
choice_back.push_str(&format!("\n解析:{}", explanation));
extra_fields.insert("explanation".to_string(), explanation.to_string());
}
back = choice_back;
} else {
return Err(AppError::validation("back字段不能为空".to_string()));
}
}
Ok((front, back, tags, extra_fields))
}
/// 从JSON中提取字段值(支持大小写不敏感)
fn extract_field_value(&self, json_value: &Value, field_name: &str) -> Option<Value> {
let obj = json_value.as_object()?;
// 首先尝试精确匹配
if let Some(value) = obj.get(field_name) {
return Some(value.clone());
}
// 然后尝试大小写不敏感匹配
let field_lower = field_name.to_lowercase();
for (key, value) in obj {
if key.to_lowercase() == field_lower {
return Some(value.clone());
}
}
None
}
/// 根据字段类型处理字段值
fn process_field_value(&self, value: &Value, field_type: &FieldType) -> Result<String, AppError> {
match field_type {
FieldType::Text => {
if let Some(s) = value.as_str() {
Ok(s.to_string())
} else {
// 如果不是字符串,尝试序列化为字符串
Ok(value.to_string().trim_matches('"').to_string())
}
}
FieldType::Array => {
if let Some(arr) = value.as_array() {
let strings = arr.iter()
.filter_map(|v| v.as_str())
.collect::<Vec<_>>()
.join(", ");
Ok(strings)
} else if let Some(s) = value.as_str() {
Ok(s.to_string())
} else {
Ok(value.to_string().trim_matches('"').to_string())
}
}
FieldType::Number => {
if let Some(n) = value.as_f64() {
Ok(n.to_string())
} else if let Some(s) = value.as_str() {
Ok(s.to_string())
} else {
Ok(value.to_string().trim_matches('"').to_string())
}
}
FieldType::Boolean => {
if let Some(b) = value.as_bool() {
Ok(b.to_string())
} else if let Some(s) = value.as_str() {
Ok(s.to_string())
} else {
Ok(value.to_string().trim_matches('"').to_string())
}
}
}
}
/// 处理tags字段
fn process_tags_field(&self, value: &Value, field_type: &FieldType) -> Result<Vec<String>, AppError> {
match field_type {
FieldType::Array => {
if let Some(arr) = value.as_array() {
Ok(arr.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect())
} else if let Some(s) = value.as_str() {
// 尝试解析逗号分隔的字符串
Ok(s.split(',')
.map(|tag| tag.trim().to_string())
.filter(|tag| !tag.is_empty())
.collect())
} else {
Ok(vec![])
}
}
FieldType::Text => {
if let Some(s) = value.as_str() {
Ok(s.split(',')
.map(|tag| tag.trim().to_string())
.filter(|tag| !tag.is_empty())
.collect())
} else {
Ok(vec![])
}
}
_ => Ok(vec![])
}
}
/// 回退的旧式字段提取逻辑(兼容性)
fn extract_fields_legacy(
&self,
json_value: &Value
) -> Result<(String, String, Vec<String>, std::collections::HashMap<String, String>), AppError> {
// 提取必需字段 (支持大小写不敏感)
let front = json_value["front"].as_str()
.or_else(|| json_value["Front"].as_str())
.ok_or_else(|| AppError::validation("缺少front/Front字段"))?
.to_string();
let mut back = json_value["back"].as_str()
.or_else(|| json_value["Back"].as_str())
.map(|s| s.to_string())
.unwrap_or_default();
// 如果没有back字段,检查是否为选择题模板,自动生成back内容
if back.is_empty() && json_value["optiona"].is_string() {
let mut choice_back = String::new();
// 添加选项
if let Some(option_a) = json_value["optiona"].as_str() {
choice_back.push_str(&format!("A. {}\n", option_a));
}
if let Some(option_b) = json_value["optionb"].as_str() {
choice_back.push_str(&format!("B. {}\n", option_b));
}
if let Some(option_c) = json_value["optionc"].as_str() {
choice_back.push_str(&format!("C. {}\n", option_c));
}
if let Some(option_d) = json_value["optiond"].as_str() {
choice_back.push_str(&format!("D. {}\n", option_d));
}
// 添加正确答案
if let Some(correct) = json_value["correct"].as_str() {
choice_back.push_str(&format!("\n正确答案:{}\n", correct));
}
// 添加解析
if let Some(explanation) = json_value["explanation"].as_str() {
choice_back.push_str(&format!("\n解析:{}", explanation));
}
back = choice_back;
}
// 确保back字段不为空
if back.is_empty() {
return Err(AppError::validation("缺少back/Back字段".to_string()));
}
let tags = json_value["tags"].as_array()
.or_else(|| json_value["Tags"].as_array())
.map(|arr| arr.iter().filter_map(|v| v.as_str().map(|s| s.to_string())).collect())
.unwrap_or_default();
// 提取扩展字段
let mut extra_fields = std::collections::HashMap::new();
if let Some(obj) = json_value.as_object() {
for (key, value) in obj {
// 跳过基础字段 (大小写不敏感)
let key_lower = key.to_lowercase();
if !matches!(key_lower.as_str(), "front" | "back" | "tags" | "images") {
if let Some(str_value) = value.as_str() {
// 将字段名转换为统一的小写格式存储
extra_fields.insert(key_lower, str_value.to_string());
} else if let Some(arr_value) = value.as_array() {
// 将数组转换为字符串
let arr_str = arr_value.iter()
.filter_map(|v| v.as_str())
.collect::<Vec<_>>()
.join(", ");
extra_fields.insert(key_lower, arr_str);
} else {
// 其他类型转换为字符串
extra_fields.insert(key_lower, value.to_string());
}
}
}
}
Ok((front, back, tags, extra_fields))
}
/// 创建错误卡片
async fn create_error_card(&self, error_content: &str, task_id: &str) -> Result<AnkiCard, AppError> {
let now = Utc::now().to_rfc3339();
let card = AnkiCard {
id: Uuid::new_v4().to_string(),
task_id: task_id.to_string(),
front: "内容可能被截断或AI输出不完整".to_string(),
back: "请检查以下原始片段并手动创建或编辑卡片。".to_string(),
text: None, // 错误卡片不需要text字段
tags: vec!["错误".to_string(), "截断".to_string()],
images: Vec::new(),
is_error_card: true,
error_content: Some(error_content.to_string()),
created_at: now.clone(),
updated_at: now,
extra_fields: std::collections::HashMap::new(),
template_id: None,
};
// 保存到数据库
self.db.insert_anki_card(&card)
.map_err(|e| AppError::database(format!("保存错误卡片失败: {}", e)))?;
Ok(card)
}
/// 更新任务状态
async fn update_task_status(
&self,
task_id: &str,
status: TaskStatus,
error_message: Option<String>,
segment_index: Option<u32>, // 新增参数
window: &Window,
) -> Result<(), AppError> {
self.db.update_document_task_status(task_id, status.clone(), error_message.clone())
.map_err(|e| AppError::database(format!("更新任务状态失败: {}", e)))?;
// 发送状态更新事件
let event = StreamEvent {
payload: StreamedCardPayload::TaskStatusUpdate {
task_id: task_id.to_string(),
status,
message: error_message,
segment_index, // 包含 segment_index
},
};
if let Err(e) = window.emit("anki_generation_event", &event) {
println!("发送任务状态更新事件失败: {}", e);
}
Ok(())
}
/// 发送新卡片事件
async fn emit_new_card(&self, card: AnkiCard, window: &Window) {
let event = StreamEvent {
payload: StreamedCardPayload::NewCard(card),
};
if let Err(e) = window.emit("anki_generation_event", &event) {
println!("发送新卡片事件失败: {}", e);
}
}
/// 发送错误卡片事件
async fn emit_error_card(&self, card: AnkiCard, window: &Window) {
let event = StreamEvent {
payload: StreamedCardPayload::NewErrorCard(card),
};
if let Err(e) = window.emit("anki_generation_event", &event) {
println!("发送错误卡片事件失败: {}", e);
}
}
/// 成功完成任务
async fn complete_task_successfully(
&self,
task_id: &str,
card_count: u32,
window: &Window,
) -> Result<(), AppError> {
// For TaskCompleted, segment_index might be less critical if task_id is already real.
// Passing None for now, as the primary use of segment_index is for the initial ID update.
self.update_task_status(task_id, TaskStatus::Completed, None, None, window).await?;
// 发送任务完成事件
let event = StreamEvent {
payload: StreamedCardPayload::TaskCompleted {
task_id: task_id.to_string(),
final_status: TaskStatus::Completed,
total_cards_generated: card_count,
},
};
if let Err(e) = window.emit("anki_generation_event", &event) {
println!("发送任务完成事件失败: {}", e);
}
Ok(())
}
/// 处理任务错误
async fn handle_task_error(
&self,
task_id: &str,
error: &AppError,
window: &Window,
) -> Result<(), AppError> {
let error_message = error.message.clone();
let final_status = if error_message.contains("超时") || error_message.contains("截断") {
TaskStatus::Truncated
} else {
TaskStatus::Failed
};
// Similarly for TaskProcessingError, passing None for segment_index.
self.update_task_status(task_id, final_status.clone(), Some(error_message.clone()), None, window).await?;
// 发送错误事件
let event = StreamEvent {
payload: StreamedCardPayload::TaskProcessingError {
task_id: task_id.to_string(),
error_message,
},
};
if let Err(e) = window.emit("anki_generation_event", &event) {
println!("发送任务错误事件失败: {}", e);
}
Ok(())
}
}
|
000haoji/deep-student
| 6,997 |
src-tauri/src/gemini_adapter.rs
|
// src-tauri/src/gemini_adapter.rs
use crate::models::{AppError, ChatMessage, StandardModel2Output, StreamChunk};
use crate::llm_manager::ApiConfig;
use futures_util::StreamExt;
use reqwest::Client;
use serde_json::{json, Value};
use tauri::{Emitter, Window};
use std::time::Duration;
type Result<T> = std::result::Result<T, AppError>;
/// 处理流式聊天请求
pub async fn stream_chat(
client: &Client,
config: &ApiConfig,
messages: &[ChatMessage],
window: Window,
stream_event: &str,
) -> Result<StandardModel2Output> {
let url = build_gemini_url(config, true)?;
let body = build_gemini_request_body(messages, config)?;
let response = client
.post(&url)
.json(&body)
.timeout(Duration::from_secs(300))
.send()
.await
.map_err(|e| AppError::network(format!("Gemini API request failed: {}", e)))?;
if !response.status().is_success() {
let status = response.status();
let error_text = response.text().await.unwrap_or_default();
return Err(AppError::llm(format!(
"Gemini API error: {} - {}",
status, error_text
)));
}
process_gemini_stream(response, config, window, stream_event).await
}
/// 处理非流式聊天请求
pub async fn non_stream_chat(
client: &Client,
config: &ApiConfig,
messages: &[ChatMessage],
) -> Result<StandardModel2Output> {
let url = build_gemini_url(config, false)?;
let body = build_gemini_request_body(messages, config)?;
let response = client
.post(&url)
.json(&body)
.timeout(Duration::from_secs(300))
.send()
.await
.map_err(|e| AppError::network(format!("Gemini API request failed: {}", e)))?;
if !response.status().is_success() {
let status = response.status();
let error_text = response.text().await.unwrap_or_default();
return Err(AppError::llm(format!(
"Gemini API error: {} - {}",
status, error_text
)));
}
let response_json: Value = response.json().await
.map_err(|e| AppError::network(format!("Failed to parse Gemini response: {}", e)))?;
// 提取响应内容
let content = response_json
.pointer("/candidates/0/content/parts/0/text")
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
Ok(StandardModel2Output {
assistant_message: content,
raw_response: Some(serde_json::to_string(&response_json).unwrap_or_default()),
chain_of_thought_details: None,
})
}
/// 构建 Gemini API URL
fn build_gemini_url(config: &ApiConfig, stream: bool) -> Result<String> {
let endpoint = if stream { "streamGenerateContent" } else { "generateContent" };
Ok(format!(
"{}/v1beta/models/{}:{}?key={}",
config.base_url.trim_end_matches('/'),
config.model,
endpoint,
config.api_key
))
}
/// 将通用 ChatMessage 转换为 Gemini 的 `contents` 格式
fn to_gemini_contents(messages: &[ChatMessage], is_multimodal: bool) -> Vec<Value> {
let mut gemini_contents: Vec<Value> = Vec::new();
let mut last_role: Option<String> = None;
for msg in messages {
let current_role = if msg.role == "assistant" { "model" } else { "user" };
let mut parts = Vec::new();
// 处理多模态图片数据
if is_multimodal {
if let Some(base64_vec) = &msg.image_base64 {
for img_base64 in base64_vec {
parts.push(json!({
"inline_data": {
"mime_type": "image/jpeg",
"data": img_base64
}
}));
}
}
}
// 处理文本内容
if !msg.content.is_empty() {
parts.push(json!({ "text": msg.content }));
}
// Gemini 要求 user/model 角色交替出现,此处合并相同角色的连续消息
if last_role.as_deref() == Some(current_role) && !gemini_contents.is_empty() {
if let Some(last_content) = gemini_contents.last_mut() {
if let Some(last_parts) = last_content["parts"].as_array_mut() {
last_parts.extend(parts);
}
}
} else {
gemini_contents.push(json!({
"role": current_role,
"parts": parts
}));
last_role = Some(current_role.to_string());
}
}
gemini_contents
}
/// 构建 Gemini 请求体
fn build_gemini_request_body(messages: &[ChatMessage], config: &ApiConfig) -> Result<Value> {
Ok(json!({
"contents": to_gemini_contents(messages, config.is_multimodal),
"generationConfig": {
"temperature": config.temperature,
"maxOutputTokens": config.max_output_tokens,
}
}))
}
/// 处理 Gemini 的流式响应,并转换为 OpenAI SSE 格式发送到前端
async fn process_gemini_stream(
response: reqwest::Response,
config: &ApiConfig,
window: Window,
stream_event: &str,
) -> Result<StandardModel2Output> {
let mut byte_stream = response.bytes_stream();
let mut full_content = String::new();
let mut chunk_id_counter = 0;
while let Some(chunk_result) = byte_stream.next().await {
let chunk = chunk_result.map_err(|e| AppError::network(format!("Stream read error: {}", e)))?;
let chunk_str = String::from_utf8_lossy(&chunk);
for line in chunk_str.lines() {
if line.starts_with("data: ") {
let data = &line[6..];
if let Ok(json_data) = serde_json::from_str::<Value>(data) {
if let Some(text_delta) = json_data.pointer("/candidates/0/content/parts/0/text").and_then(Value::as_str) {
if !text_delta.is_empty() {
full_content.push_str(text_delta);
// 使用统一的 StreamChunk 结构体发送事件
let stream_chunk = StreamChunk {
content: text_delta.to_string(),
is_complete: false,
chunk_id: format!("gemini_chunk_{}", chunk_id_counter),
};
window.emit(stream_event, &stream_chunk)
.map_err(|e| AppError::unknown(format!("Failed to emit stream chunk: {}", e)))?;
chunk_id_counter += 1;
}
}
}
}
}
}
// 发送完成信号
let final_chunk = StreamChunk {
content: full_content.clone(),
is_complete: true,
chunk_id: format!("gemini_final_{}", chunk_id_counter),
};
window.emit(stream_event, &final_chunk)
.map_err(|e| AppError::unknown(format!("Failed to emit finish chunk: {}", e)))?;
Ok(StandardModel2Output {
assistant_message: full_content,
raw_response: Some("stream_response".to_string()),
chain_of_thought_details: None,
})
}
|
0015/LVGL_Joystick
| 3,446 |
examples/arduino_example/arduino_example.ino
|
/*
This example is based on WT32-SC01-Plus in Arduino environment. The graphics library uses LovyanGFX.
$ Tested version
Arduino ESP32: 3.0.4
LVGL: 9.2.0
LovyanGFX: 1.1.16
*/
#include "LGFX_WT32-SC01-Plus.h"
#include <lvgl.h>
#include <lvgl_joystick.h>
static LGFX tft;
#define TFT_HOR_RES 320
#define TFT_VER_RES 480
#define Movement_Factor 4 // You can adjust the amount of movement.
/* LVGL draw into this buffer, 1/10 screen size usually works well. The size is in bytes */
#define DRAW_BUF_SIZE (TFT_HOR_RES * TFT_VER_RES / 10 * (LV_COLOR_DEPTH / 8))
void *draw_buf_1;
/* Black Dot */
lv_obj_t *target;
/* Display flushing */
void my_disp_flush(lv_display_t *disp, const lv_area_t *area, uint8_t *px_map) {
uint32_t w = lv_area_get_width(area);
uint32_t h = lv_area_get_height(area);
tft.startWrite();
tft.setAddrWindow(area->x1, area->y1, w, h);
tft.writePixels((lgfx::rgb565_t *)px_map, w * h);
tft.endWrite();
lv_disp_flush_ready(disp);
}
/*Read the touchpad*/
void my_touchpad_read(lv_indev_t *indev, lv_indev_data_t *data) {
uint16_t touchX, touchY;
bool touched = tft.getTouch(&touchX, &touchY);
if (!touched) {
data->state = LV_INDEV_STATE_RELEASED;
} else {
data->state = LV_INDEV_STATE_PRESSED;
data->point.x = touchX;
data->point.y = touchY;
}
}
uint32_t millis_cb(void) {
return millis();
}
void setup() {
Serial.begin(115200);
display_init();
lv_init();
lv_tick_set_cb(millis_cb);
lv_display_t *disp = lv_display_create(TFT_HOR_RES, TFT_VER_RES);
draw_buf_1 = heap_caps_malloc(DRAW_BUF_SIZE, MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL);
lv_display_set_flush_cb(disp, my_disp_flush);
lv_display_set_buffers(disp, draw_buf_1, NULL, DRAW_BUF_SIZE, LV_DISPLAY_RENDER_MODE_PARTIAL);
lv_indev_t *indev = lv_indev_create();
lv_indev_set_type(indev, LV_INDEV_TYPE_POINTER);
lv_indev_set_read_cb(indev, my_touchpad_read);
ui_init();
}
void loop() {
lv_task_handler();
}
void display_init() {
tft.begin();
tft.setRotation(2);
tft.setBrightness(255);
}
// Example callback function
void joystick_position_callback(uint8_t joystick_id, int16_t x, int16_t y) {
Serial.printf("Joystick ID: %d, Position - X: %d, Y: %d\n", joystick_id, x, y);
int16_t _x = lv_obj_get_x_aligned(target) + (x * Movement_Factor);
int16_t _y = lv_obj_get_y_aligned(target) + (y * Movement_Factor);
lv_obj_set_pos(target, _x, _y);
}
void ui_init() {
// Main screen style
static lv_style_t style_base;
lv_style_init(&style_base);
lv_style_set_border_width(&style_base, 0);
// Main screen
lv_obj_t *screen = lv_obj_create(lv_screen_active());
lv_obj_set_size(screen, TFT_HOR_RES, TFT_VER_RES);
lv_obj_center(screen);
lv_obj_add_style(screen, &style_base, LV_PART_MAIN);
lv_obj_clear_flag(screen, LV_OBJ_FLAG_SCROLLABLE);
// Moving target style
static lv_style_t style_target;
lv_style_init(&style_target);
lv_style_set_border_width(&style_target, 4);
lv_style_set_radius(&style_target, 20);
lv_style_set_bg_color(&style_target, lv_color_black());
// Moving target object
target = lv_obj_create(screen);
lv_obj_set_size(target, 40, 40);
lv_obj_set_pos(target, TFT_HOR_RES / 2 - 30, TFT_VER_RES / 2 - 40);
lv_obj_add_style(target, &style_target, LV_PART_MAIN);
// Create joystick
create_joystick(screen, 10, LV_ALIGN_BOTTOM_MID, 0, 0, 100, 25, NULL, NULL, joystick_position_callback);
Serial.println("UI DRAW Done");
}
|
0015/LVGL_Joystick
| 10,838 |
examples/espidf_example/main/main.c
|
/*
This example is based on WT32-SC01-Plus in ESP-IDF environment.
Using BSP-IDF5-ESP_LCD-LVGL9 [https://github.com/sukesh-ak/BSP-IDF5-ESP_LCD-LVGL9]
$ Tested version
ESP-IDF: 5.3.0
LVGL: 9.2.0
esp_lvgl_port: 2.3.1
esp_lcd_st7796: 1.3.0
esp_lcd_touch_ft5x06: 1.0.6
*/
#include <stdio.h>
#include <inttypes.h>
#include "sdkconfig.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_err.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "driver/ledc.h"
#include "driver/i2c.h"
#include "driver/spi_master.h"
#include "esp_lcd_types.h"
#include "esp_lcd_st7796.h"
#include "esp_lcd_panel_io.h"
#include "esp_lcd_panel_ops.h"
#include "esp_lvgl_port.h"
#include "esp_lcd_touch_ft5x06.h"
#include "lvgl.h"
#include "lvgl_joystick.h"
static const char *TAG = "WT32-SC01_Plus";
#define BSP_I2C_SCL (GPIO_NUM_5)
#define BSP_I2C_SDA (GPIO_NUM_6)
/* LCD display color format */
#define BSP_LCD_COLOR_FORMAT (1) //RGB565
/* LCD display color bytes endianess */
#define BSP_LCD_BIGENDIAN (1)
/* LCD display color bits */
#define BSP_LCD_BITS_PER_PIXEL (16)
/* LCD display color space */
#define BSP_LCD_COLOR_SPACE (ESP_LCD_COLOR_SPACE_BGR)
/* LCD definition */
#define BSP_LCD_H_RES (320)
#define BSP_LCD_V_RES (480)
#define BSP_LCD_PIXEL_CLOCK_HZ (40 * 1000 * 1000)
/* Display - ST7789 8 Bit parellel */
#define BSP_LCD_WIDTH (8)
#define BSP_LCD_DATA0 (GPIO_NUM_9)
#define BSP_LCD_DATA1 (GPIO_NUM_46)
#define BSP_LCD_DATA2 (GPIO_NUM_3)
#define BSP_LCD_DATA3 (GPIO_NUM_8)
#define BSP_LCD_DATA4 (GPIO_NUM_18)
#define BSP_LCD_DATA5 (GPIO_NUM_17)
#define BSP_LCD_DATA6 (GPIO_NUM_16)
#define BSP_LCD_DATA7 (GPIO_NUM_15)
#define BSP_LCD_CS (GPIO_NUM_NC)
#define BSP_LCD_DC (GPIO_NUM_0)
#define BSP_LCD_WR (GPIO_NUM_47)
#define BSP_LCD_RD (GPIO_NUM_NC)
#define BSP_LCD_RST (GPIO_NUM_4)
#define BSP_LCD_TE (GPIO_NUM_48)
#define BSP_LCD_BACKLIGHT (GPIO_NUM_45)
#define BSP_LCD_TP_INT (GPIO_NUM_7)
#define BSP_LCD_TP_RST (GPIO_NUM_NC)
#define LCD_CMD_BITS 8
#define LCD_PARAM_BITS 8
#define LCD_LEDC_CH 1
#define BSP_I2C_NUM 1
#define BSP_I2C_CLK_SPEED_HZ 400000
#define Movement_Factor 4 // You can adjust the amount of movement.
static esp_lcd_touch_handle_t tp; // LCD touch handle
static esp_lcd_panel_handle_t panel_handle = NULL;
/* Black Dot */
lv_obj_t *target;
esp_err_t bsp_i2c_init(void) {
const i2c_config_t i2c_conf = {
.mode = I2C_MODE_MASTER,
.sda_io_num = BSP_I2C_SDA,
.sda_pullup_en = GPIO_PULLUP_ENABLE,
.scl_io_num = BSP_I2C_SCL,
.scl_pullup_en = GPIO_PULLUP_ENABLE,
.master.clk_speed = BSP_I2C_CLK_SPEED_HZ
};
/* Initialize I2C */
ESP_ERROR_CHECK(i2c_param_config(BSP_I2C_NUM, &i2c_conf));
ESP_ERROR_CHECK(i2c_driver_install(BSP_I2C_NUM, i2c_conf.mode, 0, 0, 0));
ESP_LOGI(TAG, "Initialize touch IO (I2C)");
return ESP_OK;
}
esp_err_t bsp_i2c_deinit(void) {
ESP_ERROR_CHECK(i2c_driver_delete(BSP_I2C_NUM));
ESP_LOGI(TAG, "De-Initialize touch IO (I2C)");
return ESP_OK;
}
esp_err_t bsp_touch_new()
{
/* Initilize I2C */
ESP_ERROR_CHECK(bsp_i2c_init());
/* Initialize touch */
const esp_lcd_touch_config_t tp_cfg = {
.x_max = BSP_LCD_V_RES,
.y_max = BSP_LCD_H_RES,
.rst_gpio_num = BSP_LCD_TP_RST, // Shared with LCD reset
.int_gpio_num = BSP_LCD_TP_INT,
.levels = {
.reset = 0,
.interrupt = 0,
},
.flags = {
.swap_xy = 0,
.mirror_x = 0,
.mirror_y = 0,
},
};
esp_lcd_panel_io_handle_t tp_io_handle = NULL;
const esp_lcd_panel_io_i2c_config_t tp_io_config = ESP_LCD_TOUCH_IO_I2C_FT5x06_CONFIG();
ESP_ERROR_CHECK(esp_lcd_new_panel_io_i2c((esp_lcd_i2c_bus_handle_t)BSP_I2C_NUM, &tp_io_config, &tp_io_handle));
ESP_ERROR_CHECK(esp_lcd_touch_new_i2c_ft5x06(tp_io_handle, &tp_cfg, &tp));
assert(tp);
return ESP_OK;
}
lv_indev_t *bsp_display_indev_init(lv_display_t *disp) {
ESP_ERROR_CHECK(bsp_touch_new(NULL, &tp));
assert(tp);
/* Add touch input (for selected screen) */
const lvgl_port_touch_cfg_t touch_cfg = {
.disp = disp,
.handle = tp,
};
return lvgl_port_add_touch(&touch_cfg);
}
static esp_err_t bsp_display_brightness_init(void)
{
// Setup LEDC peripheral for PWM backlight control
const ledc_channel_config_t LCD_backlight_channel = {
.gpio_num = BSP_LCD_BACKLIGHT,
.speed_mode = LEDC_LOW_SPEED_MODE,
.channel = LCD_LEDC_CH,
.intr_type = LEDC_INTR_DISABLE,
.timer_sel = 1,
.duty = 0,
.hpoint = 0
};
const ledc_timer_config_t LCD_backlight_timer = {
.speed_mode = LEDC_LOW_SPEED_MODE,
.duty_resolution = LEDC_TIMER_10_BIT,
.timer_num = 1,
.freq_hz = 5000,
.clk_cfg = LEDC_AUTO_CLK
};
ESP_ERROR_CHECK(ledc_timer_config(&LCD_backlight_timer));
ESP_ERROR_CHECK(ledc_channel_config(&LCD_backlight_channel));
return ESP_OK;
}
esp_err_t bsp_display_brightness_set(int percent)
{
if (percent > 100) {
percent = 100;
}
if (percent < 0) {
percent = 0;
}
ESP_LOGI(TAG, "Setting LCD backlight: %d%%", percent);
uint32_t duty_cycle = (1023 * percent) / 100;
ESP_ERROR_CHECK(ledc_set_duty(LEDC_LOW_SPEED_MODE, LCD_LEDC_CH, duty_cycle));
ESP_ERROR_CHECK(ledc_update_duty(LEDC_LOW_SPEED_MODE, LCD_LEDC_CH));
return ESP_OK;
}
void display_start(void)
{
/* Init Intel 8080 bus */
esp_lcd_i80_bus_handle_t i80_bus = NULL;
esp_lcd_i80_bus_config_t bus_config = {
.clk_src = LCD_CLK_SRC_PLL160M,
.dc_gpio_num = BSP_LCD_DC,
.wr_gpio_num = BSP_LCD_WR,
.data_gpio_nums = {
BSP_LCD_DATA0,
BSP_LCD_DATA1,
BSP_LCD_DATA2,
BSP_LCD_DATA3,
BSP_LCD_DATA4,
BSP_LCD_DATA5,
BSP_LCD_DATA6,
BSP_LCD_DATA7,
},
.bus_width = BSP_LCD_WIDTH,
.max_transfer_bytes = (BSP_LCD_H_RES) * 128 * sizeof(uint16_t),
.psram_trans_align = 64,
.sram_trans_align = 4,
};
ESP_ERROR_CHECK(esp_lcd_new_i80_bus(&bus_config, &i80_bus));
ESP_LOGD(TAG, "Install panel IO");
esp_lcd_panel_io_handle_t io_handle = NULL;
esp_lcd_panel_io_i80_config_t io_config = {
.cs_gpio_num = BSP_LCD_CS,
.pclk_hz = BSP_LCD_PIXEL_CLOCK_HZ,
.trans_queue_depth = 10,
.dc_levels = {
.dc_idle_level = 0,
.dc_cmd_level = 0,
.dc_dummy_level = 0,
.dc_data_level = 1,
},
.flags = {
.swap_color_bytes = 1,
.pclk_idle_low = 0,
},
.lcd_cmd_bits = LCD_CMD_BITS,
.lcd_param_bits = LCD_PARAM_BITS,
};
ESP_ERROR_CHECK(esp_lcd_new_panel_io_i80(i80_bus, &io_config, &io_handle));
ESP_LOGD(TAG, "Install LCD driver of ST7796");
esp_lcd_panel_dev_config_t panel_config = {
.reset_gpio_num = BSP_LCD_RST,
.rgb_endian = LCD_RGB_ENDIAN_BGR,
.bits_per_pixel = 16,
};
ESP_ERROR_CHECK(esp_lcd_new_panel_st7796(io_handle, &panel_config, &panel_handle));
ESP_ERROR_CHECK(esp_lcd_panel_reset(panel_handle));
ESP_ERROR_CHECK(esp_lcd_panel_init(panel_handle));
// Set inversion, x/y coordinate order, x/y mirror according to your LCD module spec
// the gap is LCD panel specific, even panels with the same driver IC, can have different gap value
esp_lcd_panel_invert_color(panel_handle, true);
esp_lcd_panel_mirror(panel_handle, true, false);
// user can flush pre-defined pattern to the screen before we turn on the screen or backlight
ESP_ERROR_CHECK(esp_lcd_panel_disp_on_off(panel_handle, false));
/* Add LCD screen */
ESP_LOGD(TAG, "Add LCD screen");
const lvgl_port_display_cfg_t disp_cfg = {
.io_handle = io_handle,
.panel_handle = panel_handle,
.buffer_size = (BSP_LCD_H_RES * BSP_LCD_V_RES) /10,
.trans_size = BSP_LCD_H_RES * BSP_LCD_V_RES,
.double_buffer = true,
.hres = BSP_LCD_H_RES,
.vres = BSP_LCD_V_RES,
.monochrome = false,
/* Rotation values must be same as used in esp_lcd for initial settings of the screen */
.rotation = {
.swap_xy = false,
.mirror_x = true,
.mirror_y = false,
},
.flags = {
.buff_dma = true,
.buff_spiram = false,
}
};
const lvgl_port_cfg_t lvgl_cfg = ESP_LVGL_PORT_INIT_CONFIG();
ESP_ERROR_CHECK(lvgl_port_init(&lvgl_cfg));
lv_display_t * disp = lvgl_port_add_disp(&disp_cfg);
bsp_display_indev_init(disp);
lv_disp_set_rotation(disp, LV_DISP_ROTATION_180);
ESP_ERROR_CHECK(bsp_display_brightness_init());
}
esp_err_t bsp_display_on(void)
{
ESP_ERROR_CHECK(esp_lcd_panel_disp_on_off(panel_handle, true));
return ESP_OK;
}
// Example callback function
void joystick_position_callback(uint8_t joystick_id, int16_t x, int16_t y) {
printf("Joystick ID: %d, Position - X: %d, Y: %d\n", joystick_id, x, y);
int16_t _x = lv_obj_get_x_aligned(target) + (x * Movement_Factor);
int16_t _y = lv_obj_get_y_aligned(target) + (y * Movement_Factor);
lv_obj_set_pos(target, _x, _y);
}
/* Entry point to LVGL UI */
void ui_init()
{
// Main screen style
static lv_style_t style_base;
lv_style_init(&style_base);
lv_style_set_border_width(&style_base, 0);
// Main screen
lv_obj_t *screen = lv_obj_create(lv_screen_active());
lv_obj_set_size(screen, BSP_LCD_H_RES, BSP_LCD_V_RES);
lv_obj_center(screen);
lv_obj_add_style(screen, &style_base, LV_PART_MAIN);
lv_obj_clear_flag(screen, LV_OBJ_FLAG_SCROLLABLE);
// Moving target style
static lv_style_t style_target;
lv_style_init(&style_target);
lv_style_set_border_width(&style_target, 4);
lv_style_set_radius(&style_target, 20);
lv_style_set_bg_color(&style_target, lv_color_black());
// Moving target object
target = lv_obj_create(screen);
lv_obj_set_size(target, 40, 40);
lv_obj_set_pos(target, BSP_LCD_H_RES / 2 - 30, BSP_LCD_V_RES / 2 - 40);
lv_obj_add_style(target, &style_target, LV_PART_MAIN);
// Create joystick
create_joystick(screen, 10, LV_ALIGN_BOTTOM_MID, 0, 0, 100, 25, NULL, NULL, joystick_position_callback);
printf("UI DRAW Done\n");
}
void app_main(void)
{
display_start();
bsp_display_brightness_set(100);
ui_init();
bsp_display_on();
}
|
000haoji/deep-student
| 5,045 |
src-tauri/src/cogni_graph/models.rs
|
use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ProblemCard {
pub id: String,
pub content_problem: String,
pub content_insight: String,
pub status: String, // 'unsolved', 'solved'
pub embedding: Option<Vec<f32>>,
pub created_at: DateTime<Utc>,
pub last_accessed_at: DateTime<Utc>,
pub access_count: i32,
pub source_excalidraw_path: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Tag {
pub id: String,
pub name: String,
pub tag_type: TagType,
pub level: i32, // 0=根节点, 1=一级分类, 2=二级分类, etc.
pub description: Option<String>,
pub created_at: DateTime<Utc>,
}
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub enum TagType {
#[default]
KnowledgeArea, // 知识领域 (如: 代数、几何)
Topic, // 主题 (如: 函数、三角形)
Concept, // 概念 (如: 二次函数、等腰三角形)
Method, // 方法 (如: 换元法、辅助线法)
Difficulty, // 难度 (如: 基础、进阶、竞赛)
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Relationship {
pub from_id: String,
pub to_id: String,
pub relationship_type: RelationshipType,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum RelationshipType {
// ProblemCard 关系
HasTag,
IsVariationOf,
UsesGeneralMethod,
ContrastsWith,
// Tag 层次关系
ParentOf, // 父标签关系
ChildOf, // 子标签关系 (ParentOf的反向)
RelatedTo, // 相关标签
PrerequisiteOf, // 前置知识关系
}
impl ToString for RelationshipType {
fn to_string(&self) -> String {
match self {
RelationshipType::HasTag => "HAS_TAG".to_string(),
RelationshipType::IsVariationOf => "IS_VARIATION_OF".to_string(),
RelationshipType::UsesGeneralMethod => "USES_GENERAL_METHOD".to_string(),
RelationshipType::ContrastsWith => "CONTRASTS_WITH".to_string(),
RelationshipType::ParentOf => "PARENT_OF".to_string(),
RelationshipType::ChildOf => "CHILD_OF".to_string(),
RelationshipType::RelatedTo => "RELATED_TO".to_string(),
RelationshipType::PrerequisiteOf => "PREREQUISITE_OF".to_string(),
}
}
}
impl ToString for TagType {
fn to_string(&self) -> String {
match self {
TagType::KnowledgeArea => "knowledge_area".to_string(),
TagType::Topic => "topic".to_string(),
TagType::Concept => "concept".to_string(),
TagType::Method => "method".to_string(),
TagType::Difficulty => "difficulty".to_string(),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SearchRequest {
pub query: String,
pub limit: Option<usize>,
pub libraries: Option<Vec<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SearchResult {
pub card: ProblemCard,
pub score: f32,
pub matched_by: Vec<String>, // "vector", "fulltext", "graph"
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RecommendationRequest {
pub card_id: String,
pub limit: Option<usize>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Recommendation {
pub card: ProblemCard,
pub relationship_type: RelationshipType,
pub confidence: f32,
pub reasoning: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CreateCardRequest {
pub content_problem: String,
pub content_insight: String,
pub tags: Vec<String>,
pub source_excalidraw_path: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CreateTagRequest {
pub name: String,
pub tag_type: TagType,
pub parent_id: Option<String>,
pub description: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct TagHierarchy {
pub tag: Tag,
pub children: Vec<TagHierarchy>,
pub parent: Option<Tag>,
}
impl ProblemCard {
pub fn new(
content_problem: String,
content_insight: String,
source_excalidraw_path: Option<String>,
) -> Self {
let now = Utc::now();
Self {
id: uuid::Uuid::new_v4().to_string(),
content_problem,
content_insight,
status: "unsolved".to_string(),
embedding: None,
created_at: now,
last_accessed_at: now,
access_count: 0,
source_excalidraw_path,
}
}
pub fn get_combined_content(&self) -> String {
format!("{}\n{}", self.content_problem, self.content_insight)
}
pub fn mark_accessed(&mut self) {
self.last_accessed_at = Utc::now();
self.access_count += 1;
}
}
impl Tag {
pub fn new(name: String, tag_type: TagType, level: i32, description: Option<String>) -> Self {
Self {
id: uuid::Uuid::new_v4().to_string(),
name,
tag_type,
level,
description,
created_at: Utc::now(),
}
}
pub fn get_type_string(&self) -> String {
self.tag_type.to_string()
}
}
|
000haoji/deep-student
| 12,040 |
src-tauri/src/cogni_graph/handlers.rs
|
use crate::cogni_graph::{
GraphConfig, GraphService, SearchService, CreateCardRequest, SearchRequest,
RecommendationRequest, ProblemCard, SearchResult, Recommendation, Tag,
CreateTagRequest, TagHierarchy, TagType
};
use crate::commands::AppState;
use crate::llm_manager::LLMManager;
use anyhow::{Result, anyhow};
use std::sync::Arc;
use tokio::sync::RwLock;
use tauri::State;
// Global state for the graph services
pub struct GraphState {
pub graph_service: Option<GraphService>,
pub search_service: Option<SearchService>,
pub config: GraphConfig,
}
impl GraphState {
pub fn new() -> Self {
Self {
graph_service: None,
search_service: None,
config: GraphConfig::default(),
}
}
}
// Tauri commands for the knowledge graph
#[tauri::command]
pub async fn initialize_knowledge_graph(
config: GraphConfig,
graph_state: State<'_, Arc<RwLock<GraphState>>>,
app_state: State<'_, AppState>,
) -> Result<String, String> {
let mut state = graph_state.write().await;
// Initialize services
let graph_service = GraphService::new(config.clone(), app_state.llm_manager.clone())
.await
.map_err(|e| format!("Failed to initialize graph service: {}", e))?;
let search_service = SearchService::new(config.clone(), app_state.llm_manager.clone())
.await
.map_err(|e| format!("Failed to initialize search service: {}", e))?;
state.graph_service = Some(graph_service);
state.search_service = Some(search_service);
state.config = config;
Ok("Knowledge graph initialized successfully".to_string())
}
#[tauri::command]
pub async fn create_problem_card(
request: CreateCardRequest,
graph_state: State<'_, Arc<RwLock<GraphState>>>,
) -> Result<String, String> {
let state = graph_state.read().await;
let service = state.graph_service.as_ref()
.ok_or("Graph service not initialized")?;
service.create_problem_card(request)
.await
.map_err(|e| format!("Failed to create problem card: {}", e))
}
#[tauri::command]
pub async fn get_problem_card(
card_id: String,
graph_state: tauri::State<'_, Arc<RwLock<GraphState>>>,
) -> Result<Option<ProblemCard>, String> {
let state = graph_state.read().await;
let service = state.graph_service.as_ref()
.ok_or("Graph service not initialized")?;
service.get_problem_card(&card_id)
.await
.map_err(|e| format!("Failed to get problem card: {}", e))
}
#[tauri::command]
pub async fn search_knowledge_graph(
request: SearchRequest,
graph_state: tauri::State<'_, Arc<RwLock<GraphState>>>,
) -> Result<Vec<SearchResult>, String> {
let state = graph_state.read().await;
let service = state.search_service.as_ref()
.ok_or("Search service not initialized")?;
service.search(request)
.await
.map_err(|e| format!("Failed to search knowledge graph: {}", e))
}
#[tauri::command]
pub async fn get_ai_recommendations(
request: RecommendationRequest,
graph_state: tauri::State<'_, Arc<RwLock<GraphState>>>,
) -> Result<Vec<Recommendation>, String> {
let state = graph_state.read().await;
let service = state.graph_service.as_ref()
.ok_or("Graph service not initialized")?;
service.get_recommendations(request)
.await
.map_err(|e| format!("Failed to get recommendations: {}", e))
}
#[tauri::command]
pub async fn search_similar_cards(
card_id: String,
limit: Option<usize>,
graph_state: tauri::State<'_, Arc<RwLock<GraphState>>>,
) -> Result<Vec<SearchResult>, String> {
let state = graph_state.read().await;
let service = state.search_service.as_ref()
.ok_or("Search service not initialized")?;
service.search_similar_cards(&card_id, limit)
.await
.map_err(|e| format!("Failed to search similar cards: {}", e))
}
#[tauri::command]
pub async fn get_cards_by_tag(
tag_name: String,
limit: Option<usize>,
graph_state: tauri::State<'_, Arc<RwLock<GraphState>>>,
) -> Result<Vec<ProblemCard>, String> {
let state = graph_state.read().await;
let service = state.search_service.as_ref()
.ok_or("Search service not initialized")?;
service.get_cards_by_tag(&tag_name, limit)
.await
.map_err(|e| format!("Failed to get cards by tag: {}", e))
}
#[tauri::command]
pub async fn get_all_tags(
graph_state: tauri::State<'_, Arc<RwLock<GraphState>>>,
) -> Result<Vec<Tag>, String> {
let state = graph_state.read().await;
let service = state.search_service.as_ref()
.ok_or("Search service not initialized")?;
service.get_all_tags()
.await
.map_err(|e| format!("Failed to get all tags: {}", e))
}
#[tauri::command]
pub async fn get_graph_config(
graph_state: tauri::State<'_, Arc<RwLock<GraphState>>>,
) -> Result<GraphConfig, String> {
let state = graph_state.read().await;
Ok(state.config.clone())
}
#[tauri::command]
pub async fn update_graph_config(
config: GraphConfig,
graph_state: tauri::State<'_, Arc<RwLock<GraphState>>>,
app_state: State<'_, AppState>,
) -> Result<String, String> {
// Reinitialize services with new config
initialize_knowledge_graph(config, graph_state, app_state).await
}
#[tauri::command]
pub async fn test_neo4j_connection(
config: GraphConfig,
) -> Result<String, String> {
use crate::cogni_graph::Neo4jService;
match Neo4jService::new(config).await {
Ok(_) => Ok("Connection successful".to_string()),
Err(e) => Err(format!("Connection failed: {}", e)),
}
}
// OCR integration command for handwritten input
#[tauri::command]
pub async fn process_handwritten_input(
_image_data: String, // Base64 encoded image
_graph_state: tauri::State<'_, Arc<RwLock<GraphState>>>,
app_state: State<'_, AppState>,
) -> Result<CreateCardRequest, String> {
// Use existing LLM manager for OCR processing
let llm_manager = &app_state.llm_manager;
// Convert base64 image to temporary file for OCR processing
// Note: For now, we'll create a simple text extraction since image processing needs proper file handling
let ocr_result = llm_manager.call_unified_model_1(
vec![], // Empty image paths for now
"Extract mathematical problem and solution from the provided content. Format as JSON with 'problem' and 'insight' fields.",
"数学", // Default subject
Some("OCR extraction task")
).await.map_err(|e| format!("OCR processing failed: {}", e))?;
// Parse OCR result from StandardModel1Output
let content_problem = if !ocr_result.ocr_text.is_empty() {
ocr_result.ocr_text.clone()
} else {
"手写内容识别中...".to_string()
};
let content_insight = "请在此处添加解题洞察和思路".to_string();
// Auto-generate tags based on content
let tags = generate_auto_tags(&content_problem, &content_insight, llm_manager)
.await
.unwrap_or_default();
Ok(CreateCardRequest {
content_problem,
content_insight,
tags,
source_excalidraw_path: None,
})
}
async fn generate_auto_tags(problem: &str, insight: &str, llm_manager: &Arc<LLMManager>) -> Result<Vec<String>> {
let prompt = format!(
r#"Analyze this mathematical problem and solution to generate relevant tags:
Problem: {}
Solution: {}
Generate 3-5 tags that categorize this content. Focus on:
- Mathematical topics (e.g., "calculus", "algebra", "geometry")
- Solution methods (e.g., "substitution", "integration_by_parts")
- Difficulty level (e.g., "basic", "intermediate", "advanced")
Respond with a JSON array of strings: ["tag1", "tag2", "tag3"]"#,
problem, insight
);
let response = llm_manager.call_unified_model_1(
vec![], // No images
&prompt,
"数学", // Default subject
Some("Tag generation task")
).await?;
// Extract tags from OCR text or use default tags
let tags = if !response.tags.is_empty() {
response.tags
} else {
vec!["数学".to_string(), "解题".to_string()]
};
Ok(tags)
}
// Tag management commands
#[tauri::command]
pub async fn create_tag(
request: CreateTagRequest,
graph_state: State<'_, Arc<RwLock<GraphState>>>,
) -> Result<String, String> {
let state = graph_state.read().await;
if let Some(ref graph_service) = state.graph_service {
graph_service.create_tag(request).await
.map_err(|e| format!("Failed to create tag: {}", e))
} else {
Err("Graph service not initialized".to_string())
}
}
#[tauri::command]
pub async fn get_tag_hierarchy(
root_tag_id: Option<String>,
graph_state: State<'_, Arc<RwLock<GraphState>>>,
) -> Result<Vec<TagHierarchy>, String> {
let state = graph_state.read().await;
if let Some(ref graph_service) = state.graph_service {
graph_service.get_tag_hierarchy(root_tag_id).await
.map_err(|e| format!("Failed to get tag hierarchy: {}", e))
} else {
Err("Graph service not initialized".to_string())
}
}
#[tauri::command]
pub async fn get_tags_by_type(
tag_type: TagType,
graph_state: State<'_, Arc<RwLock<GraphState>>>,
) -> Result<Vec<Tag>, String> {
let state = graph_state.read().await;
if let Some(ref graph_service) = state.graph_service {
graph_service.get_tags_by_type(tag_type).await
.map_err(|e| format!("Failed to get tags by type: {}", e))
} else {
Err("Graph service not initialized".to_string())
}
}
#[tauri::command]
pub async fn initialize_default_tag_hierarchy(
graph_state: State<'_, Arc<RwLock<GraphState>>>,
) -> Result<String, String> {
let state = graph_state.read().await;
if let Some(ref graph_service) = state.graph_service {
// Create default hierarchy for mathematics
let math_areas = vec![
("代数", TagType::KnowledgeArea, None, Some("代数学相关内容".to_string())),
("几何", TagType::KnowledgeArea, None, Some("几何学相关内容".to_string())),
("解析几何", TagType::KnowledgeArea, None, Some("解析几何相关内容".to_string())),
("概率统计", TagType::KnowledgeArea, None, Some("概率与统计相关内容".to_string())),
];
let mut created_ids: Vec<(String, String)> = Vec::new();
// Create knowledge areas
for (name, tag_type, parent_id, description) in math_areas {
let request = CreateTagRequest {
name: name.to_string(),
tag_type,
parent_id: parent_id.clone(),
description,
};
match graph_service.create_tag(request).await {
Ok(id) => {
created_ids.push((name.to_string(), id));
},
Err(e) => eprintln!("Failed to create tag {}: {}", name, e),
}
}
// Create some topics under algebra
if let Some((_, algebra_id)) = created_ids.iter().find(|(name, _)| name == "代数") {
let algebra_topics = vec![
("函数", TagType::Topic, Some("函数相关概念和方法".to_string())),
("方程", TagType::Topic, Some("方程求解方法".to_string())),
("不等式", TagType::Topic, Some("不等式相关内容".to_string())),
];
for (name, tag_type, description) in algebra_topics {
let request = CreateTagRequest {
name: name.to_string(),
tag_type,
parent_id: Some(algebra_id.clone()),
description,
};
if let Err(e) = graph_service.create_tag(request).await {
eprintln!("Failed to create topic {}: {}", name, e);
}
}
}
Ok(format!("Created default tag hierarchy with {} top-level areas", created_ids.len()))
} else {
Err("Graph service not initialized".to_string())
}
}
|
000haoji/deep-student
| 1,044 |
src-tauri/src/cogni_graph/config.rs
|
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Neo4jConfig {
pub uri: String,
pub username: String,
pub password: String,
pub database: Option<String>,
}
impl Default for Neo4jConfig {
fn default() -> Self {
Self {
uri: "bolt://localhost:7687".to_string(),
username: "neo4j".to_string(),
password: "password".to_string(),
database: None,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GraphConfig {
pub neo4j: Neo4jConfig,
pub vector_dimensions: usize,
pub similarity_threshold: f32,
pub max_search_results: usize,
pub recommendation_limit: usize,
}
impl Default for GraphConfig {
fn default() -> Self {
Self {
neo4j: Neo4jConfig::default(),
vector_dimensions: 1536, // OpenAI embedding dimensions
similarity_threshold: 0.7,
max_search_results: 100,
recommendation_limit: 10,
}
}
}
|
000haoji/deep-student
| 10,812 |
src-tauri/src/cogni_graph/services/search_service.rs
|
use crate::cogni_graph::{
GraphConfig, ProblemCard, SearchRequest, SearchResult, Neo4jService, Tag, TagType
};
use crate::llm_manager::LLMManager;
use anyhow::{Result, anyhow};
use std::sync::Arc;
use std::collections::{HashMap, HashSet};
use tokio::sync::RwLock;
pub struct SearchService {
neo4j: Neo4jService,
llm_manager: Arc<LLMManager>,
config: GraphConfig,
}
impl SearchService {
pub async fn new(config: GraphConfig, llm_manager: Arc<LLMManager>) -> Result<Self> {
let neo4j = Neo4jService::new(config.clone()).await?;
Ok(Self {
neo4j,
llm_manager,
config,
})
}
pub async fn search(&self, request: SearchRequest) -> Result<Vec<SearchResult>> {
let limit = request.limit.unwrap_or(self.config.max_search_results);
// Step 1: Multi-path recall
let (vector_results, fulltext_results) = self.multi_path_recall(&request.query, limit).await?;
// Step 2: Merge and deduplicate results
let merged_ids = self.merge_recall_results(vector_results, fulltext_results);
// Step 3: Fetch full card data
let cards_with_scores = self.fetch_cards_with_scores(merged_ids).await?;
// Step 4: Re-rank using configurable weights
let ranked_results = self.rerank_results(cards_with_scores, &request.query).await?;
// Step 5: Apply final limit and return
Ok(ranked_results.into_iter().take(limit).collect())
}
async fn multi_path_recall(&self, query: &str, limit: usize) -> Result<(Vec<(String, f32)>, Vec<(String, f32)>)> {
// Generate query embedding for vector search
let query_embedding = {
let llm_manager = &self.llm_manager;
let model_assignments = llm_manager.get_model_assignments().await.unwrap_or(crate::models::ModelAssignments {
model1_config_id: None,
model2_config_id: None,
review_analysis_model_config_id: None,
anki_card_model_config_id: None,
embedding_model_config_id: None,
reranker_model_config_id: None,
summary_model_config_id: None,
});
let embedding_config_id = model_assignments.embedding_model_config_id
.unwrap_or_else(|| "default".to_string());
match llm_manager.call_embedding_api(vec![query.to_string()], &embedding_config_id).await {
Ok(embeddings) if !embeddings.is_empty() => embeddings[0].clone(),
_ => vec![0.0; self.config.vector_dimensions]
}
};
// Execute both searches in parallel
let (vector_future, fulltext_future) = tokio::join!(
self.neo4j.vector_search(&query_embedding, limit),
self.neo4j.fulltext_search(query, limit)
);
let vector_results = vector_future.unwrap_or_default();
let fulltext_results = fulltext_future.unwrap_or_default();
Ok((vector_results, fulltext_results))
}
fn merge_recall_results(&self, vector_results: Vec<(String, f32)>, fulltext_results: Vec<(String, f32)>) -> Vec<(String, f32, Vec<String>)> {
let mut score_map: HashMap<String, (f32, Vec<String>)> = HashMap::new();
// Add vector search results
for (id, score) in vector_results {
score_map.insert(id.clone(), (score, vec!["vector".to_string()]));
}
// Merge fulltext search results
for (id, score) in fulltext_results {
match score_map.get_mut(&id) {
Some((existing_score, matched_by)) => {
// Average the scores if found by both methods
*existing_score = (*existing_score + score) / 2.0;
matched_by.push("fulltext".to_string());
}
None => {
score_map.insert(id.clone(), (score * 0.8, vec!["fulltext".to_string()])); // Weight fulltext slightly lower
}
}
}
// Convert to vector and sort by score
let mut merged_results: Vec<(String, f32, Vec<String>)> = score_map
.into_iter()
.map(|(id, (score, matched_by))| (id, score, matched_by))
.collect();
merged_results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
merged_results
}
async fn fetch_cards_with_scores(&self, merged_results: Vec<(String, f32, Vec<String>)>) -> Result<Vec<(ProblemCard, f32, Vec<String>)>> {
let mut cards_with_scores = Vec::new();
for (id, score, matched_by) in merged_results {
if let Some(card) = self.neo4j.get_problem_card(&id).await? {
cards_with_scores.push((card, score, matched_by));
}
}
Ok(cards_with_scores)
}
async fn rerank_results(&self, cards_with_scores: Vec<(ProblemCard, f32, Vec<String>)>, query: &str) -> Result<Vec<SearchResult>> {
// Configurable weights for different factors
let vector_weight = 0.4;
let fulltext_weight = 0.3;
let access_count_weight = 0.1;
let recency_weight = 0.1;
let multi_match_bonus = 0.1;
let mut search_results = Vec::new();
let current_time = chrono::Utc::now();
for (card, base_score, matched_by) in cards_with_scores {
// Calculate component scores
let mut final_score = base_score;
// Access count factor (normalized)
let access_factor = (card.access_count as f32).ln_1p() / 10.0; // Logarithmic scaling
final_score += access_factor * access_count_weight;
// Recency factor (days since last access, inverse relationship)
let days_since_access = (current_time - card.last_accessed_at).num_days() as f32;
let recency_factor = 1.0 / (1.0 + days_since_access / 30.0); // Decay over 30 days
final_score += recency_factor * recency_weight;
// Multi-match bonus (found by both vector and fulltext)
if matched_by.len() > 1 {
final_score += multi_match_bonus;
}
// Ensure score is within reasonable bounds
final_score = final_score.min(1.0).max(0.0);
search_results.push(SearchResult {
card,
score: final_score,
matched_by,
});
}
// Sort by final score
search_results.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
Ok(search_results)
}
pub async fn search_similar_cards(&self, card_id: &str, limit: Option<usize>) -> Result<Vec<SearchResult>> {
let card = match self.neo4j.get_problem_card(card_id).await? {
Some(card) => card,
None => return Err(anyhow!("Card not found: {}", card_id)),
};
// Use the card's content as search query
let query = card.get_combined_content();
let request = SearchRequest {
query,
limit,
libraries: None,
};
let mut results = self.search(request).await?;
// Remove the original card from results
results.retain(|result| result.card.id != card_id);
Ok(results)
}
pub async fn get_cards_by_tag(&self, tag_name: &str, limit: Option<usize>) -> Result<Vec<ProblemCard>> {
// This would require a Cypher query to find all cards with a specific tag
// For now, we'll implement a simple version
let query = neo4rs::Query::new(
r#"
MATCH (pc:ProblemCard)-[:HAS_TAG]->(t:Tag {name: $tag_name})
RETURN pc.id, pc.content_problem, pc.content_insight, pc.status,
pc.embedding, pc.created_at, pc.last_accessed_at,
pc.access_count, pc.source_excalidraw_path
ORDER BY pc.last_accessed_at DESC
LIMIT $limit
"#.to_string()
)
.param("tag_name", tag_name)
.param("limit", limit.unwrap_or(50) as i64);
let rows = self.neo4j.execute_simple_query(query).await
.map_err(|e| anyhow!("Failed to query cards by tag: {}", e))?;
let mut cards = Vec::new();
for row in rows {
let embedding_str: String = row.get("pc.embedding").unwrap_or_default();
let embedding = if embedding_str != "null" && !embedding_str.is_empty() {
serde_json::from_str(&embedding_str).ok()
} else {
None
};
let card = ProblemCard {
id: row.get("pc.id").unwrap_or_default(),
content_problem: row.get("pc.content_problem").unwrap_or_default(),
content_insight: row.get("pc.content_insight").unwrap_or_default(),
status: row.get("pc.status").unwrap_or_default(),
embedding,
created_at: chrono::DateTime::parse_from_rfc3339(&row.get::<String>("pc.created_at").unwrap_or_default())
.unwrap_or_default().with_timezone(&chrono::Utc),
last_accessed_at: chrono::DateTime::parse_from_rfc3339(&row.get::<String>("pc.last_accessed_at").unwrap_or_default())
.unwrap_or_default().with_timezone(&chrono::Utc),
access_count: row.get("pc.access_count").unwrap_or_default(),
source_excalidraw_path: {
let path: String = row.get("pc.source_excalidraw_path").unwrap_or_default();
if path.is_empty() { None } else { Some(path) }
},
};
cards.push(card);
}
Ok(cards)
}
pub async fn get_all_tags(&self) -> Result<Vec<crate::cogni_graph::Tag>> {
use crate::cogni_graph::Tag;
let query = neo4rs::Query::new(
r#"
MATCH (t:Tag)
RETURN t.name, t.type
ORDER BY t.name
"#.to_string()
);
let rows = self.neo4j.execute_simple_query(query).await
.map_err(|e| anyhow!("Failed to query tags: {}", e))?;
let mut tags = Vec::new();
for row in rows {
let tag = Tag {
id: row.get("t.id").unwrap_or_default(),
name: row.get("t.name").unwrap_or_default(),
tag_type: TagType::Concept, // Default to concept for now
level: row.get("t.level").unwrap_or(0) as i32,
description: None,
created_at: chrono::Utc::now(),
};
tags.push(tag);
}
Ok(tags)
}
}
// Note: SearchService doesn't implement Clone due to Neo4jService limitations
|
000haoji/deep-student
| 10,053 |
src-tauri/src/cogni_graph/services/graph_service.rs
|
use crate::cogni_graph::{
GraphConfig, ProblemCard, Tag, CreateCardRequest, RecommendationRequest,
Recommendation, RelationshipType, Neo4jService, CreateTagRequest, TagHierarchy, TagType
};
use crate::llm_manager::LLMManager;
use anyhow::{Result, anyhow};
use std::sync::Arc;
use tokio::sync::RwLock;
pub struct GraphService {
neo4j: Neo4jService,
llm_manager: Arc<LLMManager>,
config: GraphConfig,
}
impl GraphService {
pub async fn new(config: GraphConfig, llm_manager: Arc<LLMManager>) -> Result<Self> {
let neo4j = Neo4jService::new(config.clone()).await?;
// Initialize Neo4j schema
neo4j.initialize_schema().await?;
Ok(Self {
neo4j,
llm_manager,
config,
})
}
pub async fn create_problem_card(&self, request: CreateCardRequest) -> Result<String> {
// Create initial problem card
let mut card = ProblemCard::new(
request.content_problem.clone(),
request.content_insight.clone(),
request.source_excalidraw_path,
);
// Generate embedding using existing LLM manager
let combined_content = card.get_combined_content();
let embedding = self.generate_embedding(&combined_content).await?;
card.embedding = Some(embedding);
// Store in Neo4j with tags
let card_id = self.neo4j.create_problem_card(card, request.tags).await?;
// Note: Skip async AI recommendations for now due to Clone limitations
// This can be implemented later using shared service instances or message passing
eprintln!("Note: AI recommendations will be generated on-demand via get_recommendations API");
Ok(card_id)
}
pub async fn get_problem_card(&self, card_id: &str) -> Result<Option<ProblemCard>> {
// Update access count
if let Err(e) = self.neo4j.update_access_count(card_id).await {
eprintln!("Failed to update access count for card {}: {}", card_id, e);
}
self.neo4j.get_problem_card(card_id).await
}
async fn generate_embedding(&self, text: &str) -> Result<Vec<f32>> {
let llm_manager = &self.llm_manager;
// Get embedding model assignment
let model_assignments = llm_manager.get_model_assignments().await.unwrap_or(crate::models::ModelAssignments {
model1_config_id: None,
model2_config_id: None,
review_analysis_model_config_id: None,
anki_card_model_config_id: None,
embedding_model_config_id: None,
reranker_model_config_id: None,
summary_model_config_id: None,
});
let embedding_config_id = model_assignments.embedding_model_config_id
.unwrap_or_else(|| "default".to_string());
match llm_manager.call_embedding_api(vec![text.to_string()], &embedding_config_id).await {
Ok(embeddings) if !embeddings.is_empty() => Ok(embeddings[0].clone()),
Ok(_) => {
eprintln!("No embeddings returned");
Ok(vec![0.0; self.config.vector_dimensions])
},
Err(e) => {
eprintln!("Failed to generate embedding: {}", e);
// Return zero vector as fallback
Ok(vec![0.0; self.config.vector_dimensions])
}
}
}
// Tag management methods
pub async fn create_tag(&self, request: CreateTagRequest) -> Result<String> {
self.neo4j.create_tag(request).await
}
pub async fn get_tag_hierarchy(&self, root_tag_id: Option<String>) -> Result<Vec<TagHierarchy>> {
self.neo4j.get_tag_hierarchy(root_tag_id).await
}
pub async fn get_tags_by_type(&self, tag_type: TagType) -> Result<Vec<Tag>> {
self.neo4j.get_tags_by_type(tag_type).await
}
async fn generate_ai_recommendations(&self, card_id: &str) -> Result<()> {
// Get the card details
let card = match self.neo4j.get_problem_card(card_id).await? {
Some(card) => card,
None => return Err(anyhow!("Card not found: {}", card_id)),
};
// Find candidate cards using multi-path recall
let candidates = self.find_candidate_cards(&card).await?;
// Generate AI recommendations for promising candidates
for (candidate_id, similarity_score) in candidates {
if similarity_score > self.config.similarity_threshold {
if let Some(candidate_card) = self.neo4j.get_problem_card(&candidate_id).await? {
// Use LLM to determine relationship type and confidence
if let Ok(recommendation) = self.analyze_relationship(&card, &candidate_card).await {
if recommendation.confidence > 0.7 {
// Create the relationship in Neo4j
if let Err(e) = self.neo4j.create_relationship(
&card.id,
&candidate_card.id,
recommendation.relationship_type.clone()
).await {
eprintln!("Failed to create relationship: {}", e);
}
}
}
}
}
}
Ok(())
}
async fn find_candidate_cards(&self, card: &ProblemCard) -> Result<Vec<(String, f32)>> {
let mut candidates = Vec::new();
// Vector similarity search
if let Some(ref embedding) = card.embedding {
if let Ok(vector_results) = self.neo4j.vector_search(embedding, 50).await {
candidates.extend(vector_results);
}
}
// Full-text search
let search_text = format!("{} {}", card.content_problem, card.content_insight);
if let Ok(fulltext_results) = self.neo4j.fulltext_search(&search_text, 50).await {
for (id, score) in fulltext_results {
// Merge with existing results or add new ones
if let Some(existing) = candidates.iter_mut().find(|(existing_id, _)| existing_id == &id) {
existing.1 = (existing.1 + score) / 2.0; // Average the scores
} else {
candidates.push((id, score * 0.8)); // Weight fulltext lower than vector
}
}
}
// Filter out the card itself
candidates.retain(|(id, _)| id != &card.id);
// Sort by combined score
candidates.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
// Take top candidates
candidates.truncate(20);
Ok(candidates)
}
async fn analyze_relationship(&self, card1: &ProblemCard, card2: &ProblemCard) -> Result<Recommendation> {
let prompt = format!(
r#"Analyze the relationship between these two problem cards:
Card 1:
Problem: {}
Insight: {}
Card 2:
Problem: {}
Insight: {}
Determine the most appropriate relationship type and provide a confidence score (0.0-1.0).
Respond in JSON format:
{{
"relationship_type": "IS_VARIATION_OF" | "USES_GENERAL_METHOD" | "CONTRASTS_WITH" | "SIMILAR_CONCEPT",
"confidence": 0.0-1.0,
"reasoning": "Explanation for this relationship"
}}
Only suggest high-confidence relationships (>0.7) that would be valuable for learning."#,
card1.content_problem,
card1.content_insight,
card2.content_problem,
card2.content_insight
);
let llm_manager = &self.llm_manager;
let response = llm_manager.call_unified_model_1(
vec![], // No images
&prompt,
"数学", // Default subject
Some("Relationship analysis task")
).await.map_err(|e| anyhow!("Failed to analyze relationship: {}", e))?;
// For now, create a simple recommendation based on OCR result
// In a full implementation, this would parse JSON from the response
let relationship_type = RelationshipType::UsesGeneralMethod; // Default
let confidence = 0.8; // Default confidence
let reasoning = if !response.ocr_text.is_empty() {
response.ocr_text
} else {
"Similar problem pattern detected".to_string()
};
Ok(Recommendation {
card: card2.clone(),
relationship_type,
confidence,
reasoning,
})
}
pub async fn get_recommendations(&self, request: RecommendationRequest) -> Result<Vec<Recommendation>> {
let card = match self.neo4j.get_problem_card(&request.card_id).await? {
Some(card) => card,
None => return Err(anyhow!("Card not found: {}", request.card_id)),
};
let candidates = self.find_candidate_cards(&card).await?;
let limit = request.limit.unwrap_or(self.config.recommendation_limit);
let mut recommendations = Vec::new();
for (candidate_id, _) in candidates.into_iter().take(limit * 2) { // Get more candidates than needed
if let Some(candidate_card) = self.neo4j.get_problem_card(&candidate_id).await? {
if let Ok(recommendation) = self.analyze_relationship(&card, &candidate_card).await {
recommendations.push(recommendation);
}
if recommendations.len() >= limit {
break;
}
}
}
// Sort by confidence
recommendations.sort_by(|a, b| b.confidence.partial_cmp(&a.confidence).unwrap_or(std::cmp::Ordering::Equal));
Ok(recommendations)
}
}
// Note: GraphService doesn't implement Clone due to Neo4jService limitations
// For async spawning, we'll create a new service instance when needed
// Note: Neo4jService doesn't implement Clone due to private fields
// We'll need to handle this differently in the async spawning
|
000haoji/deep-student
| 19,219 |
src-tauri/src/cogni_graph/services/neo4j_service.rs
|
use crate::cogni_graph::{GraphConfig, ProblemCard, Tag, RelationshipType, CreateTagRequest, TagHierarchy, TagType};
use anyhow::{Result, anyhow};
use neo4rs::{Graph, Query};
use serde_json::Value;
use std::collections::HashMap;
pub struct Neo4jService {
pub graph: Graph,
config: GraphConfig,
}
impl Neo4jService {
pub async fn new(config: GraphConfig) -> Result<Self> {
let graph = Graph::new(&config.neo4j.uri, &config.neo4j.username, &config.neo4j.password)
.await
.map_err(|e| anyhow!("Failed to connect to Neo4j at {}: {}. Please check that Neo4j is running and credentials are correct.", config.neo4j.uri, e))?;
Ok(Self { graph, config })
}
pub async fn initialize_schema(&self) -> Result<()> {
// Create constraints and indexes as per the design document
let queries = vec![
// Create unique constraints
"CREATE CONSTRAINT pc_id IF NOT EXISTS FOR (n:ProblemCard) REQUIRE n.id IS UNIQUE",
"CREATE CONSTRAINT tag_id IF NOT EXISTS FOR (n:Tag) REQUIRE n.id IS UNIQUE",
// Create full-text index for content search (Neo4j 4.x/5.x compatible syntax)
"CREATE FULLTEXT INDEX problem_card_content IF NOT EXISTS FOR (n:ProblemCard) ON EACH [n.content_problem, n.content_insight]",
// Create vector index for embeddings (Note: this requires Neo4j 5.11+ with vector search plugin)
"CREATE VECTOR INDEX problem_card_embedding IF NOT EXISTS FOR (n:ProblemCard) ON (n.embedding) OPTIONS { indexConfig: { `vector.dimensions`: 1536, `vector.similarity_function`: 'cosine' }}"
];
for query_str in queries {
let query = Query::new(query_str.to_string());
if let Err(e) = self.execute_simple_query(query).await {
// Log warning for advanced features that may not be supported
if query_str.contains("VECTOR INDEX") {
eprintln!("Warning: Vector index creation failed (may not be supported in this Neo4j version): {}", e);
} else if query_str.contains("FULLTEXT INDEX") {
eprintln!("Warning: Fulltext index creation failed (trying alternative approach): {}", e);
// Try alternative fulltext syntax for older versions
let alt_query = "CREATE FULLTEXT INDEX problem_card_content IF NOT EXISTS FOR (n:ProblemCard) ON (n.content_problem, n.content_insight)";
if let Err(e2) = self.execute_simple_query(Query::new(alt_query.to_string())).await {
eprintln!("Warning: Alternative fulltext index syntax also failed: {}", e2);
}
} else {
return Err(anyhow!("Failed to execute schema query '{}': {}", query_str, e));
}
}
}
Ok(())
}
pub async fn create_problem_card(&self, mut card: ProblemCard, tags: Vec<String>) -> Result<String> {
let card_id = card.id.clone();
// Convert embedding vector to string representation for Neo4j
let embedding_str = if let Some(ref embedding) = card.embedding {
serde_json::to_string(embedding)?
} else {
"null".to_string()
};
let query = Query::new(
r#"
CREATE (pc:ProblemCard {
id: $id,
content_problem: $content_problem,
content_insight: $content_insight,
status: $status,
embedding: $embedding,
created_at: $created_at,
last_accessed_at: $last_accessed_at,
access_count: $access_count,
source_excalidraw_path: $source_excalidraw_path
})
WITH pc
UNWIND $tags_list AS tag_name
MERGE (t:Tag {name: tag_name, tag_type: 'concept', level: 2})
ON CREATE SET t.id = randomUUID(), t.created_at = datetime()
CREATE (pc)-[:HAS_TAG]->(t)
RETURN pc.id
"#.to_string()
)
.param("id", card.id.clone())
.param("content_problem", card.content_problem.clone())
.param("content_insight", card.content_insight.clone())
.param("status", card.status.clone())
.param("embedding", embedding_str)
.param("created_at", card.created_at.to_rfc3339())
.param("last_accessed_at", card.last_accessed_at.to_rfc3339())
.param("access_count", card.access_count)
.param("source_excalidraw_path", card.source_excalidraw_path.clone().unwrap_or_default())
.param("tags_list", tags);
let mut result = self.graph.execute(query).await
.map_err(|e| anyhow!("Failed to create problem card: {}", e))?;
if let Some(row) = result.next().await? {
let id: String = row.get("pc.id").unwrap_or_default();
Ok(id)
} else {
Err(anyhow!("Failed to create problem card: no result returned"))
}
}
pub async fn get_problem_card(&self, card_id: &str) -> Result<Option<ProblemCard>> {
let query = Query::new(
r#"
MATCH (pc:ProblemCard {id: $id})
RETURN pc.id, pc.content_problem, pc.content_insight, pc.status,
pc.embedding, pc.created_at, pc.last_accessed_at,
pc.access_count, pc.source_excalidraw_path
"#.to_string()
).param("id", card_id);
let mut result = self.graph.execute(query).await
.map_err(|e| anyhow!("Failed to query problem card: {}", e))?;
if let Some(row) = result.next().await? {
let embedding_str: String = row.get("pc.embedding").unwrap_or_default();
let embedding = if embedding_str != "null" && !embedding_str.is_empty() {
serde_json::from_str(&embedding_str).ok()
} else {
None
};
let card = ProblemCard {
id: row.get("pc.id").unwrap_or_default(),
content_problem: row.get("pc.content_problem").unwrap_or_default(),
content_insight: row.get("pc.content_insight").unwrap_or_default(),
status: row.get("pc.status").unwrap_or_default(),
embedding,
created_at: chrono::DateTime::parse_from_rfc3339(&row.get::<String>("pc.created_at").unwrap_or_default())
.unwrap_or_default().with_timezone(&chrono::Utc),
last_accessed_at: chrono::DateTime::parse_from_rfc3339(&row.get::<String>("pc.last_accessed_at").unwrap_or_default())
.unwrap_or_default().with_timezone(&chrono::Utc),
access_count: row.get("pc.access_count").unwrap_or_default(),
source_excalidraw_path: {
let path: String = row.get("pc.source_excalidraw_path").unwrap_or_default();
if path.is_empty() { None } else { Some(path) }
},
};
Ok(Some(card))
} else {
Ok(None)
}
}
pub async fn vector_search(&self, query_vector: &[f32], limit: usize) -> Result<Vec<(String, f32)>> {
// Try vector index search first (if supported)
let vector_str = serde_json::to_string(query_vector)?;
let query = Query::new(
r#"
CALL db.index.vector.queryNodes('problem_card_embedding', $limit, $query_vector)
YIELD node, score
RETURN node.id, score
ORDER BY score DESC
"#.to_string()
)
.param("limit", limit as i64)
.param("query_vector", vector_str);
match self.graph.execute(query).await {
Ok(mut result) => {
let mut results = Vec::new();
while let Some(row) = result.next().await? {
let id: String = row.get("node.id").unwrap_or_default();
let score: f64 = row.get("score").unwrap_or_default();
results.push((id, score as f32));
}
Ok(results)
}
Err(_) => {
// Fallback to manual vector search if index is not available
self.manual_vector_search(query_vector, limit).await
}
}
}
async fn manual_vector_search(&self, query_vector: &[f32], limit: usize) -> Result<Vec<(String, f32)>> {
let query = Query::new(
r#"
MATCH (pc:ProblemCard)
WHERE pc.embedding IS NOT NULL AND pc.embedding <> 'null'
RETURN pc.id, pc.embedding
"#.to_string()
);
let mut result = self.graph.execute(query).await
.map_err(|e| anyhow!("Failed to execute manual vector search: {}", e))?;
let mut results = Vec::new();
while let Some(row) = result.next().await? {
let id: String = row.get("pc.id").unwrap_or_default();
let embedding_str: String = row.get("pc.embedding").unwrap_or_default();
if let Ok(embedding) = serde_json::from_str::<Vec<f32>>(&embedding_str) {
let similarity = cosine_similarity(query_vector, &embedding);
results.push((id, similarity));
}
}
// Sort by similarity score (descending) and take top results
results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
results.truncate(limit);
Ok(results)
}
pub async fn fulltext_search(&self, query: &str, limit: usize) -> Result<Vec<(String, f32)>> {
let query = Query::new(
r#"
CALL db.index.fulltext.queryNodes('problem_card_content', $query_string, {limit: $limit})
YIELD node, score
RETURN node.id, score
ORDER BY score DESC
"#.to_string()
)
.param("query_string", query)
.param("limit", limit as i64);
let mut result = self.graph.execute(query).await
.map_err(|e| anyhow!("Failed to execute fulltext search: {}", e))?;
let mut results = Vec::new();
while let Some(row) = result.next().await? {
let id: String = row.get("node.id").unwrap_or_default();
let score: f64 = row.get("score").unwrap_or_default();
results.push((id, score as f32));
}
Ok(results)
}
pub async fn get_card_relationships(&self, card_id: &str) -> Result<Vec<(String, String, f32)>> {
let query = Query::new(
r#"
MATCH (c:ProblemCard {id: $candidate_id})
OPTIONAL MATCH (c)-[r]-()
RETURN c.access_count as access_count, count(r) AS degree
"#.to_string()
).param("candidate_id", card_id);
let mut result = self.graph.execute(query).await
.map_err(|e| anyhow!("Failed to get card relationships: {}", e))?;
if let Some(row) = result.next().await? {
let access_count: i64 = row.get("access_count").unwrap_or_default();
let degree: i64 = row.get("degree").unwrap_or_default();
// Calculate a simple value score based on relationships and access
let value_score = (access_count as f32 * 0.1) + (degree as f32 * 0.5);
Ok(vec![(card_id.to_string(), "value_assessment".to_string(), value_score)])
} else {
Ok(vec![])
}
}
pub async fn create_relationship(&self, from_id: &str, to_id: &str, rel_type: RelationshipType) -> Result<()> {
let rel_type_str = rel_type.to_string();
let query = Query::new(
format!(
r#"
MATCH (from:ProblemCard {{id: $from_id}})
MATCH (to:ProblemCard {{id: $to_id}})
CREATE (from)-[:{}]->(to)
"#,
rel_type_str
)
)
.param("from_id", from_id)
.param("to_id", to_id);
self.graph.execute(query).await
.map_err(|e| anyhow!("Failed to create relationship: {}", e))?;
Ok(())
}
pub async fn update_access_count(&self, card_id: &str) -> Result<()> {
let query = Query::new(
r#"
MATCH (pc:ProblemCard {id: $id})
SET pc.last_accessed_at = $timestamp, pc.access_count = pc.access_count + 1
"#.to_string()
)
.param("id", card_id)
.param("timestamp", chrono::Utc::now().to_rfc3339());
self.graph.execute(query).await
.map_err(|e| anyhow!("Failed to update access count: {}", e))?;
Ok(())
}
// Tag management methods
pub async fn create_tag(&self, request: CreateTagRequest) -> Result<String> {
let tag = Tag::new(
request.name.clone(),
request.tag_type.clone(),
if request.parent_id.is_some() { 1 } else { 0 }, // Auto-calculate level
request.description.clone(),
);
let query = Query::new(
r#"
CREATE (t:Tag {
id: $id,
name: $name,
tag_type: $tag_type,
level: $level,
description: $description,
created_at: $created_at
})
RETURN t.id
"#.to_string()
)
.param("id", tag.id.clone())
.param("name", tag.name.clone())
.param("tag_type", tag.get_type_string())
.param("level", tag.level)
.param("description", tag.description.clone().unwrap_or_default())
.param("created_at", tag.created_at.to_rfc3339());
let mut result = self.graph.execute(query).await
.map_err(|e| anyhow!("Failed to create tag: {}", e))?;
// Create parent relationship if specified
if let Some(parent_id) = request.parent_id {
let rel_query = Query::new(
r#"
MATCH (parent:Tag {id: $parent_id})
MATCH (child:Tag {id: $child_id})
CREATE (parent)-[:PARENT_OF]->(child)
CREATE (child)-[:CHILD_OF]->(parent)
SET child.level = parent.level + 1
"#.to_string()
)
.param("parent_id", parent_id)
.param("child_id", tag.id.clone());
self.graph.execute(rel_query).await
.map_err(|e| anyhow!("Failed to create parent relationship: {}", e))?;
}
Ok(tag.id)
}
pub async fn get_tag_hierarchy(&self, root_tag_id: Option<String>) -> Result<Vec<TagHierarchy>> {
let query = if let Some(root_id) = root_tag_id {
Query::new(
r#"
MATCH (root:Tag {id: $root_id})
CALL {
WITH root
MATCH path = (root)-[:PARENT_OF*0..]->(descendant:Tag)
RETURN descendant, length(path) as depth
ORDER BY depth, descendant.name
}
RETURN descendant as tag, depth
"#.to_string()
)
.param("root_id", root_id)
} else {
Query::new(
r#"
MATCH (tag:Tag)
WHERE NOT (tag)<-[:PARENT_OF]-()
CALL {
WITH tag
MATCH path = (tag)-[:PARENT_OF*0..]->(descendant:Tag)
RETURN descendant, length(path) as depth
ORDER BY depth, descendant.name
}
RETURN descendant as tag, depth
"#.to_string()
)
};
let rows = self.execute_simple_query(query).await?;
let mut hierarchies = Vec::new();
// Build hierarchy structure (simplified version)
for row in rows {
if let (Ok(tag_node), Ok(depth)) = (row.get::<neo4rs::Node>("tag"), row.get::<i64>("depth")) {
let tag = self.node_to_tag(tag_node)?;
// For now, return a flat structure. Full hierarchy building would be more complex
hierarchies.push(TagHierarchy {
tag,
children: Vec::new(),
parent: None,
});
}
}
Ok(hierarchies)
}
pub async fn get_tags_by_type(&self, tag_type: TagType) -> Result<Vec<Tag>> {
let query = Query::new(
r#"
MATCH (t:Tag {tag_type: $tag_type})
RETURN t
ORDER BY t.level, t.name
"#.to_string()
)
.param("tag_type", tag_type.to_string());
let rows = self.execute_simple_query(query).await?;
let mut tags = Vec::new();
for row in rows {
if let Ok(tag_node) = row.get::<neo4rs::Node>("t") {
tags.push(self.node_to_tag(tag_node)?);
}
}
Ok(tags)
}
fn node_to_tag(&self, node: neo4rs::Node) -> Result<Tag> {
let id: String = node.get("id").unwrap_or_default();
let name: String = node.get("name").unwrap_or_default();
let tag_type_str: String = node.get("tag_type").unwrap_or_default();
let level: i64 = node.get("level").unwrap_or(0);
let description: String = node.get("description").unwrap_or_default();
let created_at_str: String = node.get("created_at").unwrap_or_default();
let tag_type = match tag_type_str.as_str() {
"knowledge_area" => TagType::KnowledgeArea,
"topic" => TagType::Topic,
"concept" => TagType::Concept,
"method" => TagType::Method,
"difficulty" => TagType::Difficulty,
_ => TagType::Concept,
};
let created_at = chrono::DateTime::parse_from_rfc3339(&created_at_str)
.unwrap_or_else(|_| chrono::Utc::now().into())
.with_timezone(&chrono::Utc);
Ok(Tag {
id,
name,
tag_type,
level: level as i32,
description: if description.is_empty() { None } else { Some(description) },
created_at,
})
}
// Helper method to execute queries and return results
pub async fn execute_simple_query(&self, query: Query) -> Result<Vec<neo4rs::Row>> {
let mut result = self.graph.execute(query).await
.map_err(|e| anyhow!("Failed to execute query: {}", e))?;
let mut rows = Vec::new();
while let Ok(Some(row)) = result.next().await {
rows.push(row);
}
Ok(rows)
}
}
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
if a.len() != b.len() {
return 0.0;
}
let dot_product: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
let magnitude_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
let magnitude_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
if magnitude_a == 0.0 || magnitude_b == 0.0 {
0.0
} else {
dot_product / (magnitude_a * magnitude_b)
}
}
|
000haoji/deep-student
| 8,022 |
src/components/MessageWithThinking.tsx
|
import React, { useState } from 'react';
import { MarkdownRenderer } from './MarkdownRenderer';
import { StreamingMarkdownRenderer } from './StreamingMarkdownRenderer';
import { SummaryBox } from './SummaryBox';
import { ChatMessageContentPart, ChatMessage } from '../types';
interface MessageWithThinkingProps {
content: string | ChatMessageContentPart[];
thinkingContent?: string;
isStreaming: boolean;
role: 'user' | 'assistant';
timestamp: string;
ragSources?: Array<{
document_id: string;
file_name: string;
chunk_text: string;
score: number;
chunk_index: number;
}>;
// 新增:总结框相关props
showSummaryBox?: boolean;
chatHistory?: ChatMessage[];
subject?: string;
mistakeId?: string;
reviewSessionId?: string;
}
export const MessageWithThinking: React.FC<MessageWithThinkingProps> = ({
content,
thinkingContent,
isStreaming,
role,
timestamp,
ragSources,
showSummaryBox = false,
chatHistory = [],
subject,
mistakeId,
reviewSessionId
}) => {
const [isThinkingExpanded, setIsThinkingExpanded] = useState(true);
const [isRagSourcesExpanded, setIsRagSourcesExpanded] = useState(false);
// 渲染多模态内容的函数
const renderContent = (content: string | ChatMessageContentPart[], isStreaming: boolean) => {
// 处理新的多模态数组格式
if (Array.isArray(content)) {
return content.map((part, index) => {
if (part.type === 'text') {
return (
<div key={`text-${index}`} className="content-text-part">
{isStreaming ? (
<StreamingMarkdownRenderer
content={part.text}
isStreaming={true}
/>
) : (
<MarkdownRenderer content={part.text} />
)}
</div>
);
}
if (part.type === 'image_url' && part.image_url && part.image_url.url) {
return (
<div key={`image-${index}`} className="content-image-part">
<img
src={part.image_url.url}
alt="上传的内容"
style={{
maxWidth: '100%',
maxHeight: '300px',
display: 'block',
marginTop: '8px',
marginBottom: '8px',
borderRadius: '8px',
border: '1px solid #e5e7eb'
}}
onError={(e) => {
e.currentTarget.style.display = 'none';
console.error('图片显示错误:', part.image_url.url.substring(0, 50));
}}
/>
</div>
);
}
return null;
});
}
// 兼容旧的字符串格式
else if (typeof content === 'string') {
return isStreaming ? (
<StreamingMarkdownRenderer
content={content}
isStreaming={true}
/>
) : (
<MarkdownRenderer content={content} />
);
}
// 未知内容格式的占位符
return <div className="content-unknown">未知内容格式</div>;
};
return (
<div className={`message ${role} ${isStreaming ? 'streaming' : ''}`}>
{thinkingContent && role === 'assistant' && (
<div className="thinking-container">
<div
className="thinking-header"
onClick={() => setIsThinkingExpanded(!isThinkingExpanded)}
>
<span className="thinking-icon">🧠</span>
<span className="thinking-title">AI 思考过程</span>
<span className="thinking-toggle">
{isThinkingExpanded ? '▼' : '▶'}
</span>
</div>
{isThinkingExpanded && (
<div className="thinking-content-box">
{isStreaming ? (
<StreamingMarkdownRenderer
content={thinkingContent || ''}
isStreaming={true}
/>
) : (
<MarkdownRenderer content={thinkingContent || ''} />
)}
</div>
)}
</div>
)}
<div className="message-content">
{renderContent(content, isStreaming)}
</div>
{ragSources && ragSources.length > 0 && role === 'assistant' && (
<div className="rag-sources-container" style={{
marginTop: '12px',
border: '1px solid #e0e7ff',
borderRadius: '8px',
backgroundColor: '#f8faff'
}}>
<div
className="rag-sources-header"
onClick={() => setIsRagSourcesExpanded(!isRagSourcesExpanded)}
style={{
padding: '8px 12px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '6px',
borderBottom: isRagSourcesExpanded ? '1px solid #e0e7ff' : 'none',
fontSize: '13px',
fontWeight: '500',
color: '#4338ca'
}}
>
<span>📚</span>
<span>知识库来源 ({ragSources.length})</span>
<span style={{ marginLeft: 'auto' }}>
{isRagSourcesExpanded ? '▼' : '▶'}
</span>
</div>
{isRagSourcesExpanded && (
<div className="rag-sources-content" style={{ padding: '8px 12px' }}>
{ragSources.map((source, index) => (
<div
key={`${source.document_id}-${source.chunk_index}`}
style={{
marginBottom: index < ragSources.length - 1 ? '12px' : '0',
padding: '10px',
backgroundColor: 'white',
borderRadius: '6px',
border: '1px solid #e5e7eb'
}}
>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '6px'
}}>
<div style={{
fontSize: '12px',
fontWeight: '600',
color: '#374151',
display: 'flex',
alignItems: 'center',
gap: '4px'
}}>
<span>📄</span>
<span>{source.file_name}</span>
<span style={{ color: '#6b7280', fontWeight: 'normal' }}>
(块 #{source.chunk_index + 1})
</span>
</div>
<div style={{
fontSize: '11px',
color: '#6b7280',
backgroundColor: '#f3f4f6',
padding: '2px 6px',
borderRadius: '4px'
}}>
相关度: {Math.round(source.score * 100)}%
</div>
</div>
<div style={{
fontSize: '12px',
color: '#4b5563',
lineHeight: '1.4',
fontStyle: 'italic',
backgroundColor: '#f9fafb',
padding: '8px',
borderRadius: '4px',
border: '1px solid #f3f4f6'
}}>
{source.chunk_text.length > 200
? `${source.chunk_text.substring(0, 200)}...`
: source.chunk_text
}
</div>
</div>
))}
</div>
)}
</div>
)}
{/* 总结框 - 仅在assistant消息且启用时显示 */}
{showSummaryBox && role === 'assistant' && (
<SummaryBox
chatHistory={chatHistory}
isVisible={true}
subject={subject}
mistakeId={mistakeId}
reviewSessionId={reviewSessionId}
/>
)}
<div className="message-time">
{new Date(timestamp).toLocaleTimeString()}
</div>
</div>
);
};
|
000haoji/deep-student
| 19,790 |
src/components/TemplateManagementPage.css
|
/* 模板管理页面 - 彻底重写,优先保证卡片完整显示 */
.template-management-page {
min-height: 100vh;
display: flex;
flex-direction: column;
background: #fafafa;
/* 移除所有高度限制,让内容自然扩展 */
/* height: 100vh; */
/* max-height: 100vh; */
/* overflow: hidden; */
/* 强制移除所有可能的限制 */
width: auto !important;
height: auto !important;
max-width: none !important;
max-height: none !important;
overflow: visible !important;
}
/* 页面头部 */
.page-header {
background: white;
border-bottom: 1px solid #e5e7eb;
padding: 24px 32px;
position: relative;
/* 移除flex-shrink限制,因为容器已经没有高度限制 */
/* flex-shrink: 0; */
}
.page-header::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: transparent;
}
.page-header.selecting-mode::before {
background: linear-gradient(90deg, #fbbf24, #f59e0b);
}
.page-header.management-mode::before {
background: linear-gradient(90deg, #3b82f6, #2563eb);
}
.header-content {
/* 移除宽度限制,让内容自然扩展 */
/* max-width: 1200px; */
margin: 0 auto;
}
.header-main {
display: flex;
align-items: center;
gap: 16px;
}
.title-section {
display: flex;
align-items: center;
gap: 16px;
}
/* 模式指示器 */
.mode-indicator {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
border-radius: 16px;
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.mode-indicator.selecting {
background: #fef3c7;
color: #92400e;
border: 1px solid #fbbf24;
}
.mode-indicator.management {
background: #dbeafe;
color: #1e40af;
border: 1px solid #60a5fa;
}
.mode-icon {
font-size: 14px;
}
.mode-text {
font-size: 11px;
}
.back-button {
background: #f3f4f6;
border: 1px solid #d1d5db;
color: #374151;
padding: 8px 16px;
border-radius: 6px;
font-size: 14px;
cursor: pointer;
transition: all 0.2s ease;
display: flex;
align-items: center;
gap: 8px;
}
.back-button:hover {
background: #e5e7eb;
border-color: #9ca3af;
}
.back-icon {
font-size: 16px;
}
.page-title {
margin: 0 0 8px 0;
font-size: 28px;
font-weight: 600;
color: #111827;
display: flex;
align-items: center;
gap: 12px;
}
.page-icon {
font-size: 32px;
}
.page-description {
margin: 0;
color: #6b7280;
font-size: 16px;
line-height: 1.5;
}
/* 标签页导航 */
.page-tabs {
background: white;
border-bottom: 1px solid #e5e7eb;
padding: 0 32px;
display: flex;
gap: 8px;
/* 移除flex-shrink限制 */
/* flex-shrink: 0; */
}
.tab-button {
background: none;
border: none;
padding: 16px 20px;
font-size: 14px;
font-weight: 500;
color: #6b7280;
cursor: pointer;
border-bottom: 2px solid transparent;
transition: all 0.2s ease;
display: flex;
align-items: center;
gap: 8px;
white-space: nowrap;
}
.tab-button:hover {
color: #374151;
background: #f9fafb;
}
.tab-button.active {
color: #3b82f6;
border-bottom-color: #3b82f6;
background: #f8fafc;
}
.tab-icon {
font-size: 16px;
}
/* 错误提示 */
.error-alert {
background: #fef2f2;
border-bottom: 1px solid #fecaca;
padding: 12px 32px;
}
.alert-content {
display: flex;
align-items: center;
gap: 12px;
max-width: 1200px;
margin: 0 auto;
}
.alert-icon {
color: #dc2626;
font-size: 16px;
}
.alert-message {
flex: 1;
color: #dc2626;
font-size: 14px;
}
.alert-close {
background: none;
border: none;
color: #dc2626;
cursor: pointer;
font-size: 16px;
padding: 4px;
border-radius: 4px;
transition: background 0.2s;
}
.alert-close:hover {
background: rgba(220, 38, 38, 0.1);
}
/* 内容区域 - 彻底重写,移除所有限制 */
.page-content {
/* 移除flex限制,让内容自然扩展 */
/* flex: 1; */
/* 移除所有overflow限制 */
/* overflow-y: auto; */
/* overflow-x: hidden; */
/* 移除宽度限制!!!这是关键!!! */
/* max-width: 1200px; */
margin: 0 auto;
width: 100%;
/* 增加充足的填充,确保卡片完整显示 */
padding: 0 32px 200px 32px;
/* 移除高度限制 */
/* min-height: 0; */
/* 强制移除所有可能的限制 */
width: auto !important;
height: auto !important;
max-width: none !important;
max-height: none !important;
overflow: visible !important;
}
/* 模板浏览器 - 移除所有限制 */
.template-browser {
display: flex;
flex-direction: column;
padding: 24px 0;
/* 移除所有高度和flex限制 */
/* min-height: 0; */
/* flex: 1; */
/* 强制移除所有可能的限制 */
width: auto !important;
height: auto !important;
max-width: none !important;
max-height: none !important;
overflow: visible !important;
}
.browser-toolbar {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24px;
gap: 20px;
}
.search-container {
flex: 1;
max-width: 400px;
}
.search-input-wrapper {
position: relative;
}
.search-input {
width: 100%;
padding: 12px 16px 12px 44px;
border: 1px solid #d1d5db;
border-radius: 8px;
font-size: 14px;
background: white;
transition: all 0.2s ease;
}
.search-input:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.search-icon {
position: absolute;
left: 16px;
top: 50%;
transform: translateY(-50%);
color: #9ca3af;
font-size: 16px;
}
.toolbar-stats {
color: #6b7280;
font-size: 14px;
display: flex;
align-items: center;
gap: 16px;
}
.mode-hint {
display: flex;
align-items: center;
gap: 6px;
padding: 4px 8px;
background: #fef3c7;
color: #92400e;
border: 1px solid #fbbf24;
border-radius: 6px;
font-size: 12px;
}
.hint-icon {
font-size: 14px;
}
.hint-text {
font-weight: 500;
}
/* 模板网格 - 强制单列布局,彻底移除所有限制 */
.templates-grid {
display: grid;
/* 强制单列布局 */
grid-template-columns: 1fr;
gap: 20px;
/* 让每行完全自适应内容高度 */
grid-auto-rows: auto;
align-items: start;
/* 超大底部填充,确保所有卡片都能完整显示 */
padding: 0 0 300px 0;
/* 完全移除所有限制 */
overflow: visible;
/* 强制移除任何可能的尺寸限制 */
width: auto !important;
height: auto !important;
max-width: none !important;
max-height: none !important;
min-width: 0 !important;
min-height: 0 !important;
}
/* 模板卡片 - 彻底重写,移除所有高度限制 */
.template-card {
background: white;
border: 1px solid #e5e7eb;
border-radius: 12px;
padding: 20px;
transition: all 0.2s ease;
cursor: pointer;
position: relative;
/* 完全移除所有限制,让内容自然扩展 */
overflow: visible;
/* 让内容完全决定卡片高度,移除所有高度限制 */
height: auto;
/* min-height: 400px; */
display: flex;
flex-direction: column;
width: 100%;
}
.template-card:hover {
border-color: #d1d5db;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
transform: translateY(-1px);
}
.template-card.selected {
border-color: #3b82f6;
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}
.template-card.inactive {
opacity: 0.6;
}
/* 选择模式的卡片样式 */
.template-card.selecting-mode {
border-left: 4px solid #fbbf24;
background: linear-gradient(135deg, #ffffff 0%, #fefbf3 100%);
}
.template-card.selecting-mode:hover {
border-left-color: #f59e0b;
box-shadow: 0 8px 25px rgba(251, 191, 36, 0.15);
}
/* 管理模式的卡片样式 */
.template-card.management-mode {
border-left: 4px solid #e5e7eb;
}
.template-card.management-mode:hover {
border-left-color: #3b82f6;
}
.card-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 16px;
}
.template-name {
font-size: 18px;
font-weight: 600;
color: #111827;
margin: 0;
line-height: 1.3;
flex: 1;
margin-right: 12px;
}
.template-badges {
display: flex;
gap: 6px;
flex-wrap: wrap;
}
.badge {
padding: 2px 8px;
border-radius: 12px;
font-size: 11px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.badge.built-in {
background: #eff6ff;
color: #1d4ed8;
}
.badge.inactive {
background: #f3f4f6;
color: #6b7280;
}
.badge.version {
background: #f0fdf4;
color: #166534;
}
/* 预览区域 */
.card-preview {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-bottom: 16px;
/* 确保预览区域可以自适应内容高度 */
grid-auto-rows: auto;
align-items: start;
}
.preview-section {
background: #f9fafb !important;
border: 1px solid #f3f4f6;
border-radius: 6px;
padding: 12px;
/* 移除所有高度限制,让内容完全自然显示 */
/* min-height: 120px; */
display: flex;
flex-direction: column;
/* 让内容完全决定预览区域高度 */
height: auto;
}
.preview-label {
font-size: 11px;
font-weight: 600;
color: #6b7280;
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 6px;
flex-shrink: 0;
}
.preview-content {
font-size: 13px;
color: #374151 !important;
line-height: 1.4;
/* 完全移除所有overflow限制,让内容自然显示 */
overflow: visible;
flex: 1;
word-wrap: break-word;
overflow-wrap: break-word;
hyphens: auto;
/* 移除所有高度限制 */
/* min-height: 60px; */
/* max-height: 300px; */
}
/* 预览内容的样式重置和优化 */
.preview-content * {
max-width: 100% !important;
box-sizing: border-box;
/* 强制设置所有子元素的文字颜色 */
color: #374151 !important;
}
.preview-content img {
max-width: 100% !important;
height: auto !important;
object-fit: contain;
}
.preview-content .card {
padding: 8px !important;
margin: 0 !important;
background: white !important;
border-radius: 4px !important;
font-size: 12px !important;
line-height: 1.3 !important;
color: #374151 !important;
}
.preview-content .cloze {
background: #fef3c7 !important;
color: #92400e !important;
padding: 1px 4px !important;
border-radius: 3px !important;
font-weight: 500 !important;
}
.preview-content .tag {
background: #e5e7eb !important;
color: #374151 !important;
padding: 1px 4px !important;
border-radius: 3px !important;
font-size: 10px !important;
margin: 0 2px !important;
}
.preview-content code {
background: #f3f4f6 !important;
color: #1f2937 !important;
padding: 2px 4px !important;
border-radius: 3px !important;
font-family: 'Monaco', 'Menlo', monospace !important;
font-size: 11px !important;
white-space: pre-wrap !important;
}
.preview-content pre {
background: #f3f4f6 !important;
padding: 8px !important;
border-radius: 4px !important;
overflow-x: auto !important;
font-size: 11px !important;
line-height: 1.3 !important;
}
/* 确保预览区域的滚动条样式 */
.preview-content::-webkit-scrollbar {
width: 4px;
}
.preview-content::-webkit-scrollbar-track {
background: transparent;
}
.preview-content::-webkit-scrollbar-thumb {
background: #d1d5db;
border-radius: 2px;
}
.preview-content::-webkit-scrollbar-thumb:hover {
background: #9ca3af;
}
/* 强制修复预览内容中的文字显示问题 */
.preview-content,
.preview-content p,
.preview-content div,
.preview-content span,
.preview-content h1,
.preview-content h2,
.preview-content h3,
.preview-content h4,
.preview-content h5,
.preview-content h6,
.preview-content li,
.preview-content td,
.preview-content th {
color: #374151 !important;
background-color: transparent !important;
}
/* 确保内联样式的文本也能正常显示 */
.preview-content [style*="color"] {
color: #374151 !important;
}
/* 选择题卡片特殊样式修复 */
.preview-content .choice-card {
background: #f8fafc !important;
color: #374151 !important;
}
.preview-content .choice-card .option {
color: #374151 !important;
background-color: transparent !important;
}
.preview-content .choice-card .option-text {
color: #374151 !important;
}
.preview-content .choice-card .option-label {
color: #374151 !important;
}
.preview-content .choice-card .question-text {
color: #374151 !important;
}
.preview-content .choice-card .instruction {
color: #374151 !important;
}
/* 卡片信息 */
.card-info {
margin-bottom: 16px;
flex: 1;
}
.template-description {
font-size: 14px;
color: #6b7280;
line-height: 1.5;
margin-bottom: 12px;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.template-meta {
display: flex;
gap: 16px;
margin-bottom: 12px;
font-size: 12px;
}
.meta-item {
display: flex;
align-items: center;
gap: 4px;
color: #9ca3af;
}
.meta-icon {
font-size: 12px;
}
.template-fields {
display: flex;
gap: 6px;
flex-wrap: wrap;
}
.field-tag {
background: #f3f4f6;
color: #374151;
padding: 2px 8px;
border-radius: 12px;
font-size: 11px;
font-weight: 500;
}
.field-tag.more {
background: #e5e7eb;
color: #6b7280;
}
/* 模式横幅 */
.mode-banner {
display: flex;
align-items: center;
gap: 6px;
padding: 8px 12px;
background: #fef3c7;
border: 1px solid #fbbf24;
border-radius: 6px;
margin-bottom: 12px;
font-size: 12px;
color: #92400e;
flex-shrink: 0;
}
.banner-icon {
font-size: 14px;
}
.banner-text {
font-weight: 500;
}
/* 卡片操作 */
.card-actions {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin-top: auto;
flex-shrink: 0;
}
.btn-select {
background: #3b82f6;
color: white;
border: none;
padding: 8px 16px;
border-radius: 6px;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
flex: 1;
}
.btn-select:hover {
background: #2563eb;
transform: translateY(-1px);
}
.btn-select.primary {
background: #059669;
width: 100%;
}
.btn-select.primary:hover {
background: #047857;
}
.btn-icon {
margin-right: 6px;
font-size: 14px;
}
.action-buttons {
display: flex;
gap: 4px;
}
.action-btn {
background: #f9fafb;
border: 1px solid #e5e7eb;
color: #6b7280;
width: 32px;
height: 32px;
border-radius: 6px;
font-size: 14px;
cursor: pointer;
transition: all 0.2s ease;
display: flex;
align-items: center;
justify-content: center;
}
.action-btn:hover {
background: #f3f4f6;
border-color: #d1d5db;
color: #374151;
}
.action-btn.danger:hover {
background: #fef2f2;
border-color: #fecaca;
color: #dc2626;
}
/* 加载状态 */
.loading-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 60px 20px;
color: #6b7280;
}
.loading-spinner {
width: 40px;
height: 40px;
border: 3px solid #f3f4f6;
border-top: 3px solid #3b82f6;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-bottom: 16px;
}
.loading-text {
font-size: 14px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* 空状态 */
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 60px 20px;
text-align: center;
}
.empty-icon {
font-size: 64px;
margin-bottom: 20px;
opacity: 0.4;
}
.empty-title {
font-size: 20px;
color: #374151;
margin: 0 0 8px 0;
font-weight: 600;
}
.empty-description {
color: #6b7280;
margin: 0;
max-width: 300px;
line-height: 1.5;
}
/* 模板编辑器 */
.template-editor {
display: flex;
flex-direction: column;
padding: 24px 0;
}
.editor-header {
margin-bottom: 24px;
}
.editor-title {
margin: 0;
font-size: 24px;
color: #111827;
font-weight: 600;
}
.editor-tabs {
display: flex;
border-bottom: 1px solid #e5e7eb;
margin-bottom: 24px;
gap: 8px;
}
.editor-tab {
background: none;
border: none;
padding: 12px 16px;
font-size: 14px;
font-weight: 500;
color: #6b7280;
cursor: pointer;
border-bottom: 2px solid transparent;
transition: all 0.2s ease;
display: flex;
align-items: center;
gap: 8px;
}
.editor-tab:hover {
color: #374151;
}
.editor-tab.active {
color: #3b82f6;
border-bottom-color: #3b82f6;
}
.editor-form {
flex: 1;
overflow-y: auto;
}
.editor-section {
background: white;
border: 1px solid #e5e7eb;
border-radius: 12px;
padding: 24px;
}
/* 表单样式 */
.form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.form-group {
display: flex;
flex-direction: column;
}
.form-group.full-width {
grid-column: 1 / -1;
}
.form-label {
font-size: 14px;
font-weight: 500;
color: #374151;
margin-bottom: 6px;
}
.form-input,
.form-textarea {
padding: 12px 16px;
border: 1px solid #d1d5db;
border-radius: 8px;
font-size: 14px;
transition: all 0.2s ease;
font-family: inherit;
background: white;
}
.form-input:focus,
.form-textarea:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.form-textarea {
resize: vertical;
min-height: 80px;
}
.form-help {
font-size: 12px;
color: #6b7280;
margin-top: 4px;
}
/* 代码编辑器 */
.template-code-editor {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 24px;
}
.code-group {
display: flex;
flex-direction: column;
}
.code-textarea {
padding: 16px;
border: 1px solid #d1d5db;
border-radius: 8px;
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
font-size: 13px;
line-height: 1.5;
background: #f8fafc;
resize: vertical;
transition: all 0.2s ease;
}
.code-textarea:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
background: white;
}
/* 样式编辑器 */
.styles-editor {
display: flex;
flex-direction: column;
}
.css-textarea {
padding: 16px;
border: 1px solid #d1d5db;
border-radius: 8px;
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
font-size: 13px;
line-height: 1.5;
background: #f8fafc;
resize: vertical;
min-height: 300px;
transition: all 0.2s ease;
}
.css-textarea:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
background: white;
}
/* 高级设置 */
.advanced-settings {
display: flex;
flex-direction: column;
}
.prompt-textarea {
padding: 16px;
border: 1px solid #d1d5db;
border-radius: 8px;
font-size: 14px;
line-height: 1.6;
resize: vertical;
min-height: 200px;
transition: all 0.2s ease;
background: white;
}
.prompt-textarea:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
/* 编辑器操作按钮 */
.editor-actions {
display: flex;
gap: 12px;
justify-content: flex-end;
padding: 24px 0 0;
margin-top: 24px;
border-top: 1px solid #e5e7eb;
}
.btn-primary {
background: #3b82f6;
color: white;
border: none;
padding: 12px 24px;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
}
.btn-primary:hover {
background: #2563eb;
transform: translateY(-1px);
}
.btn-primary:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
}
.btn-secondary {
background: #f9fafb;
color: #374151;
border: 1px solid #d1d5db;
padding: 12px 24px;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
}
.btn-secondary:hover {
background: #f3f4f6;
border-color: #9ca3af;
}
/* 响应式设计 */
@media (max-width: 1200px) {
.page-content {
/* 移除宽度限制,保持padding */
padding: 0 24px 200px 24px;
}
.templates-grid {
/* 强制单列布局 */
grid-template-columns: 1fr;
gap: 16px;
grid-auto-rows: auto;
}
.template-code-editor {
grid-template-columns: 1fr;
gap: 16px;
}
.form-grid {
grid-template-columns: 1fr;
gap: 16px;
}
}
@media (max-width: 768px) {
.page-header {
padding: 16px 20px;
}
.page-title {
font-size: 24px;
}
.page-tabs,
.page-content {
padding-left: 20px;
padding-right: 20px;
}
.browser-toolbar {
flex-direction: column;
gap: 12px;
align-items: stretch;
}
.search-container {
max-width: none;
}
.templates-grid {
/* 强制单列布局 */
grid-template-columns: 1fr;
gap: 16px;
grid-auto-rows: auto;
}
.card-preview {
grid-template-columns: 1fr;
}
.template-meta {
flex-direction: column;
gap: 8px;
}
}
/* 滚动条样式优化 */
.page-content::-webkit-scrollbar {
width: 8px;
}
.page-content::-webkit-scrollbar-track {
background: #f1f5f9;
border-radius: 4px;
}
.page-content::-webkit-scrollbar-thumb {
background: #cbd5e1;
border-radius: 4px;
transition: background 0.2s ease;
}
.page-content::-webkit-scrollbar-thumb:hover {
background: #94a3b8;
}
/* 确保内容可以完全滚动到底部 */
/* 这个规则会被合并到上面的.page-content定义中 */
|
000haoji/deep-student
| 9,416 |
src/components/SimplifiedChatInterface.tsx
|
/**
* Simplified Chat Interface
*
* Replaces the complex AI SDK implementation with a simpler approach
* that uses the unified stream handler directly.
*/
import React, { useState, useRef, useEffect } from 'react';
import { useUnifiedStream, StreamMessage, MarkdownRenderer, MessageWithThinking } from '../chat-core';
interface SimplifiedChatInterfaceProps {
tempId?: string;
mistakeId?: number;
initialMessages?: StreamMessage[];
enableChainOfThought?: boolean;
onAnalysisStart?: () => void;
onAnalysisComplete?: (response: any) => void;
className?: string;
}
export const SimplifiedChatInterface = React.forwardRef<any, SimplifiedChatInterfaceProps>(({
tempId,
mistakeId: _mistakeId,
initialMessages = [],
enableChainOfThought = true,
onAnalysisStart,
onAnalysisComplete,
className = ''
}, ref) => {
const [messages, setMessages] = useState<StreamMessage[]>(initialMessages);
const [input, setInput] = useState('');
const [currentStreamId, setCurrentStreamId] = useState<string | null>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const {
startStream,
stopStream,
isStreamActive
} = useUnifiedStream();
// Auto-scroll to bottom when new messages appear
useEffect(() => {
if (messagesEndRef.current) {
messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
}
}, [messages, streamProgress]);
// Update messages from streaming progress
useEffect(() => {
if (currentStreamId && streamProgress[currentStreamId]) {
const progress = streamProgress[currentStreamId];
setMessages(prev => {
const updated = [...prev];
const lastMessage = updated[updated.length - 1];
if (lastMessage && lastMessage.role === 'assistant') {
// Update the last assistant message with streaming content
updated[updated.length - 1] = {
...lastMessage,
content: progress.content,
thinking_content: progress.thinking
};
}
return updated;
});
}
}, [currentStreamId, streamProgress]);
// Handle form submission
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!input.trim() || isStreaming) return;
const userMessage: StreamMessage = {
id: `msg-${Date.now()}`,
role: 'user',
content: input.trim(),
timestamp: new Date().toISOString()
};
// Add user message immediately
setMessages(prev => [...prev, userMessage]);
setInput('');
// Create placeholder assistant message
const assistantMessage: StreamMessage = {
id: `msg-${Date.now() + 1}`,
role: 'assistant',
content: '',
thinking_content: '',
timestamp: new Date().toISOString()
};
setMessages(prev => [...prev, assistantMessage]);
try {
if (onAnalysisStart) {
onAnalysisStart();
}
const updatedChatHistory = [...messages, userMessage];
// Start streaming
const streamId = await startStream(
'chat_stream',
JSON.stringify({
type: tempId ? 'continue_chat' : 'chat',
tempId,
chatHistory: updatedChatHistory,
enableChainOfThought
}),
{
onComplete: (content, thinking) => {
// Final update with complete content
setMessages(prev => {
const updated = [...prev];
const lastMessage = updated[updated.length - 1];
if (lastMessage && lastMessage.role === 'assistant') {
updated[updated.length - 1] = {
...lastMessage,
content,
thinking_content: thinking
};
}
return updated;
});
setCurrentStreamId(null);
if (onAnalysisComplete) {
onAnalysisComplete({ content, thinking });
}
},
onError: (error) => {
console.error('Chat stream error:', error);
setCurrentStreamId(null);
// Update the last message to show error
setMessages(prev => {
const updated = [...prev];
const lastMessage = updated[updated.length - 1];
if (lastMessage && lastMessage.role === 'assistant') {
updated[updated.length - 1] = {
...lastMessage,
content: `错误: ${error}`
};
}
return updated;
});
}
}
);
setCurrentStreamId(streamId);
} catch (error) {
console.error('Failed to start chat stream:', error);
}
};
// Handle keyboard shortcuts
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSubmit(e as any);
}
};
// Send message programmatically
const sendMessage = async (content: string) => {
setInput(content);
// Trigger form submission
setTimeout(() => {
const form = document.querySelector('.chat-input-form') as HTMLFormElement;
if (form) {
form.requestSubmit();
}
}, 0);
};
// Clear chat
const clearChat = () => {
setMessages(initialMessages);
setInput('');
if (currentStreamId) {
stopStream(currentStreamId);
setCurrentStreamId(null);
}
};
// Stop current stream
const stopCurrentStream = () => {
if (currentStreamId) {
stopStream(currentStreamId);
setCurrentStreamId(null);
}
};
// Expose methods to parent
React.useImperativeHandle(ref, () => ({
sendMessage,
clearChat,
stopStream: stopCurrentStream
}));
return (
<div className={`simplified-chat-interface ${className}`}>
{/* Chat Messages */}
<div className="chat-messages">
{messages.map((message, index) => (
<div key={message.id} className={`message ${message.role}`}>
<div className="message-header">
<span className="role">{message.role === 'user' ? '用户' : 'AI助手'}</span>
<span className="timestamp">
{new Date(message.timestamp).toLocaleTimeString()}
</span>
</div>
<div className="message-content">
{message.role === 'assistant' ? (
<MessageWithThinking
content={message.content}
thinkingContent={message.thinking_content}
isStreaming={isStreaming && index === messages.length - 1}
role="assistant"
timestamp={message.timestamp}
/>
) : (
<div className="user-message">
<MarkdownRenderer content={message.content} />
</div>
)}
</div>
</div>
))}
{/* Loading indicator */}
{isStreaming && (
<div className="streaming-indicator">
<div className="typing-dots">
<span></span>
<span></span>
<span></span>
</div>
<span>AI正在思考和回答中...</span>
</div>
)}
{/* Auto-scroll anchor */}
<div ref={messagesEndRef} />
</div>
{/* Chat Input */}
<form onSubmit={handleSubmit} className="chat-input-form">
<div className="input-container">
<textarea
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="输入您的问题..."
disabled={isStreaming}
rows={3}
className="chat-input"
/>
<div className="input-actions">
<button
type="submit"
disabled={!input.trim() || isStreaming}
className="send-button"
>
{isStreaming ? '发送中...' : '发送'}
</button>
{isStreaming && (
<button
type="button"
onClick={stopCurrentStream}
className="stop-button"
>
停止
</button>
)}
<button
type="button"
onClick={clearChat}
disabled={isStreaming}
className="clear-button"
>
清空
</button>
</div>
</div>
</form>
{/* Chat Controls */}
<div className="chat-controls">
<label className="chain-of-thought-toggle">
<input
type="checkbox"
checked={enableChainOfThought}
onChange={() => {
// This would need to be controlled by parent component
}}
disabled={isStreaming}
/>
<span>显示思维过程</span>
</label>
<div className="chat-stats">
<span>消息数: {messages.length}</span>
{isStreaming && <span className="analyzing">分析中...</span>}
{currentStreamId && <span className="stream-id">Stream: {currentStreamId.slice(-8)}</span>}
</div>
</div>
</div>
);
});
|
000haoji/deep-student
| 25,006 |
src/components/ImageOcclusion.tsx
|
import React, { useState, useRef, useCallback, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import './ImageOcclusion.css';
interface TextRegion {
text: string;
bbox: [number, number, number, number];
confidence: number;
region_id: string;
}
interface ImageOcrResponse {
success: boolean;
text_regions: TextRegion[];
full_text: string;
image_width: number;
image_height: number;
error_message?: string;
}
interface OcclusionMask {
mask_id: string;
bbox: [number, number, number, number];
original_text: string;
hint?: string;
mask_style: MaskStyle;
}
interface MaskStyle {
SolidColor?: { color: string };
BlurEffect?: { intensity: number };
Rectangle?: { color: string; opacity: number };
}
interface ImageOcclusionCard {
id: string;
task_id: string;
image_path: string;
image_base64?: string;
image_width: number;
image_height: number;
masks: OcclusionMask[];
title: string;
description?: string;
tags: string[];
created_at: string;
updated_at: string;
subject: string;
}
interface ImageOcclusionResponse {
success: boolean;
card?: ImageOcclusionCard;
error_message?: string;
}
const ImageOcclusion: React.FC = () => {
const [selectedImage, setSelectedImage] = useState<string | null>(null);
const [isProcessing, setIsProcessing] = useState(false);
const [textRegions, setTextRegions] = useState<TextRegion[]>([]);
const [selectedRegions, setSelectedRegions] = useState<Set<string>>(new Set());
const [cardTitle, setCardTitle] = useState('');
const [cardDescription, setCardDescription] = useState('');
const [cardSubject, setCardSubject] = useState('数学');
const [cardTags, setCardTags] = useState('');
const [maskStyle, setMaskStyle] = useState<MaskStyle>({ Rectangle: { color: '#FF0000', opacity: 0.7 } });
const [imageScale, setImageScale] = useState(1);
const [createdCard, setCreatedCard] = useState<ImageOcclusionCard | null>(null);
const [showPreview, setShowPreview] = useState(false);
const [imageLoaded, setImageLoaded] = useState(false);
const [useHighResolution, setUseHighResolution] = useState(true);
const fileInputRef = useRef<HTMLInputElement>(null);
const imageRef = useRef<HTMLImageElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const [originalImageDimensions, setOriginalImageDimensions] = useState<{ width: number; height: number } | null>(null);
const handleImageUpload = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
const base64 = e.target?.result as string;
setSelectedImage(base64);
setTextRegions([]);
setSelectedRegions(new Set());
setCreatedCard(null);
setImageLoaded(false);
};
reader.readAsDataURL(file);
}, []);
const extractTextCoordinates = useCallback(async () => {
if (!selectedImage) return;
setIsProcessing(true);
try {
const base64Data = selectedImage.split(',')[1];
const response = await invoke<ImageOcrResponse>('extract_image_text_coordinates', {
request: {
image_base64: base64Data,
extract_coordinates: true,
target_text: null,
vl_high_resolution_images: useHighResolution,
},
});
if (response.success) {
console.log('✅ OCR识别成功:', {
区域数量: response.text_regions.length,
图片尺寸: `${response.image_width}x${response.image_height}`,
全文: response.full_text.substring(0, 100) + ('...'),
示例区域: response.text_regions.slice(0, 3).map((r, i) => ({
索引: i,
文字: r.text,
坐标: `[${r.bbox.join(', ')}]`,
置信度: `${(r.confidence * 100).toFixed(1)}%`
}))
});
setTextRegions(response.text_regions);
const dimensions = { width: response.image_width, height: response.image_height };
setOriginalImageDimensions(dimensions);
// 如果图片已加载,立即计算缩放比例;否则等待图片加载完成
if (imageLoaded) {
console.log('🔄 OCR完成,图片已加载,立即计算缩放比例');
updateImageScale(response.image_width, response.image_height, true);
} else {
console.log('⏳ OCR完成,等待图片加载完成后计算缩放比例');
}
} else {
const errorMsg = response.error_message || '未知错误';
console.error('❌ OCR识别失败:', errorMsg);
alert(`OCR识别失败: ${errorMsg}\n\n请检查:\n1. 网络连接是否正常\n2. API配置是否正确\n3. 图片格式是否支持`);
}
} catch (error) {
console.error('❌ OCR识别异常:', error);
const errorMessage = error instanceof Error ? error.message : String(error);
alert(`OCR识别异常: ${errorMessage}\n\n可能的原因:\n1. 网络连接中断\n2. 服务器响应超时\n3. 图片文件损坏`);
} finally {
setIsProcessing(false);
}
}, [selectedImage, useHighResolution]);
const updateImageScale = useCallback((originalWidth: number, originalHeight: number, forceUpdate = false) => {
if (!imageRef.current) {
console.warn('⚠️ 图片引用不存在,无法计算缩放比例');
return;
}
// 等待图片完全渲染后再计算尺寸
const calculateScale = () => {
const img = imageRef.current!;
const displayWidth = img.clientWidth;
const displayHeight = img.clientHeight;
const naturalWidth = img.naturalWidth;
const naturalHeight = img.naturalHeight;
console.log('🔍 尺寸信息收集:', {
原始OCR尺寸: `${originalWidth}x${originalHeight}`,
图片自然尺寸: `${naturalWidth}x${naturalHeight}`,
显示尺寸: `${displayWidth}x${displayHeight}`,
图片加载状态: imageLoaded
});
// 验证原始尺寸
if (originalWidth <= 0 || originalHeight <= 0) {
console.error('❌ 原始图片尺寸无效:', { originalWidth, originalHeight });
setImageScale(1);
return;
}
// 验证显示尺寸
if (displayWidth <= 0 || displayHeight <= 0) {
if (!forceUpdate) {
console.warn('⚠️ 显示尺寸无效,延迟重试:', { displayWidth, displayHeight });
// 延迟重试,给图片更多时间渲染
setTimeout(() => updateImageScale(originalWidth, originalHeight, true), 100);
return;
} else {
console.error('❌ 显示尺寸持续无效,使用默认缩放比例');
setImageScale(1);
return;
}
}
// 计算缩放比例 - 确保图片按比例缩放
const scaleX = displayWidth / originalWidth;
const scaleY = displayHeight / originalHeight;
const scale = Math.min(scaleX, scaleY); // 使用较小的缩放比例保持图片比例
console.log('✅ 缩放计算完成:', {
X轴缩放: scaleX.toFixed(4),
Y轴缩放: scaleY.toFixed(4),
最终缩放: scale.toFixed(4)
});
setImageScale(scale);
};
// 如果图片已加载,立即计算;否则等待加载完成
if (imageLoaded) {
calculateScale();
} else {
console.log('⏳ 等待图片加载完成后计算缩放比例');
// 等待下一个渲染周期
requestAnimationFrame(calculateScale);
}
}, [imageLoaded]);
const handleRegionClick = useCallback((regionId: string) => {
setSelectedRegions(prev => {
const newSet = new Set(prev);
if (newSet.has(regionId)) {
newSet.delete(regionId);
} else {
newSet.add(regionId);
}
return newSet;
});
}, []);
const createImageOcclusionCard = useCallback(async () => {
if (!selectedImage || selectedRegions.size === 0 || !cardTitle.trim()) {
alert('请上传图片、选择要遮罩的区域,并填写卡片标题');
return;
}
setIsProcessing(true);
try {
const base64Data = selectedImage.split(',')[1];
const response = await invoke<ImageOcclusionResponse>('create_image_occlusion_card', {
request: {
image_base64: base64Data,
title: cardTitle.trim(),
description: cardDescription.trim() || null,
subject: cardSubject,
tags: cardTags.split(',').map(tag => tag.trim()).filter(tag => tag.length > 0),
selected_regions: Array.from(selectedRegions),
mask_style: maskStyle,
use_high_resolution: useHighResolution,
},
});
if (response.success && response.card) {
console.log('✅ 遮罩卡创建成功:', {
卡片ID: response.card.id,
标题: response.card.title,
遮罩数量: response.card.masks.length,
图片尺寸: `${response.card.image_width}x${response.card.image_height}`
});
setCreatedCard(response.card);
setShowPreview(true);
alert('✅ 图片遮罩卡创建成功!');
} else {
const errorMsg = response.error_message || '未知错误';
console.error('❌ 遮罩卡创建失败:', errorMsg);
alert(`创建失败: ${errorMsg}\n\n请检查:\n1. 是否选择了遮罩区域\n2. 卡片信息是否完整\n3. 网络连接是否正常`);
}
} catch (error) {
console.error('❌ 创建遮罩卡异常:', error);
const errorMessage = error instanceof Error ? error.message : String(error);
alert(`创建失败: ${errorMessage}\n\n可能的原因:\n1. 网络连接问题\n2. 服务器处理错误\n3. 数据格式异常`);
} finally {
setIsProcessing(false);
}
}, [selectedImage, selectedRegions, cardTitle, cardDescription, cardSubject, cardTags, maskStyle, useHighResolution]);
const renderTextRegions = useCallback(() => {
if (!textRegions.length || !imageRef.current || !imageLoaded || imageScale <= 0) {
console.log('🚫 无法渲染文字区域:', {
文字区域数量: textRegions.length,
图片引用: !!imageRef.current,
图片加载: imageLoaded,
缩放比例: imageScale
});
return null;
}
if (!imageRef.current.parentElement) {
console.error('❌ 图片父元素不存在');
return null;
}
// 获取精确的容器和图片位置信息
const imgRect = imageRef.current.getBoundingClientRect();
const containerRect = imageRef.current.parentElement.getBoundingClientRect();
// 计算图片相对于容器的精确偏移(不重复计算padding)
const imgOffsetX = imgRect.left - containerRect.left;
const imgOffsetY = imgRect.top - containerRect.top;
console.log('🎯 渲染文字区域 - 精确坐标计算:', {
容器位置: `${containerRect.left}, ${containerRect.top}`,
图片位置: `${imgRect.left}, ${imgRect.top}`,
图片偏移: `${imgOffsetX}, ${imgOffsetY}`,
图片尺寸: `${imgRect.width}x${imgRect.height}`,
缩放比例: imageScale.toFixed(4),
区域数量: textRegions.length
});
return textRegions.map((region) => {
const [x1, y1, x2, y2] = region.bbox;
const isSelected = selectedRegions.has(region.region_id);
// 精确的坐标转换:原始坐标 * 缩放比例 + 图片偏移
const finalLeft = x1 * imageScale + imgOffsetX;
const finalTop = y1 * imageScale + imgOffsetY;
const finalWidth = (x2 - x1) * imageScale;
const finalHeight = (y2 - y1) * imageScale;
// 调试信息(只为第一个区域输出,避免日志混乱)
if (region === textRegions[0]) {
console.log('📍 第一个区域坐标转换:', {
原始坐标: `[${x1}, ${y1}, ${x2}, ${y2}]`,
缩放后: `[${(x1 * imageScale).toFixed(1)}, ${(y1 * imageScale).toFixed(1)}, ${(x2 * imageScale).toFixed(1)}, ${(y2 * imageScale).toFixed(1)}]`,
最终位置: `${finalLeft.toFixed(1)}, ${finalTop.toFixed(1)}`,
区域尺寸: `${finalWidth.toFixed(1)}x${finalHeight.toFixed(1)}`,
文字内容: region.text
});
}
return (
<div
key={region.region_id}
className={`text-region ${isSelected ? 'selected' : ''}`}
style={{
position: 'absolute',
left: `${Math.round(finalLeft)}px`,
top: `${Math.round(finalTop)}px`,
width: `${Math.round(finalWidth)}px`,
height: `${Math.round(finalHeight)}px`,
border: `2px solid ${isSelected ? '#FF0000' : '#00FF00'}`,
backgroundColor: isSelected ? 'rgba(255, 0, 0, 0.2)' : 'rgba(0, 255, 0, 0.1)',
cursor: 'pointer',
borderRadius: '2px',
boxSizing: 'border-box',
pointerEvents: 'auto'
}}
onClick={() => handleRegionClick(region.region_id)}
title={`${region.text} (置信度: ${(region.confidence * 100).toFixed(1)}%)`}
/>
);
});
}, [textRegions, selectedRegions, imageScale, imageLoaded, handleRegionClick]);
const renderMaskPreview = useCallback(() => {
if (!createdCard || !showPreview || !imageRef.current || imageScale <= 0) {
console.log('🚫 无法渲染遮罩预览:', {
有卡片: !!createdCard,
显示预览: showPreview,
图片引用: !!imageRef.current,
缩放比例: imageScale
});
return null;
}
if (!imageRef.current.parentElement) {
console.error('❌ 遮罩预览: 图片父元素不存在');
return null;
}
// 使用与文字区域相同的坐标计算方法
const imgRect = imageRef.current.getBoundingClientRect();
const containerRect = imageRef.current.parentElement.getBoundingClientRect();
const imgOffsetX = imgRect.left - containerRect.left;
const imgOffsetY = imgRect.top - containerRect.top;
console.log('🎭 渲染遮罩预览:', {
遮罩数量: createdCard.masks.length,
图片偏移: `${imgOffsetX}, ${imgOffsetY}`,
缩放比例: imageScale.toFixed(4)
});
return createdCard.masks.map((mask) => {
const [x1, y1, x2, y2] = mask.bbox;
let maskStyleCSS: React.CSSProperties = {};
if ('SolidColor' in mask.mask_style && mask.mask_style.SolidColor) {
maskStyleCSS.backgroundColor = mask.mask_style.SolidColor.color;
} else if ('BlurEffect' in mask.mask_style && mask.mask_style.BlurEffect) {
maskStyleCSS.backgroundColor = 'rgba(128, 128, 128, 0.8)';
maskStyleCSS.backdropFilter = `blur(${mask.mask_style.BlurEffect.intensity}px)`;
} else if ('Rectangle' in mask.mask_style && mask.mask_style.Rectangle) {
const rectStyle = mask.mask_style.Rectangle;
maskStyleCSS.backgroundColor = rectStyle.color;
maskStyleCSS.opacity = rectStyle.opacity;
}
// 使用与文字区域相同的坐标转换方法
const finalLeft = x1 * imageScale + imgOffsetX;
const finalTop = y1 * imageScale + imgOffsetY;
const finalWidth = (x2 - x1) * imageScale;
const finalHeight = (y2 - y1) * imageScale;
return (
<div
key={mask.mask_id}
className="mask-overlay"
style={{
position: 'absolute',
left: `${Math.round(finalLeft)}px`,
top: `${Math.round(finalTop)}px`,
width: `${Math.round(finalWidth)}px`,
height: `${Math.round(finalHeight)}px`,
cursor: 'pointer',
borderRadius: '2px',
border: '1px solid rgba(0, 0, 0, 0.3)',
boxSizing: 'border-box',
pointerEvents: 'auto',
...maskStyleCSS,
}}
onClick={() => {
const isHidden = (document.querySelector(`[data-mask-id="${mask.mask_id}"]`) as HTMLElement)?.style.display === 'none';
const element = document.querySelector(`[data-mask-id="${mask.mask_id}"]`) as HTMLElement;
if (element) {
element.style.display = isHidden ? 'block' : 'none';
}
}}
data-mask-id={mask.mask_id}
title={`点击切换显示: ${mask.original_text}`}
/>
);
});
}, [createdCard, showPreview, imageScale]);
useEffect(() => {
// 只有在有OCR数据和图片已加载时才监听窗口大小变化
if (!originalImageDimensions || !imageLoaded) {
return;
}
const debouncedUpdateScale = () => {
console.log('🔄 窗口大小变化,重新计算缩放比例');
updateImageScale(originalImageDimensions.width, originalImageDimensions.height, true);
};
let timeoutId: number | null = null;
const handleResize = () => {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(debouncedUpdateScale, 300); // 增加防抖时间
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
if (timeoutId) {
clearTimeout(timeoutId);
}
};
}, [originalImageDimensions, imageLoaded, updateImageScale]);
return (
<div style={{
width: '100%',
height: '100%',
overflow: 'auto',
background: '#f8fafc'
}}>
{/* 头部区域 - 统一白色样式 */}
<div style={{
background: 'white',
borderBottom: '1px solid #e5e7eb',
padding: '24px 32px',
position: 'relative'
}}>
<div style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
height: '4px',
background: 'linear-gradient(90deg, #667eea, #764ba2)'
}}></div>
<div style={{ position: 'relative', zIndex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
<svg style={{ width: '32px', height: '32px', marginRight: '12px', color: '#667eea' }} fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
<rect width="18" height="18" x="3" y="3" rx="2" ry="2" />
<circle cx="9" cy="9" r="2" />
<path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" />
</svg>
<h1 style={{ fontSize: '28px', fontWeight: '700', margin: 0, color: '#1f2937' }}>图片遮罩卡制作</h1>
</div>
<p style={{ fontSize: '16px', color: '#6b7280', margin: 0, lineHeight: '1.5' }}>
上传图片,选择要遮罩的文字区域,创建互动学习卡片
</p>
</div>
</div>
<div className="image-occlusion-container" style={{padding: '24px'}}>
<div className="upload-section">
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleImageUpload}
style={{ display: 'none' }}
/>
<button
onClick={() => fileInputRef.current?.click()}
className="upload-button"
disabled={isProcessing}
>
选择图片
</button>
{selectedImage && (
<button
onClick={extractTextCoordinates}
className="extract-button"
disabled={isProcessing}
>
{isProcessing ? '识别中...' : '识别文字区域'}
</button>
)}
{selectedImage && (
<div className="form-group-inline">
<input
type="checkbox"
id="highResToggle"
checked={useHighResolution}
onChange={(e) => setUseHighResolution(e.target.checked)}
disabled={isProcessing}
/>
<label htmlFor="highResToggle">使用高分辨率模式</label>
</div>
)}
</div>
{selectedImage && (
<div className="image-workspace">
<div className="image-container">
<img
ref={imageRef}
src={selectedImage}
alt="待处理图片"
className="main-image"
onLoad={(e) => {
const img = e.target as HTMLImageElement;
console.log('🖼️ 图片加载完成:', {
自然尺寸: `${img.naturalWidth}x${img.naturalHeight}`,
显示尺寸: `${img.clientWidth}x${img.clientHeight}`,
是否有OCR数据: originalImageDimensions !== null
});
setImageLoaded(true);
// 如果已有OCR数据,立即重新计算缩放比例
if (originalImageDimensions) {
console.log('🔄 图片加载完成,重新计算缩放比例');
// 使用setTimeout确保图片尺寸已经更新
setTimeout(() => {
updateImageScale(originalImageDimensions.width, originalImageDimensions.height, true);
}, 50);
}
}}
/>
{!showPreview && renderTextRegions()}
{showPreview && renderMaskPreview()}
</div>
{textRegions.length > 0 && !showPreview && (
<div className="controls-panel">
<div className="card-info">
<h3>卡片信息</h3>
<div className="form-group">
<label htmlFor="cardTitle">标题 *</label>
<input
id="cardTitle"
type="text"
value={cardTitle}
onChange={(e) => setCardTitle(e.target.value)}
placeholder="输入卡片标题"
/>
</div>
<div className="form-group">
<label htmlFor="cardDescription">描述</label>
<textarea
id="cardDescription"
value={cardDescription}
onChange={(e) => setCardDescription(e.target.value)}
placeholder="输入卡片描述(可选)"
rows={3}
/>
</div>
<div className="form-row">
<div className="form-group">
<label htmlFor="cardSubject">学科</label>
<select
id="cardSubject"
value={cardSubject}
onChange={(e) => setCardSubject(e.target.value)}
>
<option value="数学">数学</option>
<option value="物理">物理</option>
<option value="化学">化学</option>
<option value="英语">英语</option>
<option value="语文">语文</option>
<option value="历史">历史</option>
<option value="地理">地理</option>
<option value="生物">生物</option>
<option value="其他">其他</option>
</select>
</div>
<div className="form-group">
<label htmlFor="cardTags">标签</label>
<input
id="cardTags"
type="text"
value={cardTags}
onChange={(e) => setCardTags(e.target.value)}
placeholder="用逗号分隔多个标签"
/>
</div>
</div>
</div>
<div className="mask-settings">
<h3>遮罩样式</h3>
<div className="mask-style-options">
<label>
<input
type="radio"
name="maskStyle"
checked={'Rectangle' in maskStyle}
onChange={() => setMaskStyle({ Rectangle: { color: '#FF0000', opacity: 0.7 } })}
/>
半透明矩形
</label>
<label>
<input
type="radio"
name="maskStyle"
checked={'SolidColor' in maskStyle}
onChange={() => setMaskStyle({ SolidColor: { color: '#000000' } })}
/>
纯色遮罩
</label>
<label>
<input
type="radio"
name="maskStyle"
checked={'BlurEffect' in maskStyle}
onChange={() => setMaskStyle({ BlurEffect: { intensity: 5 } })}
/>
模糊效果
</label>
</div>
</div>
<div className="region-stats">
<p>已识别 {textRegions.length} 个文字区域</p>
<p>已选择 {selectedRegions.size} 个区域进行遮罩</p>
</div>
<button
onClick={createImageOcclusionCard}
className="create-button"
disabled={isProcessing || selectedRegions.size === 0 || !cardTitle.trim()}
>
{isProcessing ? '创建中...' : '创建遮罩卡'}
</button>
</div>
)}
{showPreview && createdCard && (
<div className="preview-panel">
<h3>预览模式</h3>
<p>点击红色遮罩区域可以切换显示/隐藏文字</p>
<div className="preview-controls">
<button onClick={() => setShowPreview(false)}>返回编辑</button>
<button onClick={() => {
console.log('📄 尝试导出ANKI卡片:', {
卡片ID: createdCard?.id,
标题: createdCard?.title,
遮罩数量: createdCard?.masks.length
});
alert('🔧 导出功能即将推出\n\n将支持:\n1. 导出为Anki apkg文件\n2. 自定义遮罩样式\n3. 批量导出功能');
}}>
导出到ANKI
</button>
</div>
<div className="card-details">
<h4>{createdCard.title}</h4>
{createdCard.description && <p>{createdCard.description}</p>}
<div className="tags">
{createdCard.tags.map((tag, index) => (
<span key={index} className="tag">{tag}</span>
))}
</div>
</div>
</div>
)}
</div>
)}
</div>
</div>
);
};
export default ImageOcclusion;
|
000haoji/deep-student
| 2,488 |
src/components/MarkdownRenderer.tsx
|
import React from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import rehypeKatex from 'rehype-katex';
interface MarkdownRendererProps {
content: string;
className?: string;
}
// 简化的LaTeX预处理,最小化干预
const preprocessLatex = (content: string): string => {
if (!content) return '';
let processedContent = content;
// 专门处理 bmatrix 环境
processedContent = processedContent.replace(/\\begin{bmatrix}(.*?)\\end{bmatrix}/gs, (match, matrixContent) => {
// 移除每行末尾 \ 之前和之后的空格
let cleanedMatrix = matrixContent.replace(/\s*\\\\\s*/g, ' \\\\ '); // 保留一个空格以便阅读,KaTeX应能处理
// 移除 & 周围的空格
cleanedMatrix = cleanedMatrix.replace(/\s*&\s*/g, '&');
// 移除行首和行尾的空格
cleanedMatrix = cleanedMatrix.split(' \\\\ ').map((row: string) => row.trim()).join(' \\\\ ');
return `\\begin{bmatrix}${cleanedMatrix}\\end{bmatrix}`;
});
return processedContent;
};
export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
content,
className = ''
}) => {
// 预处理内容,处理LaTeX公式
const processedContent = preprocessLatex(content);
return (
<div className={`markdown-content ${className}`}>
<ReactMarkdown
remarkPlugins={[remarkGfm, remarkMath]}
rehypePlugins={[
[rehypeKatex, {
throwOnError: false, // 不抛出错误,以红色显示错误内容
errorColor: '#cc0000',
strict: false, // 宽松模式
trust: false, // 安全模式
macros: {
'\\RR': '\\mathbb{R}',
'\\NN': '\\mathbb{N}',
'\\ZZ': '\\mathbb{Z}',
'\\QQ': '\\mathbb{Q}',
'\\CC': '\\mathbb{C}'
}
}]
]}
components={{
// 自定义代码块渲染
code: ({ node, inline, className, children, ...props }: any) => {
return !inline ? (
<pre className="code-block">
<code className={className} {...props}>
{children}
</code>
</pre>
) : (
<code className="inline-code" {...props}>
{children}
</code>
);
},
// 自定义表格渲染
table: ({ children }) => (
<div className="table-wrapper">
<table className="markdown-table">{children}</table>
</div>
),
}}
>
{processedContent}
</ReactMarkdown>
</div>
);
};
|
000haoji/deep-student
| 20,531 |
src/components/ReviewAnalysisSessionView_old.tsx
|
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { ReviewSessionTask, ChatMessage } from '../types/index';
import { useNotification } from '../hooks/useNotification';
import { TauriAPI } from '../utils/tauriApi';
import { listen } from '@tauri-apps/api/event';
import { MessageWithThinking } from '../chat-core';
interface ReviewAnalysisSessionViewProps {
sessionId: string;
onBack: () => void;
}
const ReviewAnalysisSessionView: React.FC<ReviewAnalysisSessionViewProps> = ({
sessionId,
onBack,
}) => {
const [session, setSession] = useState<ReviewSessionTask | null>(null);
const [loading, setLoading] = useState(true);
const [userInput, setUserInput] = useState('');
const [isStreaming, setIsStreaming] = useState(false);
const [showThinking, setShowThinking] = useState(true);
const [sessionError, setSessionError] = useState<string | null>(null);
const chatContainerRef = useRef<HTMLDivElement>(null);
const { showNotification } = useNotification();
useEffect(() => {
loadSession();
}, [sessionId]);
useEffect(() => {
scrollToBottom();
}, [session?.chatHistory]);
const loadSession = async () => {
try {
setLoading(true);
// 优先尝试从后端API加载会话数据
try {
const backendSession = await TauriAPI.getConsolidatedReviewSession(sessionId);
if (backendSession) {
// 如果后端有数据,将其转换为前端格式
const sessionData: ReviewSessionTask = {
id: sessionId,
name: backendSession.name || '统一回顾分析',
creationDate: backendSession.created_at || new Date().toISOString(),
subject: backendSession.subject,
mistakeIds: backendSession.mistake_ids || [],
userConsolidatedInput: backendSession.consolidated_input || '',
userOverallPrompt: backendSession.overall_prompt || '',
status: 'pending', // 从后端加载的会话默认为pending状态
review_session_id: backendSession.review_session_id,
chatHistory: [],
thinkingContent: new Map(),
currentFullContentForStream: '',
currentThinkingContentForStream: '',
};
setSession(sessionData);
// 如果会话状态为pending,自动开始分析
if (sessionData.status === 'pending') {
startAnalysis(sessionData);
}
console.log('✅ 从后端API成功加载会话数据');
return;
}
} catch (apiError) {
console.warn('从后端API加载会话失败,尝试从localStorage加载:', apiError);
}
// 如果API调用失败或数据不存在,回退到localStorage
const existingSessions = JSON.parse(localStorage.getItem('reviewSessions') || '[]');
const foundSession = existingSessions.find((s: ReviewSessionTask) => s.id === sessionId);
if (foundSession) {
// 转换Map对象
foundSession.thinkingContent = new Map(Object.entries(foundSession.thinkingContent || {}));
setSession(foundSession);
// 如果会话状态为pending,自动开始分析
if (foundSession.status === 'pending') {
startAnalysis(foundSession);
}
console.log('✅ 从localStorage成功加载会话数据(回退)');
} else {
showNotification('error', '找不到指定的回顾分析会话');
}
} catch (error) {
console.error('加载回顾分析会话失败:', error);
showNotification('error', '加载回顾分析会话失败');
} finally {
setLoading(false);
}
};
const startAnalysis = async (sessionData: ReviewSessionTask) => {
try {
setSession(prev => prev ? { ...prev, status: 'processing_setup' } : null);
// 如果会话已经有review_session_id,直接开始流式分析
if (sessionData.review_session_id) {
setSession(prev => prev ? {
...prev,
status: 'awaiting_stream_start'
} : null);
// 监听流式事件
await setupStreamListeners(sessionData.review_session_id);
// 开始流式分析
await TauriAPI.triggerConsolidatedReviewStream({
reviewSessionId: sessionData.review_session_id,
enableChainOfThought: true
});
} else {
// 应该不会发生,因为创建时就有了review_session_id
throw new Error('缺少review_session_id');
}
} catch (error) {
console.error('开始分析失败:', error);
const errorMessage = error instanceof Error ? error.message : String(error);
setSession(prev => prev ? { ...prev, status: 'error_setup', errorDetails: errorMessage } : null);
setSessionError('分析启动失败: ' + errorMessage);
showNotification('error', '分析启动失败: ' + errorMessage);
}
};
const setupStreamListeners = async (reviewSessionId: string) => {
const streamEvent = `review_analysis_stream_${reviewSessionId}`;
const thinkingEvent = `review_analysis_stream_${reviewSessionId}_reasoning`;
let fullContent = '';
let fullThinkingContent = '';
// 监听主内容流
await listen(streamEvent, (event: any) => {
console.log('回顾分析流内容:', event.payload);
if (event.payload) {
if (event.payload.is_complete) {
console.log('回顾分析流完成');
setSession(prev => {
if (!prev) return null;
const assistantMessage: ChatMessage = {
role: 'assistant',
content: fullContent,
timestamp: new Date().toISOString(),
thinking_content: fullThinkingContent || undefined,
};
return {
...prev,
chatHistory: [...prev.chatHistory, assistantMessage],
status: 'completed',
};
});
setIsStreaming(false);
} else if (event.payload.content) {
fullContent += event.payload.content;
// 实时更新显示
setSession(prev => {
if (!prev) return null;
return {
...prev,
currentFullContentForStream: fullContent,
status: 'streaming_answer',
};
});
}
}
});
// 监听思维链流
if (showThinking) {
await listen(thinkingEvent, (event: any) => {
console.log('回顾分析思维链:', event.payload);
if (event.payload) {
if (event.payload.is_complete) {
console.log('回顾分析思维链完成');
} else if (event.payload.content) {
fullThinkingContent += event.payload.content;
setSession(prev => {
if (!prev) return null;
return {
...prev,
currentThinkingContentForStream: fullThinkingContent,
};
});
}
}
});
}
};
const handleSendMessage = async () => {
if (!userInput.trim() || !session || isStreaming) return;
try {
setIsStreaming(true);
const newUserMessage: ChatMessage = {
role: 'user',
content: userInput.trim(),
timestamp: new Date().toISOString(),
};
// 更新聊天历史
setSession(prev => prev ? {
...prev,
chatHistory: [...prev.chatHistory, newUserMessage]
} : null);
setUserInput('');
// 调用后端API继续对话
if (session.review_session_id) {
try {
// 设置流式监听器
await setupStreamListeners(session.review_session_id);
// 发起对话请求
await TauriAPI.continueConsolidatedReviewStream({
reviewSessionId: session.review_session_id,
chatHistory: [...session.chatHistory, newUserMessage],
enableChainOfThought: true,
});
} catch (apiError) {
console.error('继续对话API调用失败:', apiError);
const errorMessage = apiError instanceof Error ? apiError.message : String(apiError);
setSessionError('对话失败: ' + errorMessage);
setIsStreaming(false);
showNotification('error', '对话失败: ' + errorMessage);
}
} else {
showNotification('error', '缺少回顾分析会话ID');
}
} catch (error) {
console.error('发送消息失败:', error);
const errorMessage = error instanceof Error ? error.message : String(error);
setSessionError('发送消息失败: ' + errorMessage);
showNotification('error', '发送消息失败: ' + errorMessage);
setIsStreaming(false);
}
};
const scrollToBottom = () => {
if (chatContainerRef.current) {
chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
}
};
if (loading) {
return (
<div className="flex justify-center items-center h-64">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
<span className="ml-2 text-gray-600">加载中...</span>
</div>
);
}
if (!session) {
return (
<div className="text-center py-12">
<h3 className="text-lg font-medium text-gray-900 mb-2">未找到回顾分析会话</h3>
<button
onClick={onBack}
className="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-colors"
>
返回列表
</button>
</div>
);
}
return (
<div className="review-analysis-session-view">
{/* 头部信息 - 简化并移除思维链控制(移动到聊天区域) */}
<div style={{
backgroundColor: 'white',
borderBottom: '1px solid #e2e8f0',
padding: '16px 24px',
flexShrink: 0
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
<div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
<button
onClick={onBack}
style={{
marginRight: '12px',
padding: '4px',
border: 'none',
background: 'transparent',
cursor: 'pointer',
borderRadius: '4px',
display: 'flex',
alignItems: 'center'
}}
onMouseOver={(e) => e.currentTarget.style.backgroundColor = '#f3f4f6'}
onMouseOut={(e) => e.currentTarget.style.backgroundColor = 'transparent'}
>
<svg style={{ width: '20px', height: '20px' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
</button>
<h2 style={{ fontSize: '20px', fontWeight: '600', color: '#1f2937', margin: 0 }}>
{session.name}
</h2>
<span style={{
marginLeft: '12px',
padding: '4px 8px',
fontSize: '12px',
fontWeight: '500',
borderRadius: '12px',
backgroundColor: session.status === 'completed' ? '#dcfce7' :
session.status === 'streaming_answer' ? '#dbeafe' :
session.status.includes('error') ? '#fecaca' : '#fef3c7',
color: session.status === 'completed' ? '#166534' :
session.status === 'streaming_answer' ? '#1d4ed8' :
session.status.includes('error') ? '#dc2626' : '#d97706'
}}>
{session.status === 'completed' ? '已完成' :
session.status === 'streaming_answer' ? '分析中' :
session.status.includes('error') ? '错误' : '处理中'}
</span>
</div>
<div style={{ fontSize: '14px', color: '#6b7280' }}>
<span>科目: {session.subject}</span>
<span style={{ margin: '0 8px' }}>•</span>
<span>错题数量: {session.mistakeIds.length}</span>
<span style={{ margin: '0 8px' }}>•</span>
<span>创建时间: {new Date(session.creationDate).toLocaleString()}</span>
</div>
</div>
</div>
</div>
{/* 统一回顾分析上下文信息区域 - 参考BatchTaskDetailView结构 */}
<div style={{
backgroundColor: 'white',
borderBottom: '1px solid #e2e8f0',
padding: '16px 24px',
flexShrink: 0
}}>
<div className="task-info-section">
<h4 style={{ fontSize: '16px', fontWeight: '600', color: '#374151', marginBottom: '12px' }}>
📋 回顾分析信息
</h4>
<div className="info-row" style={{ display: 'flex', marginBottom: '8px' }}>
<span className="info-label" style={{ minWidth: '80px', color: '#6b7280', fontWeight: '500' }}>
分析目标:
</span>
<span className="info-value" style={{ color: '#1f2937', flex: 1 }}>
{session.userOverallPrompt || '统一分析多个错题的共同问题和改进建议'}
</span>
</div>
<div className="info-row" style={{ display: 'flex', marginBottom: '8px' }}>
<span className="info-label" style={{ minWidth: '80px', color: '#6b7280', fontWeight: '500' }}>
错题数量:
</span>
<span className="info-value" style={{ color: '#1f2937' }}>
{session.mistakeIds.length} 个错题
</span>
</div>
{session.mistakeIds.length > 0 && (
<div className="info-row" style={{ display: 'flex', marginBottom: '8px' }}>
<span className="info-label" style={{ minWidth: '80px', color: '#6b7280', fontWeight: '500' }}>
错题ID:
</span>
<span className="info-value" style={{ color: '#1f2937' }}>
{session.mistakeIds.slice(0, 3).join(', ')}
{session.mistakeIds.length > 3 && ` 等${session.mistakeIds.length}个`}
</span>
</div>
)}
{session.userConsolidatedInput && (
<div className="consolidated-input-section" style={{ marginTop: '16px' }}>
<h5 style={{ fontSize: '14px', fontWeight: '600', color: '#374151', marginBottom: '8px' }}>
📝 整合内容预览
</h5>
<div className="consolidated-preview" style={{
backgroundColor: '#f8fafc',
border: '1px solid #e2e8f0',
borderRadius: '8px',
padding: '12px',
fontSize: '13px',
color: '#4b5563',
maxHeight: '120px',
overflow: 'auto',
lineHeight: '1.4',
whiteSpace: 'pre-wrap'
}}>
{session.userConsolidatedInput.length > 200
? session.userConsolidatedInput.substring(0, 200) + '...'
: session.userConsolidatedInput}
</div>
</div>
)}
{/* 错误信息 - 借鉴BatchTaskDetailView */}
{(session.errorDetails || sessionError) && (
<div className="error-section" style={{ marginTop: '16px' }}>
<h4 style={{ fontSize: '14px', fontWeight: '600', color: '#dc2626', marginBottom: '8px' }}>
❌ 错误信息
</h4>
<div className="error-text" style={{
backgroundColor: '#fef2f2',
border: '1px solid #fecaca',
borderRadius: '8px',
padding: '12px',
fontSize: '13px',
color: '#991b1b',
lineHeight: '1.4'
}}>
{sessionError || session.errorDetails}
</div>
</div>
)}
{/* 处理状态显示 - 借鉴BatchTaskDetailView的状态指示 */}
{session.status !== 'completed' && session.status !== 'pending' && !session.status.includes('error') && (
<div className="processing-status" style={{ marginTop: '16px' }}>
<div style={{
backgroundColor: '#eff6ff',
border: '1px solid #bfdbfe',
borderRadius: '8px',
padding: '12px',
display: 'flex',
alignItems: 'center',
gap: '8px'
}}>
<div className="spinner" style={{
width: '16px',
height: '16px',
border: '2px solid #dbeafe',
borderTop: '2px solid #3b82f6',
borderRadius: '50%',
animation: 'spin 1s linear infinite'
}}></div>
<span style={{ fontSize: '14px', color: '#1d4ed8', fontWeight: '500' }}>
{session.status === 'processing_setup' ? '正在设置分析环境...' :
session.status === 'awaiting_stream_start' ? '等待AI开始分析...' :
session.status === 'streaming_answer' ? 'AI正在分析您的错题...' :
'处理中...'}
</span>
</div>
</div>
)}
</div>
</div>
{/* AI解答区域 - 复用BatchTaskDetailView的聊天界面结构 */}
<div className="chat-container">
<div className="chat-header">
<h4>💬 AI回顾分析</h4>
<div className="chat-header-actions">
<span className="chain-indicator">🧠 思维链模式</span>
<button
onClick={() => setShowThinking(!showThinking)}
className="chat-fullscreen-toggle"
style={{ marginLeft: '8px' }}
>
{showThinking ? '隐藏思维链' : '显示思维链'}
</button>
</div>
</div>
<div className="chat-history" ref={chatContainerRef} style={{
flex: 1,
overflowY: 'auto',
padding: '1rem',
minHeight: 0
}}>
{session.chatHistory.map((message, index) => {
const thinking = session.thinkingContent.get(index);
return (
<MessageWithThinking
key={index}
content={message.content}
thinkingContent={thinking}
isStreaming={isStreaming && index === session.chatHistory.length - 1}
role={message.role as 'user' | 'assistant'}
timestamp={message.timestamp}
/>
);
})}
{isStreaming && session.chatHistory.length === 0 && (
<div className="message assistant">
<div className="message-content typing">
<span className="typing-indicator">
<span></span>
<span></span>
<span></span>
</span>
AI正在分析您的错题...
</div>
</div>
)}
{isStreaming && (
<div className="message assistant">
<div className="message-content typing">
<span className="typing-indicator">
<span></span>
<span></span>
<span></span>
</span>
正在思考中...
</div>
</div>
)}
</div>
{/* 输入框 - 复用BatchTaskDetailView的输入区域结构 */}
{session.status === 'completed' && (
<div className="chat-input" style={{
flexShrink: 0,
padding: '1rem',
borderTop: '1px solid #e1e5e9',
backgroundColor: 'white',
display: 'flex',
gap: '0.5rem',
alignItems: 'center'
}}>
<input
type="text"
value={userInput}
onChange={(e) => setUserInput(e.target.value)}
placeholder="继续提问..."
onKeyDown={(e) => e.key === 'Enter' && handleSendMessage()}
disabled={isStreaming}
style={{
flex: 1,
padding: '0.75rem',
border: '1px solid #d1d5db',
borderRadius: '0.375rem',
fontSize: '0.875rem',
outline: 'none'
}}
/>
<button
onClick={handleSendMessage}
disabled={isStreaming || !userInput.trim()}
className="send-button"
style={{
padding: '0.75rem 1rem',
backgroundColor: '#3b82f6',
color: 'white',
border: 'none',
borderRadius: '0.375rem',
cursor: 'pointer',
fontSize: '0.875rem',
opacity: (isStreaming || !userInput.trim()) ? 0.5 : 1
}}
>
{isStreaming ? '⏳' : '📤'}
</button>
</div>
)}
</div>
</div>
);
};
export default ReviewAnalysisSessionView;
|
000haoji/deep-student
| 12,423 |
src/components/TemplateManager.css
|
/* 模板管理器主容器 */
.template-manager-modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1000;
display: flex;
align-items: center;
justify-content: center;
}
.template-manager-backdrop {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(4px);
}
.template-manager-container {
position: relative;
width: 95vw;
height: 90vh;
max-width: 1400px;
max-height: 900px;
background: white;
border-radius: 16px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
display: flex;
flex-direction: column;
overflow: hidden;
}
/* 头部 */
.template-manager-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 24px 32px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.template-manager-header h2 {
margin: 0;
font-size: 24px;
font-weight: 600;
}
.close-btn {
background: rgba(255, 255, 255, 0.2);
border: none;
color: white;
width: 36px;
height: 36px;
border-radius: 8px;
font-size: 18px;
cursor: pointer;
transition: all 0.2s;
}
.close-btn:hover {
background: rgba(255, 255, 255, 0.3);
transform: scale(1.05);
}
/* 标签页导航 */
.template-manager-tabs {
display: flex;
background: #f8fafc;
border-bottom: 1px solid #e2e8f0;
padding: 0 32px;
}
.tab-btn {
background: none;
border: none;
padding: 16px 24px;
font-size: 14px;
font-weight: 500;
color: #64748b;
cursor: pointer;
border-bottom: 2px solid transparent;
transition: all 0.2s;
white-space: nowrap;
}
.tab-btn:hover {
color: #475569;
background: rgba(0, 0, 0, 0.05);
}
.tab-btn.active {
color: #667eea;
border-bottom-color: #667eea;
background: white;
}
/* 错误横幅 */
.error-banner {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 32px;
background: #fee2e2;
color: #dc2626;
border-bottom: 1px solid #fca5a5;
font-size: 14px;
}
.error-banner button {
background: none;
border: none;
color: #dc2626;
cursor: pointer;
font-size: 16px;
padding: 0;
margin-left: 16px;
}
/* 内容区域 */
.template-manager-content {
flex: 1;
overflow: hidden;
display: flex;
flex-direction: column;
}
/* 模板浏览器 */
.template-browser {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
.browser-toolbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px 32px;
background: white;
border-bottom: 1px solid #e2e8f0;
}
.search-box {
position: relative;
flex: 1;
max-width: 400px;
}
.search-input {
width: 100%;
padding: 12px 16px 12px 44px;
border: 1px solid #d1d5db;
border-radius: 8px;
font-size: 14px;
transition: all 0.2s;
}
.search-input:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.search-icon {
position: absolute;
left: 16px;
top: 50%;
transform: translateY(-50%);
color: #9ca3af;
font-size: 16px;
}
.toolbar-info {
color: #6b7280;
font-size: 14px;
}
/* 模板网格 */
.templates-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
gap: 20px;
padding: 20px 32px 32px;
overflow-y: auto;
max-height: calc(100vh - 280px);
}
/* 模板卡片 */
.template-card {
background: white;
border: 1px solid #e5e7eb;
border-radius: 12px;
padding: 20px;
transition: all 0.2s;
cursor: pointer;
position: relative;
}
.template-card:hover {
border-color: #667eea;
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
transform: translateY(-2px);
}
.template-card.selected {
border-color: #667eea;
box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}
.template-card.inactive {
opacity: 0.6;
}
.card-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 16px;
}
.template-name {
font-size: 18px;
font-weight: 600;
color: #1f2937;
margin: 0;
line-height: 1.3;
}
.template-badges {
display: flex;
gap: 6px;
flex-wrap: wrap;
}
.badge {
padding: 2px 8px;
border-radius: 12px;
font-size: 11px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.badge.built-in {
background: #dbeafe;
color: #1e40af;
}
.badge.inactive {
background: #f3f4f6;
color: #6b7280;
}
.badge.version {
background: #f0fdf4;
color: #15803d;
}
/* 预览区域 */
.card-preview {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-bottom: 16px;
}
.preview-front, .preview-back {
background: #f9fafb;
border: 1px solid #e5e7eb;
border-radius: 8px;
padding: 12px;
}
.preview-label {
font-size: 11px;
font-weight: 600;
color: #6b7280;
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 6px;
}
.preview-content {
font-size: 13px;
color: #374151;
line-height: 1.4;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
/* 卡片信息 */
.card-info {
margin-bottom: 16px;
}
.template-description {
font-size: 14px;
color: #6b7280;
line-height: 1.5;
margin-bottom: 12px;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.template-meta {
display: flex;
gap: 16px;
margin-bottom: 12px;
font-size: 12px;
color: #9ca3af;
}
.template-fields {
display: flex;
gap: 6px;
flex-wrap: wrap;
}
.field-tag {
background: #f3f4f6;
color: #374151;
padding: 2px 8px;
border-radius: 12px;
font-size: 11px;
font-weight: 500;
}
.field-tag.more {
background: #e5e7eb;
color: #6b7280;
}
/* 卡片操作 */
.card-actions {
display: flex;
justify-content: space-between;
align-items: center;
}
.btn-select {
background: #667eea;
color: white;
border: none;
padding: 8px 16px;
border-radius: 6px;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
}
.btn-select:hover {
background: #5a67d8;
transform: translateY(-1px);
}
.action-menu {
display: flex;
gap: 4px;
}
.btn-action {
background: #f9fafb;
border: 1px solid #e5e7eb;
color: #6b7280;
width: 32px;
height: 32px;
border-radius: 6px;
font-size: 14px;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
}
.btn-action:hover {
background: #f3f4f6;
border-color: #d1d5db;
color: #374151;
}
.btn-action.danger:hover {
background: #fee2e2;
border-color: #fca5a5;
color: #dc2626;
}
/* 加载状态 */
.loading-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 60px 20px;
color: #6b7280;
}
.loading-spinner {
width: 40px;
height: 40px;
border: 3px solid #f3f4f6;
border-top: 3px solid #667eea;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-bottom: 16px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* 空状态 */
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 60px 20px;
text-align: center;
}
.empty-icon {
font-size: 64px;
margin-bottom: 20px;
opacity: 0.5;
}
.empty-state h3 {
font-size: 20px;
color: #374151;
margin: 0 0 8px 0;
}
.empty-state p {
color: #6b7280;
margin: 0;
max-width: 300px;
}
/* 模板编辑器 */
.template-editor {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
.editor-header {
padding: 20px 32px 0;
}
.editor-header h3 {
margin: 0;
font-size: 20px;
color: #1f2937;
}
.editor-tabs {
display: flex;
padding: 0 32px;
border-bottom: 1px solid #e5e7eb;
margin-bottom: 0;
}
.editor-tab {
background: none;
border: none;
padding: 16px 20px;
font-size: 14px;
font-weight: 500;
color: #6b7280;
cursor: pointer;
border-bottom: 2px solid transparent;
transition: all 0.2s;
}
.editor-tab:hover {
color: #374151;
}
.editor-tab.active {
color: #667eea;
border-bottom-color: #667eea;
}
.editor-form {
flex: 1;
overflow-y: auto;
padding: 0 32px 32px;
}
.editor-section {
padding-top: 24px;
}
/* 表单样式 */
.form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.form-group {
display: flex;
flex-direction: column;
}
.form-group.full-width {
grid-column: 1 / -1;
}
.form-group label {
font-size: 14px;
font-weight: 500;
color: #374151;
margin-bottom: 6px;
}
.form-input, .form-textarea {
padding: 12px 16px;
border: 1px solid #d1d5db;
border-radius: 8px;
font-size: 14px;
transition: all 0.2s;
font-family: inherit;
}
.form-input:focus, .form-textarea:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-textarea {
resize: vertical;
min-height: 80px;
}
.form-help {
font-size: 12px;
color: #6b7280;
margin-top: 4px;
}
/* 代码编辑器 */
.template-code-editor {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 24px;
}
.code-group {
display: flex;
flex-direction: column;
}
.code-group label {
font-size: 14px;
font-weight: 500;
color: #374151;
margin-bottom: 8px;
}
.code-textarea {
padding: 16px;
border: 1px solid #d1d5db;
border-radius: 8px;
font-family: 'Fira Code', 'Monaco', 'Consolas', monospace;
font-size: 13px;
line-height: 1.5;
background: #f9fafb;
resize: vertical;
transition: all 0.2s;
}
.code-textarea:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
background: white;
}
/* 样式编辑器 */
.styles-editor {
display: flex;
flex-direction: column;
}
.styles-editor label {
font-size: 14px;
font-weight: 500;
color: #374151;
margin-bottom: 8px;
}
.css-textarea {
padding: 16px;
border: 1px solid #d1d5db;
border-radius: 8px;
font-family: 'Fira Code', 'Monaco', 'Consolas', monospace;
font-size: 13px;
line-height: 1.5;
background: #f9fafb;
resize: vertical;
min-height: 300px;
transition: all 0.2s;
}
.css-textarea:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
background: white;
}
/* 高级设置 */
.advanced-settings {
display: flex;
flex-direction: column;
}
.advanced-settings label {
font-size: 14px;
font-weight: 500;
color: #374151;
margin-bottom: 8px;
}
.prompt-textarea {
padding: 16px;
border: 1px solid #d1d5db;
border-radius: 8px;
font-size: 14px;
line-height: 1.6;
resize: vertical;
min-height: 200px;
transition: all 0.2s;
}
.prompt-textarea:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
/* 编辑器操作按钮 */
.editor-actions {
display: flex;
gap: 12px;
justify-content: flex-end;
padding: 24px 0 0;
border-top: 1px solid #e5e7eb;
margin-top: 24px;
}
.btn-primary {
background: #667eea;
color: white;
border: none;
padding: 12px 24px;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
}
.btn-primary:hover {
background: #5a67d8;
transform: translateY(-1px);
}
.btn-primary:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
}
.btn-secondary {
background: #f9fafb;
color: #374151;
border: 1px solid #d1d5db;
padding: 12px 24px;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
}
.btn-secondary:hover {
background: #f3f4f6;
border-color: #9ca3af;
}
/* 响应式设计 */
@media (max-width: 1200px) {
.template-manager-container {
width: 98vw;
height: 95vh;
}
.templates-grid {
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 16px;
padding: 16px 24px 24px;
}
.template-code-editor {
grid-template-columns: 1fr;
gap: 16px;
}
.form-grid {
grid-template-columns: 1fr;
gap: 16px;
}
}
@media (max-width: 768px) {
.template-manager-header {
padding: 16px 20px;
}
.template-manager-header h2 {
font-size: 20px;
}
.template-manager-tabs,
.browser-toolbar,
.editor-form {
padding-left: 20px;
padding-right: 20px;
}
.browser-toolbar {
flex-direction: column;
gap: 12px;
align-items: stretch;
}
.search-box {
max-width: none;
}
.templates-grid {
grid-template-columns: 1fr;
padding: 16px 20px 24px;
}
.card-preview {
grid-template-columns: 1fr;
}
}
|
000haoji/deep-student
| 3,374 |
src/components/WindowControls.tsx
|
import { useState, useEffect } from 'react';
import { getCurrentWindow } from '@tauri-apps/api/window';
export const WindowControls: React.FC = () => {
const [isMaximized, setIsMaximized] = useState(false);
useEffect(() => {
const initWindow = async () => {
const window = getCurrentWindow();
// 检查初始最大化状态
try {
const maximized = await window.isMaximized();
setIsMaximized(maximized);
} catch (error) {
console.error('Failed to get maximized state:', error);
}
// 监听窗口状态变化
try {
const unlisten = await window.listen('tauri://resize', async () => {
try {
const maximized = await window.isMaximized();
setIsMaximized(maximized);
} catch (error) {
console.error('Failed to update maximized state:', error);
}
});
return () => {
};
} catch (error) {
console.error('Failed to listen to window events:', error);
}
};
initWindow();
}, []);
const handleMinimize = async (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
try {
const window = getCurrentWindow();
await window.minimize();
} catch (error) {
console.error('Failed to minimize window:', error);
}
};
const handleMaximize = async (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
try {
const window = getCurrentWindow();
if (isMaximized) {
await window.unmaximize();
setIsMaximized(false);
} else {
await window.maximize();
setIsMaximized(true);
}
} catch (error) {
console.error('Failed to toggle maximize:', error);
}
};
const handleClose = async (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
try {
const window = getCurrentWindow();
await window.close();
} catch (error) {
console.error('Failed to close window:', error);
}
};
return (
<div className="window-controls">
<button
className="window-button minimize"
onClick={handleMinimize}
onMouseDown={(e) => e.stopPropagation()}
title="最小化"
>
<svg width="12" height="12" viewBox="0 0 12 12">
<path d="M2 6h8" stroke="currentColor" strokeWidth="1" />
</svg>
</button>
<button
className="window-button maximize"
onClick={handleMaximize}
onMouseDown={(e) => e.stopPropagation()}
title={isMaximized ? "还原" : "最大化"}
>
{isMaximized ? (
<svg width="12" height="12" viewBox="0 0 12 12">
<path d="M3 3h6v6H3V3z M1 1h6v2H3v4H1V1z" stroke="currentColor" strokeWidth="1" fill="none" />
</svg>
) : (
<svg width="12" height="12" viewBox="0 0 12 12">
<path d="M2 2h8v8H2V2z" stroke="currentColor" strokeWidth="1" fill="none" />
</svg>
)}
</button>
<button
className="window-button close"
onClick={handleClose}
onMouseDown={(e) => e.stopPropagation()}
title="关闭"
>
<svg width="12" height="12" viewBox="0 0 12 12">
<path d="M3 3l6 6M9 3l-6 6" stroke="currentColor" strokeWidth="1" />
</svg>
</button>
</div>
);
};
|
000haoji/deep-student
| 9,586 |
src/components/EnhancedRagQueryView.css
|
/* 增强RAG查询视图样式 */
.enhanced-rag-query-view {
padding: 20px;
max-width: 1200px;
margin: 0 auto;
background: #f8fafc;
min-height: 100vh;
}
/* 查询头部 */
.query-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding: 20px;
background: white;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.query-header h2 {
margin: 0;
color: #1e293b;
font-size: 1.5rem;
font-weight: 600;
}
.header-actions {
display: flex;
gap: 10px;
}
/* 分库选择器 */
.library-selector {
margin-bottom: 20px;
padding: 20px;
background: white;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
border-left: 4px solid #3b82f6;
}
.selector-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
}
.selector-header h3 {
margin: 0;
color: #1e293b;
font-size: 1.125rem;
font-weight: 600;
}
.selector-actions {
display: flex;
gap: 8px;
}
.btn-sm {
padding: 6px 12px;
font-size: 0.75rem;
}
.library-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 12px;
}
.library-card {
display: flex;
align-items: center;
gap: 12px;
padding: 15px;
border: 2px solid #e2e8f0;
border-radius: 8px;
cursor: pointer;
transition: all 0.2s ease;
background: #f8fafc;
}
.library-card:hover {
border-color: #3b82f6;
background: #eff6ff;
}
.library-card.selected {
border-color: #3b82f6;
background: #dbeafe;
}
.library-checkbox {
flex-shrink: 0;
}
.library-checkbox input[type="checkbox"] {
width: 16px;
height: 16px;
cursor: pointer;
}
.library-info {
flex: 1;
}
.library-name {
font-weight: 600;
color: #1e293b;
margin-bottom: 4px;
}
.library-stats {
font-size: 0.875rem;
color: #64748b;
margin-bottom: 4px;
}
.library-description {
font-size: 0.75rem;
color: #64748b;
font-style: italic;
line-height: 1.4;
}
/* 高级选项 */
.advanced-options {
margin-bottom: 20px;
padding: 20px;
background: white;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
border-left: 4px solid #f59e0b;
}
.options-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
}
.option-group {
display: flex;
flex-direction: column;
gap: 8px;
}
.option-group label {
font-weight: 500;
color: #374151;
font-size: 0.875rem;
}
.checkbox-label {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
}
.checkbox-label input[type="checkbox"] {
width: 16px;
height: 16px;
}
.form-input {
padding: 8px 12px;
border: 1px solid #d1d5db;
border-radius: 6px;
font-size: 0.875rem;
transition: border-color 0.2s ease;
}
.form-input:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.option-hint {
font-size: 0.75rem;
color: #6b7280;
font-style: italic;
}
/* 查询输入区域 */
.query-input-section {
margin-bottom: 30px;
padding: 20px;
background: white;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.input-group {
display: flex;
gap: 15px;
align-items: flex-end;
}
.query-input {
flex: 1;
padding: 12px 16px;
border: 2px solid #e2e8f0;
border-radius: 8px;
font-size: 1rem;
resize: vertical;
transition: border-color 0.2s ease;
font-family: inherit;
}
.query-input:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.query-input:disabled {
background: #f3f4f6;
color: #6b7280;
}
.query-btn {
height: fit-content;
padding: 12px 24px;
font-size: 1rem;
white-space: nowrap;
}
.selected-libraries-info {
margin-top: 15px;
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.info-label {
font-size: 0.875rem;
color: #64748b;
font-weight: 500;
}
.library-tags {
display: flex;
gap: 6px;
flex-wrap: wrap;
}
.library-tag {
background: #dbeafe;
color: #1e40af;
padding: 4px 8px;
border-radius: 4px;
font-size: 0.75rem;
font-weight: 500;
}
/* 查询结果 */
.query-results {
background: white;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
overflow: hidden;
}
.results-header {
padding: 20px;
border-bottom: 1px solid #e2e8f0;
background: #f8fafc;
}
.results-header h3 {
margin: 0 0 15px 0;
color: #1e293b;
font-size: 1.25rem;
font-weight: 600;
}
.results-meta {
display: flex;
gap: 20px;
flex-wrap: wrap;
}
.meta-item {
display: flex;
gap: 6px;
font-size: 0.875rem;
}
.meta-item .label {
color: #64748b;
font-weight: 500;
}
.meta-item .value {
color: #1e293b;
font-weight: 600;
}
/* 无结果状态 */
.no-results {
text-align: center;
padding: 60px 20px;
}
.no-results-icon {
font-size: 4rem;
margin-bottom: 15px;
opacity: 0.5;
}
.no-results-text {
font-size: 1.25rem;
font-weight: 500;
color: #334155;
margin-bottom: 8px;
}
.no-results-hint {
color: #64748b;
font-size: 0.875rem;
}
/* 结果列表 */
.results-list {
padding: 20px;
display: flex;
flex-direction: column;
gap: 20px;
}
.result-item {
border: 1px solid #e2e8f0;
border-radius: 8px;
overflow: hidden;
transition: box-shadow 0.2s ease;
}
.result-item:hover {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.result-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px;
background: #f8fafc;
border-bottom: 1px solid #e2e8f0;
}
.result-meta {
display: flex;
gap: 15px;
align-items: center;
flex-wrap: wrap;
}
.result-index {
background: #3b82f6;
color: white;
padding: 2px 8px;
border-radius: 12px;
font-size: 0.75rem;
font-weight: 600;
}
.result-source,
.result-chunk {
font-size: 0.875rem;
color: #64748b;
font-weight: 500;
}
.similarity-score {
font-size: 0.875rem;
font-weight: 600;
padding: 4px 8px;
border-radius: 4px;
background: rgba(255, 255, 255, 0.8);
}
.result-content {
padding: 20px;
line-height: 1.6;
color: #374151;
}
.result-content p {
margin: 0 0 12px 0;
}
.result-content p:last-child {
margin-bottom: 0;
}
.result-content code {
background: #f3f4f6;
padding: 2px 4px;
border-radius: 4px;
font-size: 0.875em;
}
.result-content pre {
background: #f3f4f6;
padding: 12px;
border-radius: 6px;
overflow-x: auto;
margin: 12px 0;
}
.result-content blockquote {
border-left: 4px solid #3b82f6;
padding-left: 16px;
margin: 16px 0;
color: #64748b;
font-style: italic;
}
/* 元数据 */
.result-metadata {
border-top: 1px solid #e2e8f0;
}
.result-metadata details {
padding: 15px;
}
.result-metadata summary {
cursor: pointer;
font-size: 0.875rem;
color: #64748b;
font-weight: 500;
user-select: none;
}
.result-metadata summary:hover {
color: #3b82f6;
}
.metadata-content {
margin-top: 12px;
padding: 12px;
background: #f8fafc;
border-radius: 6px;
border: 1px solid #e2e8f0;
}
.metadata-item {
display: flex;
justify-content: space-between;
padding: 4px 0;
font-size: 0.875rem;
}
.metadata-item:not(:last-child) {
border-bottom: 1px solid #e2e8f0;
}
.metadata-key {
color: #64748b;
font-weight: 500;
}
.metadata-value {
color: #1e293b;
word-break: break-word;
text-align: right;
max-width: 60%;
}
/* 使用指南 */
.usage-guide {
margin-top: 30px;
padding: 30px;
background: white;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.usage-guide h3 {
margin: 0 0 20px 0;
color: #1e293b;
font-size: 1.25rem;
font-weight: 600;
}
.guide-content {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 25px;
}
.guide-section h4 {
margin: 0 0 12px 0;
color: #374151;
font-size: 1rem;
font-weight: 600;
}
.guide-section ul {
margin: 0;
padding-left: 20px;
color: #64748b;
line-height: 1.6;
}
.guide-section li {
margin-bottom: 6px;
}
.guide-section strong {
color: #374151;
font-weight: 600;
}
/* 按钮样式 */
.btn {
padding: 8px 16px;
border: none;
border-radius: 6px;
font-size: 0.875rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
display: inline-flex;
align-items: center;
gap: 6px;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-primary {
background: #3b82f6;
color: white;
}
.btn-primary:hover:not(:disabled) {
background: #2563eb;
}
.btn-secondary {
background: #64748b;
color: white;
}
.btn-secondary:hover:not(:disabled) {
background: #475569;
}
/* 响应式设计 */
@media (max-width: 1024px) {
.query-header {
flex-direction: column;
gap: 15px;
align-items: stretch;
}
.header-actions {
justify-content: center;
}
.results-meta {
gap: 15px;
}
}
@media (max-width: 768px) {
.enhanced-rag-query-view {
padding: 10px;
}
.input-group {
flex-direction: column;
align-items: stretch;
}
.query-btn {
align-self: center;
}
.library-grid {
grid-template-columns: 1fr;
}
.options-grid {
grid-template-columns: 1fr;
}
.guide-content {
grid-template-columns: 1fr;
}
.result-header {
flex-direction: column;
align-items: flex-start;
gap: 10px;
}
.result-meta {
gap: 10px;
}
.similarity-score {
align-self: flex-end;
}
}
@media (max-width: 480px) {
.selected-libraries-info {
flex-direction: column;
align-items: flex-start;
gap: 8px;
}
.metadata-item {
flex-direction: column;
align-items: flex-start;
gap: 4px;
}
.metadata-value {
text-align: left;
max-width: 100%;
}
}
|
000haoji/deep-student
| 22,970 |
src/components/TemplateManager.tsx
|
import React, { useState, useEffect, useRef } from 'react';
import { CustomAnkiTemplate, CreateTemplateRequest, FieldExtractionRule, AnkiCardTemplate } from '../types';
import { templateManager } from '../data/ankiTemplates';
import './TemplateManager.css';
import { IframePreview, renderCardPreview } from './SharedPreview';
import {
Palette,
BookOpen,
Plus,
Edit,
AlertTriangle,
Search,
FileText,
User,
Copy,
Trash2,
CheckCircle,
X,
Settings,
Paintbrush
} from 'lucide-react';
interface TemplateManagerProps {
onClose: () => void;
onSelectTemplate?: (template: CustomAnkiTemplate) => void;
}
const TemplateManager: React.FC<TemplateManagerProps> = ({ onClose, onSelectTemplate }) => {
const [templates, setTemplates] = useState<CustomAnkiTemplate[]>([]);
const [activeTab, setActiveTab] = useState<'browse' | 'edit' | 'create'>('browse');
const [selectedTemplate, setSelectedTemplate] = useState<CustomAnkiTemplate | null>(null);
const [editingTemplate, setEditingTemplate] = useState<CustomAnkiTemplate | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [searchTerm, setSearchTerm] = useState('');
// 加载模板
useEffect(() => {
loadTemplates();
// 订阅模板变化
const unsubscribe = templateManager.subscribe(setTemplates);
return unsubscribe;
}, []);
const loadTemplates = async () => {
setIsLoading(true);
try {
await templateManager.refresh();
setTemplates(templateManager.getAllTemplates());
} catch (err) {
setError(`加载模板失败: ${err}`);
} finally {
setIsLoading(false);
}
};
// 过滤模板
const filteredTemplates = templates.filter(template =>
template.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
template.description.toLowerCase().includes(searchTerm.toLowerCase())
);
// 选择模板
const handleSelectTemplate = (template: CustomAnkiTemplate) => {
setSelectedTemplate(template);
if (onSelectTemplate) {
onSelectTemplate(template);
}
};
// 编辑模板
const handleEditTemplate = (template: CustomAnkiTemplate) => {
setEditingTemplate({ ...template });
setActiveTab('edit');
};
// 复制模板
const handleDuplicateTemplate = (template: CustomAnkiTemplate) => {
const duplicated: CustomAnkiTemplate = {
...template,
id: `${template.id}-copy-${Date.now()}`,
name: `${template.name} - 副本`,
author: '用户创建',
is_built_in: false,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
};
setEditingTemplate(duplicated);
setActiveTab('create');
};
// 删除模板
const handleDeleteTemplate = async (template: CustomAnkiTemplate) => {
if (template.is_built_in) {
setError('不能删除内置模板');
return;
}
if (!confirm(`确定要删除模板 "${template.name}" 吗?此操作不可撤销。`)) {
return;
}
try {
await templateManager.deleteTemplate(template.id);
setError(null);
} catch (err) {
setError(`删除模板失败: ${err}`);
}
};
return (
<div className="template-manager-modal">
<div className="template-manager-backdrop" onClick={onClose} />
<div className="template-manager-container">
{/* 头部 */}
<div className="template-manager-header">
<h2 style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Palette size={20} />
模板管理器
</h2>
<button className="close-btn" onClick={onClose}>
<X size={16} />
</button>
</div>
{/* 标签页导航 */}
<div className="template-manager-tabs">
<button
className={`tab-btn ${activeTab === 'browse' ? 'active' : ''}`}
onClick={() => setActiveTab('browse')}
style={{ display: 'flex', alignItems: 'center', gap: '6px' }}
>
<BookOpen size={16} />
浏览模板
</button>
<button
className={`tab-btn ${activeTab === 'create' ? 'active' : ''}`}
onClick={() => setActiveTab('create')}
style={{ display: 'flex', alignItems: 'center', gap: '6px' }}
>
<Plus size={16} />
创建模板
</button>
{editingTemplate && (
<button
className={`tab-btn ${activeTab === 'edit' ? 'active' : ''}`}
onClick={() => setActiveTab('edit')}
style={{ display: 'flex', alignItems: 'center', gap: '6px' }}
>
<Edit size={16} />
编辑模板
</button>
)}
</div>
{/* 错误提示 */}
{error && (
<div className="error-banner">
<span style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
<AlertTriangle size={16} />
{error}
</span>
<button onClick={() => setError(null)}>
<X size={14} />
</button>
</div>
)}
{/* 内容区域 */}
<div className="template-manager-content">
{activeTab === 'browse' && (
<TemplateBrowser
templates={filteredTemplates}
selectedTemplate={selectedTemplate}
searchTerm={searchTerm}
onSearchChange={setSearchTerm}
onSelectTemplate={handleSelectTemplate}
onEditTemplate={handleEditTemplate}
onDuplicateTemplate={handleDuplicateTemplate}
onDeleteTemplate={handleDeleteTemplate}
isLoading={isLoading}
/>
)}
{activeTab === 'create' && (
<TemplateEditor
template={editingTemplate}
mode="create"
onSave={async (templateData) => {
try {
await templateManager.createTemplate(templateData);
setActiveTab('browse');
setEditingTemplate(null);
setError(null);
} catch (err) {
setError(`创建模板失败: ${err}`);
}
}}
onCancel={() => {
setActiveTab('browse');
setEditingTemplate(null);
}}
/>
)}
{activeTab === 'edit' && editingTemplate && (
<TemplateEditor
template={editingTemplate}
mode="edit"
onSave={async (_templateData) => {
try {
// TODO: 实现模板更新
setActiveTab('browse');
setEditingTemplate(null);
setError(null);
} catch (err) {
setError(`更新模板失败: ${err}`);
}
}}
onCancel={() => {
setActiveTab('browse');
setEditingTemplate(null);
}}
/>
)}
</div>
</div>
</div>
);
};
// 模板浏览器组件
interface TemplateBrowserProps {
templates: CustomAnkiTemplate[];
selectedTemplate: CustomAnkiTemplate | null;
searchTerm: string;
onSearchChange: (term: string) => void;
onSelectTemplate: (template: CustomAnkiTemplate) => void;
onEditTemplate: (template: CustomAnkiTemplate) => void;
onDuplicateTemplate: (template: CustomAnkiTemplate) => void;
onDeleteTemplate: (template: CustomAnkiTemplate) => void;
isLoading: boolean;
}
const TemplateBrowser: React.FC<TemplateBrowserProps> = ({
templates,
selectedTemplate,
searchTerm,
onSearchChange,
onSelectTemplate,
onEditTemplate,
onDuplicateTemplate,
onDeleteTemplate,
isLoading
}) => {
return (
<div className="template-browser">
{/* 搜索和工具栏 */}
<div className="browser-toolbar">
<div className="search-box">
<input
type="text"
placeholder="搜索模板..."
value={searchTerm}
onChange={(e) => onSearchChange(e.target.value)}
className="search-input"
/>
<span className="search-icon">
<Search size={16} />
</span>
</div>
<div className="toolbar-info">
共 {templates.length} 个模板
</div>
</div>
{/* 模板网格 */}
{isLoading ? (
<div className="loading-state">
<div className="loading-spinner"></div>
<span>加载模板中...</span>
</div>
) : (
<div className="templates-grid">
{templates.map(template => (
<TemplateCard
key={template.id}
template={template}
isSelected={selectedTemplate?.id === template.id}
onSelect={() => onSelectTemplate(template)}
onEdit={() => onEditTemplate(template)}
onDuplicate={() => onDuplicateTemplate(template)}
onDelete={() => onDeleteTemplate(template)}
/>
))}
</div>
)}
{templates.length === 0 && !isLoading && (
<div className="empty-state">
<div className="empty-icon">
<FileText size={48} />
</div>
<h3>没有找到模板</h3>
<p>试试调整搜索条件,或创建一个新模板。</p>
</div>
)}
</div>
);
};
// 模板卡片组件
interface TemplateCardProps {
template: CustomAnkiTemplate;
isSelected: boolean;
onSelect: () => void;
onEdit: () => void;
onDuplicate: () => void;
onDelete: () => void;
}
const TemplateCard: React.FC<TemplateCardProps> = ({
template,
isSelected,
onSelect,
onEdit,
onDuplicate,
onDelete
}) => {
const cardTemplate = templateManager.toAnkiCardTemplate(template);
return (
<div className={`template-card ${isSelected ? 'selected' : ''} ${!template.is_active ? 'inactive' : ''}`}>
{/* 卡片头部 */}
<div className="card-header">
<h4 className="template-name">{template.name}</h4>
<div className="template-badges">
{template.is_built_in && <span className="badge built-in">内置</span>}
{!template.is_active && <span className="badge inactive">停用</span>}
<span className="badge version">v{template.version}</span>
</div>
</div>
{/* 预览区域 */}
<div className="card-preview">
<div className="preview-front">
<div className="preview-label">正面</div>
<div className="preview-content">
<IframePreview
htmlContent={renderCardPreview(cardTemplate.front_template, cardTemplate)}
cssContent={cardTemplate.css_style}
/>
</div>
</div>
<div className="preview-back">
<div className="preview-label">背面</div>
<div className="preview-content">
<IframePreview
htmlContent={renderCardPreview(cardTemplate.back_template, cardTemplate)}
cssContent={cardTemplate.css_style}
/>
</div>
</div>
</div>
{/* 卡片信息 */}
<div className="card-info">
<p className="template-description">{template.description}</p>
<div className="template-meta">
<span className="author" style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<User size={14} />
{template.author || '未知'}
</span>
<span className="fields" style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<FileText size={14} />
{template.fields.length} 个字段
</span>
</div>
<div className="template-fields">
{template.fields.slice(0, 3).map(field => (
<span key={field} className="field-tag">{field}</span>
))}
{template.fields.length > 3 && (
<span className="field-tag more">+{template.fields.length - 3}</span>
)}
</div>
</div>
{/* 操作按钮 */}
<div className="card-actions">
<button className="btn-select" onClick={onSelect} style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
{isSelected ? (
<>
<CheckCircle size={16} />
已选择
</>
) : (
'选择'
)}
</button>
<div className="action-menu">
<button className="btn-action" onClick={onEdit}>
<Edit size={16} />
</button>
<button className="btn-action" onClick={onDuplicate}>
<Copy size={16} />
</button>
{!template.is_built_in && (
<button className="btn-action danger" onClick={onDelete}>
<Trash2 size={16} />
</button>
)}
</div>
</div>
</div>
);
};
// 模板编辑器组件(简化版,完整版需要更多功能)
interface TemplateEditorProps {
template: CustomAnkiTemplate | null;
mode: 'create' | 'edit';
onSave: (templateData: CreateTemplateRequest) => Promise<void>;
onCancel: () => void;
}
const TemplateEditor: React.FC<TemplateEditorProps> = ({
template,
mode,
onSave,
onCancel
}) => {
const [formData, setFormData] = useState({
name: template?.name || '',
description: template?.description || '',
author: template?.author || '',
preview_front: template?.preview_front || '',
preview_back: template?.preview_back || '',
note_type: template?.note_type || 'Basic',
fields: template?.fields.join(',') || 'Front,Back,Notes',
generation_prompt: template?.generation_prompt || '',
front_template: template?.front_template || '<div class="card">{{Front}}</div>',
back_template: template?.back_template || '<div class="card">{{Front}}<hr>{{Back}}</div>',
css_style: template?.css_style || '.card { padding: 20px; background: white; border-radius: 8px; }'
});
const [isSubmitting, setIsSubmitting] = useState(false);
const [activeEditorTab, setActiveEditorTab] = useState<'basic' | 'templates' | 'styles' | 'advanced'>('basic');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsSubmitting(true);
try {
const fields = formData.fields.split(',').map(f => f.trim()).filter(f => f);
const fieldExtractionRules: Record<string, FieldExtractionRule> = {};
fields.forEach(field => {
fieldExtractionRules[field] = {
field_type: field.toLowerCase() === 'tags' ? 'Array' : 'Text',
is_required: field.toLowerCase() === 'front' || field.toLowerCase() === 'back',
default_value: field.toLowerCase() === 'tags' ? '[]' : '',
description: `${field} 字段`
};
});
const templateData: CreateTemplateRequest = {
name: formData.name,
description: formData.description,
author: formData.author || undefined,
preview_front: formData.preview_front,
preview_back: formData.preview_back,
note_type: formData.note_type,
fields,
generation_prompt: formData.generation_prompt,
front_template: formData.front_template,
back_template: formData.back_template,
css_style: formData.css_style,
field_extraction_rules: fieldExtractionRules
};
await onSave(templateData);
} finally {
setIsSubmitting(false);
}
};
return (
<div className="template-editor">
<div className="editor-header">
<h3>{mode === 'create' ? '创建新模板' : '编辑模板'}</h3>
</div>
{/* 编辑器标签页 */}
<div className="editor-tabs">
<button
className={`editor-tab ${activeEditorTab === 'basic' ? 'active' : ''}`}
onClick={() => setActiveEditorTab('basic')}
style={{ display: 'flex', alignItems: 'center', gap: '6px' }}
>
<FileText size={16} />
基本信息
</button>
<button
className={`editor-tab ${activeEditorTab === 'templates' ? 'active' : ''}`}
onClick={() => setActiveEditorTab('templates')}
style={{ display: 'flex', alignItems: 'center', gap: '6px' }}
>
<Palette size={16} />
模板代码
</button>
<button
className={`editor-tab ${activeEditorTab === 'styles' ? 'active' : ''}`}
onClick={() => setActiveEditorTab('styles')}
style={{ display: 'flex', alignItems: 'center', gap: '6px' }}
>
<Paintbrush size={16} />
样式设计
</button>
<button
className={`editor-tab ${activeEditorTab === 'advanced' ? 'active' : ''}`}
onClick={() => setActiveEditorTab('advanced')}
style={{ display: 'flex', alignItems: 'center', gap: '6px' }}
>
<Settings size={16} />
高级设置
</button>
</div>
<form onSubmit={handleSubmit} className="editor-form">
{/* 基本信息标签页 */}
{activeEditorTab === 'basic' && (
<div className="editor-section">
<div className="form-grid">
<div className="form-group">
<label>模板名称 *</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData({...formData, name: e.target.value})}
required
className="form-input"
placeholder="请输入模板名称"
/>
</div>
<div className="form-group">
<label>作者</label>
<input
type="text"
value={formData.author}
onChange={(e) => setFormData({...formData, author: e.target.value})}
className="form-input"
placeholder="可选"
/>
</div>
<div className="form-group full-width">
<label>描述</label>
<textarea
value={formData.description}
onChange={(e) => setFormData({...formData, description: e.target.value})}
className="form-textarea"
rows={3}
placeholder="请描述这个模板的用途和特点..."
/>
</div>
<div className="form-group">
<label>笔记类型</label>
<input
type="text"
value={formData.note_type}
onChange={(e) => setFormData({...formData, note_type: e.target.value})}
className="form-input"
placeholder="Basic"
/>
</div>
<div className="form-group">
<label>字段列表 *</label>
<input
type="text"
value={formData.fields}
onChange={(e) => setFormData({...formData, fields: e.target.value})}
required
className="form-input"
placeholder="Front,Back,Notes"
/>
<small className="form-help">用逗号分隔,至少需要包含 Front 和 Back 字段</small>
</div>
<div className="form-group">
<label>预览正面 *</label>
<input
type="text"
value={formData.preview_front}
onChange={(e) => setFormData({...formData, preview_front: e.target.value})}
required
className="form-input"
placeholder="示例问题"
/>
</div>
<div className="form-group">
<label>预览背面 *</label>
<input
type="text"
value={formData.preview_back}
onChange={(e) => setFormData({...formData, preview_back: e.target.value})}
required
className="form-input"
placeholder="示例答案"
/>
</div>
</div>
</div>
)}
{/* 模板代码标签页 */}
{activeEditorTab === 'templates' && (
<div className="editor-section">
<div className="template-code-editor">
<div className="code-group">
<label>正面模板 *</label>
<textarea
value={formData.front_template}
onChange={(e) => setFormData({...formData, front_template: e.target.value})}
required
className="code-textarea"
rows={8}
placeholder="<div class="card">{{Front}}</div>"
/>
<small className="form-help">使用 Mustache 语法,如 {`{{Front}}`}、{`{{Back}}`} 等</small>
</div>
<div className="code-group">
<label>背面模板 *</label>
<textarea
value={formData.back_template}
onChange={(e) => setFormData({...formData, back_template: e.target.value})}
required
className="code-textarea"
rows={8}
placeholder="<div class="card">{{Front}}<hr>{{Back}}</div>"
/>
</div>
</div>
</div>
)}
{/* 样式设计标签页 */}
{activeEditorTab === 'styles' && (
<div className="editor-section">
<div className="styles-editor">
<label>CSS 样式</label>
<textarea
value={formData.css_style}
onChange={(e) => setFormData({...formData, css_style: e.target.value})}
className="css-textarea"
rows={12}
placeholder=".card { padding: 20px; background: white; border-radius: 8px; }"
/>
<small className="form-help">自定义CSS样式来美化卡片外观</small>
</div>
</div>
)}
{/* 高级设置标签页 */}
{activeEditorTab === 'advanced' && (
<div className="editor-section">
<div className="advanced-settings">
<label>AI生成提示词 *</label>
<textarea
value={formData.generation_prompt}
onChange={(e) => setFormData({...formData, generation_prompt: e.target.value})}
required
className="prompt-textarea"
rows={8}
placeholder="请输入AI生成卡片时使用的提示词..."
/>
<small className="form-help">指导AI如何生成符合此模板的卡片内容</small>
</div>
</div>
)}
{/* 操作按钮 */}
<div className="editor-actions">
<button
type="submit"
disabled={isSubmitting}
className="btn-primary"
>
{isSubmitting ? '保存中...' : mode === 'create' ? '创建模板' : '保存修改'}
</button>
<button
type="button"
onClick={onCancel}
className="btn-secondary"
>
取消
</button>
</div>
</form>
</div>
);
};
export default TemplateManager;
|
000haoji/deep-student
| 10,366 |
src/components/KnowledgeGraphManagement.css
|
.knowledge-graph-management {
padding: 20px;
max-width: 1200px;
margin: 0 auto;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.knowledge-graph-management h2 {
color: #2c3e50;
border-bottom: 3px solid #3498db;
padding-bottom: 10px;
margin-bottom: 30px;
}
.error-message {
background-color: #fee;
border: 1px solid #fcc;
border-radius: 8px;
padding: 12px;
margin-bottom: 20px;
color: #c33;
font-weight: 500;
}
/* Tab navigation */
.tab-navigation {
display: flex;
gap: 4px;
margin-bottom: 20px;
background: #ecf0f1;
padding: 4px;
border-radius: 8px;
}
.tab-button {
flex: 1;
padding: 12px 20px;
border: none;
background: transparent;
color: #7f8c8d;
font-size: 14px;
font-weight: 600;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s ease;
}
.tab-button:hover {
background: #d5dbdb;
color: #2c3e50;
}
.tab-button.active {
background: #3498db;
color: white;
box-shadow: 0 2px 4px rgba(52, 152, 219, 0.3);
}
.tab-content {
background: white;
border-radius: 12px;
min-height: 600px;
padding: 20px;
}
/* Initialization section */
.initialization-section {
background: #f8f9fa;
border-radius: 12px;
padding: 30px;
margin-bottom: 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.initialization-section h3 {
color: #2c3e50;
margin-bottom: 20px;
font-size: 1.2em;
}
/* Setup help section */
.setup-help {
background: #e8f4f8;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
border-left: 4px solid #3498db;
}
.setup-help h4 {
color: #2c3e50;
margin-bottom: 15px;
font-size: 1.1em;
}
.help-option {
margin-bottom: 15px;
}
.help-option strong {
color: #2c3e50;
display: block;
margin-bottom: 5px;
}
.help-option code {
background: #2c3e50;
color: #ecf0f1;
padding: 8px 12px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.9em;
display: block;
word-break: break-all;
overflow-x: auto;
}
.help-option a {
color: #3498db;
text-decoration: none;
}
.help-option a:hover {
text-decoration: underline;
}
.config-form {
display: grid;
gap: 15px;
}
.form-group {
display: flex;
flex-direction: column;
gap: 8px;
}
.form-group label {
font-weight: 600;
color: #34495e;
font-size: 0.9em;
}
.form-group input,
.form-group textarea {
padding: 12px;
border: 2px solid #ddd;
border-radius: 8px;
font-size: 14px;
transition: border-color 0.3s;
}
.form-group input:focus,
.form-group textarea:focus {
outline: none;
border-color: #3498db;
box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}
.button-group {
display: flex;
gap: 12px;
margin-top: 20px;
}
button {
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
background: linear-gradient(135deg, #3498db, #2980b9);
color: white;
}
button:hover:not(:disabled) {
background: linear-gradient(135deg, #2980b9, #21618c);
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
}
button:disabled {
background: #bdc3c7;
cursor: not-allowed;
transform: none;
box-shadow: none;
}
/* Main interface */
.main-interface {
display: grid;
gap: 30px;
}
/* Create card section */
.create-card-section {
background: #fff;
border-radius: 12px;
padding: 25px;
box-shadow: 0 2px 12px rgba(0,0,0,0.08);
border: 1px solid #e9ecef;
}
.create-card-section h3 {
color: #27ae60;
margin-bottom: 20px;
font-size: 1.2em;
display: flex;
align-items: center;
gap: 8px;
}
.create-card-section h3::before {
content: "➕";
font-size: 1.1em;
}
/* Search section */
.search-section {
background: #fff;
border-radius: 12px;
padding: 25px;
box-shadow: 0 2px 12px rgba(0,0,0,0.08);
border: 1px solid #e9ecef;
}
.search-section h3 {
color: #e74c3c;
margin-bottom: 20px;
font-size: 1.2em;
display: flex;
align-items: center;
gap: 8px;
}
.search-section h3::before {
content: "🔍";
font-size: 1.1em;
}
.search-form {
display: flex;
gap: 12px;
margin-bottom: 20px;
}
.search-form input {
flex: 1;
padding: 12px;
border: 2px solid #ddd;
border-radius: 8px;
font-size: 14px;
}
.search-form button {
background: linear-gradient(135deg, #e74c3c, #c0392b);
}
.search-form button:hover:not(:disabled) {
background: linear-gradient(135deg, #c0392b, #a93226);
}
/* Search results */
.search-results h4 {
color: #2c3e50;
margin-bottom: 15px;
font-size: 1.1em;
}
.search-result-item {
background: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 8px;
padding: 15px;
margin-bottom: 12px;
cursor: pointer;
transition: all 0.3s;
}
.search-result-item:hover {
background: #e9ecef;
border-color: #3498db;
transform: translateX(5px);
box-shadow: 0 2px 8px rgba(52, 152, 219, 0.2);
}
.result-score {
color: #e74c3c;
font-weight: 600;
font-size: 0.9em;
margin-bottom: 8px;
}
.result-content,
.result-insight {
margin-bottom: 8px;
line-height: 1.4;
}
.result-content strong,
.result-insight strong {
color: #2c3e50;
}
.result-meta {
font-size: 0.8em;
color: #7f8c8d;
border-top: 1px solid #dee2e6;
padding-top: 8px;
}
/* Selected card section */
.selected-card-section {
background: #fff;
border-radius: 12px;
padding: 25px;
box-shadow: 0 2px 12px rgba(0,0,0,0.08);
border: 1px solid #e9ecef;
}
.selected-card-section h3 {
color: #8e44ad;
margin-bottom: 20px;
font-size: 1.2em;
display: flex;
align-items: center;
gap: 8px;
}
.selected-card-section h3::before {
content: "📋";
font-size: 1.1em;
}
.card-details {
background: #f8f9fa;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
}
.card-problem,
.card-insight {
margin-bottom: 15px;
}
.card-problem strong,
.card-insight strong {
color: #2c3e50;
display: block;
margin-bottom: 8px;
}
.card-problem p,
.card-insight p {
background: white;
padding: 12px;
border-radius: 6px;
border-left: 4px solid #3498db;
margin: 0;
line-height: 1.5;
}
.card-meta {
display: flex;
gap: 20px;
flex-wrap: wrap;
font-size: 0.9em;
color: #7f8c8d;
border-top: 1px solid #dee2e6;
padding-top: 12px;
}
/* Recommendations */
.recommendations h4 {
color: #8e44ad;
margin-bottom: 15px;
font-size: 1.1em;
}
.recommendation-item {
background: #faf5ff;
border: 1px solid #e1bee7;
border-radius: 8px;
padding: 15px;
margin-bottom: 12px;
}
.rec-header {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
}
.rec-type {
background: #8e44ad;
color: white;
padding: 4px 8px;
border-radius: 4px;
font-size: 0.8em;
font-weight: 600;
text-transform: uppercase;
}
.rec-confidence {
color: #8e44ad;
font-weight: 600;
font-size: 0.9em;
}
.rec-content,
.rec-reasoning {
margin-bottom: 8px;
line-height: 1.4;
}
.rec-content strong,
.rec-reasoning strong {
color: #2c3e50;
}
/* Tags section */
.tags-section {
background: #fff;
border-radius: 12px;
padding: 25px;
box-shadow: 0 2px 12px rgba(0,0,0,0.08);
border: 1px solid #e9ecef;
}
.tags-section h3 {
color: #f39c12;
margin-bottom: 20px;
font-size: 1.2em;
display: flex;
align-items: center;
gap: 8px;
}
.tags-section h3::before {
content: "🏷️";
font-size: 1.1em;
}
.tags-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.tag {
padding: 6px 12px;
border-radius: 20px;
font-size: 0.85em;
font-weight: 500;
border: 1px solid;
}
.tag-knowledge_point {
background: #e8f5e8;
color: #2e7d2e;
border-color: #a8d8a8;
}
.tag-method {
background: #fff3cd;
color: #856404;
border-color: #ffeaa7;
}
.tag-auto {
background: #e2e6ea;
color: #495057;
border-color: #ced4da;
}
/* Loading overlay */
.loading-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.loading-spinner {
background: white;
padding: 30px;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
font-size: 16px;
font-weight: 600;
color: #2c3e50;
display: flex;
align-items: center;
gap: 12px;
}
.loading-spinner::before {
content: "";
width: 20px;
height: 20px;
border: 3px solid #f3f3f3;
border-top: 3px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* Visualization setup hint */
.visualization-setup-hint {
padding: 40px;
text-align: center;
background: #f8f9fa;
border-radius: 12px;
border: 2px dashed #3498db;
margin: 20px 0;
}
.visualization-setup-hint h3 {
color: #2c3e50;
margin-bottom: 20px;
font-size: 1.5em;
}
.setup-message {
max-width: 600px;
margin: 0 auto 30px auto;
text-align: left;
line-height: 1.6;
}
.setup-message p {
margin-bottom: 15px;
font-size: 16px;
color: #2c3e50;
}
.setup-message ol,
.setup-message ul {
margin-bottom: 20px;
padding-left: 20px;
}
.setup-message li {
margin-bottom: 8px;
color: #34495e;
}
.setup-message code {
background: #2c3e50;
color: #ecf0f1;
padding: 4px 8px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.9em;
}
.setup-message a {
color: #3498db;
text-decoration: none;
}
.setup-message a:hover {
text-decoration: underline;
}
.nav-hint {
margin-top: 30px;
}
.nav-button {
background: linear-gradient(135deg, #3498db, #2980b9);
color: white;
border: none;
padding: 12px 24px;
border-radius: 8px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
}
.nav-button:hover {
background: linear-gradient(135deg, #2980b9, #21618c);
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
}
/* Responsive design */
@media (max-width: 768px) {
.knowledge-graph-management {
padding: 15px;
}
.search-form {
flex-direction: column;
}
.button-group {
flex-direction: column;
}
.card-meta {
flex-direction: column;
gap: 8px;
}
.rec-header {
flex-direction: column;
gap: 8px;
}
.visualization-setup-hint {
padding: 20px;
}
.setup-message {
text-align: left;
}
.setup-message ol,
.setup-message ul {
padding-left: 15px;
}
}
|
000haoji/deep-student
| 1,806 |
src/components/ModernSelect.tsx
|
import React, { useState, useRef, useEffect } from 'react';
import './ModernSelect.css';
export interface ModernSelectProps {
options: string[];
value: string;
onChange: (value: string) => void;
placeholder?: string;
disabled?: boolean;
fullWidth?: boolean;
}
// 一个轻量级、无依赖的自定义下拉选择器
const ModernSelect: React.FC<ModernSelectProps> = ({
options,
value,
onChange,
placeholder = '请选择',
disabled = false,
fullWidth = true,
}) => {
const [open, setOpen] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
// 处理点击外部时自动关闭
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
setOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
return (
<div
className={`modern-select ${fullWidth ? 'full-width' : ''} ${disabled ? 'disabled' : ''}`}
ref={containerRef}
>
<button
type="button"
className="select-trigger"
onClick={() => !disabled && setOpen((prev) => !prev)}
disabled={disabled}
>
<span className="selected-text">{value || placeholder}</span>
<span className="arrow">▾</span>
</button>
{open && (
<ul className="options-list">
{options.map((opt) => (
<li
key={opt}
className={opt === value ? 'selected' : ''}
onClick={() => {
onChange(opt);
setOpen(false);
}}
>
{opt}
</li>
))}
</ul>
)}
</div>
);
};
export default ModernSelect;
|
000haoji/deep-student
| 13,480 |
src/components/ReviewAnalysis.css
|
/* 统一回顾分析组件样式 */
/* 通用容器样式 */
.review-analysis-container {
width: 100%;
height: 100%;
overflow: hidden;
display: flex;
flex-direction: column;
}
.review-analysis-main {
flex: 1;
padding: 20px;
overflow-y: auto;
background-color: #f8fafc;
}
/* 头部样式 */
.review-analysis-header {
background: white;
border-bottom: 1px solid #e2e8f0;
padding: 16px 24px;
display: flex;
justify-content: space-between;
align-items: center;
}
.review-analysis-title {
font-size: 20px;
font-weight: 600;
color: #1f2937;
margin: 0;
}
.review-analysis-back-btn {
padding: 8px 12px;
background: #f3f4f6;
border: none;
border-radius: 6px;
cursor: pointer;
color: #374151;
display: flex;
align-items: center;
gap: 8px;
transition: background-color 0.2s;
}
.review-analysis-back-btn:hover {
background: #e5e7eb;
}
/* 创建新分析按钮 */
.review-analysis-create-btn {
padding: 12px 24px;
background: #3b82f6;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-weight: 500;
transition: background-color 0.2s;
}
.review-analysis-create-btn:hover {
background: #2563eb;
}
/* 步骤指示器 */
.review-analysis-steps {
display: flex;
align-items: center;
gap: 16px;
margin-bottom: 24px;
padding: 0 20px;
}
.review-step {
display: flex;
align-items: center;
gap: 8px;
}
.review-step-circle {
width: 32px;
height: 32px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
font-weight: 500;
}
.review-step-circle.active {
background: #3b82f6;
color: white;
}
.review-step-circle.completed {
background: #10b981;
color: white;
}
.review-step-circle.pending {
background: #e5e7eb;
color: #6b7280;
}
.review-step-label {
font-size: 14px;
color: #374151;
}
.review-step-divider {
width: 32px;
height: 1px;
background: #d1d5db;
}
/* 表单容器 */
.review-form-container {
background: white;
border-radius: 12px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
border: 1px solid #e5e7eb;
padding: 24px;
margin: 0 20px;
min-height: 400px;
}
/* 表单组 */
.review-form-group {
margin-bottom: 20px;
}
.review-form-label {
display: block;
font-size: 14px;
font-weight: 500;
color: #374151;
margin-bottom: 8px;
}
.review-form-input,
.review-form-select,
.review-form-textarea {
width: 100%;
padding: 12px;
border: 1px solid #d1d5db;
border-radius: 6px;
font-size: 14px;
transition: border-color 0.2s, box-shadow 0.2s;
}
.review-form-input:focus,
.review-form-select:focus,
.review-form-textarea:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.review-form-textarea {
resize: vertical;
min-height: 120px;
}
/* 错题选择区域 */
.review-mistakes-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 16px;
max-height: 400px;
overflow-y: auto;
padding-right: 8px;
}
.review-mistake-card {
border: 1px solid #e5e7eb;
border-radius: 8px;
padding: 16px;
cursor: pointer;
transition: all 0.2s;
background: white;
}
.review-mistake-card:hover {
border-color: #d1d5db;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.review-mistake-card.selected {
border-color: #3b82f6;
background: #eff6ff;
box-shadow: 0 0 0 1px #3b82f6;
}
.review-mistake-header {
display: flex;
align-items: center;
margin-bottom: 8px;
gap: 12px;
}
.review-mistake-checkbox {
width: 16px;
height: 16px;
}
.review-mistake-subject {
font-size: 12px;
color: #3b82f6;
font-weight: 500;
background: #eff6ff;
padding: 2px 8px;
border-radius: 12px;
}
.review-mistake-date {
font-size: 12px;
color: #6b7280;
margin-left: auto;
}
.review-mistake-question {
font-weight: 500;
color: #1f2937;
margin-bottom: 8px;
line-height: 1.4;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.review-mistake-content {
color: #6b7280;
font-size: 14px;
line-height: 1.4;
margin-bottom: 12px;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}
.review-mistake-tags {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.review-mistake-tag {
background: #f3f4f6;
color: #374151;
padding: 2px 8px;
border-radius: 12px;
font-size: 12px;
}
/* 筛选控件 */
.review-filters {
display: grid;
grid-template-columns: 1fr 1fr 2fr;
gap: 20px;
margin-bottom: 24px;
background: white;
padding: 20px;
border-radius: 12px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
border: 1px solid #e5e7eb;
}
/* 加载状态 */
.review-loading {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
gap: 12px;
}
.review-loading-spinner {
width: 24px;
height: 24px;
border: 2px solid #e5e7eb;
border-top: 2px solid #3b82f6;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.review-loading-text {
color: #6b7280;
font-size: 14px;
}
/* 空状态 */
.review-empty {
text-align: center;
padding: 48px 24px;
color: #6b7280;
}
/* 底部操作按钮 */
.review-actions {
display: flex;
justify-content: space-between;
padding: 20px;
background: white;
border-top: 1px solid #e5e7eb;
}
.review-action-group {
display: flex;
gap: 12px;
}
.review-btn {
padding: 12px 24px;
border: none;
border-radius: 8px;
cursor: pointer;
font-size: 14px;
font-weight: 500;
transition: all 0.2s;
}
.review-btn-primary {
background: #3b82f6;
color: white;
}
.review-btn-primary:hover {
background: #2563eb;
}
.review-btn-primary:disabled {
background: #d1d5db;
cursor: not-allowed;
}
.review-btn-secondary {
background: #6b7280;
color: white;
}
.review-btn-secondary:hover {
background: #4b5563;
}
.review-btn-ghost {
background: #f3f4f6;
color: #374151;
}
.review-btn-ghost:hover {
background: #e5e7eb;
}
/* 模板按钮 */
.review-templates {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 8px;
margin-bottom: 16px;
}
.review-template-btn {
text-align: left;
padding: 12px;
font-size: 14px;
border: 1px solid #e5e7eb;
border-radius: 6px;
background: white;
cursor: pointer;
transition: all 0.2s;
}
.review-template-btn:hover {
border-color: #3b82f6;
background: #eff6ff;
}
/* 选中错题预览 */
.review-selected-preview {
background: #f9fafb;
padding: 12px;
border-radius: 6px;
max-height: 120px;
overflow-y: auto;
margin-top: 8px;
}
.review-selected-item {
font-size: 14px;
color: #374151;
margin-bottom: 4px;
line-height: 1.4;
}
/* 响应式设计 */
@media (max-width: 1024px) {
.review-filters {
grid-template-columns: 1fr 1fr;
gap: 16px;
}
.search-group {
grid-column: 1 / -1;
}
}
@media (max-width: 768px) {
.review-filters {
grid-template-columns: 1fr;
padding: 16px;
gap: 12px;
}
.search-group {
grid-column: 1;
}
.review-mistakes-grid {
grid-template-columns: 1fr;
}
.review-templates {
grid-template-columns: 1fr;
}
.review-actions {
flex-direction: column;
gap: 12px;
}
.review-analysis-header {
padding: 12px 16px;
flex-direction: column;
gap: 12px;
align-items: flex-start;
}
.library-stats {
width: 100%;
align-items: flex-start;
}
}
/* 分析库专用样式 */
.library-stats {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 4px;
}
.stats-text {
font-size: 16px;
font-weight: 500;
color: #1f2937;
}
.stats-filter {
font-size: 14px;
color: #6b7280;
}
.search-group {
grid-column: 1 / -1;
}
.search-input {
background: white;
}
.search-input:focus {
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
/* 空状态样式 */
.empty-icon {
font-size: 48px;
margin-bottom: 16px;
}
.empty-title {
font-size: 18px;
font-weight: 600;
color: #374151;
margin-bottom: 8px;
}
.empty-description {
font-size: 14px;
color: #6b7280;
margin-bottom: 4px;
}
.empty-hint {
font-size: 14px;
color: #9ca3af;
}
/* 分析库网格 */
.analysis-library-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
gap: 20px;
padding: 20px;
}
/* 分析库卡片样式 */
.analysis-library-card {
background: white;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
border: 1px solid #e5e7eb;
padding: 20px;
cursor: pointer;
transition: all 0.3s ease;
position: relative;
overflow: hidden;
}
.analysis-library-card:hover {
transform: translateY(-2px);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
border-color: #d1d5db;
}
.analysis-library-card:active {
transform: translateY(0);
}
/* 卡片头部 */
.analysis-card-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 16px;
padding-bottom: 12px;
border-bottom: 1px solid #f3f4f6;
}
.analysis-card-info {
flex: 1;
min-width: 0;
}
.analysis-card-title {
font-size: 16px;
font-weight: 600;
color: #1f2937;
margin: 0 0 4px 0;
line-height: 1.4;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.analysis-card-id {
font-size: 12px;
color: #9ca3af;
font-family: monospace;
background: #f9fafb;
padding: 2px 6px;
border-radius: 4px;
}
.analysis-card-actions {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.analysis-status-badge {
font-size: 12px;
font-weight: 500;
padding: 4px 8px;
border-radius: 12px;
white-space: nowrap;
}
.analysis-delete-btn {
background: #f3f4f6;
border: none;
border-radius: 6px;
padding: 6px 8px;
cursor: pointer;
font-size: 14px;
transition: all 0.2s;
color: #6b7280;
}
.analysis-delete-btn:hover {
background: #fee2e2;
color: #dc2626;
}
/* 卡片内容 */
.analysis-card-content {
display: flex;
flex-direction: column;
gap: 12px;
}
.analysis-meta-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.meta-item {
font-size: 12px;
padding: 4px 8px;
border-radius: 12px;
white-space: nowrap;
flex-shrink: 0;
}
.subject-tag {
background: #eff6ff;
color: #1d4ed8;
font-weight: 500;
}
.mistake-count {
background: #f0fdf4;
color: #166534;
}
.chat-count {
background: #fef3c7;
color: #92400e;
}
.analysis-target-section,
.analysis-preview-section {
background: #f9fafb;
padding: 12px;
border-radius: 8px;
border-left: 3px solid #3b82f6;
}
.target-label,
.preview-label {
font-size: 12px;
font-weight: 600;
color: #374151;
margin-bottom: 4px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.target-content,
.preview-content {
font-size: 14px;
color: #6b7280;
line-height: 1.5;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.analysis-date-section {
display: flex;
align-items: center;
gap: 6px;
padding-top: 8px;
border-top: 1px solid #f3f4f6;
}
.date-icon {
font-size: 14px;
color: #9ca3af;
}
.date-text {
font-size: 12px;
color: #6b7280;
font-weight: 500;
}
/* 响应式设计 */
@media (max-width: 768px) {
.analysis-library-grid {
grid-template-columns: 1fr;
gap: 16px;
padding: 16px;
}
.analysis-library-card {
padding: 16px;
}
.analysis-card-header {
flex-direction: column;
gap: 8px;
align-items: flex-start;
}
.analysis-card-actions {
align-self: flex-end;
}
.library-stats {
align-items: flex-start;
}
}
@media (max-width: 480px) {
.analysis-meta-row {
flex-direction: column;
gap: 6px;
}
.meta-item {
align-self: flex-start;
}
}
/* 动画效果 */
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.analysis-library-card {
animation: fadeInUp 0.3s ease-out;
}
.analysis-library-card:nth-child(odd) {
animation-delay: 0.1s;
}
.analysis-library-card:nth-child(even) {
animation-delay: 0.2s;
}
/* 添加筛选项的悬停效果 */
.review-form-select:hover,
.review-form-input:hover {
border-color: #9ca3af;
}
/* 改进状态徽章样式 */
.analysis-status-badge {
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
}
/* 卡片内容区域的微妙动画 */
.analysis-target-section,
.analysis-preview-section {
transition: all 0.2s ease;
}
.analysis-library-card:hover .analysis-target-section,
.analysis-library-card:hover .analysis-preview-section {
background: #f3f4f6;
}
/* 改进元信息标签的悬停效果 */
.meta-item {
transition: all 0.2s ease;
}
.analysis-library-card:hover .meta-item {
transform: scale(1.05);
}
/* 添加加载动画的平滑过渡 */
.review-loading {
opacity: 0;
animation: fadeIn 0.3s ease-in-out forwards;
}
@keyframes fadeIn {
to {
opacity: 1;
}
}
/* 滚动条样式 */
.review-mistakes-grid::-webkit-scrollbar,
.review-selected-preview::-webkit-scrollbar,
.analysis-library-grid::-webkit-scrollbar {
width: 6px;
}
.review-mistakes-grid::-webkit-scrollbar-track,
.review-selected-preview::-webkit-scrollbar-track,
.analysis-library-grid::-webkit-scrollbar-track {
background: #f1f5f9;
border-radius: 3px;
}
.review-mistakes-grid::-webkit-scrollbar-thumb,
.review-selected-preview::-webkit-scrollbar-thumb,
.analysis-library-grid::-webkit-scrollbar-thumb {
background: #cbd5e1;
border-radius: 3px;
}
.review-mistakes-grid::-webkit-scrollbar-thumb:hover,
.review-selected-preview::-webkit-scrollbar-thumb:hover,
.analysis-library-grid::-webkit-scrollbar-thumb:hover {
background: #94a3b8;
}
|
000haoji/deep-student
| 55,570 |
src/components/BatchAnalysis.tsx
|
import React, { useState, useEffect, useCallback } from 'react';
import { TauriAPI } from '../utils/tauriApi';
import { BatchTask, ChatMessage } from '../types';
import UniversalAppChatHost, { UniversalAppChatHostProps } from './UniversalAppChatHost';
interface BatchAnalysisProps {
onBack: () => void;
}
export const BatchAnalysis: React.FC<BatchAnalysisProps> = ({ onBack }) => {
// 基础状态
const [tasks, setTasks] = useState<BatchTask[]>([]);
const [isProcessing, setIsProcessing] = useState(false);
const [currentTaskIndex, setCurrentTaskIndex] = useState(-1);
const [showDetailView, setShowDetailView] = useState(false);
const [selectedTaskForDetail, setSelectedTaskForDetail] = useState<BatchTask | null>(null);
const [availableSubjects, setAvailableSubjects] = useState<string[]>([]);
const [isLoadingSubjects, setIsLoadingSubjects] = useState(true);
// RAG相关状态
const [enableRag, setEnableRag] = useState(false);
const [ragTopK, setRagTopK] = useState(5);
// 工具函数
const base64ToFile = (base64: string, filename: string): File => {
const arr = base64.split(',');
const mime = arr[0].match(/:(.*?);/)?.[1] || 'image/jpeg';
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type: mime });
};
const generateUniqueId = () => {
return `batch_task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
};
// 基础函数定义
const updateTask = useCallback((taskId: string, updates: Partial<BatchTask>) => {
setTasks(prev => prev.map(task =>
task.id === taskId ? { ...task, ...updates } : task
));
}, []);
const addTask = useCallback(() => {
const newTask: BatchTask = {
id: generateUniqueId(),
subject: availableSubjects[0] || '数学',
userQuestion: '',
questionImages: [],
analysisImages: [],
status: 'pending',
chatHistory: [],
thinkingContent: new Map(),
temp_id: null,
ocr_result: null,
currentFullContentForStream: '',
currentThinkingContentForStream: '',
};
setTasks(prev => [...prev, newTask]);
}, [availableSubjects]);
const removeTask = useCallback((taskId: string) => {
setTasks(prev => prev.filter(task => task.id !== taskId));
}, []);
const saveTasksToStorage = useCallback(async (tasksToSave: BatchTask[]) => {
try {
const tasksToStore = tasksToSave.map(task => ({
...task,
thinkingContent: Object.fromEntries(task.thinkingContent || new Map()),
questionImagesBase64: task.questionImages?.map(file => ({
name: file.name,
base64: '' // 简化处理
})) || [],
analysisImagesBase64: task.analysisImages?.map(file => ({
name: file.name,
base64: '' // 简化处理
})) || []
}));
localStorage.setItem('batch-analysis-tasks', JSON.stringify(tasksToStore));
} catch (error) {
console.error('保存任务失败:', error);
}
}, []);
const handleImageUpload = useCallback((taskId: string, files: FileList | File[] | null, isAnalysis = false) => {
if (!files) return;
const fileArray = Array.from(files);
updateTask(taskId, {
[isAnalysis ? 'analysisImages' : 'questionImages']: fileArray
});
}, [updateTask]);
const removeImage = useCallback((taskId: string, imageIndex: number, isAnalysis = false) => {
const task = tasks.find(t => t.id === taskId);
if (!task) return;
const images = isAnalysis ? task.analysisImages : task.questionImages;
if (!images) return;
const newImages = images.filter((_, index) => index !== imageIndex);
updateTask(taskId, {
[isAnalysis ? 'analysisImages' : 'questionImages']: newImages
});
}, [tasks, updateTask]);
// 加载支持的科目
useEffect(() => {
const loadSubjects = async () => {
try {
const subjects = await TauriAPI.getSupportedSubjects();
setAvailableSubjects(subjects);
} catch (error) {
console.error('加载科目失败:', error);
setAvailableSubjects(['数学', '物理', '化学', '英语']);
} finally {
setIsLoadingSubjects(false);
}
};
loadSubjects();
}, []);
// 组件挂载时恢复正在运行的任务
useEffect(() => {
const resumeRunningTasks = async () => {
const runningTasks = tasks.filter(task =>
['ocr_processing', 'awaiting_stream_start', 'streaming_answer'].includes(task.status)
);
if (runningTasks.length > 0) {
console.log(`🔄 发现 ${runningTasks.length} 个运行中的任务,正在恢复...`);
// 建立全局状态监听器
await setupGlobalStatusListeners();
// 恢复流式监听
for (const task of runningTasks) {
if (task.temp_id) {
try {
if (task.status === 'streaming_answer') {
console.log(`🔄 恢复流式监听: 任务 ${task.id}`);
await resumeTaskStreaming(task);
} else {
console.log(`🔄 监听状态变化: 任务 ${task.id} (${task.status})`);
// 为OCR和等待阶段的任务建立状态监听
await setupTaskStatusListener(task);
}
} catch (error) {
console.error(`恢复任务 ${task.id} 失败:`, error);
updateTask(task.id, {
status: 'error_stream',
errorDetails: '页面切换后恢复失败: ' + error
});
}
}
}
}
};
// 延迟执行,确保组件完全挂载
const timer = setTimeout(resumeRunningTasks, 100);
return () => clearTimeout(timer);
}, []); // 只在组件挂载时执行一次
const setupGlobalStatusListeners = async () => {
const { listen } = await import('@tauri-apps/api/event');
// 监听任务状态变更事件
const unlistenStatus = await listen('task_status_update', (event: any) => {
console.log('🔄 收到任务状态更新:', event.payload);
const { temp_id, status, details } = event.payload;
// 查找对应的任务并更新状态
setTasks(prevTasks => {
const taskIndex = prevTasks.findIndex(t => t.temp_id === temp_id);
if (taskIndex === -1) return prevTasks;
const newTasks = [...prevTasks];
newTasks[taskIndex] = {
...newTasks[taskIndex],
status: status,
...(details && { errorDetails: details })
};
console.log(`✅ 更新任务状态: ${newTasks[taskIndex].id} -> ${status}`);
// 如果状态变为streaming_answer,建立流式监听
if (status === 'streaming_answer') {
setTimeout(() => {
resumeTaskStreaming(newTasks[taskIndex]).catch(console.error);
}, 100);
}
// 异步保存状态
saveTasksToStorage(newTasks).catch(console.error);
return newTasks;
});
});
// 监听流开始事件
const unlistenStreamStart = await listen('stream_started', (event: any) => {
console.log('🚀 收到流开始事件:', event.payload);
const { temp_id } = event.payload;
setTasks(prevTasks => {
const taskIndex = prevTasks.findIndex(t => t.temp_id === temp_id);
if (taskIndex === -1) return prevTasks;
const newTasks = [...prevTasks];
newTasks[taskIndex] = {
...newTasks[taskIndex],
status: 'streaming_answer'
};
console.log(`🚀 任务开始流式处理: ${newTasks[taskIndex].id}`);
// 建立流式监听
setTimeout(() => {
resumeTaskStreaming(newTasks[taskIndex]).catch(console.error);
}, 100);
saveTasksToStorage(newTasks).catch(console.error);
return newTasks;
});
});
};
// 为单个任务建立状态监听
const setupTaskStatusListener = async (task: BatchTask) => {
if (!task.temp_id) return;
const { listen } = await import('@tauri-apps/api/event');
// 监听该任务的流启动事件
const streamEvent = `analysis_stream_${task.temp_id}`;
const reasoningEvent = `${streamEvent}_reasoning`;
console.log(`🎧 为任务 ${task.id} 建立状态监听: ${streamEvent}`);
// 监听流事件,用于检测流开始
const unlistenStream = await listen(streamEvent, (event: any) => {
console.log(`📡 任务 ${task.id} 收到流事件,切换到streaming状态`);
updateTask(task.id, { status: 'streaming_answer' });
// 立即建立完整的流式监听
setTimeout(() => {
resumeTaskStreaming(task).catch(console.error);
}, 50);
});
};
// 恢复流式任务监听
const resumeTaskStreaming = async (task: BatchTask) => {
if (!task.temp_id) return;
console.log(`🔄 恢复任务 ${task.id} 的流式监听`);
const streamEvent = `analysis_stream_${task.temp_id}`;
let fullContent = task.currentFullContentForStream || '';
let fullThinkingContent = task.currentThinkingContentForStream || '';
let contentListenerActive = true;
let thinkingListenerActive = true;
const { listen } = await import('@tauri-apps/api/event');
// 监听主内容流
const unlistenContent = await listen(streamEvent, (event: any) => {
if (!contentListenerActive) return;
console.log(`💬 任务 ${task.id} 收到主内容流:`, event.payload);
if (event.payload) {
if (event.payload.is_complete) {
if (event.payload.content && event.payload.content.length >= fullContent.length) {
fullContent = event.payload.content;
}
console.log(`🎉 任务 ${task.id} 主内容流完成,总长度:`, fullContent.length);
updateTask(task.id, {
chatHistory: [{
role: 'assistant',
content: fullContent,
timestamp: new Date().toISOString(),
}],
status: 'completed',
currentFullContentForStream: fullContent,
});
contentListenerActive = false;
} else if (event.payload.content) {
fullContent += event.payload.content;
console.log(`📝 任务 ${task.id} 累积内容,当前长度: ${fullContent.length}`);
updateTask(task.id, {
chatHistory: [{
role: 'assistant',
content: fullContent,
timestamp: new Date().toISOString(),
}],
currentFullContentForStream: fullContent,
});
}
}
});
// 监听思维链流
const reasoningEvent = `${streamEvent}_reasoning`;
const unlistenThinking = await listen(reasoningEvent, (event: any) => {
if (!thinkingListenerActive) return;
console.log(`🧠 任务 ${task.id} 思维链流内容:`, event.payload);
if (event.payload) {
if (event.payload.is_complete) {
if (event.payload.content && event.payload.content.length >= fullThinkingContent.length) {
fullThinkingContent = event.payload.content;
}
console.log(`🎉 任务 ${task.id} 思维链流完成,总长度:`, fullThinkingContent.length);
updateTask(task.id, {
thinkingContent: new Map([[0, fullThinkingContent]]),
currentThinkingContentForStream: fullThinkingContent,
});
thinkingListenerActive = false;
} else if (event.payload.content) {
fullThinkingContent += event.payload.content;
console.log(`🧠 任务 ${task.id} 累积思维链,当前长度: ${fullThinkingContent.length}`);
updateTask(task.id, {
thinkingContent: new Map([[0, fullThinkingContent]]),
currentThinkingContentForStream: fullThinkingContent,
});
}
}
});
// 监听流错误
const unlistenError = await listen('stream_error', (event: any) => {
console.error(`❌ 任务 ${task.id} 流式处理错误:`, event.payload);
updateTask(task.id, {
status: 'error_stream',
errorDetails: '流式处理出错: ' + (event.payload?.message || '未知错误'),
});
contentListenerActive = false;
thinkingListenerActive = false;
});
// 注册监听器注销函数
const taskListeners = [unlistenContent, unlistenThinking, unlistenError];
};
// 处理单个任务的完整分析流程
const processSingleTask = async (task: BatchTask) => {
console.log(`🚀 开始处理任务: ${task.id}`);
try {
// 步骤1: 更新状态为OCR处理中
updateTask(task.id, { status: 'ocr_processing' });
// 步骤2: 调用OCR与初步分析
console.log(`📝 任务 ${task.id}: 开始OCR分析...`);
const stepResult = await TauriAPI.analyzeStepByStep({
subject: task.subject,
question_image_files: task.questionImages,
analysis_image_files: task.analysisImages,
user_question: task.userQuestion,
enable_chain_of_thought: true,
});
console.log(`✅ 任务 ${task.id}: OCR分析完成`, stepResult.ocr_result);
// 步骤3: 存储OCR结果并更新状态
updateTask(task.id, {
temp_id: stepResult.temp_id,
ocr_result: stepResult.ocr_result,
status: 'awaiting_stream_start',
});
// 步骤4: 准备流式处理
console.log(`🤖 任务 ${task.id}: 开始流式AI解答...`);
updateTask(task.id, { status: 'streaming_answer' });
// 创建初始的助手消息(空内容,等待流式填充)
const initialMessage: ChatMessage = {
role: 'assistant',
content: '',
timestamp: new Date().toISOString(),
};
updateTask(task.id, {
chatHistory: [initialMessage],
currentFullContentForStream: '',
currentThinkingContentForStream: '',
});
// 步骤5: 设置流式监听器
const streamEvent = `analysis_stream_${stepResult.temp_id}`;
let fullContent = '';
let fullThinkingContent = '';
let contentListenerActive = true;
let thinkingListenerActive = true;
const { listen } = await import('@tauri-apps/api/event');
// 先定义一个占位函数,稍后在Promise中重新定义
let checkAndFinalizeTaskStreams = () => {};
// 监听主内容流
const unlistenContent = await listen(streamEvent, (event: any) => {
if (!contentListenerActive) return;
console.log(`💬 任务 ${task.id} 收到主内容流:`, event.payload);
if (event.payload) {
if (event.payload.is_complete) {
if (event.payload.content && event.payload.content.length >= fullContent.length) {
fullContent = event.payload.content;
}
console.log(`🎉 任务 ${task.id} 主内容流完成,总长度:`, fullContent.length);
// 更新聊天历史的最终内容
updateTask(task.id, {
chatHistory: [{
role: 'assistant',
content: fullContent,
timestamp: new Date().toISOString(),
}],
});
contentListenerActive = false;
checkAndFinalizeTaskStreams();
} else if (event.payload.content) {
fullContent += event.payload.content;
console.log(`📝 任务 ${task.id} 累积内容,当前长度: ${fullContent.length}`);
// 实时更新聊天历史
updateTask(task.id, {
chatHistory: [{
role: 'assistant',
content: fullContent,
timestamp: new Date().toISOString(),
}],
currentFullContentForStream: fullContent,
});
}
}
});
// 监听思维链流
const reasoningEvent = `${streamEvent}_reasoning`;
console.log(`🧠 任务 ${task.id} 监听思维链事件: ${reasoningEvent}`);
const unlistenThinking = await listen(reasoningEvent, (event: any) => {
if (!thinkingListenerActive) return;
console.log(`🧠 任务 ${task.id} 思维链流内容:`, event.payload);
if (event.payload) {
if (event.payload.is_complete) {
if (event.payload.content && event.payload.content.length >= fullThinkingContent.length) {
fullThinkingContent = event.payload.content;
}
console.log(`🎉 任务 ${task.id} 思维链流完成,总长度:`, fullThinkingContent.length);
// 更新思维链内容
updateTask(task.id, {
thinkingContent: new Map([[0, fullThinkingContent]]),
currentThinkingContentForStream: fullThinkingContent,
});
thinkingListenerActive = false;
checkAndFinalizeTaskStreams();
} else if (event.payload.content) {
fullThinkingContent += event.payload.content;
console.log(`🧠 任务 ${task.id} 累积思维链,当前长度: ${fullThinkingContent.length}`);
// 实时更新思维链内容
updateTask(task.id, {
thinkingContent: new Map([[0, fullThinkingContent]]),
currentThinkingContentForStream: fullThinkingContent,
});
}
}
});
// 监听流错误
const unlistenError = await listen('stream_error', (event: any) => {
console.error(`❌ 任务 ${task.id} 流式处理错误:`, event.payload);
updateTask(task.id, {
status: 'error_stream',
errorDetails: '流式处理出错: ' + (event.payload?.message || '未知错误'),
});
contentListenerActive = false;
thinkingListenerActive = false;
});
// 监听RAG来源信息(如果启用了RAG)
let unlistenRagSources: (() => void) | null = null;
if (enableRag) {
const ragSourcesEvent = `${streamEvent}_rag_sources`;
console.log(`📚 任务 ${task.id} 监听RAG来源事件: ${ragSourcesEvent}`);
unlistenRagSources = await listen(ragSourcesEvent, (event: any) => {
console.log(`📚 任务 ${task.id} 收到RAG来源信息:`, event.payload);
if (event.payload && event.payload.sources) {
// 更新任务的聊天历史,为助手消息添加RAG来源信息
setTasks(prevTasks =>
prevTasks.map(currentTask => {
if (currentTask.id === task.id) {
const updatedChatHistory = [...currentTask.chatHistory];
if (updatedChatHistory.length > 0 && updatedChatHistory[0].role === 'assistant') {
updatedChatHistory[0] = {
...updatedChatHistory[0],
rag_sources: event.payload.sources
};
}
return { ...currentTask, chatHistory: updatedChatHistory };
}
return currentTask;
})
);
console.log(`✅ 任务 ${task.id} RAG来源信息已更新`);
}
});
}
// 注册监听器注销函数(任务级别)
const taskListeners = enableRag
? [unlistenContent, unlistenThinking, unlistenError, unlistenRagSources!]
: [unlistenContent, unlistenThinking, unlistenError];
// 步骤6: 启动流式解答
console.log(`🚀 任务 ${task.id} 启动流式解答,temp_id: ${stepResult.temp_id}, enable_rag: ${enableRag}`);
if (enableRag) {
// 使用RAG增强的流式解答
await TauriAPI.startRagEnhancedStreamingAnswer({
temp_id: stepResult.temp_id,
enable_chain_of_thought: true,
enable_rag: true,
rag_options: {
top_k: ragTopK,
enable_reranking: true
}
});
} else {
// 使用普通的流式解答
await TauriAPI.startStreamingAnswer(stepResult.temp_id, true);
}
// 等待流处理完成(通过Promise机制避免状态循环检查)
return new Promise<void>((resolve, reject) => {
let isResolved = false;
const resolveOnce = () => {
if (!isResolved) {
isResolved = true;
console.log(`✅ 任务 ${task.id} 处理完成`);
resolve();
}
};
const rejectOnce = (error: string) => {
if (!isResolved) {
isResolved = true;
console.error(`❌ 任务 ${task.id} 处理失败:`, error);
reject(new Error(error));
}
};
// 在流监听器中直接调用resolve
let checkAndFinalizeTaskStreams = () => {
console.log(`🔍 任务 ${task.id} 检查流完成状态: contentActive=${contentListenerActive}, thinkingActive=${thinkingListenerActive}`);
if (!contentListenerActive) {
console.log(`✅ 任务 ${task.id} 主内容流已完成,标记任务为完成状态`);
updateTask(task.id, {
status: 'completed',
currentFullContentForStream: fullContent,
currentThinkingContentForStream: fullThinkingContent,
});
resolveOnce();
}
if (!contentListenerActive && !thinkingListenerActive) {
console.log(`🎉 任务 ${task.id} 所有流式内容均已完成`);
}
};
// 设置超时
setTimeout(() => {
rejectOnce('任务处理超时');
}, 60000); // 60秒超时
});
} catch (error) {
console.error(`❌ 任务 ${task.id} 处理失败:`, error);
updateTask(task.id, {
status: 'error_ocr',
errorDetails: `处理失败: ${error}`,
});
throw error;
}
};
// 开始批量处理
const startBatchProcessing = async () => {
if (tasks.length === 0) {
alert('请先添加要分析的题目');
return;
}
const validTasks = tasks.filter(task =>
task.userQuestion.trim() && task.questionImages.length > 0 && task.status === 'pending'
);
if (validTasks.length === 0) {
alert('请确保每个任务都有问题描述和题目图片');
return;
}
setIsProcessing(true);
console.log(`🚀 开始批量处理 ${validTasks.length} 个任务`);
try {
// 严格按顺序处理队列中的任务
for (let i = 0; i < validTasks.length; i++) {
const task = validTasks[i];
setCurrentTaskIndex(i);
console.log(`📋 处理任务 ${i + 1}/${validTasks.length}: ${task.id}`);
try {
await processSingleTask(task);
console.log(`✅ 任务 ${task.id} 处理成功`);
} catch (error) {
console.error(`❌ 任务 ${task.id} 处理失败:`, error);
// 继续处理下一个任务
}
}
console.log('🎉 批量分析完成!');
alert('批量分析完成!');
} catch (error) {
console.error('❌ 批量处理失败:', error);
alert('批量处理失败: ' + error);
} finally {
setIsProcessing(false);
setCurrentTaskIndex(-1);
}
};
// 创建优化的文件上传点击处理器
const createFileUploadClickHandler = useCallback((taskId: string, isAnalysisImage = false) => {
return () => {
const inputId = isAnalysisImage ? `#analysis-input-${taskId}` : `#file-input-${taskId}`;
const fileInput = document.querySelector(inputId) as HTMLInputElement;
if (fileInput) {
fileInput.click();
}
};
}, []);
// 保存单个任务到错题库
const saveTaskToLibrary = async (taskToSave: BatchTask) => {
if (!taskToSave.temp_id) {
alert('任务数据不完整,无法保存');
return;
}
try {
updateTask(taskToSave.id, { status: 'saving' });
// 复制聊天历史,并将思维链内容保存到message中
const chatHistoryWithThinking = taskToSave.chatHistory.map((message, index) => {
if (message.role === 'assistant' && taskToSave.thinkingContent.has(index)) {
return {
...message,
thinking_content: taskToSave.thinkingContent.get(index)
};
}
return message;
});
const result = await TauriAPI.saveMistakeFromAnalysis({
temp_id: taskToSave.temp_id,
final_chat_history: chatHistoryWithThinking,
});
if (result.success) {
alert(`任务 ${taskToSave.id} 已保存到错题库!`);
// 可以选择从队列中移除已保存的任务
// removeTask(taskToSave.id);
} else {
alert('保存失败,请重试');
updateTask(taskToSave.id, { status: 'completed' });
}
} catch (error) {
console.error('保存失败:', error);
alert('保存失败: ' + error);
updateTask(taskToSave.id, { status: 'completed' });
}
};
// 为统一组件创建的适配器函数
const saveTaskToLibraryAdapter = async (saveData: any, chatImagesToSave?: any[]) => {
if (!selectedTaskForDetail) return;
// 从当前任务数据构造完整的 BatchTask
const currentTaskData = tasks.find(t => t.id === selectedTaskForDetail.id);
if (!currentTaskData) return;
const fullTaskData: BatchTask = {
...currentTaskData,
chatHistory: saveData.chatHistory || currentTaskData.chatHistory,
thinkingContent: saveData.thinkingContent || currentTaskData.thinkingContent,
// 如果有图片数据,可以在这里处理
};
await saveTaskToLibrary(fullTaskData);
};
// 保存所有有内容的任务到错题库
const saveAllToLibrary = async () => {
const savableTasks = tasks.filter(task => task.chatHistory.length > 0 || task.status === 'completed');
if (savableTasks.length === 0) {
alert('没有可保存的分析结果');
return;
}
if (!confirm(`确定要保存 ${savableTasks.length} 个任务到错题库吗?`)) {
return;
}
let successCount = 0;
let failCount = 0;
for (const task of savableTasks) {
try {
await saveTaskToLibrary(task);
successCount++;
} catch (error) {
console.error(`保存任务 ${task.id} 失败:`, error);
failCount++;
}
}
if (failCount === 0) {
alert(`已成功将 ${successCount} 道题目保存到错题库!`);
} else {
alert(`保存完成:成功 ${successCount} 道,失败 ${failCount} 道`);
}
};
// 清空所有任务
const clearAllTasks = () => {
if (confirm('确定要清空所有任务吗?')) {
setTasks([]);
saveTasksToStorage([]).catch(console.error);
}
};
// 处理聊天历史更新回调 - 添加防抖逻辑
const handleChatHistoryUpdated = useCallback((taskId: string, newChatHistory: ChatMessage[], newThinkingContent: Map<number, string>) => {
// 只在聊天历史真正有变化时才更新
setTasks(prevTasks => {
const taskIndex = prevTasks.findIndex(t => t.id === taskId);
if (taskIndex === -1) return prevTasks;
const currentTask = prevTasks[taskIndex];
// 检查是否真的有变化
if (currentTask.chatHistory.length === newChatHistory.length &&
currentTask.thinkingContent.size === newThinkingContent.size) {
return prevTasks; // 没有变化,不更新
}
const newTasks = [...prevTasks];
newTasks[taskIndex] = {
...currentTask,
chatHistory: newChatHistory,
thinkingContent: newThinkingContent,
};
return newTasks;
});
}, []);
// 为UniversalAppChatHost创建稳定的核心状态更新回调
const handleCoreStateUpdate = useCallback((taskId: string) => {
return (data: any) => {
// 实时更新聊天历史,确保批量分析详情页面能够实时渲染
if (data.chatHistory.length > 0) {
console.log('📝 BatchAnalysis: 实时状态更新', {
taskId,
chatHistoryLength: data.chatHistory.length,
lastMessageLength: data.chatHistory[data.chatHistory.length - 1]?.content?.length || 0
});
handleChatHistoryUpdated(taskId, data.chatHistory, data.thinkingContent);
}
};
}, [handleChatHistoryUpdated]);
const getStatusText = (status: string) => {
switch (status) {
case 'pending': return '等待中';
case 'ocr_processing': return 'OCR处理中';
case 'awaiting_stream_start': return '等待AI解答';
case 'streaming_answer': return 'AI解答中';
case 'completed': return '已完成';
case 'error_ocr': return 'OCR错误';
case 'error_stream': return '流式处理错误';
case 'saving': return '保存中';
default: return '未知状态';
}
};
const getStatusColor = (status: string) => {
switch (status) {
case 'pending': return '#6c757d';
case 'ocr_processing':
case 'awaiting_stream_start':
case 'streaming_answer': return '#007bff';
case 'completed': return '#28a745';
case 'error_ocr':
case 'error_stream': return '#dc3545';
case 'saving': return '#ffc107';
default: return '#6c757d';
}
};
// 如果显示详情页面,渲染详情视图
if (showDetailView && selectedTaskForDetail) {
// 获取实时的任务数据
const currentTaskData = tasks.find(t => t.id === selectedTaskForDetail.id) || selectedTaskForDetail;
return (
<div className="batch-detail-page">
<div className="detail-header">
<button
onClick={() => {
setShowDetailView(false);
setSelectedTaskForDetail(null);
}}
className="back-button"
>
← 返回批量分析
</button>
<h2>📋 任务详情 - #{tasks.findIndex(t => t.id === selectedTaskForDetail.id) + 1}</h2>
</div>
<div className="detail-content">
<UniversalAppChatHost
mode="EXISTING_BATCH_TASK_DETAIL"
businessSessionId={currentTaskData.id}
preloadedData={{
subject: currentTaskData.subject,
userQuestion: currentTaskData.userQuestion,
questionImages: currentTaskData.questionImages,
ocrText: currentTaskData.ocr_result?.ocr_text,
tags: currentTaskData.ocr_result?.tags || [],
chatHistory: currentTaskData.chatHistory || [],
thinkingContent: currentTaskData.thinkingContent || new Map()
}}
serviceConfig={{
apiProvider: {
initiateAndGetStreamId: async (params) => {
// 🎯 修复:检查原临时会话是否还存在,如果不存在则创建新的
let workingTempId = currentTaskData.temp_id;
if (workingTempId) {
try {
// 测试原临时会话是否还存在
await TauriAPI.continueChatStream({
temp_id: workingTempId,
chat_history: [],
enable_chain_of_thought: false
});
} catch (error) {
// 原临时会话不存在,需要重新创建
console.log('🔄 [批量分析] 原临时会话已失效,重新创建临时会话');
if (currentTaskData.questionImages && currentTaskData.questionImages.length > 0) {
const stepResult = await TauriAPI.analyzeStepByStep({
subject: currentTaskData.subject,
question_image_files: currentTaskData.questionImages,
analysis_image_files: currentTaskData.analysisImages || [],
user_question: currentTaskData.userQuestion,
enable_chain_of_thought: true,
});
workingTempId = stepResult.temp_id;
console.log('✅ [批量分析] 重新创建临时会话:', workingTempId);
}
}
}
return {
streamIdForEvents: workingTempId || params.businessId!,
ocrResultData: currentTaskData.ocr_result,
initialMessages: currentTaskData.chatHistory || []
};
},
startMainStreaming: async (params) => {
// 如果任务还在流式处理中,重新建立流监听
if (currentTaskData.status === 'streaming_answer' && currentTaskData.temp_id) {
console.log(`🔄 重新建立批量任务 ${currentTaskData.id} 的流监听`);
// 不需要调用API,只需要重新监听已经在进行的流
}
// 如果任务已完成,不需要做任何事情
},
continueUserChat: async (params) => {
// 🎯 修复:批量分析使用临时会话API,因为使用的是temp_id不是真实的错题ID
console.log('🔍 [批量分析追问] 调用参数:', {
streamIdForEvents: params.streamIdForEvents,
businessId: params.businessId,
currentTaskTempId: currentTaskData.temp_id,
chatHistoryLength: params.fullChatHistory.length
});
await TauriAPI.continueChatStream({
temp_id: params.streamIdForEvents, // 使用temp_id
chat_history: params.fullChatHistory,
enable_chain_of_thought: params.enableChainOfThought
});
}
},
streamEventNames: {
initialStream: (id) => ({
data: `analysis_stream_${id}`,
reasoning: `analysis_stream_${id}_reasoning`,
ragSources: `analysis_stream_${id}_rag_sources`
}),
continuationStream: (id) => ({
data: `continue_chat_stream_${id}`,
reasoning: `continue_chat_stream_${id}_reasoning`,
ragSources: `continue_chat_stream_${id}_rag_sources`
}),
},
defaultEnableChainOfThought: true,
defaultEnableRag: false,
defaultRagTopK: 5,
}}
onCoreStateUpdate={handleCoreStateUpdate(currentTaskData.id)}
onSaveRequest={async (data) => {
// 保存批量任务到错题库
await saveTaskToLibraryAdapter(data, []);
alert('批量任务已保存到错题库!');
}}
onExitRequest={() => {
setShowDetailView(false);
setSelectedTaskForDetail(null);
}}
/>
</div>
</div>
);
}
return (
<div className="batch-analysis">
<div className="batch-header">
<button onClick={onBack} className="back-button">
← 返回
</button>
<h2>📋 批量分析</h2>
<div className="batch-actions">
<button onClick={addTask} className="add-button">
➕ 添加题目
</button>
<button
onClick={startBatchProcessing}
disabled={isProcessing || tasks.length === 0}
className="process-button"
>
{isProcessing ? '处理中...' : '🚀 开始批量分析'}
</button>
</div>
</div>
{/* RAG设置面板 */}
<div className="rag-settings-panel" style={{
margin: '1rem 0',
padding: '1rem',
backgroundColor: '#f8f9fa',
borderRadius: '8px',
border: '1px solid #e9ecef'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '0.5rem' }}>
<span style={{ fontSize: '1.1rem' }}>🧠</span>
<label style={{ fontSize: '0.95rem', fontWeight: '500', margin: 0 }}>
RAG知识库增强(批量分析)
</label>
</div>
<label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer' }}>
<input
type="checkbox"
checked={enableRag}
onChange={(e) => setEnableRag(e.target.checked)}
style={{ transform: 'scale(1.1)' }}
/>
<span style={{ fontSize: '0.9rem', color: '#495057' }}>
为所有任务启用知识库增强AI分析(需要先上传文档到知识库)
</span>
</label>
{enableRag && (
<div style={{
marginTop: '0.75rem',
paddingTop: '0.75rem',
borderTop: '1px solid #dee2e6'
}}>
<label style={{
display: 'flex',
alignItems: 'center',
gap: '0.5rem',
fontSize: '0.85rem',
color: '#6c757d'
}}>
检索文档数量:
<input
type="number"
min="1"
max="10"
value={ragTopK}
onChange={(e) => setRagTopK(parseInt(e.target.value) || 5)}
style={{
width: '60px',
padding: '0.25rem',
borderRadius: '4px',
border: '1px solid #ced4da',
fontSize: '0.85rem'
}}
/>
</label>
</div>
)}
{enableRag && (
<div style={{
marginTop: '0.5rem',
fontSize: '0.8rem',
color: '#6c757d',
fontStyle: 'italic'
}}>
💡 启用后,AI将从您的知识库中检索相关信息来增强分析准确性
</div>
)}
</div>
{isProcessing && (
<div className="progress-info">
<div className="progress-text">
正在处理第 {currentTaskIndex + 1} / {tasks.length} 道题目
</div>
<div className="progress-bar">
<div
className="progress-fill"
style={{ width: `${((currentTaskIndex + 1) / Math.max(tasks.length, 1)) * 100}%` }}
/>
</div>
</div>
)}
<div className="batch-content">
{tasks.length === 0 ? (
<div className="empty-batch">
<p>还没有添加任何题目</p>
<button onClick={addTask} className="add-first-button">
添加第一道题目
</button>
</div>
) : (
<>
<div className="batch-summary">
<div className="summary-item">
<span className="label">总题目数:</span>
<span className="value">{tasks.length}</span>
</div>
<div className="summary-item">
<span className="label">已完成:</span>
<span className="value">
{tasks.filter(t => t.status === 'completed').length}
</span>
</div>
<div className="summary-item">
<span className="label">处理中:</span>
<span className="value">
{tasks.filter(t => ['ocr_processing', 'awaiting_stream_start', 'streaming_answer'].includes(t.status)).length}
</span>
</div>
<div className="summary-item">
<span className="label">失败:</span>
<span className="value">
{tasks.filter(t => t.status.startsWith('error_')).length}
</span>
</div>
</div>
<div className="tasks-list">
{tasks.map((task, index) => (
<div key={task.id} className={`task-card ${currentTaskIndex === index ? 'current' : ''}`}>
<div className="task-header">
<span className="task-number">#{index + 1}</span>
<span
className="task-status"
style={{ color: getStatusColor(task.status) }}
>
{getStatusText(task.status)}
</span>
<div className="task-actions">
{(task.status !== 'pending' && task.temp_id) && (
<button
onClick={() => {
setSelectedTaskForDetail(task);
setShowDetailView(true);
}}
className="detail-button"
>
👁️ 查看详情
</button>
)}
{(task.chatHistory.length > 0 || task.status === 'completed') && (
<button
onClick={() => saveTaskToLibrary(task)}
className="save-button"
>
💾 保存
</button>
)}
<button
onClick={() => removeTask(task.id)}
disabled={isProcessing && task.status !== 'pending'}
className="remove-button"
>
✕
</button>
</div>
</div>
<div className="task-form">
<div className="form-row">
<div className="form-group">
<label>科目:</label>
<select
value={task.subject}
onChange={(e) => updateTask(task.id, { subject: e.target.value })}
disabled={isProcessing || task.status !== 'pending' || isLoadingSubjects}
>
{isLoadingSubjects ? (
<option value="">加载中...</option>
) : (
availableSubjects.map(subject => (
<option key={subject} value={subject}>{subject}</option>
))
)}
</select>
</div>
</div>
<div className="form-group">
<label>题目图片:</label>
<div
className="file-upload-area"
onClick={() => {
if (!(isProcessing || task.status !== 'pending')) {
createFileUploadClickHandler(task.id, false)();
}
}}
onDrop={(e) => {
e.preventDefault();
e.currentTarget.classList.remove('drag-over');
const files = Array.from(e.dataTransfer.files).filter(file => file.type.startsWith('image/'));
const remainingSlots = 9 - task.questionImages.length;
const filesToAdd = files.slice(0, remainingSlots);
if (filesToAdd.length > 0 && !(isProcessing || task.status !== 'pending')) {
handleImageUpload(task.id, filesToAdd);
}
}}
onDragOver={(e) => {
e.preventDefault();
if (!(isProcessing || task.status !== 'pending')) {
e.currentTarget.classList.add('drag-over');
}
}}
onDragEnter={(e) => {
e.preventDefault();
if (!(isProcessing || task.status !== 'pending')) {
e.currentTarget.classList.add('drag-over');
}
}}
onDragLeave={(e) => {
e.preventDefault();
if (!e.currentTarget.contains(e.relatedTarget as Node)) {
e.currentTarget.classList.remove('drag-over');
}
}}
>
<div className="upload-content">
<div className="upload-icon">📁</div>
<div className="upload-text">拖拽图片到此处或点击上传</div>
<input
id={`file-input-${task.id}`}
type="file"
multiple
accept="image/*"
onChange={(e) => handleImageUpload(task.id, e.target.files)}
disabled={isProcessing || task.status !== 'pending'}
className="file-input"
style={{ display: 'none' }}
/>
</div>
</div>
{task.questionImages.length > 0 && (
<div
className="image-grid-container"
onDrop={(e) => {
e.preventDefault();
e.currentTarget.classList.remove('drag-over');
const files = Array.from(e.dataTransfer.files).filter(file => file.type.startsWith('image/'));
const remainingSlots = 9 - task.questionImages.length;
const filesToAdd = files.slice(0, remainingSlots);
if (filesToAdd.length > 0 && !(isProcessing || task.status !== 'pending')) {
handleImageUpload(task.id, filesToAdd);
}
}}
onDragOver={(e) => {
e.preventDefault();
if (!(isProcessing || task.status !== 'pending')) {
e.currentTarget.classList.add('drag-over');
}
}}
onDragEnter={(e) => {
e.preventDefault();
if (!(isProcessing || task.status !== 'pending')) {
e.currentTarget.classList.add('drag-over');
}
}}
onDragLeave={(e) => {
e.preventDefault();
if (!e.currentTarget.contains(e.relatedTarget as Node)) {
e.currentTarget.classList.remove('drag-over');
}
}}
>
<div className="image-grid-scroll">
{task.questionImages.map((file, imgIndex) => {
const imageUrl = URL.createObjectURL(file);
return (
<div key={imgIndex} className="image-thumbnail-container">
<img
src={imageUrl}
alt={`题目图片 ${imgIndex + 1}`}
className="image-thumbnail"
onLoad={() => URL.revokeObjectURL(imageUrl)}
/>
<button
className="remove-image-btn tooltip-test"
onClick={() => removeImage(task.id, imgIndex)}
disabled={isProcessing || task.status !== 'pending'}
data-tooltip="删除图片"
>
✕
</button>
</div>
);
})}
{task.questionImages.length < 9 && !(isProcessing || task.status !== 'pending') && (
<div className="add-image-placeholder">
<input
type="file"
multiple
accept="image/*"
onChange={(e) => handleImageUpload(task.id, e.target.files)}
className="add-image-input"
id={`add-more-question-images-${task.id}`}
/>
<label htmlFor={`add-more-question-images-${task.id}`} className="add-image-label">
<div className="add-image-icon">➕</div>
<div className="add-image-text">添加图片</div>
</label>
</div>
)}
</div>
</div>
)}
</div>
<div className="form-group" style={{ display: 'none' }}>
<label>解析图片 (可选):</label>
<div
className="file-upload-area"
onClick={() => {
if (!(isProcessing || task.status !== 'pending')) {
createFileUploadClickHandler(task.id, true)();
}
}}
onDrop={(e) => {
e.preventDefault();
e.currentTarget.classList.remove('drag-over');
const files = Array.from(e.dataTransfer.files).filter(file => file.type.startsWith('image/'));
const remainingSlots = 9 - task.analysisImages.length;
const filesToAdd = files.slice(0, remainingSlots);
if (filesToAdd.length > 0 && !(isProcessing || task.status !== 'pending')) {
handleImageUpload(task.id, filesToAdd, true);
}
}}
onDragOver={(e) => {
e.preventDefault();
if (!(isProcessing || task.status !== 'pending')) {
e.currentTarget.classList.add('drag-over');
}
}}
onDragEnter={(e) => {
e.preventDefault();
if (!(isProcessing || task.status !== 'pending')) {
e.currentTarget.classList.add('drag-over');
}
}}
onDragLeave={(e) => {
e.preventDefault();
if (!e.currentTarget.contains(e.relatedTarget as Node)) {
e.currentTarget.classList.remove('drag-over');
}
}}
>
<div className="upload-content">
<div className="upload-icon">📁</div>
<div className="upload-text">拖拽解析图片到此处或点击上传</div>
<input
id={`analysis-input-${task.id}`}
type="file"
multiple
accept="image/*"
onChange={(e) => handleImageUpload(task.id, e.target.files, true)}
disabled={isProcessing || task.status !== 'pending'}
className="file-input"
style={{ display: 'none' }}
/>
</div>
</div>
{task.analysisImages.length > 0 && (
<div
className="image-grid-container"
onDrop={(e) => {
e.preventDefault();
e.currentTarget.classList.remove('drag-over');
const files = Array.from(e.dataTransfer.files).filter(file => file.type.startsWith('image/'));
const remainingSlots = 9 - task.analysisImages.length;
const filesToAdd = files.slice(0, remainingSlots);
if (filesToAdd.length > 0 && !(isProcessing || task.status !== 'pending')) {
handleImageUpload(task.id, filesToAdd, true);
}
}}
onDragOver={(e) => {
e.preventDefault();
if (!(isProcessing || task.status !== 'pending')) {
e.currentTarget.classList.add('drag-over');
}
}}
onDragEnter={(e) => {
e.preventDefault();
if (!(isProcessing || task.status !== 'pending')) {
e.currentTarget.classList.add('drag-over');
}
}}
onDragLeave={(e) => {
e.preventDefault();
if (!e.currentTarget.contains(e.relatedTarget as Node)) {
e.currentTarget.classList.remove('drag-over');
}
}}
>
<div className="image-grid-scroll">
{task.analysisImages.map((file, imgIndex) => {
const imageUrl = URL.createObjectURL(file);
return (
<div key={imgIndex} className="image-thumbnail-container">
<img
src={imageUrl}
alt={`解析图片 ${imgIndex + 1}`}
className="image-thumbnail"
onLoad={() => URL.revokeObjectURL(imageUrl)}
/>
<button
className="remove-image-btn tooltip-test"
onClick={() => removeImage(task.id, imgIndex, true)}
disabled={isProcessing || task.status !== 'pending'}
data-tooltip="删除图片"
>
✕
</button>
</div>
);
})}
{task.analysisImages.length < 9 && !(isProcessing || task.status !== 'pending') && (
<div className="add-image-placeholder">
<input
type="file"
multiple
accept="image/*"
onChange={(e) => handleImageUpload(task.id, e.target.files, true)}
className="add-image-input"
id={`add-more-analysis-images-${task.id}`}
/>
<label htmlFor={`add-more-analysis-images-${task.id}`} className="add-image-label">
<div className="add-image-icon">➕</div>
<div className="add-image-text">添加图片</div>
</label>
</div>
)}
</div>
</div>
)}
</div>
<div className="form-group">
<label>问题描述:</label>
<textarea
value={task.userQuestion}
onChange={(e) => updateTask(task.id, { userQuestion: e.target.value })}
placeholder="请描述你对这道题的疑问..."
disabled={isProcessing || task.status !== 'pending'}
rows={2}
/>
</div>
{/* 简化的状态显示 */}
{task.status.startsWith('error_') && (
<div className="task-error-simple">
<p>❌ 处理失败 - 点击查看详情了解错误信息</p>
</div>
)}
{task.status === 'streaming_answer' && (
<div className="task-streaming-simple">
<div className="streaming-indicator">
<span className="spinner">⏳</span>
<span>AI正在生成解答...</span>
</div>
</div>
)}
{task.status === 'completed' && (
<div className="task-completed-simple">
<p>✅ 分析完成 - 点击查看详情查看完整结果</p>
</div>
)}
</div>
</div>
))}
</div>
<div className="batch-footer">
<button onClick={clearAllTasks} className="clear-button">
🗑️ 清空所有
</button>
<button
onClick={saveAllToLibrary}
disabled={tasks.filter(t => t.chatHistory.length > 0 || t.status === 'completed').length === 0}
className="save-all-button"
>
💾 保存所有可用的题目
</button>
</div>
</>
)}
</div>
</div>
);
}
|
000haoji/deep-student
| 6,519 |
src/components/TagManagement.css
|
.tag-management-container {
padding: 20px;
background: #f8f9fa;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.tag-management-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding-bottom: 15px;
border-bottom: 2px solid #3498db;
}
.tag-management-header h3 {
margin: 0;
color: #2c3e50;
font-size: 1.4em;
}
.header-actions {
display: flex;
gap: 10px;
}
.create-tag-btn,
.init-hierarchy-btn {
padding: 10px 16px;
border: none;
border-radius: 8px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s ease;
}
.create-tag-btn {
background: #27ae60;
color: white;
}
.create-tag-btn:hover:not(:disabled) {
background: #219a52;
transform: translateY(-1px);
}
.init-hierarchy-btn {
background: #3498db;
color: white;
}
.init-hierarchy-btn:hover:not(:disabled) {
background: #2980b9;
transform: translateY(-1px);
}
.create-tag-btn:disabled,
.init-hierarchy-btn:disabled {
background: #bdc3c7;
cursor: not-allowed;
transform: none;
}
.error-message {
background: #fee;
border: 1px solid #fcc;
border-radius: 8px;
padding: 12px;
margin-bottom: 20px;
color: #c33;
font-weight: 500;
display: flex;
justify-content: space-between;
align-items: center;
}
.error-message button {
background: none;
border: none;
color: #c33;
font-size: 16px;
cursor: pointer;
padding: 0;
margin-left: 10px;
}
.create-tag-form {
background: white;
border-radius: 12px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.create-tag-form h4 {
margin: 0 0 20px 0;
color: #2c3e50;
border-bottom: 2px solid #27ae60;
padding-bottom: 10px;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-weight: 600;
color: #2c3e50;
}
.form-group input,
.form-group select,
.form-group textarea {
width: 100%;
padding: 10px 12px;
border: 1px solid #bdc3c7;
border-radius: 6px;
font-size: 14px;
color: #2c3e50;
background: white;
box-sizing: border-box;
}
.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
outline: none;
border-color: #3498db;
box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}
.form-group textarea {
resize: vertical;
font-family: inherit;
}
.form-actions {
display: flex;
gap: 10px;
justify-content: flex-end;
margin-top: 20px;
}
.form-actions button {
padding: 10px 20px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s ease;
}
.form-actions button:first-child {
background: #27ae60;
color: white;
}
.form-actions button:first-child:hover:not(:disabled) {
background: #219a52;
}
.form-actions button:last-child {
background: #e74c3c;
color: white;
}
.form-actions button:last-child:hover:not(:disabled) {
background: #c0392b;
}
.form-actions button:disabled {
background: #bdc3c7;
cursor: not-allowed;
}
.tag-content {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.tag-list-section,
.tag-hierarchy-section {
background: white;
border-radius: 12px;
padding: 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 2px solid #3498db;
}
.section-header h4 {
margin: 0;
color: #2c3e50;
}
.filter-controls {
display: flex;
align-items: center;
gap: 8px;
}
.filter-controls label {
font-size: 14px;
color: #7f8c8d;
}
.filter-controls select {
padding: 6px 10px;
border: 1px solid #bdc3c7;
border-radius: 4px;
font-size: 14px;
}
.loading {
text-align: center;
padding: 40px;
color: #7f8c8d;
font-style: italic;
}
.tag-list {
max-height: 400px;
overflow-y: auto;
}
.tag-item {
border: 1px solid #ecf0f1;
border-radius: 8px;
padding: 15px;
margin-bottom: 10px;
transition: all 0.2s ease;
}
.tag-item:hover {
border-color: #3498db;
box-shadow: 0 2px 8px rgba(52, 152, 219, 0.1);
}
.tag-header {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 8px;
}
.tag-type {
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
}
.tag-type.knowledgearea {
background: #3498db;
color: white;
}
.tag-type.topic {
background: #9b59b6;
color: white;
}
.tag-type.concept {
background: #27ae60;
color: white;
}
.tag-type.method {
background: #f39c12;
color: white;
}
.tag-type.difficulty {
background: #e74c3c;
color: white;
}
.tag-name {
font-weight: 600;
color: #2c3e50;
flex: 1;
}
.tag-level {
background: #ecf0f1;
color: #7f8c8d;
padding: 2px 6px;
border-radius: 3px;
font-size: 12px;
}
.tag-description {
color: #7f8c8d;
font-size: 14px;
margin-bottom: 8px;
line-height: 1.4;
}
.tag-meta {
font-size: 12px;
color: #95a5a6;
}
.no-tags,
.no-hierarchy {
text-align: center;
padding: 40px;
color: #7f8c8d;
font-style: italic;
}
.hierarchy-tree {
max-height: 400px;
overflow-y: auto;
}
.tag-node {
border-left: 3px solid #3498db;
margin-bottom: 10px;
padding: 10px 15px;
background: #f8f9fa;
border-radius: 0 8px 8px 0;
}
.tag-node.level-0 {
border-left-color: #3498db;
background: #ebf3fd;
}
.tag-node.level-1 {
border-left-color: #9b59b6;
background: #f4f1f8;
margin-left: 20px;
}
.tag-node.level-2 {
border-left-color: #27ae60;
background: #eef7f0;
margin-left: 40px;
}
.tag-node.level-3 {
border-left-color: #f39c12;
background: #fdf6e3;
margin-left: 60px;
}
.tag-children {
margin-top: 10px;
}
.not-initialized {
display: flex;
align-items: center;
justify-content: center;
height: 300px;
background: white;
border-radius: 8px;
color: #7f8c8d;
font-size: 16px;
}
/* Responsive design */
@media (max-width: 1024px) {
.tag-content {
grid-template-columns: 1fr;
}
}
@media (max-width: 768px) {
.tag-management-header {
flex-direction: column;
gap: 15px;
align-items: stretch;
}
.header-actions {
justify-content: center;
}
.section-header {
flex-direction: column;
gap: 10px;
align-items: stretch;
}
.filter-controls {
justify-content: center;
}
.tag-node.level-1 {
margin-left: 10px;
}
.tag-node.level-2 {
margin-left: 20px;
}
.tag-node.level-3 {
margin-left: 30px;
}
}
|
000haoji/deep-student
| 28,833 |
src/components/ReviewAnalysisDashboard.tsx
|
import React, { useState, useEffect } from 'react';
import { ReviewSessionTask } from '../types/index';
import { useNotification } from '../hooks/useNotification';
import { TauriAPI, ReviewAnalysisItem } from '../utils/tauriApi';
import { useSubject } from '../contexts/SubjectContext';
import { UnifiedSubjectSelector } from './shared/UnifiedSubjectSelector';
import './ReviewAnalysis.css';
interface ReviewAnalysisDashboardProps {
onCreateNew: () => void;
onViewSession: (sessionId: string) => void;
}
const ReviewAnalysisDashboard: React.FC<ReviewAnalysisDashboardProps> = ({
onCreateNew,
onViewSession,
}) => {
const [reviewSessions, setReviewSessions] = useState<ReviewAnalysisItem[]>([]);
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState<{
status: string;
searchTerm: string;
}>({
status: '',
searchTerm: '',
});
const [statusDropdownOpen, setStatusDropdownOpen] = useState(false);
const statusOptions = [
{ value: '', label: '全部状态' },
{ value: 'pending', label: '待处理' },
{ value: 'processing_setup', label: '设置中' },
{ value: 'streaming_answer', label: '分析中' },
{ value: 'completed', label: '已完成' },
{ value: 'error_setup', label: '设置错误' },
{ value: 'error_stream', label: '分析错误' }
];
const { showNotification } = useNotification();
const { currentSubject } = useSubject();
// 从现有数据中提取可用的科目选项
const availableSubjects = Array.from(new Set(reviewSessions.map(session => session.subject).filter(Boolean)));
useEffect(() => {
loadReviewSessions();
}, []);
// 处理点击外部关闭下拉框
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (statusDropdownOpen) {
const target = event.target as Node;
const dropdown = document.querySelector('.status-dropdown-container');
if (dropdown && !dropdown.contains(target)) {
setStatusDropdownOpen(false);
}
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [statusDropdownOpen]);
const loadReviewSessions = async () => {
try {
setLoading(true);
// 从数据库加载回顾分析会话列表(复用错题分析的模式)
const sessions = await TauriAPI.getReviewAnalyses();
setReviewSessions(sessions);
console.log('✅ 从数据库加载回顾分析列表成功:', sessions.length);
// 验证错题数量是否正确加载
sessions.forEach(s => {
console.log(`📊 回顾分析 "${s.name}" 包含 ${s.mistake_ids?.length || 0} 个错题`);
});
} catch (error) {
console.error('加载回顾分析会话失败:', error);
showNotification('error', '加载回顾分析会话失败');
setReviewSessions([]);
} finally {
setLoading(false);
}
};
const handleDeleteSession = async (sessionId: string) => {
if (!confirm('确定要删除这个回顾分析会话吗?')) {
return;
}
try {
console.log('🗑️ 开始删除回顾分析:', sessionId);
const deleted = await TauriAPI.deleteReviewAnalysis(sessionId);
if (deleted) {
showNotification('success', '回顾分析删除成功');
// 重新加载列表以反映删除操作
await loadReviewSessions();
} else {
showNotification('warning', '回顾分析不存在或已被删除');
// 即使删除失败,也刷新列表以确保数据一致性
await loadReviewSessions();
}
} catch (error) {
console.error('❌ 删除回顾分析失败:', error);
showNotification('error', `删除回顾分析失败: ${error.message || error}`);
}
};
const filteredSessions = reviewSessions.filter(session => {
const matchesSubject = !currentSubject || currentSubject === '全部' || session.subject === currentSubject;
const matchesStatus = !filter.status || session.status === filter.status;
const matchesSearch = !filter.searchTerm ||
session.name.toLowerCase().includes(filter.searchTerm.toLowerCase()) ||
session.user_question.toLowerCase().includes(filter.searchTerm.toLowerCase()) ||
session.consolidated_input.toLowerCase().includes(filter.searchTerm.toLowerCase());
return matchesSubject && matchesStatus && matchesSearch;
});
const getStatusDisplay = (status: string) => {
const statusMap: Record<string, { text: string; style: any }> = {
pending: { text: '待处理', style: { backgroundColor: '#fef3c7', color: '#92400e', padding: '4px 8px', borderRadius: '12px', fontSize: '12px', fontWeight: '500' } },
processing_setup: { text: '设置中', style: { backgroundColor: '#dbeafe', color: '#1e40af', padding: '4px 8px', borderRadius: '12px', fontSize: '12px', fontWeight: '500' } },
awaiting_stream_start: { text: '等待分析', style: { backgroundColor: '#dbeafe', color: '#1e40af', padding: '4px 8px', borderRadius: '12px', fontSize: '12px', fontWeight: '500' } },
streaming_answer: { text: '分析中', style: { backgroundColor: '#dbeafe', color: '#1e40af', padding: '4px 8px', borderRadius: '12px', fontSize: '12px', fontWeight: '500' } },
completed: { text: '已完成', style: { backgroundColor: '#dcfce7', color: '#166534', padding: '4px 8px', borderRadius: '12px', fontSize: '12px', fontWeight: '500' } },
error_setup: { text: '设置错误', style: { backgroundColor: '#fee2e2', color: '#991b1b', padding: '4px 8px', borderRadius: '12px', fontSize: '12px', fontWeight: '500' } },
error_stream: { text: '分析错误', style: { backgroundColor: '#fee2e2', color: '#991b1b', padding: '4px 8px', borderRadius: '12px', fontSize: '12px', fontWeight: '500' } },
};
return statusMap[status] || { text: status, style: { backgroundColor: '#f3f4f6', color: '#374151', padding: '4px 8px', borderRadius: '12px', fontSize: '12px', fontWeight: '500' } };
};
if (loading) {
return (
<div className="review-loading">
<div className="review-loading-spinner"></div>
<span className="review-loading-text">加载中...</span>
</div>
);
}
return (
<div style={{
width: '100%',
height: '100%',
overflow: 'auto',
background: '#f8fafc'
}}>
{/* 头部区域 - 统一白色样式 */}
<div style={{
background: 'white',
borderBottom: '1px solid #e5e7eb',
padding: '24px 32px',
position: 'relative'
}}>
<div style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
height: '4px',
background: 'linear-gradient(90deg, #667eea, #764ba2)'
}}></div>
<div style={{ position: 'relative', zIndex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
<svg style={{ width: '32px', height: '32px', marginRight: '12px', color: '#667eea' }} fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
<circle cx="12" cy="12" r="10" />
<circle cx="12" cy="12" r="6" />
<circle cx="12" cy="12" r="2" />
</svg>
<h1 style={{ fontSize: '28px', fontWeight: '700', margin: 0, color: '#1f2937' }}>统一回顾分析</h1>
</div>
<p style={{ fontSize: '16px', color: '#6b7280', margin: 0, lineHeight: '1.5' }}>
对多个错题进行统一深度分析,发现学习模式,制定改进计划
</p>
<div style={{ marginTop: '24px' }}>
<button
onClick={onCreateNew}
style={{
background: '#667eea',
border: '1px solid #667eea',
color: 'white',
padding: '12px 24px',
borderRadius: '12px',
fontSize: '16px',
fontWeight: '600',
cursor: 'pointer',
display: 'inline-flex',
alignItems: 'center',
gap: '8px',
transition: 'all 0.3s ease'
}}
onMouseOver={(e) => {
e.currentTarget.style.background = '#5a67d8';
e.currentTarget.style.transform = 'translateY(-2px)';
e.currentTarget.style.boxShadow = '0 8px 25px rgba(102, 126, 234, 0.3)';
}}
onMouseOut={(e) => {
e.currentTarget.style.background = '#667eea';
e.currentTarget.style.transform = 'translateY(0)';
e.currentTarget.style.boxShadow = 'none';
}}
>
<svg style={{ width: '20px', height: '20px' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
</svg>
创建新的回顾分析
</button>
</div>
</div>
</div>
{/* 筛选器 - 重新设计 */}
<div style={{
background: 'white',
margin: '0 24px 24px 24px',
borderRadius: '16px',
padding: '24px',
boxShadow: '0 4px 20px rgba(0, 0, 0, 0.05)',
border: '1px solid #f1f5f9'
}}>
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
gap: '20px',
alignItems: 'end'
}}>
{/* 科目筛选现在由全局状态控制 */}
<div>
<label style={{
display: 'block',
fontSize: '14px',
fontWeight: '600',
color: '#374151',
marginBottom: '8px'
}}>状态筛选</label>
{/* 自定义状态下拉框 - 保持原生样式外观 + 自定义下拉列表 */}
<div className="status-dropdown-container" style={{ position: 'relative' }}>
<div
style={{
width: '100%',
padding: '12px 16px',
border: '2px solid #e2e8f0',
borderRadius: '12px',
fontSize: '14px',
background: 'white',
cursor: 'pointer',
transition: 'all 0.2s ease',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
minHeight: '20px'
}}
onClick={() => setStatusDropdownOpen(!statusDropdownOpen)}
onMouseOver={(e) => {
if (!statusDropdownOpen) {
e.currentTarget.style.borderColor = '#667eea';
}
}}
onMouseOut={(e) => {
if (!statusDropdownOpen) {
e.currentTarget.style.borderColor = '#e2e8f0';
}
}}
>
<span style={{ color: '#374151' }}>
{filter.status ? statusOptions.find(opt => opt.value === filter.status)?.label : '全部状态'}
</span>
<span style={{
transform: statusDropdownOpen ? 'rotate(180deg)' : 'rotate(0deg)',
transition: 'transform 0.2s ease',
color: '#6b7280',
fontSize: '12px'
}}>▼</span>
</div>
{statusDropdownOpen && (
<div style={{
position: 'absolute',
top: '100%',
left: 0,
right: 0,
backgroundColor: '#fff',
borderRadius: '12px',
border: '1px solid #e0e0e0',
marginTop: '8px',
boxShadow: '0 6px 16px rgba(0,0,0,0.12)',
zIndex: 9999,
overflow: 'hidden',
maxHeight: '300px',
overflowY: 'auto'
}}>
{statusOptions.map((option, index) => (
<div
key={option.value}
style={{
padding: '12px 16px',
cursor: 'pointer',
color: '#333',
fontSize: '14px',
borderBottom: index < statusOptions.length - 1 ? '1px solid #f0f0f0' : 'none',
backgroundColor: filter.status === option.value ? '#f0f7ff' : 'transparent',
transition: 'all 0.2s ease',
minHeight: '44px',
display: 'flex',
alignItems: 'center'
}}
onClick={() => {
setFilter(prev => ({ ...prev, status: option.value }));
setStatusDropdownOpen(false);
}}
onMouseOver={(e) => {
if (filter.status !== option.value) {
e.currentTarget.style.backgroundColor = '#f7f7f7';
}
}}
onMouseOut={(e) => {
if (filter.status !== option.value) {
e.currentTarget.style.backgroundColor = 'transparent';
}
}}
>
{option.label}
</div>
))}
</div>
)}
</div>
</div>
<div style={{ gridColumn: 'span 2' }}>
<label style={{
display: 'block',
fontSize: '14px',
fontWeight: '600',
color: '#374151',
marginBottom: '8px'
}}>搜索</label>
<div style={{ position: 'relative' }}>
<svg style={{
position: 'absolute',
left: '16px',
top: '50%',
transform: 'translateY(-50%)',
width: '18px',
height: '18px',
color: '#9ca3af'
}} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<input
type="text"
placeholder="搜索回顾分析名称或问题..."
value={filter.searchTerm}
onChange={(e) => setFilter(prev => ({ ...prev, searchTerm: e.target.value }))}
style={{
width: '100%',
padding: '12px 16px 12px 48px',
border: '2px solid #e2e8f0',
borderRadius: '12px',
fontSize: '14px',
transition: 'all 0.2s ease'
}}
onFocus={(e) => e.target.style.borderColor = '#667eea'}
onBlur={(e) => e.target.style.borderColor = '#e2e8f0'}
/>
</div>
</div>
</div>
</div>
{/* 会话列表 */}
{filteredSessions.length === 0 ? (
<div style={{
textAlign: 'center',
padding: '80px 24px',
background: 'white',
margin: '0 24px',
borderRadius: '16px',
boxShadow: '0 4px 20px rgba(0, 0, 0, 0.05)',
border: '1px solid #f1f5f9'
}}>
<div style={{
width: '80px',
height: '80px',
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
borderRadius: '50%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
margin: '0 auto 24px',
opacity: 0.8
}}>
<svg style={{ width: '40px', height: '40px', color: 'white' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
</div>
<h3 style={{
fontSize: '20px',
fontWeight: '600',
color: '#1F2937',
marginBottom: '12px',
margin: 0
}}>
{reviewSessions.length === 0 ? '开始您的第一个回顾分析' : '未找到匹配的分析'}
</h3>
<p style={{
fontSize: '16px',
color: '#6B7280',
lineHeight: '1.6',
marginBottom: '32px',
maxWidth: '400px',
margin: '0 auto 32px'
}}>
{reviewSessions.length === 0
? '创建回顾分析来深度分析多个错题,发现学习模式,制定改进计划'
: '尝试调整筛选条件或搜索关键词'}
</p>
{reviewSessions.length === 0 && (
<button
onClick={onCreateNew}
style={{
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
color: 'white',
border: 'none',
padding: '16px 32px',
borderRadius: '12px',
fontSize: '16px',
fontWeight: '600',
cursor: 'pointer',
display: 'inline-flex',
alignItems: 'center',
gap: '8px',
transition: 'all 0.3s ease',
boxShadow: '0 4px 15px rgba(102, 126, 234, 0.3)'
}}
onMouseOver={(e) => {
e.currentTarget.style.transform = 'translateY(-2px)';
e.currentTarget.style.boxShadow = '0 8px 25px rgba(102, 126, 234, 0.4)';
}}
onMouseOut={(e) => {
e.currentTarget.style.transform = 'translateY(0)';
e.currentTarget.style.boxShadow = '0 4px 15px rgba(102, 126, 234, 0.3)';
}}
>
<svg style={{ width: '20px', height: '20px' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
</svg>
立即创建回顾分析
</button>
)}
</div>
) : (
<div style={{
display: 'grid',
gap: '20px',
margin: '0 24px 24px 24px'
}}>
{filteredSessions.map((session) => {
const statusInfo = getStatusDisplay(session.status);
return (
<div
key={session.id}
style={{
background: 'white',
borderRadius: '16px',
boxShadow: '0 4px 20px rgba(0, 0, 0, 0.05)',
border: '1px solid #f1f5f9',
transition: 'all 0.3s ease',
cursor: 'pointer',
position: 'relative',
overflow: 'hidden'
}}
onMouseOver={(e) => {
e.currentTarget.style.transform = 'translateY(-2px)';
e.currentTarget.style.boxShadow = '0 8px 30px rgba(0, 0, 0, 0.12)';
}}
onMouseOut={(e) => {
e.currentTarget.style.transform = 'translateY(0)';
e.currentTarget.style.boxShadow = '0 4px 20px rgba(0, 0, 0, 0.05)';
}}
>
{/* 顶部装饰条 */}
<div style={{
height: '4px',
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
width: '100%'
}}></div>
<div style={{ padding: '28px' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
<div style={{ flex: 1 }}>
{/* 标题和状态 */}
<div style={{ display: 'flex', alignItems: 'center', marginBottom: '16px' }}>
<div style={{
width: '12px',
height: '12px',
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
borderRadius: '50%',
marginRight: '12px'
}}></div>
<h3 style={{
fontSize: '20px',
fontWeight: '700',
color: '#1F2937',
margin: 0,
marginRight: '16px',
lineHeight: '1.2'
}}>
{session.name}
</h3>
<span style={statusInfo.style}>
{statusInfo.text}
</span>
</div>
{/* 元信息 */}
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))',
gap: '20px',
marginBottom: '20px',
padding: '16px',
background: '#f8fafc',
borderRadius: '12px',
border: '1px solid #f1f5f9'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<svg style={{ width: '16px', height: '16px', color: '#667eea' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
</svg>
<div>
<div style={{ fontSize: '12px', color: '#6B7280', fontWeight: '500' }}>科目</div>
<div style={{ fontSize: '14px', color: '#1F2937', fontWeight: '600' }}>{session.subject}</div>
</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<svg style={{ width: '16px', height: '16px', color: '#667eea' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
<div>
<div style={{ fontSize: '12px', color: '#6B7280', fontWeight: '500' }}>错题数量</div>
<div style={{ fontSize: '14px', color: '#1F2937', fontWeight: '600' }}>{session.mistake_ids.length} 个</div>
</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<svg style={{ width: '16px', height: '16px', color: '#667eea' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
<div>
<div style={{ fontSize: '12px', color: '#6B7280', fontWeight: '500' }}>创建时间</div>
<div style={{ fontSize: '14px', color: '#1F2937', fontWeight: '600' }}>{new Date(session.created_at).toLocaleDateString()}</div>
</div>
</div>
</div>
{/* 描述 */}
<div style={{
padding: '16px',
background: 'rgba(102, 126, 234, 0.05)',
borderRadius: '12px',
borderLeft: '4px solid #667eea'
}}>
<div style={{ fontSize: '12px', color: '#667eea', fontWeight: '600', marginBottom: '4px' }}>分析指引</div>
<p style={{
color: '#374151',
lineHeight: '1.6',
fontSize: '14px',
margin: 0,
overflow: 'hidden',
display: '-webkit-box',
WebkitLineClamp: 2,
WebkitBoxOrient: 'vertical'
}}>
{session.user_question}
</p>
</div>
</div>
{/* 操作按钮 */}
<div style={{
display: 'flex',
flexDirection: 'column',
gap: '12px',
marginLeft: '24px',
minWidth: '120px'
}}>
<button
onClick={(e) => {
e.stopPropagation();
onViewSession(session.id);
}}
style={{
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
color: 'white',
border: 'none',
padding: '12px 20px',
borderRadius: '10px',
fontSize: '14px',
fontWeight: '600',
cursor: 'pointer',
transition: 'all 0.2s ease',
boxShadow: '0 2px 8px rgba(102, 126, 234, 0.2)'
}}
onMouseOver={(e) => {
e.currentTarget.style.transform = 'translateY(-1px)';
e.currentTarget.style.boxShadow = '0 4px 15px rgba(102, 126, 234, 0.3)';
}}
onMouseOut={(e) => {
e.currentTarget.style.transform = 'translateY(0)';
e.currentTarget.style.boxShadow = '0 2px 8px rgba(102, 126, 234, 0.2)';
}}
>
<svg style={{ width: '14px', height: '14px', marginRight: '6px' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>
查看详情
</button>
<button
onClick={(e) => {
e.stopPropagation();
handleDeleteSession(session.id);
}}
style={{
background: '#ffffff',
color: '#ef4444',
border: '2px solid #fee2e2',
padding: '10px 20px',
borderRadius: '10px',
fontSize: '14px',
fontWeight: '600',
cursor: 'pointer',
transition: 'all 0.2s ease'
}}
onMouseOver={(e) => {
e.currentTarget.style.background = '#fef2f2';
e.currentTarget.style.borderColor = '#fecaca';
e.currentTarget.style.transform = 'translateY(-1px)';
}}
onMouseOut={(e) => {
e.currentTarget.style.background = '#ffffff';
e.currentTarget.style.borderColor = '#fee2e2';
e.currentTarget.style.transform = 'translateY(0)';
}}
>
<svg style={{ width: '14px', height: '14px', marginRight: '6px' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
删除
</button>
</div>
</div>
</div>
</div>
);
})}
</div>
)}
</div>
);
};
export default ReviewAnalysisDashboard;
|
000haoji/deep-student
| 8,100 |
src/components/AIChatInterface.tsx
|
/**
* AI Chat Interface using Vercel AI SDK
*
* This component replaces the custom streaming implementation with
* Vercel AI SDK's useChat hook for better performance and reliability.
*/
import React, { useState, useMemo } from 'react';
import { useChat } from '@ai-sdk/react';
import { createAISdkFetch, convertFromTauriFormat, MarkdownRenderer, MessageWithThinking } from '../chat-core';
interface AIChatInterfaceProps {
tempId?: string;
mistakeId?: number;
initialMessages?: any[];
enableChainOfThought?: boolean;
onAnalysisStart?: () => void;
onAnalysisComplete?: (response: any) => void;
className?: string;
}
export const AIChatInterface = React.forwardRef<any, AIChatInterfaceProps>(({
tempId,
mistakeId,
initialMessages = [],
enableChainOfThought = true,
onAnalysisStart,
onAnalysisComplete,
className = ''
}, ref) => {
const [isAnalyzing, setIsAnalyzing] = useState(false);
// Convert initial messages to AI SDK format
const convertedInitialMessages = useMemo(() =>
convertFromTauriFormat(initialMessages),
[initialMessages]
);
// Determine API endpoint based on props
const apiEndpoint = useMemo(() => {
if (tempId) return '/api/continue-chat';
if (mistakeId) return '/api/mistake-chat';
return '/api/chat';
}, [tempId, mistakeId]);
// Initialize AI SDK useChat hook
const {
messages,
input,
handleInputChange,
handleSubmit,
isLoading,
error,
reload,
stop,
append,
setMessages
} = useChat({
api: apiEndpoint,
initialMessages: convertedInitialMessages,
fetch: createAISdkFetch(),
body: {
tempId,
mistakeId,
enableChainOfThought
},
onResponse: (response) => {
console.log('AI SDK Response received:', response.status);
if (onAnalysisStart) {
onAnalysisStart();
}
setIsAnalyzing(true);
},
onFinish: (message) => {
console.log('AI SDK Response finished:', message);
setIsAnalyzing(false);
if (onAnalysisComplete) {
onAnalysisComplete(message);
}
},
onError: (error) => {
console.error('AI SDK Error:', error);
setIsAnalyzing(false);
}
});
// Handle form submission with custom logic
const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!input.trim() || isLoading) return;
setIsAnalyzing(true);
try {
await handleSubmit(e);
} catch (error) {
console.error('Chat submission error:', error);
setIsAnalyzing(false);
}
};
// Handle sending messages programmatically
const sendMessage = async (content: string, role: 'user' | 'assistant' = 'user') => {
if (!content.trim() || isLoading) return;
setIsAnalyzing(true);
try {
await append({
role,
content,
id: `msg-${Date.now()}`
});
} catch (error) {
console.error('Send message error:', error);
setIsAnalyzing(false);
}
};
// Expose sendMessage for external use
React.useImperativeHandle(ref, () => ({
sendMessage,
clearChat
}));
// Clear chat history
const clearChat = () => {
setMessages([]);
};
// Handle keyboard shortcuts
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
onSubmit(e as any);
}
};
return (
<div className={`ai-chat-interface ${className}`}>
{/* Chat Messages */}
<div className="chat-messages">
{messages.map((message, index) => (
<div key={message.id || index} className={`message ${message.role}`}>
<div className="message-header">
<span className="role">{message.role === 'user' ? '用户' : 'AI助手'}</span>
<span className="timestamp">
{new Date().toLocaleTimeString()}
</span>
</div>
<div className="message-content">
{message.role === 'assistant' ? (
<MessageWithThinking
content={message.content}
thinkingContent={(message as any).thinking_content}
isStreaming={isLoading && index === messages.length - 1}
role="assistant"
timestamp={new Date().toISOString()}
ragSources={(message as any).rag_sources}
/>
) : (
<div className="user-message">
<MarkdownRenderer content={message.content} />
</div>
)}
</div>
</div>
))}
{/* Loading indicator */}
{isLoading && (
<div className="message assistant">
<div className="message-header">
<span className="role">AI助手</span>
<span className="timestamp">正在回复...</span>
</div>
<div className="message-content">
<div className="loading-indicator">
<div className="typing-dots">
<span></span>
<span></span>
<span></span>
</div>
<span>正在分析中...</span>
</div>
</div>
</div>
)}
{/* Error display */}
{error && (
<div className="error-message">
<div className="error-content">
<span className="error-icon">⚠️</span>
<span className="error-text">
出错了: {error.message}
</span>
<button onClick={() => reload()} className="retry-button">
重试
</button>
</div>
</div>
)}
</div>
{/* Chat Input */}
<form onSubmit={onSubmit} className="chat-input-form">
<div className="input-container">
<textarea
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
placeholder="输入您的问题..."
disabled={isLoading}
rows={3}
className="chat-input"
/>
<div className="input-actions">
<button
type="submit"
disabled={!input.trim() || isLoading}
className="send-button"
>
{isLoading ? '发送中...' : '发送'}
</button>
{isLoading && (
<button
type="button"
onClick={stop}
className="stop-button"
>
停止
</button>
)}
<button
type="button"
onClick={clearChat}
disabled={isLoading}
className="clear-button"
>
清空
</button>
</div>
</div>
</form>
{/* Chat Controls */}
<div className="chat-controls">
<label className="chain-of-thought-toggle">
<input
type="checkbox"
checked={enableChainOfThought}
onChange={() => {
// This would need to be passed up to parent component
// for now just show the current state
}}
disabled={isLoading}
/>
<span>显示思维过程</span>
</label>
<div className="chat-stats">
<span>消息数: {messages.length}</span>
{isAnalyzing && <span className="analyzing">分析中...</span>}
</div>
</div>
</div>
);
});
// Export utility functions for external use
export const useChatHelpers = () => {
return {
sendMessage: (chatRef: React.RefObject<any>, content: string) => {
if (chatRef.current?.sendMessage) {
chatRef.current.sendMessage(content);
}
},
clearChat: (chatRef: React.RefObject<any>) => {
if (chatRef.current?.clearChat) {
chatRef.current.clearChat();
}
}
};
};
|
000haoji/deep-student
| 6,106 |
src/components/ImageOcclusion.css
|
.image-occlusion-container {
padding: 20px;
max-width: 1200px;
margin: 0 auto;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
.header {
text-align: center;
margin-bottom: 30px;
}
.header h2 {
color: #2c3e50;
margin-bottom: 10px;
font-size: 2rem;
font-weight: 600;
}
.header p {
color: #7f8c8d;
font-size: 1rem;
margin: 0;
}
.upload-section {
display: flex;
gap: 15px;
margin-bottom: 30px;
justify-content: center;
align-items: center;
}
.upload-button, .extract-button, .create-button {
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
color: white;
}
.upload-button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.upload-button:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}
.extract-button {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}
.extract-button:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(240, 147, 251, 0.3);
}
.create-button {
background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
width: 100%;
margin-top: 20px;
}
.create-button:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(79, 172, 254, 0.3);
}
.upload-button:disabled, .extract-button:disabled, .create-button:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
}
.image-workspace {
display: grid;
grid-template-columns: 1fr 350px;
gap: 30px;
align-items: start;
}
.image-container {
position: relative;
background: #f8f9fa;
border-radius: 12px;
padding: 20px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}
.main-image {
max-width: 100%;
max-height: 600px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
display: block;
}
.text-region {
transition: all 0.2s ease;
z-index: 10;
}
.text-region:hover {
border-width: 3px !important;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}
.text-region.selected {
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0% {
box-shadow: 0 0 0 0 rgba(255, 0, 0, 0.7);
}
70% {
box-shadow: 0 0 0 10px rgba(255, 0, 0, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(255, 0, 0, 0);
}
}
.controls-panel, .preview-panel {
background: white;
border-radius: 12px;
padding: 20px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
height: fit-content;
position: sticky;
top: 20px;
}
.controls-panel h3, .preview-panel h3 {
margin: 0 0 15px 0;
color: #2c3e50;
font-size: 1.2rem;
font-weight: 600;
border-bottom: 2px solid #e9ecef;
padding-bottom: 8px;
}
.form-group {
margin-bottom: 20px;
}
.form-group-inline {
display: flex;
align-items: center;
gap: 8px;
margin-left: 15px;
}
.form-group-inline input[type="checkbox"] {
width: auto;
margin: 0;
cursor: pointer;
}
.form-group-inline label {
margin-bottom: 0;
color: #495057;
font-weight: 500;
cursor: pointer;
}
.form-group label {
display: block;
margin-bottom: 6px;
color: #495057;
font-weight: 500;
font-size: 0.9rem;
}
.form-group input, .form-group textarea, .form-group select {
width: 100%;
padding: 10px 12px;
border: 2px solid #e9ecef;
border-radius: 6px;
font-size: 0.9rem;
transition: border-color 0.2s ease;
box-sizing: border-box;
}
.form-group input:focus, .form-group textarea:focus, .form-group select:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 15px;
}
.mask-settings {
margin: 20px 0;
}
.mask-style-options {
display: flex;
flex-direction: column;
gap: 10px;
}
.mask-style-options label {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
padding: 8px;
border-radius: 6px;
transition: background-color 0.2s ease;
}
.mask-style-options label:hover {
background-color: #f8f9fa;
}
.mask-style-options input[type="radio"] {
width: auto;
margin: 0;
}
.region-stats {
background: #f8f9fa;
padding: 15px;
border-radius: 8px;
margin: 20px 0;
}
.region-stats p {
margin: 5px 0;
color: #6c757d;
font-size: 0.9rem;
}
.mask-overlay {
transition: opacity 0.3s ease;
z-index: 20;
}
.mask-overlay:hover {
opacity: 0.8 !important;
}
.preview-controls {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
.preview-controls button {
padding: 8px 16px;
border: 2px solid #667eea;
border-radius: 6px;
background: white;
color: #667eea;
cursor: pointer;
transition: all 0.2s ease;
font-weight: 500;
}
.preview-controls button:hover {
background: #667eea;
color: white;
}
.preview-controls button:first-child {
border-color: #6c757d;
color: #6c757d;
}
.preview-controls button:first-child:hover {
background: #6c757d;
color: white;
}
.card-details {
padding-top: 15px;
border-top: 1px solid #e9ecef;
}
.card-details h4 {
margin: 0 0 10px 0;
color: #2c3e50;
font-size: 1.1rem;
}
.card-details p {
margin: 0 0 15px 0;
color: #6c757d;
line-height: 1.5;
}
.tags {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.tag {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 4px 8px;
border-radius: 12px;
font-size: 0.8rem;
font-weight: 500;
}
/* 响应式设计 */
@media (max-width: 768px) {
.image-workspace {
grid-template-columns: 1fr;
gap: 20px;
}
.controls-panel, .preview-panel {
position: static;
}
.form-row {
grid-template-columns: 1fr;
}
.upload-section {
flex-direction: column;
}
}
/* 加载状态动画 */
.processing {
opacity: 0.7;
pointer-events: none;
}
.processing::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 20px;
height: 20px;
margin: -10px 0 0 -10px;
border: 2px solid #667eea;
border-radius: 50%;
border-top-color: transparent;
animation: spin 1s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
|
000haoji/deep-student
| 9,374 |
src/components/RagQueryView.css
|
/* RAG查询测试组件样式 */
.rag-query-view {
padding: 20px;
max-width: 1200px;
margin: 0 auto;
color: #333;
}
.rag-query-header {
margin-bottom: 30px;
text-align: center;
}
.rag-query-header h2 {
color: #2c3e50;
margin: 0 0 8px 0;
font-size: 1.8rem;
}
.subtitle {
color: #7f8c8d;
margin: 0;
font-size: 0.95rem;
}
/* 查询配置区域 */
.query-config-section {
background: #f8f9fa;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
border: 1px solid #e9ecef;
}
.query-config-section h3 {
margin: 0 0 15px 0;
color: #495057;
font-size: 1.1rem;
}
.config-controls {
display: flex;
gap: 30px;
align-items: center;
flex-wrap: wrap;
}
.config-item {
display: flex;
align-items: center;
gap: 8px;
}
.config-item label {
font-weight: 500;
color: #495057;
}
.config-item input[type="number"] {
width: 80px;
padding: 6px 8px;
border: 1px solid #ced4da;
border-radius: 4px;
font-size: 14px;
}
.checkbox-label {
display: flex;
align-items: center;
gap: 6px;
cursor: pointer;
user-select: none;
}
.checkbox-label input[type="checkbox"] {
margin: 0;
}
/* 查询输入区域 */
.query-input-section {
background: white;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
border: 1px solid #e9ecef;
}
.query-input-section h3 {
margin: 0 0 15px 0;
color: #495057;
font-size: 1.1rem;
}
.query-input-container {
display: flex;
gap: 12px;
align-items: flex-start;
}
.query-input {
flex: 1;
padding: 12px;
border: 2px solid #e9ecef;
border-radius: 8px;
font-size: 14px;
font-family: inherit;
resize: vertical;
min-height: 80px;
transition: border-color 0.2s ease;
}
.query-input:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}
.query-input:disabled {
background-color: #f8f9fa;
color: #6c757d;
}
.query-button {
padding: 12px 24px;
background: #007bff;
color: white;
border: none;
border-radius: 8px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
white-space: nowrap;
}
.query-button:hover:not(:disabled) {
background: #0056b3;
transform: translateY(-1px);
}
.query-button:disabled {
background: #6c757d;
cursor: not-allowed;
transform: none;
}
.input-hint {
margin-top: 8px;
font-size: 0.85rem;
color: #6c757d;
}
/* 检索结果区域 */
.retrieval-results-section {
background: white;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
border: 1px solid #e9ecef;
}
.retrieval-results-section h3 {
margin: 0 0 20px 0;
color: #495057;
font-size: 1.1rem;
display: flex;
align-items: center;
gap: 8px;
}
.retrieval-results-section h3::before {
content: "🔍";
}
.retrieved-chunks {
display: flex;
flex-direction: column;
gap: 16px;
}
.retrieved-chunk {
background: #f8f9fa;
border-radius: 8px;
border: 1px solid #e9ecef;
overflow: hidden;
transition: box-shadow 0.2s ease;
}
.retrieved-chunk:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.chunk-header {
background: #e9ecef;
padding: 12px 16px;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.chunk-rank {
background: #007bff;
color: white;
padding: 4px 8px;
border-radius: 12px;
font-size: 0.85rem;
font-weight: 600;
}
.chunk-score {
background: #28a745;
color: white;
padding: 4px 8px;
border-radius: 12px;
font-size: 0.85rem;
font-weight: 500;
}
.chunk-source {
color: #495057;
font-size: 0.9rem;
font-weight: 500;
}
.chunk-content {
padding: 16px;
}
.chunk-content p {
margin: 0 0 12px 0;
line-height: 1.6;
color: #495057;
}
.expand-button {
background: none;
border: none;
color: #007bff;
cursor: pointer;
font-size: 0.9rem;
text-decoration: underline;
padding: 0;
}
.expand-button:hover {
color: #0056b3;
}
.chunk-metadata {
padding: 12px 16px;
background: #f1f3f4;
border-top: 1px solid #e9ecef;
display: flex;
gap: 20px;
font-size: 0.85rem;
color: #6c757d;
}
/* LLM回答区域 */
.llm-answer-section {
background: white;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
border: 1px solid #e9ecef;
}
.llm-answer-section h3 {
margin: 0 0 20px 0;
color: #495057;
font-size: 1.1rem;
display: flex;
align-items: center;
gap: 8px;
}
.llm-answer-section h3::before {
content: "🤖";
}
.llm-answer {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 12px;
padding: 24px;
color: white;
position: relative;
overflow: hidden;
}
.llm-answer::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.05);
backdrop-filter: blur(10px);
pointer-events: none;
}
.answer-content {
position: relative;
z-index: 1;
}
.answer-content p {
margin: 0 0 16px 0;
line-height: 1.7;
font-size: 1rem;
}
.answer-content p:last-child {
margin-bottom: 0;
}
.answer-footer {
margin-top: 20px;
padding-top: 16px;
border-top: 1px solid rgba(255, 255, 255, 0.2);
position: relative;
z-index: 1;
}
.answer-source {
font-size: 0.9rem;
opacity: 0.9;
font-style: italic;
}
/* 加载状态 */
.loading-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 1000;
color: white;
}
.loading-spinner {
width: 50px;
height: 50px;
border: 4px solid rgba(255, 255, 255, 0.3);
border-top: 4px solid #007bff;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-bottom: 16px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.loading-overlay p {
margin: 0;
font-size: 1.1rem;
font-weight: 500;
}
/* 响应式设计 */
@media (max-width: 768px) {
.rag-query-view {
padding: 15px;
}
.config-controls {
flex-direction: column;
align-items: flex-start;
gap: 15px;
}
.query-input-container {
flex-direction: column;
}
.query-button {
align-self: flex-start;
}
.chunk-header {
flex-direction: column;
align-items: flex-start;
}
.chunk-metadata {
flex-direction: column;
gap: 8px;
}
}
/* 深色主题支持 */
/* 强制应用深色主题到RAG查询页面 */
.rag-query-view {
color: #e9ecef !important;
background: #1a1a1a !important;
}
.rag-query-header h2 {
color: #ffffff !important;
}
.subtitle {
color: #b8b8b8 !important;
}
.query-config-section {
background: #2c3e50 !important;
border-color: #495057 !important;
}
.query-config-section h3 {
color: #ffffff !important;
}
.config-item label {
color: #ffffff !important;
}
.config-item input[type="number"] {
background: #495057 !important;
border-color: #6c757d !important;
color: #ffffff !important;
}
.checkbox-label {
color: #ffffff !important;
}
.query-input-section,
.retrieval-results-section,
.llm-answer-section {
background: #2c3e50 !important;
border-color: #495057 !important;
}
.query-input-section h3,
.retrieval-results-section h3,
.llm-answer-section h3 {
color: #ffffff !important;
}
.query-input {
background: #495057 !important;
border-color: #6c757d !important;
color: #ffffff !important;
}
.query-input::placeholder {
color: #adb5bd !important;
}
.query-input:focus {
border-color: #007bff !important;
}
.input-hint {
color: #ffc107 !important;
}
.retrieved-chunk {
background: #495057 !important;
border-color: #6c757d !important;
}
.chunk-header {
background: #6c757d !important;
}
.chunk-source {
color: #ffffff !important;
}
.chunk-content p {
color: #ffffff !important;
}
.chunk-metadata {
background: #6c757d !important;
border-color: #868e96 !important;
color: #ffffff !important;
}
.expand-button {
color: #66b3ff !important;
}
.expand-button:hover {
color: #4da6ff !important;
}
/* 备用的系统主题检测 */
@media (prefers-color-scheme: dark) {
.rag-query-view {
color: #e9ecef;
background: #1a1a1a;
}
.rag-query-header h2 {
color: #ffffff;
}
.subtitle {
color: #b8b8b8;
}
.query-config-section {
background: #2c3e50;
border-color: #495057;
}
.query-config-section h3 {
color: #ffffff;
}
.config-item label {
color: #ffffff;
}
.config-item input[type="number"] {
background: #495057;
border-color: #6c757d;
color: #ffffff;
}
.checkbox-label {
color: #ffffff;
}
.query-input-section,
.retrieval-results-section,
.llm-answer-section {
background: #2c3e50;
border-color: #495057;
}
.query-input-section h3,
.retrieval-results-section h3,
.llm-answer-section h3 {
color: #ffffff;
}
.query-input {
background: #495057;
border-color: #6c757d;
color: #ffffff;
}
.query-input::placeholder {
color: #adb5bd;
}
.query-input:focus {
border-color: #007bff;
}
.input-hint {
color: #ffc107;
}
.retrieved-chunk {
background: #495057;
border-color: #6c757d;
}
.chunk-header {
background: #6c757d;
}
.chunk-source {
color: #ffffff;
}
.chunk-content p {
color: #ffffff;
}
.chunk-metadata {
background: #6c757d;
border-color: #868e96;
color: #ffffff;
}
.expand-button {
color: #66b3ff;
}
.expand-button:hover {
color: #4da6ff;
}
}
|
000haoji/deep-student
| 7,987 |
src/components/SummaryBox.tsx
|
import React, { useState, useEffect } from 'react';
import { ChatMessage } from '../types';
interface SummaryBoxProps {
chatHistory: ChatMessage[];
isVisible: boolean;
onClose?: () => void;
subject?: string;
mistakeId?: string; // 用于错题库详情
reviewSessionId?: string; // 用于批量分析详情
// 新增:与AI调用一致的接口
onGenerateSummary?: (summaryPrompt: string) => void;
currentStreamId?: string;
isGenerating?: boolean;
// 新增:从父组件传递的流式内容
summaryStreamContent?: string;
summaryStreamComplete?: boolean;
}
export const SummaryBox: React.FC<SummaryBoxProps> = ({
chatHistory,
isVisible,
onClose,
subject = '数学',
mistakeId: _mistakeId,
reviewSessionId: _reviewSessionId,
onGenerateSummary,
isGenerating = false,
summaryStreamContent = '',
summaryStreamComplete = false
}) => {
const [isExpanded, setIsExpanded] = useState(true);
const [summaryRequested, setSummaryRequested] = useState(false);
const [summaryContent, setSummaryContent] = useState('');
const [isStreaming, setIsStreaming] = useState(false);
// 监听流式内容更新
useEffect(() => {
if (summaryStreamContent !== undefined) {
setSummaryContent(summaryStreamContent);
setIsStreaming(!summaryStreamComplete);
if (summaryStreamContent && !summaryRequested) {
setSummaryRequested(true);
}
}
}, [summaryStreamContent, summaryStreamComplete, summaryRequested]);
// 🎯 新增:当父组件传入的总结内容发生变化时,重置内部状态 - 配合保活机制
useEffect(() => {
// 当切换到不同错题时,重置总结请求状态
// 这确保了在保活模式下,SummaryBox能正确响应新错题的总结状态
if (summaryStreamContent === '' && summaryRequested) {
console.log('🔄 [SummaryBox] 检测到新错题无总结内容,重置请求状态');
setSummaryRequested(false);
}
}, [summaryStreamContent, summaryStreamComplete]);
// 监听生成状态
useEffect(() => {
if (isGenerating) {
setIsStreaming(true);
} else if (summaryStreamComplete) {
setIsStreaming(false);
}
}, [isGenerating, summaryStreamComplete]);
// 如果不可见就不渲染
if (!isVisible) return null;
const generateSummary = () => {
if (chatHistory.length === 0) {
return;
}
if (!onGenerateSummary) {
console.warn('⚠️ onGenerateSummary回调未提供');
return;
}
// 构建总结提示词
const chatHistoryText = chatHistory.map(msg => {
const roleDisplay = msg.role === 'user' ? '用户' : '助手';
const contentStr = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content);
return `${roleDisplay}: ${contentStr}`;
}).join('\\n\\n');
const summaryPrompt = `请基于以下对话记录,生成简洁的学习总结:
对话记录:
${chatHistoryText}
请生成:
1. 题目核心知识点:题目所涉及的知识点具体分类与定位
2. 错误分析:根据聊天上下文,学生存在的主要问题以及误区
3. 学生分析:根据聊天上下文,学生可能的薄弱点位置,需要重点注意的细节
4. 解题方法: 根据聊天上下文,学生应重点掌握的具体解题方法,
要求:
- 严禁使用markdown和latex语法,尤其是**
- 严禁使用markdown和latex语法,尤其是**
- 严禁使用markdown和latex语法,尤其是**
- 内容简洁明了,不长篇大论,不啰嗦,一针见血
- 重点突出学习要点`;
console.log('📝 准备通过回调生成总结,提示词长度:', summaryPrompt.length);
setSummaryRequested(true);
onGenerateSummary(summaryPrompt);
};
return (
<div className="summary-box" style={{
border: '1px solid #e0e0e0',
borderRadius: '8px',
margin: '8px 0',
backgroundColor: '#f9f9f9',
fontSize: '14px'
}}>
{/* 头部 */}
<div
className="summary-header"
style={{
padding: '8px 12px',
backgroundColor: '#f0f0f0',
borderRadius: '8px 8px 0 0',
cursor: 'pointer',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
borderBottom: isExpanded ? '1px solid #e0e0e0' : 'none'
}}
onClick={() => setIsExpanded(!isExpanded)}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<span style={{
fontSize: '12px',
color: '#666',
transform: isExpanded ? 'rotate(90deg)' : 'rotate(0deg)',
transition: 'transform 0.2s',
width: '12px',
textAlign: 'center'
}}>
▶
</span>
<span style={{ fontWeight: '500', color: '#333' }}>
学习总结
</span>
{summaryContent && (
<span style={{
fontSize: '11px',
color: '#999',
backgroundColor: '#e8f4fd',
padding: '2px 6px',
borderRadius: '10px'
}}>
已生成
</span>
)}
</div>
<div style={{ display: 'flex', gap: '4px' }}>
{!isGenerating && (
<button
onClick={(e) => {
e.stopPropagation();
generateSummary();
}}
style={{
padding: '4px 8px',
fontSize: '11px',
backgroundColor: '#4CAF50',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
title="生成总结"
>
{summaryRequested ? '重新生成总结' : '生成学习总结'}
</button>
)}
{onClose && (
<button
onClick={(e) => {
e.stopPropagation();
onClose();
}}
style={{
padding: '4px 6px',
fontSize: '11px',
backgroundColor: '#f44336',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
title="关闭总结框"
>
✕
</button>
)}
</div>
</div>
{/* 总结内容显示区域 */}
{isExpanded && (
<div
className="summary-content"
style={{
padding: '12px',
minHeight: '40px',
maxHeight: '300px',
overflowY: 'auto',
backgroundColor: '#f8f9fa'
}}
>
{isGenerating && (
<div style={{
color: '#666',
fontStyle: 'italic',
display: 'flex',
alignItems: 'center',
gap: '8px',
marginBottom: summaryContent ? '8px' : '0'
}}>
<div
style={{
width: '16px',
height: '16px',
border: '2px solid #e0e0e0',
borderTop: '2px solid #4CAF50',
borderRadius: '50%',
animation: 'spin 1s linear infinite'
}}
/>
正在生成学习总结...
</div>
)}
{summaryContent ? (
<div style={{
lineHeight: '1.5',
color: '#333',
whiteSpace: 'pre-wrap',
fontSize: '14px'
}}>
{summaryContent}
{isStreaming && (
<span
style={{
opacity: 0.7,
animation: 'blink 1s infinite'
}}
>
|
</span>
)}
</div>
) : !isGenerating && (
<div style={{
color: '#999',
fontStyle: 'italic',
textAlign: 'center',
padding: '20px',
fontSize: '12px'
}}>
💡 点击"生成学习总结"按钮,AI将基于当前对话生成学习要点总结
</div>
)}
</div>
)}
{/* CSS动画 */}
<style>{`
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
@keyframes blink {
0%, 50% { opacity: 1; }
51%, 100% { opacity: 0; }
}
.summary-box:hover {
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.summary-header:hover {
background-color: #e8e8e8;
}
`}</style>
</div>
);
};
|
000haoji/deep-student
| 27,511 |
src/components/TemplateManagementPage.tsx
|
import React, { useState, useEffect } from 'react';
import { CustomAnkiTemplate, CreateTemplateRequest, FieldExtractionRule } from '../types';
import { templateManager } from '../data/ankiTemplates';
import { IframePreview, renderCardPreview } from './SharedPreview';
import './TemplateManagementPage.css';
interface TemplateManagementPageProps {
isSelectingMode?: boolean;
onTemplateSelected?: (template: CustomAnkiTemplate) => void;
onCancel?: () => void;
}
const TemplateManagementPage: React.FC<TemplateManagementPageProps> = ({
isSelectingMode = false,
onTemplateSelected,
onCancel
}) => {
const [templates, setTemplates] = useState<CustomAnkiTemplate[]>([]);
const [activeTab, setActiveTab] = useState<'browse' | 'edit' | 'create'>('browse');
const [selectedTemplate, setSelectedTemplate] = useState<CustomAnkiTemplate | null>(null);
const [editingTemplate, setEditingTemplate] = useState<CustomAnkiTemplate | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [searchTerm, setSearchTerm] = useState('');
const [defaultTemplateId, setDefaultTemplateId] = useState<string | null>(null);
// 加载模板
useEffect(() => {
loadTemplates();
loadDefaultTemplateId();
// 订阅模板变化
const unsubscribe = templateManager.subscribe(setTemplates);
return unsubscribe;
}, []);
const loadDefaultTemplateId = async () => {
try {
await templateManager.loadUserDefaultTemplate();
setDefaultTemplateId(templateManager.getDefaultTemplateId());
} catch (err) {
console.warn('Failed to load default template ID:', err);
}
};
const loadTemplates = async () => {
setIsLoading(true);
try {
await templateManager.refresh();
setTemplates(templateManager.getAllTemplates());
} catch (err) {
setError(`加载模板失败: ${err}`);
} finally {
setIsLoading(false);
}
};
// 过滤模板
const filteredTemplates = templates.filter(template =>
template.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
template.description.toLowerCase().includes(searchTerm.toLowerCase())
);
// 选择模板
const handleSelectTemplate = (template: CustomAnkiTemplate) => {
setSelectedTemplate(template);
};
// 设置默认模板
const handleSetDefaultTemplate = async (template: CustomAnkiTemplate) => {
try {
await templateManager.setDefaultTemplate(template.id);
setDefaultTemplateId(template.id); // 立即更新本地状态
setError(null);
console.log(`✅ 已将"${template.name}"设置为默认模板`);
} catch (err) {
setError(`设置默认模板失败: ${err}`);
}
};
// 编辑模板
const handleEditTemplate = (template: CustomAnkiTemplate) => {
setEditingTemplate({ ...template });
setActiveTab('edit');
};
// 复制模板
const handleDuplicateTemplate = (template: CustomAnkiTemplate) => {
const duplicated: CustomAnkiTemplate = {
...template,
id: `${template.id}-copy-${Date.now()}`,
name: `${template.name} - 副本`,
author: '用户创建',
is_built_in: false,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
};
setEditingTemplate(duplicated);
setActiveTab('create');
};
// 使用统一的预览渲染函数
const renderTemplatePreview = (template: string, templateData: CustomAnkiTemplate) => {
return renderCardPreview(template, templateData);
};
// 删除模板
const handleDeleteTemplate = async (template: CustomAnkiTemplate) => {
if (template.is_built_in) {
setError('不能删除内置模板');
return;
}
if (!confirm(`确定要删除模板 "${template.name}" 吗?此操作不可撤销。`)) {
return;
}
try {
await templateManager.deleteTemplate(template.id);
setError(null);
} catch (err) {
setError(`删除模板失败: ${err}`);
}
};
return (
<>
{/* 页面头部 */}
<div className={`page-header ${isSelectingMode ? 'selecting-mode' : 'management-mode'}`}>
<div className="header-content">
<div className="header-main">
{isSelectingMode && onCancel && (
<button className="back-button" onClick={onCancel}>
<span className="back-icon">←</span>
返回
</button>
)}
<div className="title-section">
<h1 className="page-title">
<svg style={{ width: '32px', height: '32px', marginRight: '12px', color: '#667eea' }} fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
<path d="M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z" />
<circle cx="13.5" cy="6.5" r=".5" fill="currentColor" />
<circle cx="17.5" cy="10.5" r=".5" fill="currentColor" />
<circle cx="6.5" cy="12.5" r=".5" fill="currentColor" />
<circle cx="8.5" cy="7.5" r=".5" fill="currentColor" />
</svg>
{isSelectingMode ? '选择模板' : '模板管理'}
</h1>
<div className={`mode-indicator ${isSelectingMode ? 'selecting' : 'management'}`}>
<span className="mode-icon">{isSelectingMode ? '🎯' : '⚙️'}</span>
<span className="mode-text">
{isSelectingMode ? '选择模式' : '管理模式'}
</span>
</div>
</div>
</div>
<p className="page-description">
{isSelectingMode
? '请选择一个模板用于生成ANKI卡片,点击"使用此模板"按钮完成选择'
: '管理和编辑ANKI卡片模板,自定义卡片样式和字段,创建符合需求的模板'
}
</p>
</div>
</div>
{/* 标签页导航 */}
{!isSelectingMode && (
<div className="page-tabs">
<button
className={`tab-button ${activeTab === 'browse' ? 'active' : ''}`}
onClick={() => setActiveTab('browse')}
>
<span className="tab-icon">📋</span>
浏览模板
</button>
<button
className={`tab-button ${activeTab === 'create' ? 'active' : ''}`}
onClick={() => setActiveTab('create')}
>
<span className="tab-icon">➕</span>
创建模板
</button>
{editingTemplate && (
<button
className={`tab-button ${activeTab === 'edit' ? 'active' : ''}`}
onClick={() => setActiveTab('edit')}
>
<span className="tab-icon">✏️</span>
编辑模板
</button>
)}
</div>
)}
{/* 错误提示 */}
{error && (
<div className="error-alert">
<div className="alert-content">
<span className="alert-icon">⚠️</span>
<span className="alert-message">{error}</span>
<button className="alert-close" onClick={() => setError(null)}>✕</button>
</div>
</div>
)}
{/* 内容区域 */}
<div className="page-content">
{(isSelectingMode || activeTab === 'browse') && (
<TemplateBrowser
templates={filteredTemplates}
selectedTemplate={selectedTemplate}
searchTerm={searchTerm}
onSearchChange={setSearchTerm}
onSelectTemplate={handleSelectTemplate}
onEditTemplate={handleEditTemplate}
onDuplicateTemplate={handleDuplicateTemplate}
onDeleteTemplate={handleDeleteTemplate}
onSetDefaultTemplate={handleSetDefaultTemplate}
defaultTemplateId={defaultTemplateId}
isLoading={isLoading}
isSelectingMode={isSelectingMode}
onTemplateSelected={onTemplateSelected}
renderPreview={renderTemplatePreview}
/>
)}
{!isSelectingMode && activeTab === 'create' && (
<TemplateEditor
template={editingTemplate}
mode="create"
onSave={async (templateData) => {
try {
await templateManager.createTemplate(templateData);
setActiveTab('browse');
setEditingTemplate(null);
setError(null);
} catch (err) {
setError(`创建模板失败: ${err}`);
}
}}
onCancel={() => {
setActiveTab('browse');
setEditingTemplate(null);
}}
/>
)}
{!isSelectingMode && activeTab === 'edit' && editingTemplate && (
<TemplateEditor
template={editingTemplate}
mode="edit"
onSave={async (_templateData) => {
try {
// TODO: 实现模板更新
setActiveTab('browse');
setEditingTemplate(null);
setError(null);
} catch (err) {
setError(`更新模板失败: ${err}`);
}
}}
onCancel={() => {
setActiveTab('browse');
setEditingTemplate(null);
}}
/>
)}
</div>
</>
);
};
// 模板浏览器组件
interface TemplateBrowserProps {
templates: CustomAnkiTemplate[];
selectedTemplate: CustomAnkiTemplate | null;
searchTerm: string;
onSearchChange: (term: string) => void;
onSelectTemplate: (template: CustomAnkiTemplate) => void;
onEditTemplate: (template: CustomAnkiTemplate) => void;
onDuplicateTemplate: (template: CustomAnkiTemplate) => void;
onDeleteTemplate: (template: CustomAnkiTemplate) => void;
onSetDefaultTemplate: (template: CustomAnkiTemplate) => void;
defaultTemplateId: string | null;
isLoading: boolean;
isSelectingMode?: boolean;
onTemplateSelected?: (template: CustomAnkiTemplate) => void;
renderPreview: (template: string, templateData: CustomAnkiTemplate) => string;
}
const TemplateBrowser: React.FC<TemplateBrowserProps> = ({
templates,
selectedTemplate,
searchTerm,
onSearchChange,
onSelectTemplate,
onEditTemplate,
onDuplicateTemplate,
onDeleteTemplate,
onSetDefaultTemplate,
defaultTemplateId,
isLoading,
isSelectingMode = false,
onTemplateSelected,
renderPreview
}) => {
return (
<div className="template-browser">
{/* 搜索和工具栏 */}
<div className="browser-toolbar">
<div className="search-container">
<div className="search-input-wrapper">
<span className="search-icon">🔍</span>
<input
type="text"
placeholder="搜索模板名称或描述..."
value={searchTerm}
onChange={(e) => onSearchChange(e.target.value)}
className="search-input"
/>
</div>
</div>
<div className="toolbar-stats">
<span className="stats-text">共 {templates.length} 个模板</span>
{isSelectingMode && (
<div className="mode-hint">
<span className="hint-icon">💡</span>
<span className="hint-text">点击"使用此模板"选择模板</span>
</div>
)}
</div>
</div>
{/* 模板网格 */}
{isLoading ? (
<div className="loading-container">
<div className="loading-spinner"></div>
<span className="loading-text">加载模板中...</span>
</div>
) : (
<div className="templates-grid">
{templates.map(template => (
<TemplateCard
key={template.id}
template={template}
isSelected={selectedTemplate?.id === template.id}
onSelect={() => onSelectTemplate(template)}
onEdit={() => onEditTemplate(template)}
onDuplicate={() => onDuplicateTemplate(template)}
onDelete={() => onDeleteTemplate(template)}
onSetDefaultTemplate={() => onSetDefaultTemplate(template)}
defaultTemplateId={defaultTemplateId}
isSelectingMode={isSelectingMode}
onTemplateSelected={onTemplateSelected}
renderPreview={renderPreview}
/>
))}
</div>
)}
{templates.length === 0 && !isLoading && (
<div className="empty-state">
<div className="empty-icon">📝</div>
<h3 className="empty-title">没有找到模板</h3>
<p className="empty-description">试试调整搜索条件,或创建一个新模板。</p>
</div>
)}
</div>
);
};
// 模板卡片组件
interface TemplateCardProps {
template: CustomAnkiTemplate;
isSelected: boolean;
onSelect: () => void;
onEdit: () => void;
onDuplicate: () => void;
onDelete: () => void;
onSetDefaultTemplate: () => void;
defaultTemplateId: string | null;
isSelectingMode?: boolean;
onTemplateSelected?: (template: CustomAnkiTemplate) => void;
renderPreview: (template: string, templateData: CustomAnkiTemplate) => string;
}
const TemplateCard: React.FC<TemplateCardProps> = ({
template,
isSelected,
onSelect,
onEdit,
onDuplicate,
onDelete,
onSetDefaultTemplate,
defaultTemplateId,
isSelectingMode = false,
onTemplateSelected,
renderPreview
}) => {
// 检查是否为默认模板
const isDefault = defaultTemplateId === template.id;
return (
<div className={`template-card template-card-${template.id.replace(/[^a-zA-Z0-9]/g, '_')} ${isSelected ? 'selected' : ''} ${!template.is_active ? 'inactive' : ''} ${isSelectingMode ? 'selecting-mode' : 'management-mode'} ${isDefault ? 'default-template' : ''}`}>
{/* 卡片头部 */}
<div className="card-header">
<h4 className="template-name">{template.name}</h4>
<div className="template-badges">
{isDefault && <span className="badge default">默认</span>}
{template.is_built_in && <span className="badge built-in">内置</span>}
{!template.is_active && <span className="badge inactive">停用</span>}
<span className="badge version">v{template.version}</span>
</div>
</div>
{/* 预览区域 */}
<div className="card-preview">
<div className="preview-section">
<div className="preview-label">正面</div>
<div className="preview-content">
<IframePreview
htmlContent={renderPreview(template.front_template || template.preview_front || '', template)}
cssContent={template.css_style || ''}
/>
</div>
</div>
<div className="preview-section">
<div className="preview-label">背面</div>
<div className="preview-content">
<IframePreview
htmlContent={renderPreview(template.back_template || template.preview_back || '', template)}
cssContent={template.css_style || ''}
/>
</div>
</div>
</div>
{/* 卡片信息 */}
<div className="card-info">
<p className="template-description">{template.description}</p>
<div className="template-meta">
<span className="meta-item">
<span className="meta-icon">👤</span>
{template.author || '未知'}
</span>
<span className="meta-item">
<span className="meta-icon">📝</span>
{template.fields.length} 个字段
</span>
</div>
<div className="template-fields">
{template.fields.slice(0, 3).map(field => (
<span key={field} className="field-tag">{field}</span>
))}
{template.fields.length > 3 && (
<span className="field-tag more">+{template.fields.length - 3}</span>
)}
</div>
</div>
{/* 模式提示 */}
{isSelectingMode && (
<div className="mode-banner">
<span className="banner-icon">🎯</span>
<span className="banner-text">点击下方按钮选择此模板</span>
</div>
)}
{/* 操作按钮 */}
<div className="card-actions">
{isSelectingMode ? (
<button
className="btn-select primary"
onClick={() => {
console.log('🎯 点击使用模板:', template.name, template);
console.log('🔧 onTemplateSelected回调:', onTemplateSelected);
if (onTemplateSelected) {
onTemplateSelected(template);
} else {
console.error('❌ onTemplateSelected回调函数不存在');
}
}}
>
<span className="btn-icon">✨</span>
使用此模板
</button>
) : (
<>
<button
className={`btn-select ${isDefault ? 'default' : ''}`}
onClick={isDefault ? undefined : onSetDefaultTemplate}
disabled={isDefault}
>
{isDefault ? '⭐ 默认模板' : '设为默认'}
</button>
<div className="action-buttons">
<button className="action-btn" onClick={onEdit} title="编辑">
<span>✏️</span>
</button>
<button className="action-btn" onClick={onDuplicate} title="复制">
<span>📋</span>
</button>
{!template.is_built_in && (
<button className="action-btn danger" onClick={onDelete} title="删除">
<span>🗑️</span>
</button>
)}
</div>
</>
)}
</div>
</div>
);
};
// 模板编辑器组件
interface TemplateEditorProps {
template: CustomAnkiTemplate | null;
mode: 'create' | 'edit';
onSave: (templateData: CreateTemplateRequest) => Promise<void>;
onCancel: () => void;
}
const TemplateEditor: React.FC<TemplateEditorProps> = ({
template,
mode,
onSave,
onCancel
}) => {
const [formData, setFormData] = useState({
name: template?.name || '',
description: template?.description || '',
author: template?.author || '',
preview_front: template?.preview_front || '',
preview_back: template?.preview_back || '',
note_type: template?.note_type || 'Basic',
fields: template?.fields.join(',') || 'Front,Back,Notes',
generation_prompt: template?.generation_prompt || '',
front_template: template?.front_template || '<div class="card">' + '{{Front}}' + '</div>',
back_template: template?.back_template || '<div class="card">' + '{{Front}}' + '<hr>' + '{{Back}}' + '</div>',
css_style: template?.css_style || '.card { padding: 20px; background: white; border-radius: 8px; }'
});
const [isSubmitting, setIsSubmitting] = useState(false);
const [activeEditorTab, setActiveEditorTab] = useState<'basic' | 'templates' | 'styles' | 'advanced'>('basic');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsSubmitting(true);
try {
const fields = formData.fields.split(',').map(f => f.trim()).filter(f => f);
const fieldExtractionRules: Record<string, FieldExtractionRule> = {};
fields.forEach(field => {
fieldExtractionRules[field] = {
field_type: field.toLowerCase() === 'tags' ? 'Array' : 'Text',
is_required: field.toLowerCase() === 'front' || field.toLowerCase() === 'back',
default_value: field.toLowerCase() === 'tags' ? '[]' : '',
description: `${field} 字段`
};
});
const templateData: CreateTemplateRequest = {
name: formData.name,
description: formData.description,
author: formData.author || undefined,
preview_front: formData.preview_front,
preview_back: formData.preview_back,
note_type: formData.note_type,
fields,
generation_prompt: formData.generation_prompt,
front_template: formData.front_template,
back_template: formData.back_template,
css_style: formData.css_style,
field_extraction_rules: fieldExtractionRules
};
await onSave(templateData);
} finally {
setIsSubmitting(false);
}
};
return (
<div className="template-editor">
<div className="editor-header">
<h3 className="editor-title">{mode === 'create' ? '创建新模板' : '编辑模板'}</h3>
</div>
{/* 编辑器标签页 */}
<div className="editor-tabs">
<button
className={`editor-tab ${activeEditorTab === 'basic' ? 'active' : ''}`}
onClick={() => setActiveEditorTab('basic')}
>
<span className="tab-icon">📝</span>
基本信息
</button>
<button
className={`editor-tab ${activeEditorTab === 'templates' ? 'active' : ''}`}
onClick={() => setActiveEditorTab('templates')}
>
<span className="tab-icon">🎨</span>
模板代码
</button>
<button
className={`editor-tab ${activeEditorTab === 'styles' ? 'active' : ''}`}
onClick={() => setActiveEditorTab('styles')}
>
<span className="tab-icon">💄</span>
样式设计
</button>
<button
className={`editor-tab ${activeEditorTab === 'advanced' ? 'active' : ''}`}
onClick={() => setActiveEditorTab('advanced')}
>
<span className="tab-icon">⚙️</span>
高级设置
</button>
</div>
<form onSubmit={handleSubmit} className="editor-form">
{/* 基本信息标签页 */}
{activeEditorTab === 'basic' && (
<div className="editor-section">
<div className="form-grid">
<div className="form-group">
<label className="form-label">模板名称 *</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData({...formData, name: e.target.value})}
required
className="form-input"
placeholder="请输入模板名称"
/>
</div>
<div className="form-group">
<label className="form-label">作者</label>
<input
type="text"
value={formData.author}
onChange={(e) => setFormData({...formData, author: e.target.value})}
className="form-input"
placeholder="可选"
/>
</div>
<div className="form-group full-width">
<label className="form-label">描述</label>
<textarea
value={formData.description}
onChange={(e) => setFormData({...formData, description: e.target.value})}
className="form-textarea"
rows={3}
placeholder="请描述这个模板的用途和特点..."
/>
</div>
<div className="form-group">
<label className="form-label">笔记类型</label>
<input
type="text"
value={formData.note_type}
onChange={(e) => setFormData({...formData, note_type: e.target.value})}
className="form-input"
placeholder="Basic"
/>
</div>
<div className="form-group">
<label className="form-label">字段列表 *</label>
<input
type="text"
value={formData.fields}
onChange={(e) => setFormData({...formData, fields: e.target.value})}
required
className="form-input"
placeholder="Front,Back,Notes"
/>
<small className="form-help">用逗号分隔,至少需要包含 Front 和 Back 字段</small>
</div>
<div className="form-group">
<label className="form-label">预览正面 *</label>
<input
type="text"
value={formData.preview_front}
onChange={(e) => setFormData({...formData, preview_front: e.target.value})}
required
className="form-input"
placeholder="示例问题"
/>
</div>
<div className="form-group">
<label className="form-label">预览背面 *</label>
<input
type="text"
value={formData.preview_back}
onChange={(e) => setFormData({...formData, preview_back: e.target.value})}
required
className="form-input"
placeholder="示例答案"
/>
</div>
</div>
</div>
)}
{/* 模板代码标签页 */}
{activeEditorTab === 'templates' && (
<div className="editor-section">
<div className="template-code-editor">
<div className="code-group">
<label className="form-label">正面模板 *</label>
<textarea
value={formData.front_template}
onChange={(e) => setFormData({...formData, front_template: e.target.value})}
required
className="code-textarea"
rows={8}
placeholder="<div class="card">{{Front}}</div>"
/>
<small className="form-help">使用 Mustache 语法,如 {`{{Front}}`}、{`{{Back}}`} 等</small>
</div>
<div className="code-group">
<label className="form-label">背面模板 *</label>
<textarea
value={formData.back_template}
onChange={(e) => setFormData({...formData, back_template: e.target.value})}
required
className="code-textarea"
rows={8}
placeholder="<div class="card">{{Front}}<hr>{{Back}}</div>"
/>
</div>
</div>
</div>
)}
{/* 样式设计标签页 */}
{activeEditorTab === 'styles' && (
<div className="editor-section">
<div className="styles-editor">
<label className="form-label">CSS 样式</label>
<textarea
value={formData.css_style}
onChange={(e) => setFormData({...formData, css_style: e.target.value})}
className="css-textarea"
rows={12}
placeholder=".card { padding: 20px; background: white; border-radius: 8px; }"
/>
<small className="form-help">自定义CSS样式来美化卡片外观</small>
</div>
</div>
)}
{/* 高级设置标签页 */}
{activeEditorTab === 'advanced' && (
<div className="editor-section">
<div className="advanced-settings">
<label className="form-label">AI生成提示词 *</label>
<textarea
value={formData.generation_prompt}
onChange={(e) => setFormData({...formData, generation_prompt: e.target.value})}
required
className="prompt-textarea"
rows={8}
placeholder="请输入AI生成卡片时使用的提示词..."
/>
<small className="form-help">指导AI如何生成符合此模板的卡片内容</small>
</div>
</div>
)}
{/* 操作按钮 */}
<div className="editor-actions">
<button
type="submit"
disabled={isSubmitting}
className="btn-primary"
>
{isSubmitting ? '保存中...' : mode === 'create' ? '创建模板' : '保存修改'}
</button>
<button
type="button"
onClick={onCancel}
className="btn-secondary"
>
取消
</button>
</div>
</form>
</div>
);
};
export default TemplateManagementPage;
|
000haoji/deep-student
| 17,018 |
src/components/Dashboard.tsx
|
import React, { useState, useEffect } from 'react';
import { TauriAPI } from '../utils/tauriApi';
import { BarChart3, Settings, AlertTriangle, FileText, Search, BookOpen, Tag, PieChart } from 'lucide-react';
interface DashboardProps {
onBack: () => void;
}
interface Statistics {
totalMistakes: number;
totalReviews: number;
subjectStats: Record<string, number>;
typeStats: Record<string, number>;
tagStats: Record<string, number>;
recentMistakes: any[];
}
export const Dashboard: React.FC<DashboardProps> = ({ onBack }) => {
const [stats, setStats] = useState<Statistics | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [debugMode, setDebugMode] = useState(false);
useEffect(() => {
const loadStatistics = async () => {
setLoading(true);
setError(null);
try {
console.log('开始加载统计数据...');
// 先尝试加载真实数据
const statistics = await TauriAPI.getStatistics();
console.log('统计数据加载成功:', statistics);
// 转换后端数据格式到前端格式
const formattedStats: Statistics = {
totalMistakes: statistics.total_mistakes || 0,
totalReviews: statistics.total_reviews || 0,
subjectStats: statistics.subject_stats || {},
typeStats: statistics.type_stats || {},
tagStats: statistics.tag_stats || {},
recentMistakes: statistics.recent_mistakes || []
};
setStats(formattedStats);
} catch (error) {
console.error('加载统计数据失败:', error);
setError(`加载统计数据失败: ${error}`);
} finally {
setLoading(false);
}
};
loadStatistics();
}, []);
// 简化的渲染逻辑,确保总是有内容显示
return (
<div style={{
width: '100%',
height: '100%',
overflow: 'auto',
background: '#f8fafc'
}}>
{/* 头部区域 - 统一白色样式 */}
<div style={{
background: 'white',
borderBottom: '1px solid #e5e7eb',
padding: '24px 32px',
position: 'relative'
}}>
<div style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
height: '4px',
background: 'linear-gradient(90deg, #667eea, #764ba2)'
}}></div>
<div style={{ position: 'relative', zIndex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
<svg style={{ width: '32px', height: '32px', marginRight: '12px', color: '#667eea' }} fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
<path d="M3 3v16a2 2 0 0 0 2 2h16" />
<path d="M18 17V9" />
<path d="M13 17V5" />
<path d="M8 17v-3" />
</svg>
<h1 style={{ fontSize: '28px', fontWeight: '700', margin: 0, color: '#1f2937' }}>数据统计</h1>
</div>
<p style={{ fontSize: '16px', color: '#6b7280', margin: 0, lineHeight: '1.5' }}>
全面了解学习数据和进度分析,洞察知识掌握情况
</p>
{debugMode && (
<div style={{ marginTop: '24px' }}>
<button
onClick={() => setDebugMode(!debugMode)}
style={{
background: '#ef4444',
border: '1px solid #ef4444',
color: 'white',
padding: '12px 24px',
borderRadius: '12px',
fontSize: '16px',
fontWeight: '600',
cursor: 'pointer',
display: 'inline-flex',
alignItems: 'center',
gap: '8px',
transition: 'all 0.3s ease'
}}
onMouseOver={(e) => {
e.currentTarget.style.background = '#dc2626';
e.currentTarget.style.transform = 'translateY(-2px)';
e.currentTarget.style.boxShadow = '0 8px 25px rgba(239, 68, 68, 0.3)';
}}
onMouseOut={(e) => {
e.currentTarget.style.background = '#ef4444';
e.currentTarget.style.transform = 'translateY(0)';
e.currentTarget.style.boxShadow = 'none';
}}
>
<svg style={{ width: '20px', height: '20px' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4" />
</svg>
关闭调试
</button>
</div>
)}
{!debugMode && (
<div style={{ marginTop: '24px' }}>
<button
onClick={() => setDebugMode(!debugMode)}
style={{
background: '#667eea',
border: '1px solid #667eea',
color: 'white',
padding: '12px 24px',
borderRadius: '12px',
fontSize: '16px',
fontWeight: '600',
cursor: 'pointer',
display: 'inline-flex',
alignItems: 'center',
gap: '8px',
transition: 'all 0.3s ease'
}}
onMouseOver={(e) => {
e.currentTarget.style.background = '#5a67d8';
e.currentTarget.style.transform = 'translateY(-2px)';
e.currentTarget.style.boxShadow = '0 8px 25px rgba(102, 126, 234, 0.3)';
}}
onMouseOut={(e) => {
e.currentTarget.style.background = '#667eea';
e.currentTarget.style.transform = 'translateY(0)';
e.currentTarget.style.boxShadow = 'none';
}}
>
<svg style={{ width: '20px', height: '20px' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4" />
</svg>
开启调试
</button>
</div>
)}
</div>
</div>
<div className="dashboard-content" style={{ padding: '24px', background: 'transparent' }}>
{debugMode && (
<div style={{
backgroundColor: 'rgba(255, 255, 255, 0.7)',
padding: '1rem',
borderRadius: '12px',
marginBottom: '2rem',
border: '1px solid rgba(255, 255, 255, 0.2)',
backdropFilter: 'blur(10px)'
}}>
<h3 style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Settings size={20} />
调试信息
</h3>
<p><strong>加载状态:</strong> {loading ? '加载中' : '已完成'}</p>
<p><strong>错误状态:</strong> {error || '无错误'}</p>
<p><strong>数据状态:</strong> {stats ? '有数据' : '无数据'}</p>
<p><strong>组件渲染:</strong> 正常</p>
<div style={{ marginTop: '1rem' }}>
<button
onClick={async () => {
try {
console.log('手动测试API调用...');
const result = await TauriAPI.getStatistics();
console.log('手动测试结果:', result);
alert('API调用成功,请查看控制台日志');
} catch (err) {
console.error('手动测试失败:', err);
alert(`API调用失败: ${err}`);
}
}}
style={{
padding: '8px 16px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
marginRight: '8px'
}}
>
测试API
</button>
<button
onClick={() => {
setError(null);
setLoading(true);
window.location.reload();
}}
style={{
padding: '8px 16px',
backgroundColor: '#28a745',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
重新加载
</button>
</div>
</div>
)}
{loading ? (
<div style={{
textAlign: 'center',
padding: '4rem',
fontSize: '18px',
color: '#666'
}}>
<div style={{ fontSize: '48px', marginBottom: '16px', display: 'flex', justifyContent: 'center' }}>
<BarChart3 size={48} color="#667eea" />
</div>
<div>加载统计数据中...</div>
</div>
) : error && !stats ? (
<div style={{
textAlign: 'center',
padding: '4rem',
color: '#dc3545',
backgroundColor: '#f8d7da',
border: '1px solid #f5c6cb',
borderRadius: '8px'
}}>
<div style={{ fontSize: '48px', marginBottom: '16px', display: 'flex', justifyContent: 'center' }}>
<AlertTriangle size={48} color="#dc3545" />
</div>
<div style={{ fontSize: '18px', marginBottom: '8px' }}>加载统计数据失败</div>
<div style={{ fontSize: '14px', color: '#721c24' }}>{error}</div>
</div>
) : (
<div>
{/* 总览卡片 */}
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
gap: '1rem',
marginBottom: '2rem'
}}>
<div style={{
backgroundColor: 'white',
padding: '1.5rem',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
display: 'flex',
alignItems: 'center',
gap: '1rem'
}}>
<div style={{ fontSize: '2rem', display: 'flex', alignItems: 'center' }}>
<FileText size={32} color="#667eea" />
</div>
<div>
<div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#333' }}>
{stats?.totalMistakes || 0}
</div>
<div style={{ color: '#666' }}>总错题数</div>
</div>
</div>
<div style={{
backgroundColor: 'white',
padding: '1.5rem',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
display: 'flex',
alignItems: 'center',
gap: '1rem'
}}>
<div style={{ fontSize: '2rem', display: 'flex', alignItems: 'center' }}>
<Search size={32} color="#28a745" />
</div>
<div>
<div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#333' }}>
{stats?.totalReviews || 0}
</div>
<div style={{ color: '#666' }}>回顾分析次数</div>
</div>
</div>
<div style={{
backgroundColor: 'white',
padding: '1.5rem',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
display: 'flex',
alignItems: 'center',
gap: '1rem'
}}>
<div style={{ fontSize: '2rem', display: 'flex', alignItems: 'center' }}>
<BookOpen size={32} color="#ffc107" />
</div>
<div>
<div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#333' }}>
{Object.keys(stats?.subjectStats || {}).length}
</div>
<div style={{ color: '#666' }}>涉及科目</div>
</div>
</div>
<div style={{
backgroundColor: 'white',
padding: '1.5rem',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
display: 'flex',
alignItems: 'center',
gap: '1rem'
}}>
<div style={{ fontSize: '2rem', display: 'flex', alignItems: 'center' }}>
<Tag size={32} color="#6f42c1" />
</div>
<div>
<div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#333' }}>
{Object.keys(stats?.tagStats || {}).length}
</div>
<div style={{ color: '#666' }}>知识点标签</div>
</div>
</div>
</div>
{/* 详细统计 */}
{stats && (stats.totalMistakes > 0 || Object.keys(stats.subjectStats).length > 0) ? (
<div style={{ display: 'grid', gap: '2rem' }}>
{/* 科目分布 */}
{Object.keys(stats.subjectStats).length > 0 && (
<div style={{ backgroundColor: 'white', padding: '1.5rem', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)' }}>
<h3 style={{ marginBottom: '1rem', display: 'flex', alignItems: 'center', gap: '8px' }}>
<BookOpen size={20} />
科目分布
</h3>
<div>
{Object.entries(stats.subjectStats).map(([subject, count]) => (
<div key={subject} style={{ display: 'flex', alignItems: 'center', marginBottom: '0.5rem' }}>
<div style={{ minWidth: '80px' }}>{subject}</div>
<div style={{ flex: 1, backgroundColor: '#f0f0f0', height: '20px', borderRadius: '10px', margin: '0 1rem' }}>
<div style={{
width: `${stats.totalMistakes > 0 ? (count / stats.totalMistakes) * 100 : 0}%`,
height: '100%',
backgroundColor: '#007bff',
borderRadius: '10px'
}} />
</div>
<div style={{ minWidth: '30px', textAlign: 'right' }}>{count}</div>
</div>
))}
</div>
</div>
)}
{/* 题目类型分布 */}
{Object.keys(stats.typeStats).length > 0 && (
<div style={{ backgroundColor: 'white', padding: '1.5rem', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)' }}>
<h3 style={{ marginBottom: '1rem', display: 'flex', alignItems: 'center', gap: '8px' }}>
<PieChart size={20} />
题目类型分布
</h3>
<div>
{Object.entries(stats.typeStats).map(([type, count]) => (
<div key={type} style={{ display: 'flex', alignItems: 'center', marginBottom: '0.5rem' }}>
<div style={{ minWidth: '120px' }}>{type}</div>
<div style={{ flex: 1, backgroundColor: '#f0f0f0', height: '20px', borderRadius: '10px', margin: '0 1rem' }}>
<div style={{
width: `${stats.totalMistakes > 0 ? (count / stats.totalMistakes) * 100 : 0}%`,
height: '100%',
backgroundColor: '#28a745',
borderRadius: '10px'
}} />
</div>
<div style={{ minWidth: '30px', textAlign: 'right' }}>{count}</div>
</div>
))}
</div>
</div>
)}
</div>
) : (
<div style={{
textAlign: 'center',
padding: '4rem',
backgroundColor: 'white',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
}}>
<div style={{ fontSize: '48px', marginBottom: '16px', display: 'flex', justifyContent: 'center' }}>
<BarChart3 size={48} color="#667eea" />
</div>
<h3 style={{ marginBottom: '8px', color: '#333' }}>暂无数据</h3>
<p style={{ color: '#666' }}>开始分析错题后,这里将显示详细的统计信息</p>
</div>
)}
</div>
)}
</div>
</div>
);
};
|
0000cd/wolf-set
| 5,877 |
readme.md
|
## 一、简介
Bluf 是一款**慵懒**的瀑布流网址导航 Hugo 主题,源于 Wolf Set([狼集](https://ws.0000cd.com/)) 导航的实践。
与传统“规整”的网址导航相比,**自适应瀑布流**的 bluf 要随性得多,长短随意,插图随心。还有标签或颜色**筛选**、**深色**模式、网站统计、访客问候等贴心功能,更支持**多链接、多图画廊**等模式。
一切只需 YAML 轻松配置。

## 二、安装
### 2.1 快速上手
本教程基于“无需修改代码”的难度,几乎无需付费,只需三步在 [狼集](https://ws.0000cd.com/) 内容的基础上有一个属于自己的网址导航。
#### 步骤 0:准备
1. 确保你已注册 Github 与 Cloudflare 账号,我们将用此存储与发布网页。
2. (可选但推荐)准备一个你自己的域名,有助于提高国内的访问速度。
<details>
<summary>继续浏览安装步骤…</summary>
---
#### 步骤 1:复制仓库到你的 Github
1. 点击 [本页面](https://github.com/0000cd/wolf-set) 右上角的 fork 按钮,复制项目到你的 Github 仓库。
2. 记住你复制时的仓库名。(稍后会用到)
#### 步骤 2:修改网站的基础配置
1. 在你刚 fork 的仓库首页,点开 `hugo.toml` 文件(根目录)。
2. 根据文件中的注释,编辑文件,修改以下内容:
- 网址、网站名称、首页标题、SEO 信息、授权信息、网站统计等。
- 注意:如你还不确定网址,可先跳过,稍后记得修改。
- 注意:toml 格式,不要丢失两侧的英文引号`"`。
```toml
# hugo.toml 文件部分示例:
baseURL = "https://ws.0000cd.com/" #你的网址
languageCode = "zh-CN"
title = "狼牌网址导航 - 狼集 Wolf Set" #网站名称
theme = "bluf"
#……
```
#### 步骤 3:使用 Cloudflare Pages 发布网页
1. 打开 [Cloudflare Pages](https://pages.cloudflare.com/),点击创建 - Pages - 连接到 Git - Github,选择你刚记住仓库名的项目。
2. 点击开始设置,修改以下内容:
- 项目名称(注意:若没有你自己的域名,这将是你默认域名的一部分)
- 预设框架,选择 `Hugo` (无需修改其他默认设置)。
3. 点击保存并部署,通常会在一分钟内会完成,**但首次部署你还需再等 2~3 分钟**,才能点开预览链接在网上看到你的网页,请坐和放宽。
4. 修改并绑定域名:
- 如果你有自己的域名,请在项目内找到自定义域,按提示绑定域名。
- 如果你没有自己的域名,请记住 Cloudflare 提供的默认域名(如 xxx.pages.dev)。
- 确认之前 `hugo.toml` 的网址已完成修改。
---
#### 常见问题
- 访问异常:如你无法访问 Cloudflare 默认提供的域名,或访问速度过慢,请绑定你自己的域名。
- 部署失败:
- 如你部署失败,看一下部署日志,并检查你选对了仓库,以及 `hugo.toml` 内的格式。
- 如你用的不是 Cloudflare,而是 Vercel 或 Netlify 等平台部署失败,你可能需要在选择预设框架时,配置环境变量 hugo 版本为较新版本,如 `HUGO_VERSION = 0.117.0`。
### 2.2 Hugo 开始
如果你对 Hugo 有一定了解,可直接用我们自写的 Bluf 主题来构建你的网站。只需先复制 themes/bluf 到你的项目,并在 hugo 中设置 `theme = "bluf"`。
Bluf 主题代码已经过多次测试,可稳定上线使用,但部分代码仍在清理中,因此暂不提供详细教程。如有任何问题或建议,欢迎通过 Issues 提交反馈!我们期待你的参与。
</details>
## 三、使用
如果你是按上面的教程 Cloudflare 部署的,您只需编辑对应的文件,在保存后 Cloudflare 会自动部署更改,片刻后更新到网页上。只需留意 TOML 或 YAML 格式,就能规避常见错误。
但即使你熟悉 Hugo,也推荐浏览一下使用说明。因为与大多数 Hugo 内容在 content 不同,Bluf 更接近单页主题,其主要在 data 目录下。
### 3.1 导航卡片
#### 增删首页的导航卡片
请编辑 `data/cards.yaml`。该文件是 YAML 格式易于使用,如下:
```yaml
- title: Humane by Design # 卡片标题
hex: "#14151d" # (可选)卡片颜色,会自动颜色分类。注意引号
tags: # 卡片标签,会标签分类
- 网页
- 设计
- 想法
date: "2024/04" # (可选)卡片时间
description: 人性化的数字产品和服务指南。 # 卡片描述
links: https://humanebydesign.com/ #卡片链接
```
提示:在 Markdown 文章中…
- 插入 `{{< random >}}` 短码,可让该页面随机跳转所有导航网址。
- 插入 `{{< total >}}` 或 ` {{< total "tags" >}}` 短码,可统计所有或指定标签的导航卡片总数。如:`本站共 {{< total >}} 个有趣网址导航,和 {{< total "开源" >}} 个开源项目!`
<details>
<summary>继续浏览使用,如:导航卡片、导航栏、筛选、问候语、授权、个性化、SEO…</summary>
#### 导航卡片配置多条链接
如果上文的 `links`,需要多条链接,你还可以这样写:
```yaml
- title: Neal.fun
hex: "#ffc7c7"
tags:
- 网页
- 有趣
date: "2024/12"
description: 希望你有美好的一天… 游戏互动可视化等其他奇怪的东西。
links:
- name: 官网 #注意,第一条链接不会展示,而是作为卡片整体的链接
url: https://neal.fun/
- name: 设置密码?
url: https://neal.fun/password-game/
- name: 赞助
url: https://buymeacoffee.com/neal
```
#### 导航卡片头图、画廊模式
无需额外配置,只需将与卡片 `title` 名称一致的图片,放入 `assets/img` 文件夹下即可,如 `assets/img/Neal.fun.webp`。支持 jpg、png、gif、webp 格式,建议图片宽度大于 300px,但过大会影响加载速度。提示:可以获取网站的 `Open Graph` 用于插图。
请编辑 `hugo.toml`,先 `gallery = true` 开启画廊模式。之后在 `assets/gallery` 创建与卡片 `title` 名称一致的的文件夹(注意特殊符号),并放入多张图片(按文件名排序),再点击卡片头图就能进入画廊模式,浏览多张图片。适合像相册一样分享图片合集使用,如:
```markdown
- assets
- gallery
- Humane by Design
- a.jpg
- 2.webp
- Cat.gif
```
---
### 3.2 标签筛选与导航栏
#### 配置导航卡片标签
请编辑 `data/tag_classes.yaml`,将管理用于筛选的标签的映射关系:
```yaml
桌面:"desktop"
移动:"mobile"
网页:"web"
```
如你配置 `桌面:"desktop"`,在 `cards.yaml` 的 `tags` 只需输入“桌面”,就能按“desktop”筛选导航卡片。
特别的,由于颜色筛选是算法自动完成的,不建议修改颜色筛选的值。
#### 配置导航栏外链、筛选、标签
请编辑 `data/navbar.yaml`,分别在 `external_links`、`categories`、`hot_tags` 下配置外链、筛选、标签。
---
### 3.3 更多特色功能
#### 网站问候、庆祝撒花
请编辑 `hugo.toml`,会在访问首页时随机展示问候,为空不启用;也可为移动端单独配置问候,用于引导:
```toml
[params]
greetings = [
#……
"Ctrl+D 收藏本站 ⭐",
"点击【标签】,筛选内容 🔖",
"点击 ●,切换深浅配色 🐼",
] #访客随机问候,为空不启用
mobileGreetings = [
"推荐电脑访问,体验更佳 💻",
] #移动端访客随机问候,为空使用 greetings
```
输入喜欢的 emoji,会在用户清除筛选时庆祝撒花,感谢用户的访问,为空不启用:
```toml
confettiEmojis = [ '🥟', '🍜', '🍊', '🧧', '🧨', '🏮', '🎉', '🐺' ] # 清除筛选时撒花,为空不启用
```
#### 配置 CC 授权信息
请编辑 `hugo.toml` 的 `license`,会写入网站的 Meta 信息(游客不会直接看到)。
可进一步在 `layouts/partials/cc.html` 配置页脚的授权信息(只在文章页脚,不会显示在首页),如不需要可删除。
访问 [CC 授权](https://chooser-beta.creativecommons.org/) 选择授权协议,并生成页脚授权的代码。
#### 网站个性化、图标、配色
请在 `static` 下覆盖 `logo`、`favcion` 等文件修改图片,修改图标。推荐使用 [favicon.io](https://favicon.io/)。
请编辑 `hugo.toml`,修改强调色,点击导航栏的 ⚫ 切换深浅配色:
```toml
[params]
lightColor = "#0000cd" # 浅色强调色,推荐较深
darkColor = "#fafafa" # 深色强调色,推荐较浅
```
#### 优化 SEO、网站统计
请编辑 `hugo.toml` 优化 SEO,支持隐私友好的开源 [Umami](https://umami.is/) 统计。
如你使用 Cloudflare 部署,可在该项目下的指标,开启 Web Analytics 进行统计。
可在 `content/achrive` 下放置历史数据,辅助优化搜索的 SEO。
如需 Search Console 等平台验证网站所有权,请将验证文件放在 `static` 下。
</details>
---
## Bluf theme
[](https://sonarcloud.io/summary/new_code?id=0000cd_wolf-set)
Bluf 是一款简明扼要的**瀑布流**卡片式 Hugo 主题,非常适合脑暴、作品集、链接导航、等需要**简单分享**的场景。部分代码由 GPT-4o 与 Claude-3.5 AI 协助。
### 灵感
Blue + Wolf = Bluf
> BLUF (bottom line up front) is the practice of beginning a message with its key information (the "bottom line"). This provides the reader with the most important information first.
> BLUF(先行底行)是一种沟通方式,即在信息的开始部分先给出关键信息(即“底行”)。这样做可以让读者首先了解到最重要的信息。
## License
本项目基于 **[Hugo](https://gohugo.io/)** 框架,并采用自建的 **Bluf** 主题:
- `content` 与 `data` 目录下的内容遵循 **[CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh-hans)** 许可协议共享。
- **Bluf** 主题因集成 **[Isotope](https://isotope.metafizzy.co/license)**,遵守 **GPLv3** 许可协议。
- 画廊模式:[baguetteBox.js](https://github.com/feimosi/baguetteBox.js),MIT 协议。
- 庆祝撒花:[js-confetti](https://github.com/loonywizard/js-confetti),MIT 协议。
|
000haoji/deep-student
| 10,206 |
src/components/StreamingChatInterface.tsx
|
/**
* Streaming Chat Interface for AI SDK Analysis
*
* A simplified chat interface optimized for handling Tauri streaming events
* with proper thinking chain support and real-time rendering.
*/
import React, { useState, useImperativeHandle, useEffect, useRef } from 'react';
import { MessageWithThinking } from './MessageWithThinking';
import { MarkdownRenderer } from './MarkdownRenderer';
interface StreamingChatMessage {
id: string;
role: 'user' | 'assistant';
content: string;
thinking_content?: string;
timestamp: string;
rag_sources?: Array<{
document_id: string;
file_name: string;
chunk_text: string;
score: number;
chunk_index: number;
}>;
}
interface StreamingChatInterfaceProps {
messages: StreamingChatMessage[];
isStreaming: boolean;
enableChainOfThought?: boolean;
onSendMessage?: (message: string) => void;
className?: string;
streamingMode?: 'typewriter' | 'instant'; // 流式输出模式
}
export interface StreamingChatInterfaceRef {
sendMessage: (content: string) => void;
clearInput: () => void;
clearChat: () => void;
setMessages: (messages: StreamingChatMessage[]) => void;
}
export const StreamingChatInterface = React.forwardRef<StreamingChatInterfaceRef, StreamingChatInterfaceProps>(({
messages,
isStreaming,
enableChainOfThought = true,
onSendMessage,
className = '',
streamingMode = 'typewriter' // 默认使用打字机模式
}, ref) => {
const [input, setInput] = useState('');
const [displayedContent, setDisplayedContent] = useState<{[key: string]: string}>({});
const [isFullscreen, setIsFullscreen] = useState(false);
const [isAnimating, setIsAnimating] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null);
const typewriterTimeouts = useRef<{[key: string]: number}>({});
const containerRef = useRef<HTMLDivElement>(null);
// Handle form submission
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!input.trim() || isStreaming) return;
if (onSendMessage) {
onSendMessage(input);
}
setInput('');
};
// Handle keyboard shortcuts
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSubmit(e as any);
}
// ESC键退出全屏
if (e.key === 'Escape' && isFullscreen) {
handleToggleFullscreen();
}
};
// 全屏切换功能
const handleToggleFullscreen = () => {
if (isAnimating) return;
setIsAnimating(true);
if (isFullscreen) {
// 退出全屏
if (containerRef.current) {
containerRef.current.classList.add('collapsing');
containerRef.current.classList.remove('fullscreen');
}
setTimeout(() => {
setIsFullscreen(false);
setIsAnimating(false);
if (containerRef.current) {
containerRef.current.classList.remove('collapsing');
}
}, 500);
} else {
// 进入全屏
setIsFullscreen(true);
if (containerRef.current) {
containerRef.current.classList.add('expanding');
}
setTimeout(() => {
if (containerRef.current) {
containerRef.current.classList.remove('expanding');
containerRef.current.classList.add('fullscreen');
}
setIsAnimating(false);
}, 500);
}
};
// 处理全屏快捷键
useEffect(() => {
const handleKeyPress = (e: KeyboardEvent) => {
// F11或Ctrl+Enter切换全屏
if (e.key === 'F11' || (e.ctrlKey && e.key === 'Enter')) {
e.preventDefault();
handleToggleFullscreen();
}
};
if (isFullscreen) {
document.addEventListener('keydown', handleKeyPress);
return () => document.removeEventListener('keydown', handleKeyPress);
}
}, [isFullscreen]);
// 打字机效果的流式内容显示
useEffect(() => {
if (streamingMode === 'instant') return;
messages.forEach((message) => {
if (message.role === 'assistant' && message.content) {
const messageId = message.id;
const fullContent = message.content;
const currentDisplayed = displayedContent[messageId] || '';
// Only start typewriter if content has changed and is longer
if (fullContent !== currentDisplayed && fullContent.length > currentDisplayed.length) {
// Clear existing timeout for this message
if (typewriterTimeouts.current[messageId]) {
clearTimeout(typewriterTimeouts.current[messageId]);
}
// Start typewriter from current position
let currentIndex = currentDisplayed.length;
const typeNextChar = () => {
if (currentIndex < fullContent.length) {
const nextContent = fullContent.substring(0, currentIndex + 1);
setDisplayedContent(prev => ({
...prev,
[messageId]: nextContent
}));
currentIndex++;
// 根据字符类型调整显示速度
const char = fullContent[currentIndex - 1];
let delay = 25; // Base typing speed
if (char === ' ') delay = 8;
else if (char === '.' || char === '!' || char === '?') delay = 150;
else if (char === ',' || char === ';' || char === ':') delay = 80;
else if (char === '\n') delay = 100;
typewriterTimeouts.current[messageId] = setTimeout(typeNextChar, delay);
}
};
// Start typing animation
if (currentIndex < fullContent.length) {
typeNextChar();
}
}
}
});
return () => {
// Cleanup timeouts
Object.values(typewriterTimeouts.current).forEach(timeout => clearTimeout(timeout));
};
}, [messages, streamingMode, displayedContent]);
// 自动滚动到底部
useEffect(() => {
if (messagesEndRef.current) {
messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
}
}, [messages, displayedContent]);
// Get content for display (original or typewriter)
const getDisplayContent = (message: StreamingChatMessage) => {
if (message.role === 'user' || streamingMode === 'instant') {
return message.content;
}
return displayedContent[message.id] || '';
};
// Expose methods to parent component
useImperativeHandle(ref, () => ({
sendMessage: (content: string) => {
if (onSendMessage) {
onSendMessage(content);
}
},
clearInput: () => {
setInput('');
},
clearChat: () => {
setDisplayedContent({});
Object.values(typewriterTimeouts.current).forEach(timeout => clearTimeout(timeout));
typewriterTimeouts.current = {};
},
setMessages: (_newMessages: StreamingChatMessage[]) => {
// Reset displayed content for new messages
setDisplayedContent({});
}
}));
return (
<div
ref={containerRef}
className={`streaming-chat-interface ${className} ${isFullscreen ? 'fullscreen' : ''}`}
>
{/* 全屏工具栏 */}
<div className="chat-toolbar">
<div className="toolbar-left">
<span className="chat-title">💬 AI智能对话</span>
</div>
<div className="toolbar-right">
<button
onClick={handleToggleFullscreen}
disabled={isAnimating}
className="fullscreen-toggle-btn"
title={isFullscreen ? "退出全屏 (ESC)" : "进入全屏 (F11)"}
>
{isFullscreen ? '⤋' : '⤢'}
</button>
</div>
</div>
{/* Chat Messages */}
<div className="chat-messages">
{messages.map((message, index) => (
<div key={message.id} className={`message-wrapper ${message.role}`}>
<div className="message-header">
<span className="role">{message.role === 'user' ? '用户' : 'AI助手'}</span>
<span className="timestamp">
{new Date(message.timestamp).toLocaleTimeString()}
</span>
</div>
{message.role === 'assistant' ? (
<MessageWithThinking
content={getDisplayContent(message)}
thinkingContent={message.thinking_content}
isStreaming={isStreaming && index === messages.length - 1}
role="assistant"
timestamp={message.timestamp}
ragSources={message.rag_sources}
/>
) : (
<div className="user-message-content">
<MarkdownRenderer content={message.content} />
</div>
)}
</div>
))}
{/* Streaming indicator */}
{isStreaming && (
<div className="streaming-indicator">
<div className="typing-dots">
<span></span>
<span></span>
<span></span>
</div>
<span className="streaming-text">AI正在思考和回答中...</span>
</div>
)}
{/* Auto-scroll anchor */}
<div ref={messagesEndRef} />
</div>
{/* Chat Input */}
<form onSubmit={handleSubmit} className="chat-input-form">
<div className="input-container">
<textarea
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="继续提问..."
disabled={isStreaming}
rows={3}
className="chat-input"
/>
<div className="input-actions">
<button
type="submit"
disabled={!input.trim() || isStreaming}
className="send-button"
>
{isStreaming ? '回答中...' : '发送'}
</button>
</div>
</div>
</form>
{/* Chat Info */}
<div className="chat-info">
<div className="chat-stats">
<span>消息数: {messages.length}</span>
{isStreaming && <span className="streaming-status">🔄 流式回答中</span>}
{enableChainOfThought && <span className="thinking-status">🧠 显示思维过程</span>}
</div>
</div>
</div>
);
});
StreamingChatInterface.displayName = 'StreamingChatInterface';
|
0000cd/wolf-set
| 1,484 |
hugo.toml
|
baseURL = "https://ws.0000cd.com/" #你的网址,以斜杠 / 结尾
languageCode = "zh-CN"
title = "狼牌网址导航 - 狼集 Wolf Set" #网站名称
theme = "bluf"
[params]
pagename = "狼集 Wolf Set" #首页标题
description = " 狼集 Wolf Set, 源自“狼牌工作网址导航”,集设计、Markdown、软件、安全、办公必备网址于一体,All in One 最佳选择。" #SEO,你的网站描述
keywords = [
"狼集",
"Wolf Set",
"狼牌",
"狼牌工作网址导航",
"网址大全",
"网址之家",
"网址导航",
"设计工具",
"Markdown资源",
"办公软件",
"安全工具",
"All in One"
] #SEO,网站关键词
author = "0000CD.COM & 逊狼" #SEO,网站作者
alias ="狼牌网址导航" #SEO,可删除
license="CC BY-NC 4.0" #网站授权信息,https://chooser-beta.creativecommons.org/
enableUmami = true #umami 统计相关,没有请 false,https://umami.is/
UmamiLink = "https://eu.umami.is/script.js"
UmamiID = "02cc419c-d758-4a4f-a9bd-1e442b1f8435"
lightColor = "#0000cd" # 浅色强调色,推荐较深
darkColor = "#fafafa" # 深色强调色,推荐较浅
gallery = true #启用画廊模式
greetings = [
"你好朋友,你好世界 🎉",
"嗷~ 记得早点休息 🌛",
"互联网第一条消息是 LO 💡",
"互联网重量或是一颗草莓 💡",
"互联网第一个表情是:-) 💡",
"Ctrl+F 搜索本站 🔎",
"Ctrl+D 收藏本站 ⭐",
"点击【标签】,筛选内容 🔖",
"点击 ●,切换深浅配色 🐼",
] #访客随机问候,为空不启用
mobileGreetings = [
"推荐电脑访问,体验更佳 💻",
] #移动端访客随机问候,为空使用 greetings
confettiEmojis = [ '🥟', '🍜', '🍊', '🧧', '🧨', '🏮', '🎉', '🐺' ] # 清除筛选时撒花,为空不启用
[sitemap]
changefreq = "weekly"
priority = 0.5
filename = "sitemap.xml"
[outputs]
home = ["HTML", "RSS"]
[outputFormats.RSS]
mediatype = "application/rss+xml"
baseName = "feed"
[markup]
[markup.highlight]
style = "gruvbox"
[minify]
minifyOutput = true
|
000haoji/deep-student
| 48,374 |
src/components/GeminiAdapterTest.tsx
|
import React, { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
interface TestResult {
success: boolean;
message: string;
details?: any;
duration?: number;
}
interface ApiConfig {
id: string;
name: string;
apiKey: string;
baseUrl: string;
model: string;
isMultimodal: boolean;
isReasoning: boolean;
enabled: boolean;
modelAdapter: string;
maxOutputTokens: number;
temperature: number;
}
export const GeminiAdapterTest: React.FC = () => {
const [selectedConfig, setSelectedConfig] = useState<ApiConfig | null>(null);
const [apiConfigs, setApiConfigs] = useState<ApiConfig[]>([]);
const [testResults, setTestResults] = useState<Record<string, TestResult>>({});
const [isLoading, setIsLoading] = useState<Record<string, boolean>>({});
const [streamingContent, setStreamingContent] = useState('');
const [testPrompt, setTestPrompt] = useState('你好,请用中文简单介绍一下你自己。这是一个测试Gemini适配器的OpenAI兼容接口转换功能。');
const [imageBase64, setImageBase64] = useState<string>('');
const [imagePreview, setImagePreview] = useState<string>('');
const [currentLogPath, setCurrentLogPath] = useState<string>('');
const [allTestLogs, setAllTestLogs] = useState<string[]>([]);
useEffect(() => {
loadApiConfigs();
loadTestLogs();
}, []);
// 生成测试日志内容
const generateTestLog = (testType: string, config: ApiConfig, result: TestResult, additionalData?: any) => {
const timestamp = new Date().toISOString();
const logEntry = {
timestamp,
testType,
config: {
id: config.id,
name: config.name,
model: config.model,
baseUrl: config.baseUrl,
modelAdapter: config.modelAdapter,
isMultimodal: config.isMultimodal,
temperature: config.temperature,
maxOutputTokens: config.maxOutputTokens
},
testPrompt,
result: {
success: result.success,
message: result.message,
duration: result.duration,
details: result.details
},
additionalData: additionalData || {},
environment: {
userAgent: navigator.userAgent,
timestamp: timestamp,
testVersion: '1.0.0'
}
};
return JSON.stringify(logEntry, null, 2);
};
// 保存测试日志到文件
const saveTestLog = async (logContent: string, testType: string) => {
try {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const fileName = `gemini-adapter-test-${testType}-${timestamp}.log`;
// 使用 Tauri 的文件管理服务保存日志
await invoke('save_test_log', {
fileName,
content: logContent,
logType: 'gemini-adapter-test'
});
const logPath = `logs/gemini-adapter-test/${fileName}`;
setCurrentLogPath(logPath);
// 更新日志列表
setAllTestLogs(prev => [logPath, ...prev]);
console.log(`测试日志已保存: ${logPath}`);
return logPath;
} catch (error) {
console.error('保存测试日志失败:', error);
return null;
}
};
// 加载历史测试日志列表
const loadTestLogs = async () => {
try {
const logs = await invoke<string[]>('get_test_logs', {
logType: 'gemini-adapter-test'
});
setAllTestLogs(logs);
} catch (error) {
console.error('加载历史日志失败:', error);
}
};
const loadApiConfigs = async () => {
try {
const configs = await invoke<ApiConfig[]>('get_api_configurations');
const geminiConfigs = configs.filter(c => c.modelAdapter === 'google' && c.enabled);
setApiConfigs(geminiConfigs);
if (geminiConfigs.length > 0) {
setSelectedConfig(geminiConfigs[0]);
}
} catch (error) {
console.error('加载 API 配置失败:', error);
}
};
// 基础连接测试
const testBasicConnection = async () => {
if (!selectedConfig) return;
setIsLoading({ ...isLoading, basic: true });
const startTime = Date.now();
let testResult: TestResult;
try {
const result = await invoke<boolean>('test_api_connection', {
apiKey: selectedConfig.apiKey,
apiBase: selectedConfig.baseUrl,
model: selectedConfig.model
});
testResult = {
success: result,
message: result ? '连接成功!API 密钥和端点有效。' : '连接失败,请检查配置。',
duration: Date.now() - startTime,
details: { connectionResult: result }
};
setTestResults({
...testResults,
basic: testResult
});
} catch (error) {
const errorMessage = error instanceof Error ? error.message :
(typeof error === 'object' ? JSON.stringify(error) : String(error));
testResult = {
success: false,
message: `连接测试失败: ${errorMessage}`,
duration: Date.now() - startTime,
details: { error: errorMessage }
};
setTestResults({
...testResults,
basic: testResult
});
} finally {
setIsLoading({ ...isLoading, basic: false });
// 保存测试日志
if (selectedConfig) {
const logContent = generateTestLog('basic-connection', selectedConfig, testResult, {
testDescription: '基础连接测试 - 验证API密钥和端点有效性'
});
await saveTestLog(logContent, 'basic-connection');
}
}
};
// 非流式OpenAI兼容接口测试(使用流式接口收集完整响应)
const testNonStreamingChat = async () => {
if (!selectedConfig) return;
setIsLoading({ ...isLoading, nonStreaming: true });
const startTime = Date.now();
let testResult: TestResult;
let collectedContent = '';
try {
// 创建临时会话进行测试
const tempId = `gemini_non_stream_test_${Date.now()}`;
const streamEvent = `analysis_stream_${tempId}`;
const chatHistory = [{
role: 'user',
content: testPrompt,
timestamp: new Date().toISOString(),
}];
console.log('发送非流式测试请求(使用流式接口),使用适配器:', selectedConfig.modelAdapter);
console.log('聊天历史:', chatHistory);
// 使用流式接口但收集完整响应
const unlistenContent = await listen(streamEvent, (event: any) => {
console.log('收到非流式测试事件:', event.payload);
if (event.payload.content) {
collectedContent += event.payload.content;
}
if (event.payload.is_complete) {
testResult = {
success: true,
message: 'Gemini适配器非流式测试成功!OpenAI格式已正确转换为Gemini API调用。',
details: {
response: { message: collectedContent },
requestData: { tempId, chatHistory },
responseLength: collectedContent.length,
method: 'streaming_collected'
},
duration: Date.now() - startTime
};
setTestResults(prev => ({
...prev,
nonStreaming: testResult
}));
setIsLoading(prev => ({ ...prev, nonStreaming: false }));
// 保存测试日志
if (selectedConfig) {
const logContent = generateTestLog('non-streaming', selectedConfig, testResult, {
testDescription: '非流式OpenAI兼容接口测试 - 使用流式接口收集完整响应',
prompt: testPrompt,
collectedContent
});
saveTestLog(logContent, 'non-streaming');
}
}
});
const unlistenError = await listen('stream_error', (event: any) => {
console.error('非流式测试流式错误:', event.payload);
const errorMessage = typeof event.payload.error === 'object' ?
JSON.stringify(event.payload.error) : String(event.payload.error);
testResult = {
success: false,
message: `Gemini适配器非流式测试失败: ${errorMessage}`,
duration: Date.now() - startTime,
details: { error: errorMessage, collectedContent }
};
setTestResults(prev => ({
...prev,
nonStreaming: testResult
}));
setIsLoading(prev => ({ ...prev, nonStreaming: false }));
});
// 发起流式请求 - 使用 analyze_new_mistake_stream 创建临时会话并测试适配器
await invoke('analyze_new_mistake_stream', {
request: {
subject: "AI适配器测试",
question_image_files: [], // 非流式测试不需要图片
analysis_image_files: [],
user_question: testPrompt,
enable_step_by_step: false
}
});
// 设置超时清理
setTimeout(() => {
unlistenContent();
unlistenError();
}, 30000);
} catch (error) {
console.error('非流式测试失败:', error);
const errorMessage = error instanceof Error ? error.message :
(typeof error === 'object' ? JSON.stringify(error) : String(error));
testResult = {
success: false,
message: `Gemini适配器非流式测试失败: ${errorMessage}`,
duration: Date.now() - startTime,
details: { error: errorMessage, collectedContent }
};
setTestResults(prev => ({
...prev,
nonStreaming: testResult
}));
setIsLoading(prev => ({ ...prev, nonStreaming: false }));
// 保存失败的测试日志
if (selectedConfig) {
const logContent = generateTestLog('non-streaming', selectedConfig, testResult, {
testDescription: '非流式OpenAI兼容接口测试 - 异常失败',
prompt: testPrompt
});
await saveTestLog(logContent, 'non-streaming-exception');
}
}
};
// 流式OpenAI兼容接口测试
const testStreamingChat = async () => {
if (!selectedConfig) return;
setIsLoading({ ...isLoading, streaming: true });
setStreamingContent('');
const startTime = Date.now();
let testResult: TestResult;
let streamData: string[] = [];
try {
const tempId = `gemini_stream_test_${Date.now()}`;
const streamEvent = `analysis_stream_${tempId}`;
console.log('发送流式测试请求,使用适配器:', selectedConfig.modelAdapter);
// 设置流式事件监听
const unlistenContent = await listen(streamEvent, (event: any) => {
console.log('收到流式事件:', event.payload);
if (event.payload.content) {
streamData.push(event.payload.content);
setStreamingContent(prev => prev + event.payload.content);
}
if (event.payload.is_complete) {
testResult = {
success: true,
message: 'Gemini适配器流式测试成功!OpenAI格式已正确转换为Gemini流式API调用。',
duration: Date.now() - startTime,
details: {
streamChunks: streamData.length,
totalContent: streamData.join(''),
contentLength: streamData.join('').length,
averageChunkSize: streamData.length > 0 ? streamData.join('').length / streamData.length : 0
}
};
setTestResults(prev => ({
...prev,
streaming: testResult
}));
setIsLoading(prev => ({ ...prev, streaming: false }));
// 保存流式测试日志
if (selectedConfig) {
const logContent = generateTestLog('streaming', selectedConfig, testResult, {
testDescription: '流式OpenAI兼容接口测试 - 验证OpenAI流式格式转换为Gemini流式API调用',
prompt: testPrompt,
streamingData: {
chunks: streamData,
totalChunks: streamData.length
}
});
saveTestLog(logContent, 'streaming');
}
}
});
const unlistenError = await listen('stream_error', (event: any) => {
console.error('流式错误:', event.payload);
testResult = {
success: false,
message: `Gemini适配器流式测试错误: ${event.payload.error}`,
duration: Date.now() - startTime,
details: { error: event.payload.error, streamData }
};
setTestResults(prev => ({
...prev,
streaming: testResult
}));
setIsLoading(prev => ({ ...prev, streaming: false }));
// 保存失败的流式测试日志
if (selectedConfig) {
const logContent = generateTestLog('streaming', selectedConfig, testResult, {
testDescription: '流式OpenAI兼容接口测试 - 失败',
prompt: testPrompt,
streamingData: {
chunks: streamData,
totalChunks: streamData.length
}
});
saveTestLog(logContent, 'streaming-error');
}
});
// 发起流式请求 - 使用 analyze_new_mistake_stream 创建临时会话并测试适配器
await invoke('analyze_new_mistake_stream', {
request: {
subject: "AI适配器流式测试",
question_image_files: [], // 流式测试不需要图片
analysis_image_files: [],
user_question: testPrompt,
enable_step_by_step: false
}
});
// 清理监听器
return () => {
unlistenContent();
unlistenError();
};
} catch (error) {
console.error('流式测试失败:', error);
const errorMessage = error instanceof Error ? error.message :
(typeof error === 'object' ? JSON.stringify(error) : String(error));
testResult = {
success: false,
message: `Gemini适配器流式测试失败: ${errorMessage}`,
duration: Date.now() - startTime,
details: { error: errorMessage, streamData }
};
setTestResults({
...testResults,
streaming: testResult
});
setIsLoading({ ...isLoading, streaming: false });
// 保存失败的流式测试日志
if (selectedConfig) {
const logContent = generateTestLog('streaming', selectedConfig, testResult, {
testDescription: '流式OpenAI兼容接口测试 - 异常失败',
prompt: testPrompt
});
await saveTestLog(logContent, 'streaming-exception');
}
}
};
// 多模态测试(图片+文本)
const testMultimodal = async () => {
if (!selectedConfig || !selectedConfig.isMultimodal || !imageBase64) {
const testResult: TestResult = {
success: false,
message: selectedConfig?.isMultimodal
? '请先上传一张图片进行测试。'
: '当前模型不支持多模态功能。',
details: {
reason: selectedConfig?.isMultimodal ? 'no_image' : 'not_multimodal',
isMultimodal: selectedConfig?.isMultimodal || false
}
};
setTestResults({
...testResults,
multimodal: testResult
});
// 保存跳过的测试日志
if (selectedConfig) {
const logContent = generateTestLog('multimodal', selectedConfig, testResult, {
testDescription: '多模态测试 - 跳过(条件不满足)',
skipReason: testResult.details?.reason
});
await saveTestLog(logContent, 'multimodal-skipped');
}
return;
}
setIsLoading({ ...isLoading, multimodal: true });
const startTime = Date.now();
let testResult: TestResult;
try {
console.log('发送多模态测试请求,使用适配器:', selectedConfig.modelAdapter);
const multimodalPrompt = '请描述这张图片的内容。测试Gemini适配器的多模态OpenAI兼容接口转换。';
// 使用分析接口测试多模态(会自动调用gemini_adapter的多模态功能)
const response = await invoke('analyze_step_by_step', {
request: {
subject: '测试',
question_image_files: [imageBase64],
analysis_image_files: [],
user_question: multimodalPrompt,
enable_chain_of_thought: false
}
});
console.log('多模态适配器响应:', response);
testResult = {
success: true,
message: 'Gemini适配器多模态测试成功!OpenAI多模态格式已正确转换为Gemini API调用。',
details: {
response,
imageSize: imageBase64.length,
prompt: multimodalPrompt,
responseLength: (response as any)?.analysis_result?.length || 0
},
duration: Date.now() - startTime
};
setTestResults({
...testResults,
multimodal: testResult
});
} catch (error) {
console.error('多模态测试失败:', error);
const errorMessage = error instanceof Error ? error.message :
(typeof error === 'object' ? JSON.stringify(error) : String(error));
testResult = {
success: false,
message: `Gemini适配器多模态测试失败: ${errorMessage}`,
duration: Date.now() - startTime,
details: {
error: errorMessage,
imageSize: imageBase64.length
}
};
setTestResults({
...testResults,
multimodal: testResult
});
} finally {
setIsLoading({ ...isLoading, multimodal: false });
// 保存多模态测试日志
if (selectedConfig) {
const logContent = generateTestLog('multimodal', selectedConfig, testResult, {
testDescription: '多模态OpenAI兼容接口测试 - 验证OpenAI多模态格式转换为Gemini多模态API调用',
imageData: {
hasImage: !!imageBase64,
imageSize: imageBase64?.length || 0,
imageType: imageBase64?.substring(0, 50) || '' // 图片头部信息
}
});
await saveTestLog(logContent, 'multimodal');
}
}
};
// 处理图片上传
const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
const base64 = e.target?.result as string;
setImageBase64(base64);
setImagePreview(base64);
};
reader.readAsDataURL(file);
};
// 运行所有测试
const runAllTests = async () => {
if (!selectedConfig) return;
const batchStartTime = Date.now();
const batchId = `batch_${Date.now()}`;
console.log(`开始批量测试 - Batch ID: ${batchId}`);
// 清除之前的测试结果
setTestResults({});
setStreamingContent('');
const testSequence = [
{ name: 'basic', func: testBasicConnection },
{ name: 'nonStreaming', func: testNonStreamingChat },
{ name: 'streaming', func: testStreamingChat }
];
// 如果支持多模态且有图片,添加多模态测试
if (selectedConfig.isMultimodal && imageBase64) {
testSequence.push({ name: 'multimodal', func: testMultimodal });
}
const batchResults: Record<string, TestResult> = {};
// 依次执行所有测试
for (const test of testSequence) {
console.log(`执行测试: ${test.name}`);
await test.func();
await new Promise(resolve => setTimeout(resolve, 1000)); // 测试间隔
// 收集测试结果
const currentResults = testResults;
if (currentResults[test.name]) {
batchResults[test.name] = currentResults[test.name];
}
}
// 生成批量测试总结日志
const batchDuration = Date.now() - batchStartTime;
const successCount = Object.values(batchResults).filter(r => r.success).length;
const totalCount = Object.keys(batchResults).length;
const batchLogEntry = {
timestamp: new Date().toISOString(),
batchId,
testType: 'batch-all-tests',
config: {
id: selectedConfig.id,
name: selectedConfig.name,
model: selectedConfig.model,
baseUrl: selectedConfig.baseUrl,
modelAdapter: selectedConfig.modelAdapter,
isMultimodal: selectedConfig.isMultimodal,
temperature: selectedConfig.temperature,
maxOutputTokens: selectedConfig.maxOutputTokens
},
testPrompt,
batchSummary: {
totalTests: totalCount,
successfulTests: successCount,
failedTests: totalCount - successCount,
successRate: totalCount > 0 ? (successCount / totalCount * 100).toFixed(2) + '%' : '0%',
totalDuration: batchDuration,
averageTestDuration: totalCount > 0 ? Math.round(batchDuration / totalCount) : 0
},
individualResults: batchResults,
testSequence: testSequence.map(t => t.name),
environment: {
userAgent: navigator.userAgent,
timestamp: new Date().toISOString(),
testVersion: '1.0.0',
hasImage: !!imageBase64,
imageSize: imageBase64?.length || 0
}
};
// 保存批量测试日志
const batchLogContent = JSON.stringify(batchLogEntry, null, 2);
await saveTestLog(batchLogContent, 'batch-all');
console.log(`批量测试完成 - 成功: ${successCount}/${totalCount}, 耗时: ${batchDuration}ms`);
};
const renderTestResult = (key: string, title: string) => {
const result = testResults[key];
const loading = isLoading[key];
return (
<div className="flex-1">
<div className="flex items-center mb-2">
<h3 className="font-semibold text-gray-800 flex-1">{title}</h3>
<div className="ml-4">
{loading ? (
<div className="inline-flex items-center px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm">
<div className="h-4 w-4 animate-spin rounded-full border-2 border-blue-600 border-t-transparent mr-2" />
测试中...
</div>
) : result ? (
result.success ? (
<div className="inline-flex items-center px-3 py-1 bg-green-100 text-green-800 rounded-full text-sm font-medium">
<span className="mr-1">✅</span>
成功
</div>
) : (
<div className="inline-flex items-center px-3 py-1 bg-red-100 text-red-800 rounded-full text-sm font-medium">
<span className="mr-1">❌</span>
失败
</div>
)
) : (
<div className="inline-flex items-center px-3 py-1 bg-gray-100 text-gray-600 rounded-full text-sm">
待测试
</div>
)}
</div>
</div>
{result && (
<div className="space-y-1">
<p className={`text-sm ${result.success ? 'text-green-700' : 'text-red-700'}`}>
{result.message}
</p>
{result?.duration && (
<p className="text-xs text-gray-500">
⏱️ 耗时: {result.duration}ms
</p>
)}
</div>
)}
</div>
);
};
if (apiConfigs.length === 0) {
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 p-6">
<div className="max-w-4xl mx-auto">
{/* 页面头部 */}
<div className="text-center mb-8">
<div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full mb-4">
<span className="text-2xl text-white">🧪</span>
</div>
<h1 className="text-4xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent mb-3">
Gemini 适配器测试
</h1>
</div>
{/* 错误提示卡片 */}
<div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
<div className="bg-gradient-to-r from-yellow-500 to-orange-600 p-6 text-white">
<h2 className="text-xl font-bold flex items-center">
<span className="mr-3">⚠️</span>
配置缺失
</h2>
</div>
<div className="p-8">
<div className="text-center">
<div className="inline-flex items-center justify-center w-20 h-20 bg-yellow-100 rounded-full mb-6">
<span className="text-3xl">⚙️</span>
</div>
<h3 className="text-xl font-semibold text-gray-800 mb-4">
未找到启用的 Gemini 配置
</h3>
<p className="text-gray-600 mb-6 max-w-md mx-auto">
请先在 API 配置中添加一个 Google (Gemini) 适配器的配置,然后启用该配置。
</p>
<div className="bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg p-6 border border-blue-200 mb-6">
<h4 className="font-semibold text-blue-800 mb-3 flex items-center justify-center">
<span className="mr-2">📝</span>
配置要求
</h4>
<div className="text-left text-sm text-blue-700 space-y-2">
<div className="flex items-center">
<span className="w-2 h-2 bg-blue-500 rounded-full mr-3"></span>
<span><strong>modelAdapter</strong> 字段必须设置为 <code className="px-2 py-1 bg-blue-100 rounded text-xs">"google"</code></span>
</div>
<div className="flex items-center">
<span className="w-2 h-2 bg-blue-500 rounded-full mr-3"></span>
<span>配置必须处于 <strong>启用</strong> 状态</span>
</div>
<div className="flex items-center">
<span className="w-2 h-2 bg-blue-500 rounded-full mr-3"></span>
<span>需要有效的 Gemini API 密钥</span>
</div>
</div>
</div>
<button
onClick={() => window.location.reload()}
className="px-6 py-3 bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-lg hover:from-blue-600 hover:to-purple-700 transition-all duration-200 flex items-center mx-auto font-semibold"
>
<span className="mr-2">🔄</span>
刷新页面
</button>
</div>
</div>
</div>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 p-6">
<div className="max-w-7xl mx-auto">
{/* 页面头部 */}
<div className="text-center mb-8">
<div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full mb-4">
<span className="text-2xl text-white">🧪</span>
</div>
<h1 className="text-4xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent mb-3">
Gemini 适配器测试
</h1>
<p className="text-lg text-gray-600 max-w-3xl mx-auto">
此测试页面验证 <code className="px-2 py-1 bg-gray-100 rounded text-sm font-mono">gemini_adapter.rs</code>
是否能正确将 OpenAI 兼容格式转换为 Gemini API 调用并正常工作
</p>
</div>
{/* 配置卡片 */}
<div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
<div className="bg-gradient-to-r from-blue-500 to-purple-600 p-6 text-white">
<h2 className="text-xl font-bold flex items-center">
<span className="mr-3">⚙️</span>
API 配置选择
</h2>
</div>
<div className="p-6">
<div className="mb-4">
<label className="block text-sm font-semibold text-gray-700 mb-3">选择 Gemini 配置</label>
<select
className="w-full p-4 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all duration-200 bg-white text-gray-800"
value={selectedConfig?.id || ''}
onChange={(e) => {
const config = apiConfigs.find(c => c.id === e.target.value);
setSelectedConfig(config || null);
}}
>
{apiConfigs.map(config => (
<option key={config.id} value={config.id}>
{config.name} - {config.model}
</option>
))}
</select>
</div>
{selectedConfig && (
<div className="bg-gradient-to-br from-blue-50 to-purple-50 rounded-lg p-6 border border-blue-200">
<h3 className="font-semibold text-gray-800 mb-4 flex items-center">
<span className="mr-2">📋</span>
配置详情
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
<div className="bg-white rounded-lg p-3 border">
<span className="font-medium text-gray-600">模型:</span>
<div className="text-gray-800 font-mono">{selectedConfig.model}</div>
</div>
<div className="bg-white rounded-lg p-3 border">
<span className="font-medium text-gray-600">端点:</span>
<div className="text-gray-800 font-mono text-xs break-all">{selectedConfig.baseUrl}</div>
</div>
<div className="bg-white rounded-lg p-3 border">
<span className="font-medium text-gray-600">适配器:</span>
<div>
<span className="inline-flex items-center px-3 py-1 bg-gradient-to-r from-blue-500 to-purple-600 text-white text-xs font-medium rounded-full">
{selectedConfig.modelAdapter}
</span>
</div>
</div>
<div className="bg-white rounded-lg p-3 border">
<span className="font-medium text-gray-600">多模态:</span>
<div className="flex items-center">
{selectedConfig.isMultimodal ? (
<span className="inline-flex items-center px-2 py-1 bg-green-100 text-green-800 text-xs font-medium rounded-full">
✓ 支持
</span>
) : (
<span className="inline-flex items-center px-2 py-1 bg-gray-100 text-gray-800 text-xs font-medium rounded-full">
✗ 不支持
</span>
)}
</div>
</div>
<div className="bg-white rounded-lg p-3 border">
<span className="font-medium text-gray-600">温度:</span>
<div className="text-gray-800">{selectedConfig.temperature}</div>
</div>
<div className="bg-white rounded-lg p-3 border">
<span className="font-medium text-gray-600">最大Token:</span>
<div className="text-gray-800">{selectedConfig.maxOutputTokens}</div>
</div>
</div>
</div>
)}
</div>
</div>
{/* 测试输入区域 */}
<div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
<div className="bg-gradient-to-r from-green-500 to-teal-600 p-6 text-white">
<h2 className="text-xl font-bold flex items-center">
<span className="mr-3">📝</span>
测试输入配置
</h2>
</div>
<div className="p-6 space-y-6">
{/* 测试提示词 */}
<div>
<label className="block text-sm font-semibold text-gray-700 mb-3">测试提示词</label>
<textarea
className="w-full p-4 border-2 border-gray-200 rounded-lg focus:border-green-500 focus:ring-2 focus:ring-green-200 transition-all duration-200 resize-vertical bg-white"
value={testPrompt}
onChange={(e) => setTestPrompt(e.target.value)}
rows={4}
placeholder="输入测试提示词,用于验证适配器功能..."
/>
</div>
{/* 图片上传 */}
{selectedConfig?.isMultimodal && (
<div>
<label className="block text-sm font-semibold text-gray-700 mb-3">上传测试图片(多模态测试)</label>
<div className="border-2 border-dashed border-gray-300 rounded-lg p-6 hover:border-green-400 transition-colors duration-200">
<div className="flex items-center justify-center">
<div className="text-center">
<input
type="file"
accept="image/*"
onChange={handleImageUpload}
className="hidden"
id="image-upload"
/>
<label
htmlFor="image-upload"
className="cursor-pointer inline-flex items-center px-4 py-2 bg-gradient-to-r from-green-500 to-teal-600 text-white rounded-lg hover:from-green-600 hover:to-teal-700 transition-all duration-200"
>
<span className="mr-2">📷</span>
选择图片
</label>
<p className="text-gray-500 text-sm mt-2">支持 JPG、PNG 等格式</p>
</div>
{imagePreview && (
<div className="ml-6">
<img
src={imagePreview}
alt="Preview"
className="h-24 w-24 object-cover rounded-lg border-2 border-green-200 shadow-md"
/>
</div>
)}
</div>
</div>
</div>
)}
</div>
</div>
{/* 测试控制区域 */}
<div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
<div className="bg-gradient-to-r from-purple-500 to-pink-600 p-6 text-white">
<h2 className="text-xl font-bold flex items-center">
<span className="mr-3">🚀</span>
测试控制
</h2>
</div>
<div className="p-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
<button
onClick={runAllTests}
disabled={Object.values(isLoading).some(v => v)}
className="w-full px-6 py-4 bg-gradient-to-r from-purple-500 to-pink-600 text-white rounded-lg hover:from-purple-600 hover:to-pink-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 flex items-center justify-center font-semibold"
>
{Object.values(isLoading).some(v => v) ? (
<>
<div className="animate-spin rounded-full h-5 w-5 border-2 border-white border-t-transparent mr-3"></div>
测试进行中...
</>
) : (
<>
<span className="mr-2">🧪</span>
运行所有测试
</>
)}
</button>
<button
onClick={() => {
setTestResults({});
setStreamingContent('');
}}
className="w-full px-6 py-4 bg-gradient-to-r from-gray-500 to-gray-600 text-white rounded-lg hover:from-gray-600 hover:to-gray-700 transition-all duration-200 flex items-center justify-center font-semibold"
>
<span className="mr-2">🗑️</span>
清除测试结果
</button>
</div>
{/* 日志管理区域 */}
<div className="border-t border-gray-200 pt-4">
<h4 className="text-sm font-semibold text-gray-700 mb-3 flex items-center">
<span className="mr-2">📄</span>
测试日志管理
</h4>
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
<button
onClick={loadTestLogs}
className="px-4 py-2 bg-gradient-to-r from-blue-500 to-indigo-600 text-white rounded-lg hover:from-blue-600 hover:to-indigo-700 transition-all duration-200 flex items-center justify-center text-sm font-medium"
>
<span className="mr-1">🔄</span>
刷新日志列表
</button>
<button
onClick={() => {
if (currentLogPath) {
invoke('open_log_file', { logPath: currentLogPath });
}
}}
disabled={!currentLogPath}
className="px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-lg hover:from-green-600 hover:to-emerald-700 disabled:opacity-50 transition-all duration-200 flex items-center justify-center text-sm font-medium"
>
<span className="mr-1">📂</span>
打开最新日志
</button>
<button
onClick={() => {
invoke('open_logs_folder', { logType: 'gemini-adapter-test' });
}}
className="px-4 py-2 bg-gradient-to-r from-yellow-500 to-orange-600 text-white rounded-lg hover:from-yellow-600 hover:to-orange-700 transition-all duration-200 flex items-center justify-center text-sm font-medium"
>
<span className="mr-1">📁</span>
打开日志文件夹
</button>
</div>
{/* 当前日志路径显示 */}
{currentLogPath && (
<div className="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-lg">
<p className="text-xs text-blue-700">
<span className="font-semibold">最新日志:</span> {currentLogPath}
</p>
</div>
)}
{/* 历史日志列表 */}
{allTestLogs.length > 0 && (
<div className="mt-4">
<h5 className="text-xs font-semibold text-gray-600 mb-2">
历史测试日志 ({allTestLogs.length} 个文件)
</h5>
<div className="max-h-32 overflow-y-auto bg-gray-50 rounded-lg border">
{allTestLogs.slice(0, 10).map((logPath, index) => (
<div
key={index}
className="px-3 py-2 border-b border-gray-200 last:border-b-0 hover:bg-gray-100 cursor-pointer transition-colors duration-150"
onClick={() => {
invoke('open_log_file', { logPath });
}}
>
<p className="text-xs text-gray-700 font-mono truncate">
{logPath.split('/').pop()}
</p>
</div>
))}
{allTestLogs.length > 10 && (
<div className="px-3 py-2 text-xs text-gray-500 italic">
... 还有 {allTestLogs.length - 10} 个日志文件
</div>
)}
</div>
</div>
)}
</div>
</div>
</div>
{/* 单项测试 */}
<div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
<div className="bg-gradient-to-r from-indigo-500 to-blue-600 p-6 text-white">
<h2 className="text-xl font-bold flex items-center">
<span className="mr-3">🔬</span>
单项测试
</h2>
<p className="text-blue-100 mt-1">分别验证适配器的各项功能</p>
</div>
<div className="p-6 space-y-4">
{/* 基础连接测试 */}
<div className="bg-gradient-to-r from-gray-50 to-gray-100 rounded-lg p-4 border border-gray-200">
<div className="flex items-center justify-between">
{renderTestResult('basic', '🔗 基础连接测试')}
<button
onClick={testBasicConnection}
disabled={isLoading.basic}
className="px-4 py-2 bg-gradient-to-r from-blue-500 to-indigo-600 text-white rounded-lg hover:from-blue-600 hover:to-indigo-700 disabled:opacity-50 transition-all duration-200 flex items-center text-sm font-medium"
>
{isLoading.basic ? (
<div className="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent mr-2"></div>
) : (
<span className="mr-1">▶️</span>
)}
测试
</button>
</div>
</div>
{/* 非流式转换测试 */}
<div className="bg-gradient-to-r from-green-50 to-emerald-100 rounded-lg p-4 border border-green-200">
<div className="flex items-center justify-between">
{renderTestResult('nonStreaming', '📤 OpenAI → Gemini 非流式转换测试')}
<button
onClick={testNonStreamingChat}
disabled={isLoading.nonStreaming}
className="px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-lg hover:from-green-600 hover:to-emerald-700 disabled:opacity-50 transition-all duration-200 flex items-center text-sm font-medium"
>
{isLoading.nonStreaming ? (
<div className="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent mr-2"></div>
) : (
<span className="mr-1">▶️</span>
)}
测试
</button>
</div>
</div>
{/* 流式转换测试 */}
<div className="bg-gradient-to-r from-purple-50 to-violet-100 rounded-lg p-4 border border-purple-200">
<div className="flex items-center justify-between">
{renderTestResult('streaming', '🌊 OpenAI → Gemini 流式转换测试')}
<button
onClick={testStreamingChat}
disabled={isLoading.streaming}
className="px-4 py-2 bg-gradient-to-r from-purple-500 to-violet-600 text-white rounded-lg hover:from-purple-600 hover:to-violet-700 disabled:opacity-50 transition-all duration-200 flex items-center text-sm font-medium"
>
{isLoading.streaming ? (
<div className="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent mr-2"></div>
) : (
<span className="mr-1">▶️</span>
)}
测试
</button>
</div>
</div>
{/* 多模态转换测试 */}
{selectedConfig?.isMultimodal && (
<div className="bg-gradient-to-r from-orange-50 to-amber-100 rounded-lg p-4 border border-orange-200">
<div className="flex items-center justify-between">
{renderTestResult('multimodal', '🖼️ OpenAI → Gemini 多模态转换测试')}
<button
onClick={testMultimodal}
disabled={isLoading.multimodal || !imageBase64}
className="px-4 py-2 bg-gradient-to-r from-orange-500 to-amber-600 text-white rounded-lg hover:from-orange-600 hover:to-amber-700 disabled:opacity-50 transition-all duration-200 flex items-center text-sm font-medium"
>
{isLoading.multimodal ? (
<div className="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent mr-2"></div>
) : (
<span className="mr-1">▶️</span>
)}
测试
</button>
</div>
{!imageBase64 && (
<div className="mt-2 text-xs text-orange-600">
💡 需要先上传图片才能进行多模态测试
</div>
)}
</div>
)}
</div>
</div>
{/* 流式响应内容显示 */}
{streamingContent && (
<div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
<div className="bg-gradient-to-r from-green-500 to-emerald-600 p-4 text-white">
<h3 className="text-lg font-bold flex items-center">
<span className="mr-2">🌊</span>
流式响应内容
</h3>
</div>
<div className="p-6">
<div className="bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg p-6 max-h-96 overflow-y-auto border-2 border-gray-200">
<div className="font-mono text-sm leading-relaxed text-gray-800 whitespace-pre-wrap">
{streamingContent}
</div>
</div>
</div>
</div>
)}
{/* 测试结果详情 */}
{Object.entries(testResults).some(([key, result]) => result.details) && (
<div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
<div className="bg-gradient-to-r from-indigo-500 to-purple-600 p-4 text-white">
<h3 className="text-lg font-bold flex items-center">
<span className="mr-2">📊</span>
测试结果详情
</h3>
</div>
<div className="p-6 space-y-4">
{Object.entries(testResults).map(([key, result]) => (
result.details && (
<div key={key} className="border border-gray-200 rounded-lg overflow-hidden">
<div className="bg-gray-50 px-4 py-3 border-b border-gray-200">
<h4 className="font-semibold text-gray-800 capitalize">{key} 测试详情</h4>
</div>
<div className="p-4">
<div className="bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg p-4 max-h-60 overflow-y-auto">
<pre className="text-xs text-gray-700 whitespace-pre-wrap font-mono leading-relaxed">
{JSON.stringify(result.details, null, 2)}
</pre>
</div>
</div>
</div>
)
))}
</div>
</div>
)}
{/* 说明信息 */}
<div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
<div className="bg-gradient-to-r from-cyan-500 to-blue-600 p-6 text-white">
<h3 className="text-xl font-bold flex items-center">
<span className="mr-3">📚</span>
测试说明
</h3>
</div>
<div className="p-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="bg-gradient-to-br from-blue-50 to-cyan-50 rounded-lg p-4 border border-blue-200">
<h4 className="font-semibold text-blue-800 mb-2 flex items-center">
<span className="mr-2">🔗</span>
基础连接测试
</h4>
<p className="text-blue-700 text-sm">验证API密钥和端点是否有效,确保网络连接正常</p>
</div>
<div className="bg-gradient-to-br from-green-50 to-emerald-50 rounded-lg p-4 border border-green-200">
<h4 className="font-semibold text-green-800 mb-2 flex items-center">
<span className="mr-2">📤</span>
非流式转换测试
</h4>
<p className="text-green-700 text-sm">验证OpenAI格式能否正确转换为Gemini API调用</p>
</div>
<div className="bg-gradient-to-br from-purple-50 to-violet-50 rounded-lg p-4 border border-purple-200">
<h4 className="font-semibold text-purple-800 mb-2 flex items-center">
<span className="mr-2">🌊</span>
流式转换测试
</h4>
<p className="text-purple-700 text-sm">验证OpenAI流式格式能否正确转换为Gemini流式API调用</p>
</div>
<div className="bg-gradient-to-br from-orange-50 to-amber-50 rounded-lg p-4 border border-orange-200">
<h4 className="font-semibold text-orange-800 mb-2 flex items-center">
<span className="mr-2">🖼️</span>
多模态转换测试
</h4>
<p className="text-orange-700 text-sm">验证OpenAI多模态格式能否正确转换为Gemini多模态API调用</p>
</div>
</div>
<div className="mt-6 p-4 bg-gradient-to-r from-yellow-100 to-orange-100 rounded-lg border border-yellow-300">
<div className="flex items-start">
<span className="text-2xl mr-3">💡</span>
<div>
<h4 className="font-semibold text-yellow-800 mb-1">使用提示</h4>
<p className="text-yellow-700 text-sm">
确保已在设置中正确配置了Gemini API密钥和端点。
测试前请检查网络连接是否正常。
所有测试都会验证适配器是否能正确处理OpenAI兼容格式并转换为Gemini API调用。
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
};
|
000haoji/deep-student
| 10,173 |
src/components/ReviewAnalysisSessionView.tsx
|
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useNotification } from '../hooks/useNotification';
import { TauriAPI, ReviewAnalysisItem } from '../utils/tauriApi';
import UniversalAppChatHost from './UniversalAppChatHost';
interface ReviewAnalysisSessionViewProps {
sessionId: string;
onBack: () => void;
}
/**
* 新的回顾分析详情页 - 完全复用错题分析的逻辑和模式
*/
const ReviewAnalysisSessionView: React.FC<ReviewAnalysisSessionViewProps> = ({
sessionId,
onBack,
}) => {
console.log('🔍 ReviewAnalysisSessionView 渲染, sessionId:', sessionId);
// 使用数据库模式,复用错题分析的状态管理
const [reviewAnalysis, setReviewAnalysis] = useState<ReviewAnalysisItem | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const { showNotification } = useNotification();
// 用于存储最新的聊天历史状态
const [latestChatHistory, setLatestChatHistory] = useState<any[]>([]);
// 定时保存的引用
const autoSaveTimerRef = useRef<NodeJS.Timeout | null>(null);
// 从数据库加载回顾分析(复用错题分析的加载模式)
const loadReviewAnalysis = useCallback(async () => {
try {
setLoading(true);
setError(null);
console.log('🔍 从数据库加载回顾分析:', sessionId);
const analysis = await TauriAPI.getReviewAnalysisById(sessionId);
if (analysis) {
console.log('✅ 成功加载回顾分析:', analysis);
setReviewAnalysis(analysis);
} else {
console.error('❌ 未找到回顾分析:', sessionId);
setError('未找到指定的回顾分析');
}
} catch (error) {
console.error('加载回顾分析失败:', error);
setError(String(error));
showNotification('error', '加载回顾分析失败');
} finally {
setLoading(false);
}
}, [sessionId, showNotification]);
useEffect(() => {
loadReviewAnalysis();
}, [loadReviewAnalysis]);
// 🎯 保存聊天历史的辅助函数
const saveReviewAnalysisData = useCallback(async (chatHistory: any[], context: string) => {
if (!reviewAnalysis || chatHistory.length === 0) return;
try {
console.log(`🔄 [${context}] 保存聊天历史,数量:`, chatHistory.length);
const updatedAnalysis = {
...reviewAnalysis,
chat_history: chatHistory,
status: 'completed' as const,
updated_at: new Date().toISOString()
};
// 🎯 首选方案:使用新的更新API
try {
await TauriAPI.updateReviewAnalysis(updatedAnalysis);
console.log(`✅ [${context}] 聊天历史保存成功 (直接更新)`);
return;
} catch (updateError) {
console.log(`⚠️ [${context}] 直接更新失败,尝试变通方案:`, updateError);
}
// 🎯 变通方案:使用追问API(它会自动保存聊天历史)
await TauriAPI.continueReviewChatStream({
reviewId: reviewAnalysis.id,
chatHistory: chatHistory,
enableChainOfThought: true,
enableRag: false,
ragTopK: 5
});
console.log(`✅ [${context}] 聊天历史保存成功 (变通方案)`);
} catch (error) {
console.error(`❌ [${context}] 保存聊天历史失败:`, error);
}
}, [reviewAnalysis]);
// 🎯 新增:页面卸载时保存最新的聊天历史
useEffect(() => {
const handleBeforeUnload = () => {
if (latestChatHistory.length > 0) {
// beforeunload 不能使用 async,所以只能发起请求
saveReviewAnalysisData(latestChatHistory, '页面卸载').catch(console.error);
}
};
// 监听页面卸载事件
window.addEventListener('beforeunload', handleBeforeUnload);
// 组件卸载时的清理
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
// 清理定时器
if (autoSaveTimerRef.current) {
clearTimeout(autoSaveTimerRef.current);
autoSaveTimerRef.current = null;
}
// 组件卸载时保存(非async)
if (latestChatHistory.length > 0) {
console.log('🔄 [组件卸载] 尝试保存最新聊天历史');
saveReviewAnalysisData(latestChatHistory, '组件卸载').catch(console.error);
}
};
}, [latestChatHistory, saveReviewAnalysisData]);
// 保存回顾分析到数据库(复用错题分析的保存模式)
const handleSaveReviewAnalysis = useCallback(async (updatedAnalysis: ReviewAnalysisItem) => {
try {
// 注意:后端API已经自动保存,这里主要是更新本地状态
setReviewAnalysis(updatedAnalysis);
console.log('✅ 回顾分析状态已更新');
} catch (error) {
console.error('更新回顾分析状态失败:', error);
showNotification('error', '更新状态失败');
}
}, [showNotification]);
// 加载中状态
if (loading) {
return (
<div className="flex justify-center items-center h-64">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
<span className="ml-2 text-gray-600">加载中...</span>
</div>
);
}
// 错误状态
if (error || !reviewAnalysis) {
return (
<div className="text-center py-12">
<h3 className="text-lg font-medium text-red-700 mb-2">加载失败</h3>
<p className="text-gray-600 mb-4">
{error || '未找到回顾分析'}
</p>
<button
onClick={onBack}
className="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-colors"
>
返回列表
</button>
</div>
);
}
// 主界面 - 使用UniversalAppChatHost,完全复用错题分析的逻辑
return (
<UniversalAppChatHost
mode="REVIEW_SESSION_DETAIL"
businessSessionId={reviewAnalysis.id}
preloadedData={{
subject: reviewAnalysis.subject,
userQuestion: reviewAnalysis.user_question,
ocrText: reviewAnalysis.consolidated_input,
tags: reviewAnalysis.mistake_ids, // 使用mistake_ids作为标签
chatHistory: reviewAnalysis.chat_history || [],
thinkingContent: new Map(), // 从聊天历史中恢复思维链
status: reviewAnalysis.status,
}}
serviceConfig={{
apiProvider: {
initiateAndGetStreamId: async () => ({
streamIdForEvents: reviewAnalysis.id,
ocrResultData: {
ocr_text: reviewAnalysis.consolidated_input,
tags: reviewAnalysis.mistake_ids,
mistake_type: reviewAnalysis.analysis_type
},
initialMessages: reviewAnalysis.chat_history || []
}),
startMainStreaming: async (params) => {
// 根据回顾分析状态决定是否启动流式处理
const needsInitialAnalysis = !reviewAnalysis.chat_history ||
reviewAnalysis.chat_history.length === 0 ||
reviewAnalysis.status === 'pending' ||
reviewAnalysis.status === 'analyzing';
if (needsInitialAnalysis) {
console.log('🚀 启动回顾分析流式处理');
try {
await TauriAPI.triggerConsolidatedReviewStream({
review_session_id: reviewAnalysis.id,
enable_chain_of_thought: params.enableChainOfThought,
enable_rag: params.enableRag,
rag_options: params.enableRag ? { top_k: params.ragTopK } : undefined
});
console.log('✅ 回顾分析流式处理已启动');
} catch (error) {
console.error('❌ 启动回顾分析流式处理失败:', error);
throw error;
}
} else {
console.log('ℹ️ 回顾分析已完成,无需启动流式处理');
}
},
continueUserChat: async (params) => {
// 使用新的API进行追问(自动保存到数据库)
await TauriAPI.continueReviewChatStream({
reviewId: params.businessId,
chatHistory: params.fullChatHistory,
enableChainOfThought: params.enableChainOfThought,
enableRag: params.enableRag,
ragTopK: params.ragTopK
});
}
},
streamEventNames: {
initialStream: (id) => ({
data: `review_analysis_stream_${id}`,
reasoning: `review_analysis_stream_${id}_reasoning`,
ragSources: `review_analysis_stream_${id}_rag_sources`
}),
// 🎯 修复:追问使用不同的事件名称,参考错题分析的正确实现
continuationStream: (id) => ({
data: `review_chat_stream_${id}`,
reasoning: `review_chat_stream_${id}_reasoning`,
ragSources: `review_chat_stream_${id}_rag_sources`
}),
},
defaultEnableChainOfThought: true,
defaultEnableRag: false,
defaultRagTopK: 5,
}}
onCoreStateUpdate={(data) => {
// 🎯 实现状态更新监听,主要用于调试和状态同步
console.log('🔄 [回顾分析] 核心状态更新:', {
sessionId,
chatHistoryLength: data.chatHistory?.length || 0,
thinkingContentSize: data.thinkingContent?.size || 0,
isAnalyzing: data.isAnalyzing,
isChatting: data.isChatting
});
// 🎯 关键修复:保存最新的聊天历史到状态中
if (data.chatHistory) {
setLatestChatHistory(data.chatHistory);
// 🎯 新增:设置定时自动保存(防抖)
if (autoSaveTimerRef.current) {
clearTimeout(autoSaveTimerRef.current);
}
// 30秒后自动保存
autoSaveTimerRef.current = setTimeout(() => {
if (data.chatHistory.length > 0) {
console.log('🕒 [定时保存] 触发自动保存');
saveReviewAnalysisData(data.chatHistory, '定时保存').catch(console.error);
}
}, 30000); // 30秒定时保存
}
// 更新本地状态
if (data.chatHistory && data.chatHistory.length > 0) {
setReviewAnalysis(prev => prev ? {
...prev,
chat_history: data.chatHistory,
status: 'completed',
updated_at: new Date().toISOString()
} : prev);
}
}}
onSaveRequest={async (data) => {
try {
console.log('💾 回顾分析手动保存请求,数据:', data);
// 🎯 使用新的保存函数
await saveReviewAnalysisData(data.chatHistory, '手动保存');
// 更新本地状态
setReviewAnalysis(prev => prev ? {
...prev,
chat_history: data.chatHistory,
status: 'completed',
updated_at: new Date().toISOString()
} : prev);
showNotification('success', '回顾分析已保存');
} catch (error) {
console.error('❌ 手动保存回顾分析失败:', error);
showNotification('error', '保存失败: ' + error);
}
}}
onExitRequest={onBack}
/>
);
};
export default ReviewAnalysisSessionView;
|
0000cd/wolf-set
| 8,115 |
data/cards.yaml
|
# https://github.com/0000cd/wolf-set
- title: 欢迎回来
hex: "#0000cd"
tags:
- 置顶
date: 24/04
description: 狼集 Wolf Set:宇宙总需要些航天器,“📀各位都好吧?” 让我们路过些互联网小行星。
links:
- name: 关于
url: https://ws.0000cd.com/posts/about/
- name: GitHub
url: https://github.com/0000cd/wolf-set
- name: 网站统计
url: https://eu.umami.is/share/inDFetQGPNU7eUt4/ws.0000cd.com
media:
- url: https://player.bilibili.com/player.html?isOutside=true&aid=113680083655495&bvid=BV1oFkBY1EjF&cid=27425508078&p=1
- url: met/?id=137470856
- title: TGAGWCAGA
hex: "#0583ab"
tags:
- 置顶
- 有趣
date: 24/12
description: 为付不起 TGA 的游戏设立的 TGA。The Game Awards for Games Who Can't Afford the Game Awards.
links:
- name: 官网
url: https://tgagwcaga.com/
- name: 获奖提名
url: https://tgagwcaga.com/nominees/
- name: Steam 特卖!
url: https://store.steampowered.com/curator/45328769-The-Great-Awards-for-Games-With-Creative/sale/tgagwcaga
- title: indienova
hex: "#ef4c26"
tags:
- 置顶
date: 24/12
description: 独立游戏新闻、评测、开发、教学。提示,点击图片查看画廊。
links:
- name: 官网
url: https://indienova.com
- name: 折扣
url: https://indienova.com/steam/discount/4-0-0-0-0-0-0-0-0/p/1
- name: 游戏库
url: https://indienova.com/gamedb
- name: 三相奇谈
url: https://store.steampowered.com/app/3084280/_/?l=schinese
media:
- url: https://player.bilibili.com/player.html?isOutside=true&aid=113309357447966&bvid=BV1ABmnYsEYu&autoplay=0
- title: 夸克
hex: "#0d53ff"
tags:
- 置顶
date: 24/04
description: 搜索有AI,扫描自动校正,网盘文件找得快,做你学习、工作、生活的高效拍档!手机电视电脑都能用。
links:
- name: 夸克
url: https://www.quark.cn/
- name: 网盘
url: https://pan.quark.cn/
- name: 扫描
url: https://scan.quark.cn/
- title: 阿里云
hex: "#ff6a00"
tags:
- 置顶
- 开发
date: 24/04
description: 新老用户服务器一年99!3分钟部署 AI 或联机游戏,更有学生特惠。
links:
- name: 服务器 99
url: https://www.aliyun.com/minisite/goods?userCode=chvg06mh
- name: AI 软件游戏
url: https://computenest.aliyun.com/services/all?userCode=chvg06mh
- name: 学生特惠
url: https://developer.aliyun.com/plan/student?userCode=chvg06mh
media:
- url: https://player.bilibili.com/player.html?isOutside=true&aid=113309357447966&bvid=BV1ABmnYsEYu&autoplay=0
# 正文
- title: DOOM CAPTCHA
hex: "#4285f4"
tags:
- 网页
- 有趣
date: "2025/01"
description: 打通 DOOM 证明你是人类。
links: https://doom-captcha.vercel.app/
- title: Button Stealer
hex: "#ff5100"
tags:
- 网页
- 有趣
- 开源
date: "2024/12"
description: 从路过的每个网页“窃取”按钮,欣赏你的按钮藏品。
links:
- name: 官网
url: https://anatolyzenkov.com/stolen-buttons/button-stealer
- name: GitHub
url: https://github.com/anatolyzenkov/button-stealer
- name: 藏品?
url: https://anatolyzenkov.com/stolen-buttons
- title: cobalt
hex: "#000000"
tags:
- 网页
- 工具
- 开源
date: "2024/12"
description: 一键下载网页上的媒体文件。
links:
- name: 官网
url: https://cobalt.tools/
- name: GitHub
url: https://github.com/imputnet/cobalt
- name: 赞助
url: https://liberapay.com/imput
- title: GOODY-2
hex: "#EBF38D"
tags:
- 网页
- AI
- 有趣
date: "2024/12"
description: 与世界上“最负责”的 AI 聊天。
links: https://www.goody2.ai/chat
- title: SONOTELLER.AI
hex: "#fcac45"
tags:
- 网页
- 声音
- AI
date: "2024/12"
description: 听懂歌的 AI,分析曲风情绪歌词等音乐的一切。
links: https://sonoteller.ai/
- title: Wappalyzer
hex: "#4608AD"
tags:
- 网页
- 开发
date: "2024/12"
description: 识别任意网页的技术栈。
links: https://www.wappalyzer.com/
- title: Neal.fun
hex: "#ffc7c7"
tags:
- 网页
- 有趣
date: "2024/12"
description: 希望你有美好的一天… 游戏互动可视化等其他奇怪的东西。
links:
- name: 官网
url: https://neal.fun/
- name: 设置密码?
url: https://neal.fun/password-game/
- name: 赞助
url: https://buymeacoffee.com/neal
- title: Wild West
hex: "#BBF7D0"
tags:
- 网页
- 有趣
- AI
date: "2024/12"
description: 由 AI 驱动的游戏,剪刀石头布。
links:
- name: 官网
url: https://www.wildwest.gg/
- name: 击败石头?
url: https://www.whatbeatsrock.com/
- title: UniGetUI
hex: "#707070"
tags:
- 桌面
- 开源
- 开发
date: "2024/12"
description: 图形化 Windows 全能包管理器。
links:
- name: 官网
url: https://www.marticliment.com/unigetui/
- name: GitHub
url: https://github.com/marticliment/UniGetUI
- name: 赞助
url: https://ko-fi.com/s/290486d079
- title: PowerToys
hex: "#666666"
tags:
- 桌面
- 开源
- 工具
date: "2024/12"
description: 一组实用工具,可帮助高级用户调整和简化其 Windows 体验,从而提高工作效率。
links:
- name: 官网
url: https://learn.microsoft.com/zh-cn/windows/powertoys/
- name: GitHub
url: https://github.com/microsoft/PowerToys
- name: 微软商店
url: https://apps.microsoft.com/detail/xp89dcgq3k6vld?hl=zh-cn&gl=CN
- title: LocalSend
hex: "#008080"
tags:
- 桌面
- 移动
- 开源
date: "2024/12"
description: 全平台 WIFI 分享文件。
links:
- name: 官网
url: https://localsend.org/zh-CN
- name: GitHub
url: https://github.com/localsend/localsend
- name: 赞助
url: https://github.com/sponsors/Tienisto
# Legacy
- title: CSS Diner
hex: "#2e2a23"
tags:
- 网页
- 开发
- 开源
date: "2024/04"
description: 练习 CSS 选择器小游戏。
links:
- name: 官网
url: https://flukeout.github.io/
- name: GitHub
url: https://github.com/flukeout/css-diner
- title: Humane by Design
hex: "#14151d"
tags:
- 网页
- 设计
- 想法
date: "2024/04"
description: 人性化的数字产品和服务指南。
links: https://humanebydesign.com/
- title: Laws of UX
hex: "#0d1e26"
tags:
- 网页
- 设计
- 想法
date: "2024/04"
description: 最佳用户体验 UX 法则合集。
links: https://lawsofux.com/
- title: Checklist Design
hex: "#5e4dcd"
tags:
- 网页
- 设计
- 开发
date: "2024/04"
description: 各类页面、组件、流程、设计、品牌等检查清单。
links: https://www.checklist.design/
- title: Method of Action
hex: "#333647"
tags:
- 网页
- 设计
- 有趣
- 开源
date: "2024/04"
description: 练习布尔运算、贝塞尔曲线、色轮、字体设计等小游戏。
links:
- name: 官网
url: https://method.ac/
- name: GitHub
url: https://github.com/methodofaction/Method-Draw
- name: 赞助
url: https://method.ac/donate/
- title: Unsplash
hex: "#000000"
tags:
- 推荐
- 网页
- 图片
date: "2024/04"
description: 全球摄影师 300万 高清免费图片。
links:
- name: 官网
url: https://unsplash.com
- name: 背景
url: https://unsplash.com/backgrounds
- name: 壁纸
url: https://unsplash.com/wallpapers
- title: The Useless Web
hex: "#ff1493"
tags:
- 推荐
- 网页
- 有趣
date: "2024/04"
description: 随机打开网上有趣而无用的网站。
links: https://theuselessweb.com
- title: i Hate Regex
hex: "#e53e3e"
tags:
- 网页
- 开源
- 开发
date: "2024/04"
description: 帮助讨厌复杂正则表达式的人理解和使用它们,现在你有两个问题了。
links:
- name: 官网
url: https://ihateregex.io/
- name: GitHub
url: https://github.com/geongeorge/i-hate-regex
- name: 赞助
url: https://opencollective.com/ihateregex
- title: Msgif
hex: "#7880dd"
tags:
- 网页
- 动图
- 有趣
date: "2024/04"
description: 打字过程转换成动图,见字如面。
links: https://msgif.net/
- title: Exploding Topics
hex: "#2e5ce5"
tags:
- 网页
- 搜索
- 想法
date: "2024/04"
description: 寻找快速增长与有潜力的科技话题。
links: https://explodingtopics.com/
- title: 100font.com
hex: "#f7c601"
tags:
- 推荐
- 网页
- 字体
date: "2024/04"
description: 一个专门收集整理“免费商用字体”的网站,有大量中文字体。
links: https://www.100font.com
- title: Recompressor
hex: "#3755dc"
tags:
- 推荐
- 网页
- 工具
- 图片
date: "2024/04"
description: 智能压缩技术,优化图片质量与尺寸,多种图像工具。
links:
- name: 压缩
url: https://zh.recompressor.com/
- name: 修复
url: https://zh.pixfix.com/
- name: 检查
url: https://zh.pixspy.com/
- title: No More Ransom
hex: "#102a87"
tags:
- 网页
- 安全
date: "2024/04"
description: 提供数十种免费的解密工具,从勒索病毒中恢复数据。
links:
- name: 官网
url: https://www.nomoreransom.org/zh/index.html
- name: 知识
url: https://www.nomoreransom.org/zh/ransomware-qa.html
- name: 建议
url: https://www.nomoreransom.org/zh/prevention-advice-for-users.html
- title: IconKitchen
hex: "#6a3de8"
tags:
- 网页
- 图标
- 开发
date: "2024/04"
description: 轻松生成标准的全平台应用图标。
links: https://icon.kitchen
- title: Game-icons.net
hex: "#000000"
tags:
- 网页
- 图标
date: "2024/04"
description: 4千 CC 授权免费矢量游戏图标。
links: https://game-icons.net/
|
000haoji/deep-student
| 40,607 |
src/components/EnhancedKnowledgeBaseManagement.tsx
|
import React, { useState, useEffect, useCallback } from 'react';
import { TauriAPI } from '../utils/tauriApi';
import { useNotification } from '../hooks/useNotification';
import './EnhancedKnowledgeBaseManagement.css';
import type {
RagDocument,
KnowledgeBaseStatusPayload,
RagProcessingEvent,
RagDocumentStatusEvent
} from '../types';
import { listen } from '@tauri-apps/api/event';
import './KnowledgeBaseManagement.css';
import {
FileText, Edit, Trash2, BookOpen, Lightbulb, X, Upload, FolderOpen
} from 'lucide-react';
// 添加CSS动画样式
const animationKeyframes = `
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
@keyframes shimmer {
0% { transform: translateX(-100%); }
100% { transform: translateX(100%); }
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.7; }
}
`;
// 将样式注入到页面中
if (typeof document !== 'undefined') {
const styleElement = document.createElement('style');
styleElement.textContent = animationKeyframes;
document.head.appendChild(styleElement);
}
// 进度条组件
interface ProgressBarProps {
progress: number;
status: string;
fileName: string;
stage?: string;
totalChunks?: number;
currentChunk?: number;
chunksProcessed?: number;
}
const ProgressBar: React.FC<ProgressBarProps> = ({
progress,
status,
fileName,
stage,
totalChunks,
currentChunk,
chunksProcessed
}) => {
const getStatusColor = (status: string) => {
switch (status) {
case 'Reading': return '#3b82f6'; // 蓝色
case 'Preprocessing': return '#8b5cf6'; // 紫色
case 'Chunking': return '#f59e0b'; // 橙色
case 'Embedding': return '#10b981'; // 绿色
case 'Storing': return '#06b6d4'; // 青色
case 'Completed': return '#22c55e'; // 成功绿色
case 'Failed': return '#ef4444'; // 错误红色
default: return '#6b7280'; // 灰色
}
};
const getStageText = (status: string) => {
switch (status) {
case 'Reading': return '📖 读取文件';
case 'Preprocessing': return '🔧 预处理';
case 'Chunking': return '✂️ 文本分块';
case 'Embedding': return '🧠 生成向量';
case 'Storing': return '💾 存储数据';
case 'Completed': return '✅ 处理完成';
case 'Failed': return '❌ 处理失败';
default: return '⏳ 处理中';
}
};
return (
<div style={{
background: 'white',
border: '1px solid #e5e7eb',
borderRadius: '12px',
padding: '16px',
marginBottom: '12px',
boxShadow: '0 2px 4px rgba(0, 0, 0, 0.05)'
}}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '8px'
}}>
<div style={{
fontSize: '14px',
fontWeight: '600',
color: '#374151',
display: 'flex',
alignItems: 'center',
gap: '8px'
}}>
<FileText size={16} />
{fileName}
</div>
<div style={{
fontSize: '12px',
color: '#6b7280',
fontWeight: '500'
}}>
{Math.round(progress * 100)}%
</div>
</div>
<div style={{
fontSize: '12px',
color: getStatusColor(status),
marginBottom: '8px',
fontWeight: '500',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
}}>
<span>{getStageText(status)}</span>
{status === 'Chunking' && totalChunks && (
<span style={{ color: '#6b7280', fontSize: '11px' }}>
预计生成 {totalChunks} 个文本块
</span>
)}
{status === 'Embedding' && chunksProcessed !== undefined && totalChunks && (
<span style={{ color: '#6b7280', fontSize: '11px' }}>
🧠 生成向量: {chunksProcessed} / {totalChunks}
</span>
)}
{status === 'Embedding' && !chunksProcessed && totalChunks && (
<span style={{ color: '#6b7280', fontSize: '11px' }}>
预计生成 {totalChunks} 个向量
</span>
)}
{status === 'Completed' && totalChunks && (
<span style={{ color: '#22c55e', fontSize: '11px' }}>
✅ 已生成 {totalChunks} 个文本块
</span>
)}
</div>
<div style={{
width: '100%',
height: '8px',
backgroundColor: '#f3f4f6',
borderRadius: '4px',
overflow: 'hidden'
}}>
<div style={{
width: `${progress * 100}%`,
height: '100%',
backgroundColor: getStatusColor(status),
borderRadius: '4px',
transition: 'width 0.5s ease, background-color 0.3s ease',
background: status === 'Embedding'
? `linear-gradient(90deg, ${getStatusColor(status)}, ${getStatusColor(status)}aa, ${getStatusColor(status)})`
: status === 'Reading' || status === 'Preprocessing' || status === 'Chunking' || status === 'Storing'
? `linear-gradient(90deg, ${getStatusColor(status)}, ${getStatusColor(status)}cc)`
: getStatusColor(status),
position: 'relative',
overflow: 'hidden'
}}>
{(status === 'Embedding' || status === 'Storing') && progress < 1 && (
<div style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
background: `linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent)`,
animation: 'shimmer 2s infinite',
transform: 'translateX(-100%)'
}} />
)}
</div>
</div>
{status === 'Failed' && (
<div style={{
marginTop: '8px',
fontSize: '12px',
color: '#ef4444',
background: '#fef2f2',
padding: '8px',
borderRadius: '6px',
border: '1px solid #fecaca'
}}>
处理失败,请检查文件格式或重试
</div>
)}
</div>
);
};
// 定义分库接口类型
interface SubLibrary {
id: string;
name: string;
description?: string;
created_at: string;
updated_at: string;
document_count: number;
chunk_count: number;
}
interface CreateSubLibraryRequest {
name: string;
description?: string;
}
interface UpdateSubLibraryRequest {
name?: string;
description?: string;
}
interface EnhancedKnowledgeBaseManagementProps {
className?: string;
}
export const EnhancedKnowledgeBaseManagement: React.FC<EnhancedKnowledgeBaseManagementProps> = ({
className = ''
}) => {
// 分库相关状态
const [subLibraries, setSubLibraries] = useState<SubLibrary[]>([]);
const [selectedLibrary, setSelectedLibrary] = useState<string>('default');
const [documents, setDocuments] = useState<RagDocument[]>([]);
const [status, setStatus] = useState<KnowledgeBaseStatusPayload | null>(null);
const [loading, setLoading] = useState(false);
const [uploading, setUploading] = useState(false);
const [processingDocuments, setProcessingDocuments] = useState<Map<string, RagDocumentStatusEvent>>(new Map());
const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
// 分库管理状态
const [showCreateLibraryModal, setShowCreateLibraryModal] = useState(false);
const [showEditLibraryModal, setShowEditLibraryModal] = useState(false);
const [editingLibrary, setEditingLibrary] = useState<SubLibrary | null>(null);
const [newLibraryName, setNewLibraryName] = useState('');
const [newLibraryDescription, setNewLibraryDescription] = useState('');
const { showSuccess, showError, showWarning } = useNotification();
// 拖拽状态
const [isDragOver, setIsDragOver] = useState(false);
// 格式化文件大小
const formatFileSize = (bytes?: number) => {
if (!bytes) return '未知';
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
};
// 格式化日期
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString('zh-CN');
};
// 加载分库列表
const loadSubLibraries = useCallback(async () => {
try {
const libraries = await TauriAPI.invoke('get_rag_sub_libraries') as SubLibrary[];
setSubLibraries(libraries);
} catch (error) {
console.error('加载分库列表失败:', error);
showError(`加载分库列表失败: ${error}`);
}
}, [showError]);
// 加载知识库状态
const loadKnowledgeBaseStatus = useCallback(async () => {
try {
setLoading(true);
const statusData = await TauriAPI.ragGetKnowledgeBaseStatus();
setStatus(statusData);
} catch (error) {
console.error('加载知识库状态失败:', error);
showError(`加载知识库状态失败: ${error}`);
} finally {
setLoading(false);
}
}, [showError]);
// 加载指定分库的文档
const loadLibraryDocuments = useCallback(async (libraryId: string) => {
try {
setLoading(true);
const documentsData = await TauriAPI.invoke('get_rag_documents_by_library', {
request: {
sub_library_id: libraryId === 'default' ? null : libraryId,
page: 1,
page_size: 100
}
}) as RagDocument[];
setDocuments(documentsData);
} catch (error) {
console.error('加载文档列表失败:', error);
showError(`加载文档列表失败: ${error}`);
} finally {
setLoading(false);
}
}, [showError]);
// 创建新分库
const createSubLibrary = async () => {
if (!newLibraryName.trim()) {
showError('请输入分库名称');
return;
}
try {
const request: CreateSubLibraryRequest = {
name: newLibraryName.trim(),
description: newLibraryDescription.trim() || undefined
};
await TauriAPI.invoke('create_rag_sub_library', { request });
showSuccess(`分库 "${newLibraryName}" 创建成功`);
// 重置表单
setNewLibraryName('');
setNewLibraryDescription('');
setShowCreateLibraryModal(false);
// 重新加载分库列表
await loadSubLibraries();
} catch (error) {
console.error('创建分库失败:', error);
showError(`创建分库失败: ${error}`);
}
};
// 更新分库
const updateSubLibrary = async () => {
if (!editingLibrary || !newLibraryName.trim()) {
showError('请输入分库名称');
return;
}
try {
const request: UpdateSubLibraryRequest = {
name: newLibraryName.trim(),
description: newLibraryDescription.trim() || undefined
};
await TauriAPI.updateRagSubLibrary(editingLibrary.id, request);
showSuccess(`分库更新成功`);
// 重置表单
setNewLibraryName('');
setNewLibraryDescription('');
setShowEditLibraryModal(false);
setEditingLibrary(null);
// 重新加载分库列表
await loadSubLibraries();
} catch (error) {
console.error('更新分库失败:', error);
showError(`更新分库失败: ${error}`);
}
};
// 删除分库
const deleteSubLibrary = async (library: SubLibrary) => {
if (library.id === 'default') {
showError('不能删除默认分库');
return;
}
const confirmMessage = `确定要删除分库 "${library.name}" 吗?
分库信息:
- 文档数量:${library.document_count} 个
- 文本块数量:${library.chunk_count} 个
⚠️ 注意:分库删除后,其中的文档将自动移动到默认分库,文档内容不会丢失。
确定要继续吗?`;
const confirmDelete = window.confirm(confirmMessage);
if (!confirmDelete) return;
try {
console.log('开始删除分库:', library.id, library.name);
await TauriAPI.deleteRagSubLibrary(library.id, false); // 将文档移动到默认分库而不是删除
console.log('分库删除成功,开始刷新数据');
showSuccess(`分库 "${library.name}" 已删除,文档已移动到默认分库`);
// 立即从本地状态中移除该分库,提升界面响应速度
setSubLibraries(prev => prev.filter(lib => lib.id !== library.id));
if (selectedLibrary === library.id) {
// 切换到默认分库并加载其文档
setSelectedLibrary('default');
await loadLibraryDocuments('default');
} else {
// 重新加载当前分库文档
await loadLibraryDocuments(selectedLibrary);
}
// 同步更新知识库状态
await loadKnowledgeBaseStatus();
} catch (error) {
console.error('删除分库失败:', error);
showError(`删除分库失败: ${error}`);
}
};
// 上传文档到指定分库
const uploadDocuments = async () => {
if (selectedFiles.length === 0) {
showError('请选择要上传的文件');
return;
}
setUploading(true);
try {
// 读取文件内容,使用内容模式上传
const documents: Array<{ file_name: string; base64_content: string }> = [];
for (const file of selectedFiles) {
try {
const content = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onerror = (e) => reject(e);
// 根据文件类型选择读取方式
if (file.type === 'text/plain' || file.name.endsWith('.txt') || file.name.endsWith('.md')) {
reader.onload = (e) => {
const result = e.target?.result as string;
resolve(result);
};
reader.readAsText(file);
} else {
// 对于PDF、DOCX等二进制文件,读取为ArrayBuffer然后转换为base64
reader.onload = (e) => {
const arrayBuffer = e.target?.result as ArrayBuffer;
const uint8Array = new Uint8Array(arrayBuffer);
// 分块处理大文件,避免栈溢出
let binary = '';
const chunkSize = 8192; // 8KB chunks
for (let i = 0; i < uint8Array.length; i += chunkSize) {
const chunk = uint8Array.subarray(i, i + chunkSize);
binary += String.fromCharCode.apply(null, Array.from(chunk));
}
const base64 = btoa(binary);
resolve(base64);
};
reader.readAsArrayBuffer(file);
}
});
documents.push({
file_name: file.name,
base64_content: content
});
} catch (fileError) {
console.error(`处理文件 ${file.name} 失败:`, fileError);
showError(`处理文件 ${file.name} 失败`);
return;
}
}
if (documents.length === 0) {
showError('没有文件被成功处理');
return;
}
// 使用内容模式上传到分库
await TauriAPI.invoke('rag_add_documents_from_content_to_library', {
request: {
documents: documents,
sub_library_id: selectedLibrary === 'default' ? null : selectedLibrary
}
});
showSuccess(`成功上传 ${selectedFiles.length} 个文件到分库`);
setSelectedFiles([]);
// 重新加载当前分库的文档
await loadLibraryDocuments(selectedLibrary);
await loadKnowledgeBaseStatus();
} catch (error) {
console.error('上传文档失败:', error);
let errorMessage = '上传文档失败';
if (typeof error === 'string') {
errorMessage = `上传失败: ${error}`;
} else if (error instanceof Error) {
errorMessage = `上传失败: ${error.message}`;
} else if (error && typeof error === 'object' && 'message' in error) {
errorMessage = `上传失败: ${(error as any).message}`;
}
// 提供更有用的错误信息和建议
if (errorMessage.includes('系统找不到指定的文件') || errorMessage.includes('文件不存在')) {
errorMessage += '\n\n建议:\n• 文件可能已被移动或删除\n• 请重新选择文件\n• 检查文件名是否包含特殊字符';
}
showError(errorMessage);
} finally {
setUploading(false);
}
};
// 初始化加载
useEffect(() => {
loadSubLibraries();
loadKnowledgeBaseStatus();
}, [loadSubLibraries, loadKnowledgeBaseStatus]);
// 当选中的分库改变时,重新加载文档
useEffect(() => {
if (selectedLibrary) {
loadLibraryDocuments(selectedLibrary);
}
}, [selectedLibrary, loadLibraryDocuments]);
// 监听文档处理事件
useEffect(() => {
const setupListeners = async () => {
// 监听处理状态更新
await listen<RagProcessingEvent>('rag-processing-status', (event) => {
console.log('RAG处理状态:', event.payload);
});
// 监听文档状态更新
await listen<RagDocumentStatusEvent>('rag_document_status', (event) => {
const data = event.payload;
setProcessingDocuments(prev => {
const newMap = new Map(prev);
newMap.set(data.document_id, data);
return newMap;
});
if (data.status === 'Completed') {
showSuccess(`文档 "${data.file_name}" 处理完成,共生成 ${data.total_chunks} 个文本块`);
setTimeout(() => {
setProcessingDocuments(prev => {
const newMap = new Map(prev);
newMap.delete(data.document_id);
return newMap;
});
}, 3000);
} else if (data.status === 'Failed') {
const errorMsg = data.error_message || '未知错误';
showError(`文档 "${data.file_name}" 处理失败: ${errorMsg}`);
setTimeout(() => {
setProcessingDocuments(prev => {
const newMap = new Map(prev);
newMap.delete(data.document_id);
return newMap;
});
}, 8000);
}
});
};
setupListeners();
}, [selectedLibrary, loadLibraryDocuments, loadKnowledgeBaseStatus]);
// 文件拖拽处理
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = 'copy';
setIsDragOver(true);
};
const handleDragEnter = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(true);
};
const handleDragLeave = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
if (!e.currentTarget.contains(e.relatedTarget as Node)) {
setIsDragOver(false);
}
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
const files = Array.from(e.dataTransfer.files);
const supportedFiles = files.filter(file => {
const lowerName = file.name.toLowerCase();
return (
lowerName.endsWith('.pdf') ||
lowerName.endsWith('.docx') ||
lowerName.endsWith('.txt') ||
lowerName.endsWith('.md')
);
});
if (supportedFiles.length > 0) {
setSelectedFiles(prev => [...prev, ...supportedFiles]);
} else {
showWarning('请选择支持的文件格式(PDF、DOCX、TXT、MD)');
}
};
return (
<div style={{
width: '100%',
height: '100%',
overflow: 'auto',
background: '#f8fafc'
}}>
{/* 头部区域 - 统一白色样式 */}
<div style={{
background: 'white',
borderBottom: '1px solid #e5e7eb',
padding: '24px 32px',
position: 'relative'
}}>
<div style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
height: '4px',
background: 'linear-gradient(90deg, #667eea, #764ba2)'
}}></div>
<div style={{ position: 'relative', zIndex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#667eea" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight: '12px' }}>
<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/>
<path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"/>
<path d="M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"/>
<path d="M17.599 6.5a3 3 0 0 0 .399-1.375"/>
<path d="M6.003 5.125A3 3 0 0 0 6.401 6.5"/>
<path d="M3.477 10.896a4 4 0 0 1 .585-.396"/>
<path d="M19.938 10.5a4 4 0 0 1 .585.396"/>
<path d="M6 18a4 4 0 0 1-1.967-.516"/>
<path d="M19.967 17.484A4 4 0 0 1 18 18"/>
</svg>
<h1 style={{ fontSize: '28px', fontWeight: '700', margin: 0, color: '#1f2937' }}>增强知识库管理</h1>
</div>
<p style={{ fontSize: '16px', color: '#6b7280', margin: 0, lineHeight: '1.5' }}>
智能管理文档资源,构建强大的RAG知识检索系统
</p>
<div style={{ marginTop: '24px', display: 'flex', gap: '12px' }}>
<button
onClick={() => setShowCreateLibraryModal(true)}
style={{
background: '#667eea',
border: '1px solid #667eea',
color: 'white',
padding: '12px 24px',
borderRadius: '12px',
fontSize: '16px',
fontWeight: '600',
cursor: 'pointer',
display: 'inline-flex',
alignItems: 'center',
gap: '8px',
transition: 'all 0.3s ease',
backdropFilter: 'blur(10px)'
}}
onMouseOver={(e) => {
e.currentTarget.style.background = '#5a67d8';
e.currentTarget.style.transform = 'translateY(-2px)';
e.currentTarget.style.boxShadow = '0 8px 25px rgba(102, 126, 234, 0.4)';
}}
onMouseOut={(e) => {
e.currentTarget.style.background = '#667eea';
e.currentTarget.style.transform = 'translateY(0)';
e.currentTarget.style.boxShadow = 'none';
}}
>
<svg style={{ width: '20px', height: '20px' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
</svg>
创建分库
</button>
<button
onClick={() => {
loadSubLibraries();
loadKnowledgeBaseStatus();
loadLibraryDocuments(selectedLibrary);
}}
disabled={loading}
style={{
background: 'white',
border: '1px solid #d1d5db',
color: '#374151',
padding: '12px 24px',
borderRadius: '12px',
fontSize: '16px',
fontWeight: '600',
cursor: loading ? 'not-allowed' : 'pointer',
display: 'inline-flex',
alignItems: 'center',
gap: '8px',
transition: 'all 0.3s ease',
opacity: loading ? 0.6 : 1
}}
onMouseOver={(e) => {
if (!loading) {
e.currentTarget.style.background = '#f9fafb';
e.currentTarget.style.transform = 'translateY(-2px)';
e.currentTarget.style.boxShadow = '0 8px 25px rgba(0, 0, 0, 0.1)';
}
}}
onMouseOut={(e) => {
if (!loading) {
e.currentTarget.style.background = 'white';
e.currentTarget.style.transform = 'translateY(0)';
e.currentTarget.style.boxShadow = 'none';
}
}}
>
<svg style={{ width: '20px', height: '20px' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
刷新
</button>
</div>
</div>
</div>
<div className={`knowledge-base-management ${className}`} style={{ padding: '24px', background: 'transparent' }}>
{/* 知识库状态概览 */}
{status && (
<div className="status-overview">
<div className="status-item">
<span className="label">总文档数:</span>
<span className="value">{status.total_documents}</span>
</div>
<div className="status-item">
<span className="label">总文本块:</span>
<span className="value">{status.total_chunks}</span>
</div>
<div className="status-item">
<span className="label">向量存储:</span>
<span className="value">{status.vector_store_type}</span>
</div>
{status.embedding_model_name && (
<div className="status-item">
<span className="label">嵌入模型:</span>
<span className="value">{status.embedding_model_name}</span>
</div>
)}
</div>
)}
<div className="main-content">
{/* 分库管理侧栏 */}
<div className="library-sidebar">
<h3>分库列表</h3>
<div className="library-list">
{subLibraries.map(library => (
<div
key={library.id}
className={`library-item ${selectedLibrary === library.id ? 'selected' : ''}`}
onClick={() => setSelectedLibrary(library.id)}
>
<div className="library-info">
<div className="library-name">{library.name}</div>
<div className="library-stats" style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
<span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<FileText size={14} />
{library.document_count}
</span>
<span>|</span>
<span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<BookOpen size={14} />
{library.chunk_count}
</span>
</div>
{library.description && (
<div className="library-description">{library.description}</div>
)}
</div>
<div className="library-actions">
{library.id !== 'default' && (
<>
<button
onClick={(e) => {
e.stopPropagation();
setEditingLibrary(library);
setNewLibraryName(library.name);
setNewLibraryDescription(library.description || '');
setShowEditLibraryModal(true);
}}
className="library-action-btn edit"
style={{ display: 'flex', alignItems: 'center', gap: '4px' }}
>
<Edit size={14} />
</button>
<button
onClick={(e) => {
e.stopPropagation();
deleteSubLibrary(library);
}}
className="library-action-btn delete"
disabled={library.id === 'default'}
style={{ display: 'flex', alignItems: 'center', gap: '4px' }}
>
<Trash2 size={14} />
</button>
</>
)}
</div>
</div>
))}
</div>
</div>
{/* 文档管理主区域 */}
<div className="documents-main">
<div className="section-header">
<h3 style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<FileText size={20} />
{subLibraries.find(lib => lib.id === selectedLibrary)?.name || '默认分库'}
- 文档管理
</h3>
</div>
{/* 文件上传区域 */}
<div
className={`upload-zone ${isDragOver ? 'drag-over' : ''} ${uploading ? 'uploading' : ''}`}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<div
className="upload-content"
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<div className="upload-icon">📁</div>
<div className="upload-text">
{uploading ? '上传中...' : '拖拽文件到此处或点击选择文件'}
</div>
<div className="upload-hint">
支持格式: PDF, DOCX, TXT, MD
</div>
<input
type="file"
multiple
accept=".pdf,.PDF,.docx,.DOCX,.txt,.TXT,.md,.MD"
onChange={(e) => {
const files = Array.from(e.target.files || []);
setSelectedFiles(prev => [...prev, ...files]);
}}
style={{ display: 'none' }}
id="file-input"
/>
<label htmlFor="file-input" className="btn btn-primary">
选择文件
</label>
</div>
{selectedFiles.length > 0 && (
<div className="selected-files">
<h4>待上传文件 ({selectedFiles.length})</h4>
<div className="file-list">
{selectedFiles.map((file, index) => (
<div key={index} className="file-item">
<span className="file-name">{file.name}</span>
<span className="file-size">
{(file.size / 1024 / 1024).toFixed(2)} MB
</span>
<button
onClick={() => setSelectedFiles(prev =>
prev.filter((_, i) => i !== index)
)}
className="btn-remove"
>
✕
</button>
</div>
))}
</div>
<div className="upload-actions">
<button
onClick={uploadDocuments}
disabled={uploading}
className="btn btn-success"
>
{uploading ? '上传中...' : `上传到 ${subLibraries.find(lib => lib.id === selectedLibrary)?.name}`}
</button>
<button
onClick={() => setSelectedFiles([])}
disabled={uploading}
className="btn btn-secondary"
>
清空
</button>
</div>
</div>
)}
</div>
{/* 文档处理进度区域 */}
{processingDocuments.size > 0 && (
<div style={{
background: 'white',
border: '1px solid #e5e7eb',
borderRadius: '12px',
padding: '20px',
marginBottom: '24px',
boxShadow: '0 2px 4px rgba(0, 0, 0, 0.05)'
}}>
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: '16px'
}}>
<div style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
fontSize: '16px',
fontWeight: '600',
color: '#374151'
}}>
<div style={{
width: '20px',
height: '20px',
border: '2px solid #3b82f6',
borderTop: '2px solid transparent',
borderRadius: '50%',
animation: 'spin 1s linear infinite'
}} />
正在处理文档 ({processingDocuments.size} 个)
</div>
{/* 总体进度 */}
<div style={{
fontSize: '14px',
color: '#6b7280',
display: 'flex',
alignItems: 'center',
gap: '8px'
}}>
<span>总体进度:</span>
<div style={{
width: '100px',
height: '6px',
backgroundColor: '#f3f4f6',
borderRadius: '3px',
overflow: 'hidden'
}}>
<div style={{
width: `${(Array.from(processingDocuments.values()).reduce((sum, doc) => sum + doc.progress, 0) / processingDocuments.size) * 100}%`,
height: '100%',
backgroundColor: '#3b82f6',
borderRadius: '3px',
transition: 'width 0.3s ease'
}} />
</div>
<span style={{ fontWeight: '500', minWidth: '35px' }}>
{Math.round((Array.from(processingDocuments.values()).reduce((sum, doc) => sum + doc.progress, 0) / processingDocuments.size) * 100)}%
</span>
</div>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
{Array.from(processingDocuments.values()).map((doc) => (
<ProgressBar
key={doc.document_id}
progress={doc.progress}
status={doc.status}
fileName={doc.file_name}
totalChunks={doc.total_chunks}
chunksProcessed={doc.chunks_processed}
/>
))}
</div>
</div>
)}
{/* 文档列表 */}
<div className="documents-section">
<div className="documents-header">
<h4 style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<FileText size={20} />
{subLibraries.find(lib => lib.id === selectedLibrary)?.name || '默认分库'} - 文档管理
</h4>
</div>
{loading ? (
<div className="loading-state">加载中...</div>
) : documents.length === 0 ? (
<div className="empty-state">
<div className="empty-icon" style={{ display: 'flex', justifyContent: 'center', marginBottom: '16px' }}>
<FolderOpen size={48} color="#ccc" />
</div>
<div className="empty-text">该分库中暂无文档</div>
<div className="empty-hint">上传一些文档开始使用吧!</div>
</div>
) : (
<div className="documents-grid">
{documents.map((doc: any) => (
<div key={doc.id} className="document-card">
<div className="doc-header">
<div className="doc-name" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<FileText size={16} />
{doc.file_name}
</div>
<div className="doc-actions">
<button
onClick={async () => {
const confirmDelete = window.confirm(`确定要删除文档 "${doc.file_name}" 吗?此操作不可撤销。`);
if (!confirmDelete) return;
try {
console.log('开始删除文档:', doc.id, doc.file_name);
await TauriAPI.ragDeleteDocument(doc.id);
console.log('文档删除成功,开始刷新数据');
showSuccess(`文档 "${doc.file_name}" 删除成功`);
// 前端即时移除该文档以提升体验
setDocuments(prev => prev.filter(d => d.id !== doc.id));
// 更新知识库状态和分库统计
await loadKnowledgeBaseStatus();
await loadSubLibraries();
} catch (error) {
console.error('删除文档失败:', error);
showError(`删除文档失败: ${error}`);
}
}}
className="btn-icon"
title="删除文档"
style={{ display: 'flex', alignItems: 'center', gap: '4px' }}
>
<Trash2 size={14} />
</button>
</div>
</div>
<div className="doc-info">
<div className="doc-meta">
<span>大小: {formatFileSize(doc.file_size)}</span>
<span>文本块: {doc.total_chunks}</span>
<span>上传时间: {formatDate(doc.created_at)}</span>
</div>
</div>
</div>
))}
</div>
)}
</div>
</div>
</div>
{/* 创建分库模态框 */}
{showCreateLibraryModal && (
<div className="modal-overlay">
<div className="modal">
<div className="modal-header">
<h3>创建新分库</h3>
<button
onClick={() => setShowCreateLibraryModal(false)}
className="btn-close"
style={{ display: 'flex', alignItems: 'center' }}
>
<X size={16} />
</button>
</div>
<div className="modal-body">
<div className="form-group">
<label>分库名称 *</label>
<input
type="text"
value={newLibraryName}
onChange={(e) => setNewLibraryName(e.target.value)}
placeholder="请输入分库名称"
className="form-input"
/>
</div>
<div className="form-group">
<label>分库描述</label>
<textarea
value={newLibraryDescription}
onChange={(e) => setNewLibraryDescription(e.target.value)}
placeholder="请输入分库描述(可选)"
className="form-textarea"
rows={3}
/>
</div>
</div>
<div className="modal-footer">
<button
onClick={() => setShowCreateLibraryModal(false)}
className="btn btn-secondary"
>
取消
</button>
<button
onClick={createSubLibrary}
className="btn btn-primary"
disabled={!newLibraryName.trim()}
>
创建
</button>
</div>
</div>
</div>
)}
{/* 编辑分库模态框 */}
{showEditLibraryModal && editingLibrary && (
<div className="modal-overlay">
<div className="modal">
<div className="modal-header">
<h3>编辑分库</h3>
<button
onClick={() => {
setShowEditLibraryModal(false);
setEditingLibrary(null);
}}
className="btn-close"
style={{ display: 'flex', alignItems: 'center' }}
>
<X size={16} />
</button>
</div>
<div className="modal-body">
<div className="form-group">
<label>分库名称 *</label>
<input
type="text"
value={newLibraryName}
onChange={(e) => setNewLibraryName(e.target.value)}
placeholder="请输入分库名称"
className="form-input"
/>
</div>
<div className="form-group">
<label>分库描述</label>
<textarea
value={newLibraryDescription}
onChange={(e) => setNewLibraryDescription(e.target.value)}
placeholder="请输入分库描述(可选)"
className="form-textarea"
rows={3}
/>
</div>
</div>
<div className="modal-footer">
<button
onClick={() => {
setShowEditLibraryModal(false);
setEditingLibrary(null);
}}
className="btn btn-secondary"
>
取消
</button>
<button
onClick={updateSubLibrary}
className="btn btn-primary"
disabled={!newLibraryName.trim()}
>
保存
</button>
</div>
</div>
</div>
)}
</div>
</div>
);
};
export default EnhancedKnowledgeBaseManagement;
|
0015/StickiNote
| 82,172 |
sdkconfig
|
#
# Automatically generated file. DO NOT EDIT.
# Espressif IoT Development Framework (ESP-IDF) 5.4.0 Project Configuration
#
CONFIG_SOC_ADC_SUPPORTED=y
CONFIG_SOC_ANA_CMPR_SUPPORTED=y
CONFIG_SOC_DEDICATED_GPIO_SUPPORTED=y
CONFIG_SOC_UART_SUPPORTED=y
CONFIG_SOC_GDMA_SUPPORTED=y
CONFIG_SOC_AHB_GDMA_SUPPORTED=y
CONFIG_SOC_AXI_GDMA_SUPPORTED=y
CONFIG_SOC_DW_GDMA_SUPPORTED=y
CONFIG_SOC_DMA2D_SUPPORTED=y
CONFIG_SOC_GPTIMER_SUPPORTED=y
CONFIG_SOC_PCNT_SUPPORTED=y
CONFIG_SOC_LCDCAM_SUPPORTED=y
CONFIG_SOC_LCDCAM_CAM_SUPPORTED=y
CONFIG_SOC_LCDCAM_I80_LCD_SUPPORTED=y
CONFIG_SOC_LCDCAM_RGB_LCD_SUPPORTED=y
CONFIG_SOC_MIPI_CSI_SUPPORTED=y
CONFIG_SOC_MIPI_DSI_SUPPORTED=y
CONFIG_SOC_MCPWM_SUPPORTED=y
CONFIG_SOC_TWAI_SUPPORTED=y
CONFIG_SOC_ETM_SUPPORTED=y
CONFIG_SOC_PARLIO_SUPPORTED=y
CONFIG_SOC_ASYNC_MEMCPY_SUPPORTED=y
CONFIG_SOC_EMAC_SUPPORTED=y
CONFIG_SOC_USB_OTG_SUPPORTED=y
CONFIG_SOC_WIRELESS_HOST_SUPPORTED=y
CONFIG_SOC_USB_SERIAL_JTAG_SUPPORTED=y
CONFIG_SOC_TEMP_SENSOR_SUPPORTED=y
CONFIG_SOC_SUPPORTS_SECURE_DL_MODE=y
CONFIG_SOC_ULP_SUPPORTED=y
CONFIG_SOC_LP_CORE_SUPPORTED=y
CONFIG_SOC_EFUSE_KEY_PURPOSE_FIELD=y
CONFIG_SOC_EFUSE_SUPPORTED=y
CONFIG_SOC_RTC_FAST_MEM_SUPPORTED=y
CONFIG_SOC_RTC_MEM_SUPPORTED=y
CONFIG_SOC_RMT_SUPPORTED=y
CONFIG_SOC_I2S_SUPPORTED=y
CONFIG_SOC_SDM_SUPPORTED=y
CONFIG_SOC_GPSPI_SUPPORTED=y
CONFIG_SOC_LEDC_SUPPORTED=y
CONFIG_SOC_ISP_SUPPORTED=y
CONFIG_SOC_I2C_SUPPORTED=y
CONFIG_SOC_SYSTIMER_SUPPORTED=y
CONFIG_SOC_AES_SUPPORTED=y
CONFIG_SOC_MPI_SUPPORTED=y
CONFIG_SOC_SHA_SUPPORTED=y
CONFIG_SOC_HMAC_SUPPORTED=y
CONFIG_SOC_DIG_SIGN_SUPPORTED=y
CONFIG_SOC_ECC_SUPPORTED=y
CONFIG_SOC_ECC_EXTENDED_MODES_SUPPORTED=y
CONFIG_SOC_FLASH_ENC_SUPPORTED=y
CONFIG_SOC_SECURE_BOOT_SUPPORTED=y
CONFIG_SOC_BOD_SUPPORTED=y
CONFIG_SOC_APM_SUPPORTED=y
CONFIG_SOC_PMU_SUPPORTED=y
CONFIG_SOC_DCDC_SUPPORTED=y
CONFIG_SOC_PAU_SUPPORTED=y
CONFIG_SOC_LP_TIMER_SUPPORTED=y
CONFIG_SOC_ULP_LP_UART_SUPPORTED=y
CONFIG_SOC_LP_GPIO_MATRIX_SUPPORTED=y
CONFIG_SOC_LP_PERIPHERALS_SUPPORTED=y
CONFIG_SOC_LP_I2C_SUPPORTED=y
CONFIG_SOC_LP_I2S_SUPPORTED=y
CONFIG_SOC_LP_SPI_SUPPORTED=y
CONFIG_SOC_LP_ADC_SUPPORTED=y
CONFIG_SOC_LP_VAD_SUPPORTED=y
CONFIG_SOC_SPIRAM_SUPPORTED=y
CONFIG_SOC_PSRAM_DMA_CAPABLE=y
CONFIG_SOC_SDMMC_HOST_SUPPORTED=y
CONFIG_SOC_CLK_TREE_SUPPORTED=y
CONFIG_SOC_ASSIST_DEBUG_SUPPORTED=y
CONFIG_SOC_DEBUG_PROBE_SUPPORTED=y
CONFIG_SOC_WDT_SUPPORTED=y
CONFIG_SOC_SPI_FLASH_SUPPORTED=y
CONFIG_SOC_TOUCH_SENSOR_SUPPORTED=y
CONFIG_SOC_RNG_SUPPORTED=y
CONFIG_SOC_GP_LDO_SUPPORTED=y
CONFIG_SOC_PPA_SUPPORTED=y
CONFIG_SOC_LIGHT_SLEEP_SUPPORTED=y
CONFIG_SOC_DEEP_SLEEP_SUPPORTED=y
CONFIG_SOC_PM_SUPPORTED=y
CONFIG_SOC_XTAL_SUPPORT_40M=y
CONFIG_SOC_AES_SUPPORT_DMA=y
CONFIG_SOC_AES_SUPPORT_GCM=y
CONFIG_SOC_AES_GDMA=y
CONFIG_SOC_AES_SUPPORT_AES_128=y
CONFIG_SOC_AES_SUPPORT_AES_256=y
CONFIG_SOC_ADC_RTC_CTRL_SUPPORTED=y
CONFIG_SOC_ADC_DIG_CTRL_SUPPORTED=y
CONFIG_SOC_ADC_DMA_SUPPORTED=y
CONFIG_SOC_ADC_PERIPH_NUM=2
CONFIG_SOC_ADC_MAX_CHANNEL_NUM=8
CONFIG_SOC_ADC_ATTEN_NUM=4
CONFIG_SOC_ADC_DIGI_CONTROLLER_NUM=2
CONFIG_SOC_ADC_PATT_LEN_MAX=16
CONFIG_SOC_ADC_DIGI_MAX_BITWIDTH=12
CONFIG_SOC_ADC_DIGI_MIN_BITWIDTH=12
CONFIG_SOC_ADC_DIGI_IIR_FILTER_NUM=2
CONFIG_SOC_ADC_DIGI_MONITOR_NUM=2
CONFIG_SOC_ADC_DIGI_RESULT_BYTES=4
CONFIG_SOC_ADC_DIGI_DATA_BYTES_PER_CONV=4
CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_HIGH=83333
CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_LOW=611
CONFIG_SOC_ADC_RTC_MIN_BITWIDTH=12
CONFIG_SOC_ADC_RTC_MAX_BITWIDTH=12
CONFIG_SOC_ADC_SHARED_POWER=y
CONFIG_SOC_BROWNOUT_RESET_SUPPORTED=y
CONFIG_SOC_SHARED_IDCACHE_SUPPORTED=y
CONFIG_SOC_CACHE_WRITEBACK_SUPPORTED=y
CONFIG_SOC_CACHE_FREEZE_SUPPORTED=y
CONFIG_SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE=y
CONFIG_SOC_CPU_CORES_NUM=2
CONFIG_SOC_CPU_INTR_NUM=32
CONFIG_SOC_CPU_HAS_FLEXIBLE_INTC=y
CONFIG_SOC_INT_CLIC_SUPPORTED=y
CONFIG_SOC_INT_HW_NESTED_SUPPORTED=y
CONFIG_SOC_BRANCH_PREDICTOR_SUPPORTED=y
CONFIG_SOC_CPU_COPROC_NUM=3
CONFIG_SOC_CPU_HAS_FPU=y
CONFIG_SOC_CPU_HAS_FPU_EXT_ILL_BUG=y
CONFIG_SOC_CPU_HAS_HWLOOP=y
CONFIG_SOC_CPU_HAS_PIE=y
CONFIG_SOC_HP_CPU_HAS_MULTIPLE_CORES=y
CONFIG_SOC_CPU_BREAKPOINTS_NUM=3
CONFIG_SOC_CPU_WATCHPOINTS_NUM=3
CONFIG_SOC_CPU_WATCHPOINT_MAX_REGION_SIZE=0x100
CONFIG_SOC_CPU_HAS_PMA=y
CONFIG_SOC_CPU_IDRAM_SPLIT_USING_PMP=y
CONFIG_SOC_CPU_PMP_REGION_GRANULARITY=128
CONFIG_SOC_CPU_HAS_LOCKUP_RESET=y
CONFIG_SOC_DS_SIGNATURE_MAX_BIT_LEN=4096
CONFIG_SOC_DS_KEY_PARAM_MD_IV_LENGTH=16
CONFIG_SOC_DS_KEY_CHECK_MAX_WAIT_US=1100
CONFIG_SOC_DMA_CAN_ACCESS_FLASH=y
CONFIG_SOC_AHB_GDMA_VERSION=2
CONFIG_SOC_GDMA_SUPPORT_CRC=y
CONFIG_SOC_GDMA_NUM_GROUPS_MAX=2
CONFIG_SOC_GDMA_PAIRS_PER_GROUP_MAX=3
CONFIG_SOC_AXI_GDMA_SUPPORT_PSRAM=y
CONFIG_SOC_GDMA_SUPPORT_ETM=y
CONFIG_SOC_GDMA_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_AXI_DMA_EXT_MEM_ENC_ALIGNMENT=16
CONFIG_SOC_DMA2D_GROUPS=1
CONFIG_SOC_DMA2D_TX_CHANNELS_PER_GROUP=3
CONFIG_SOC_DMA2D_RX_CHANNELS_PER_GROUP=2
CONFIG_SOC_ETM_GROUPS=1
CONFIG_SOC_ETM_CHANNELS_PER_GROUP=50
CONFIG_SOC_ETM_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_GPIO_PORT=1
CONFIG_SOC_GPIO_PIN_COUNT=55
CONFIG_SOC_GPIO_SUPPORT_PIN_GLITCH_FILTER=y
CONFIG_SOC_GPIO_FLEX_GLITCH_FILTER_NUM=8
CONFIG_SOC_GPIO_SUPPORT_PIN_HYS_FILTER=y
CONFIG_SOC_GPIO_SUPPORT_ETM=y
CONFIG_SOC_GPIO_SUPPORT_RTC_INDEPENDENT=y
CONFIG_SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP=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
CONFIG_SOC_ISP_HIST_INTERVAL_NUMS=15
CONFIG_SOC_ISP_LSC_GRAD_RATIO_INT_BITS=2
CONFIG_SOC_ISP_LSC_GRAD_RATIO_DEC_BITS=8
CONFIG_SOC_ISP_LSC_GRAD_RATIO_RES_BITS=22
CONFIG_SOC_LEDC_SUPPORT_PLL_DIV_CLOCK=y
CONFIG_SOC_LEDC_SUPPORT_XTAL_CLOCK=y
CONFIG_SOC_LEDC_TIMER_NUM=4
CONFIG_SOC_LEDC_CHANNEL_NUM=8
CONFIG_SOC_LEDC_TIMER_BIT_WIDTH=20
CONFIG_SOC_LEDC_GAMMA_CURVE_FADE_SUPPORTED=y
CONFIG_SOC_LEDC_GAMMA_CURVE_FADE_RANGE_MAX=16
CONFIG_SOC_LEDC_SUPPORT_FADE_STOP=y
CONFIG_SOC_LEDC_FADE_PARAMS_BIT_WIDTH=10
CONFIG_SOC_LEDC_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_MMU_PERIPH_NUM=2
CONFIG_SOC_MMU_LINEAR_ADDRESS_REGION_NUM=2
CONFIG_SOC_MMU_DI_VADDR_SHARED=y
CONFIG_SOC_MMU_PER_EXT_MEM_TARGET=y
CONFIG_SOC_MPU_MIN_REGION_SIZE=0x20000000
CONFIG_SOC_MPU_REGIONS_MAX_NUM=8
CONFIG_SOC_PCNT_GROUPS=1
CONFIG_SOC_PCNT_UNITS_PER_GROUP=4
CONFIG_SOC_PCNT_CHANNELS_PER_UNIT=2
CONFIG_SOC_PCNT_THRES_POINT_PER_UNIT=2
CONFIG_SOC_PCNT_SUPPORT_RUNTIME_THRES_UPDATE=y
CONFIG_SOC_PCNT_SUPPORT_CLEAR_SIGNAL=y
CONFIG_SOC_RMT_GROUPS=1
CONFIG_SOC_RMT_TX_CANDIDATES_PER_GROUP=4
CONFIG_SOC_RMT_RX_CANDIDATES_PER_GROUP=4
CONFIG_SOC_RMT_CHANNELS_PER_GROUP=8
CONFIG_SOC_RMT_MEM_WORDS_PER_CHANNEL=48
CONFIG_SOC_RMT_SUPPORT_RX_PINGPONG=y
CONFIG_SOC_RMT_SUPPORT_RX_DEMODULATION=y
CONFIG_SOC_RMT_SUPPORT_TX_ASYNC_STOP=y
CONFIG_SOC_RMT_SUPPORT_TX_LOOP_COUNT=y
CONFIG_SOC_RMT_SUPPORT_TX_LOOP_AUTO_STOP=y
CONFIG_SOC_RMT_SUPPORT_TX_SYNCHRO=y
CONFIG_SOC_RMT_SUPPORT_TX_CARRIER_DATA_ONLY=y
CONFIG_SOC_RMT_SUPPORT_XTAL=y
CONFIG_SOC_RMT_SUPPORT_RC_FAST=y
CONFIG_SOC_RMT_SUPPORT_DMA=y
CONFIG_SOC_RMT_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_LCD_I80_SUPPORTED=y
CONFIG_SOC_LCD_RGB_SUPPORTED=y
CONFIG_SOC_LCDCAM_I80_NUM_BUSES=1
CONFIG_SOC_LCDCAM_I80_BUS_WIDTH=24
CONFIG_SOC_LCDCAM_RGB_NUM_PANELS=1
CONFIG_SOC_LCDCAM_RGB_DATA_WIDTH=24
CONFIG_SOC_LCD_SUPPORT_RGB_YUV_CONV=y
CONFIG_SOC_MCPWM_GROUPS=2
CONFIG_SOC_MCPWM_TIMERS_PER_GROUP=3
CONFIG_SOC_MCPWM_OPERATORS_PER_GROUP=3
CONFIG_SOC_MCPWM_COMPARATORS_PER_OPERATOR=2
CONFIG_SOC_MCPWM_EVENT_COMPARATORS_PER_OPERATOR=2
CONFIG_SOC_MCPWM_GENERATORS_PER_OPERATOR=2
CONFIG_SOC_MCPWM_TRIGGERS_PER_OPERATOR=2
CONFIG_SOC_MCPWM_GPIO_FAULTS_PER_GROUP=3
CONFIG_SOC_MCPWM_CAPTURE_TIMERS_PER_GROUP=y
CONFIG_SOC_MCPWM_CAPTURE_CHANNELS_PER_TIMER=3
CONFIG_SOC_MCPWM_GPIO_SYNCHROS_PER_GROUP=3
CONFIG_SOC_MCPWM_SWSYNC_CAN_PROPAGATE=y
CONFIG_SOC_MCPWM_SUPPORT_ETM=y
CONFIG_SOC_MCPWM_SUPPORT_EVENT_COMPARATOR=y
CONFIG_SOC_MCPWM_CAPTURE_CLK_FROM_GROUP=y
CONFIG_SOC_USB_OTG_PERIPH_NUM=2
CONFIG_SOC_USB_UTMI_PHY_NUM=1
CONFIG_SOC_PARLIO_GROUPS=1
CONFIG_SOC_PARLIO_TX_UNITS_PER_GROUP=1
CONFIG_SOC_PARLIO_RX_UNITS_PER_GROUP=1
CONFIG_SOC_PARLIO_TX_UNIT_MAX_DATA_WIDTH=16
CONFIG_SOC_PARLIO_RX_UNIT_MAX_DATA_WIDTH=16
CONFIG_SOC_PARLIO_TX_CLK_SUPPORT_GATING=y
CONFIG_SOC_PARLIO_RX_CLK_SUPPORT_GATING=y
CONFIG_SOC_PARLIO_RX_CLK_SUPPORT_OUTPUT=y
CONFIG_SOC_PARLIO_TRANS_BIT_ALIGN=y
CONFIG_SOC_PARLIO_TX_SIZE_BY_DMA=y
CONFIG_SOC_PARLIO_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_MPI_MEM_BLOCKS_NUM=4
CONFIG_SOC_MPI_OPERATIONS_NUM=3
CONFIG_SOC_RSA_MAX_BIT_LEN=4096
CONFIG_SOC_SDMMC_USE_IOMUX=y
CONFIG_SOC_SDMMC_USE_GPIO_MATRIX=y
CONFIG_SOC_SDMMC_NUM_SLOTS=2
CONFIG_SOC_SDMMC_DELAY_PHASE_NUM=4
CONFIG_SOC_SDMMC_IO_POWER_EXTERNAL=y
CONFIG_SOC_SDMMC_PSRAM_DMA_CAPABLE=y
CONFIG_SOC_SDMMC_UHS_I_SUPPORTED=y
CONFIG_SOC_SHA_DMA_MAX_BUFFER_SIZE=3968
CONFIG_SOC_SHA_SUPPORT_DMA=y
CONFIG_SOC_SHA_SUPPORT_RESUME=y
CONFIG_SOC_SHA_GDMA=y
CONFIG_SOC_SHA_SUPPORT_SHA1=y
CONFIG_SOC_SHA_SUPPORT_SHA224=y
CONFIG_SOC_SHA_SUPPORT_SHA256=y
CONFIG_SOC_SHA_SUPPORT_SHA384=y
CONFIG_SOC_SHA_SUPPORT_SHA512=y
CONFIG_SOC_SHA_SUPPORT_SHA512_224=y
CONFIG_SOC_SHA_SUPPORT_SHA512_256=y
CONFIG_SOC_SHA_SUPPORT_SHA512_T=y
CONFIG_SOC_ECDSA_SUPPORT_EXPORT_PUBKEY=y
CONFIG_SOC_ECDSA_SUPPORT_DETERMINISTIC_MODE=y
CONFIG_SOC_ECDSA_USES_MPI=y
CONFIG_SOC_SDM_GROUPS=1
CONFIG_SOC_SDM_CHANNELS_PER_GROUP=8
CONFIG_SOC_SDM_CLK_SUPPORT_PLL_F80M=y
CONFIG_SOC_SDM_CLK_SUPPORT_XTAL=y
CONFIG_SOC_SPI_PERIPH_NUM=3
CONFIG_SOC_SPI_MAX_CS_NUM=6
CONFIG_SOC_SPI_MAXIMUM_BUFFER_SIZE=64
CONFIG_SOC_SPI_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_SPI_SUPPORT_SLAVE_HD_VER2=y
CONFIG_SOC_SPI_SLAVE_SUPPORT_SEG_TRANS=y
CONFIG_SOC_SPI_SUPPORT_DDRCLK=y
CONFIG_SOC_SPI_SUPPORT_CD_SIG=y
CONFIG_SOC_SPI_SUPPORT_OCT=y
CONFIG_SOC_SPI_SUPPORT_CLK_XTAL=y
CONFIG_SOC_SPI_SUPPORT_CLK_RC_FAST=y
CONFIG_SOC_SPI_SUPPORT_CLK_SPLL=y
CONFIG_SOC_MEMSPI_IS_INDEPENDENT=y
CONFIG_SOC_SPI_MAX_PRE_DIVIDER=16
CONFIG_SOC_LP_SPI_PERIPH_NUM=y
CONFIG_SOC_LP_SPI_MAXIMUM_BUFFER_SIZE=64
CONFIG_SOC_SPIRAM_XIP_SUPPORTED=y
CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_WAIT_IDLE=y
CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_SUSPEND=y
CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_RESUME=y
CONFIG_SOC_SPI_MEM_SUPPORT_IDLE_INTR=y
CONFIG_SOC_SPI_MEM_SUPPORT_SW_SUSPEND=y
CONFIG_SOC_SPI_MEM_SUPPORT_CHECK_SUS=y
CONFIG_SOC_SPI_MEM_SUPPORT_TIMING_TUNING=y
CONFIG_SOC_MEMSPI_TIMING_TUNING_BY_DQS=y
CONFIG_SOC_SPI_MEM_SUPPORT_CACHE_32BIT_ADDR_MAP=y
CONFIG_SOC_SPI_PERIPH_SUPPORT_CONTROL_DUMMY_OUT=y
CONFIG_SOC_MEMSPI_SRC_FREQ_80M_SUPPORTED=y
CONFIG_SOC_MEMSPI_SRC_FREQ_40M_SUPPORTED=y
CONFIG_SOC_MEMSPI_SRC_FREQ_20M_SUPPORTED=y
CONFIG_SOC_MEMSPI_FLASH_PSRAM_INDEPENDENT=y
CONFIG_SOC_SYSTIMER_COUNTER_NUM=2
CONFIG_SOC_SYSTIMER_ALARM_NUM=3
CONFIG_SOC_SYSTIMER_BIT_WIDTH_LO=32
CONFIG_SOC_SYSTIMER_BIT_WIDTH_HI=20
CONFIG_SOC_SYSTIMER_FIXED_DIVIDER=y
CONFIG_SOC_SYSTIMER_SUPPORT_RC_FAST=y
CONFIG_SOC_SYSTIMER_INT_LEVEL=y
CONFIG_SOC_SYSTIMER_ALARM_MISS_COMPENSATE=y
CONFIG_SOC_SYSTIMER_SUPPORT_ETM=y
CONFIG_SOC_LP_TIMER_BIT_WIDTH_LO=32
CONFIG_SOC_LP_TIMER_BIT_WIDTH_HI=16
CONFIG_SOC_TIMER_GROUPS=2
CONFIG_SOC_TIMER_GROUP_TIMERS_PER_GROUP=2
CONFIG_SOC_TIMER_GROUP_COUNTER_BIT_WIDTH=54
CONFIG_SOC_TIMER_GROUP_SUPPORT_XTAL=y
CONFIG_SOC_TIMER_GROUP_SUPPORT_RC_FAST=y
CONFIG_SOC_TIMER_GROUP_TOTAL_TIMERS=4
CONFIG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OC_SUPPORT_SECURE_BOOT_REVOKE_KEY=y
CONFIG_SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX=64
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES=y
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_OPTIONS=y
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_128=y
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_256=y
CONFIG_SOC_UART_NUM=6
CONFIG_SOC_UART_HP_NUM=5
CONFIG_SOC_UART_LP_NUM=1
CONFIG_SOC_UART_FIFO_LEN=128
CONFIG_SOC_LP_UART_FIFO_LEN=16
CONFIG_SOC_UART_BITRATE_MAX=5000000
CONFIG_SOC_UART_SUPPORT_PLL_F80M_CLK=y
CONFIG_SOC_UART_SUPPORT_RTC_CLK=y
CONFIG_SOC_UART_SUPPORT_XTAL_CLK=y
CONFIG_SOC_UART_SUPPORT_WAKEUP_INT=y
CONFIG_SOC_UART_HAS_LP_UART=y
CONFIG_SOC_UART_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_UART_SUPPORT_FSM_TX_WAIT_SEND=y
CONFIG_SOC_LP_I2S_SUPPORT_VAD=y
CONFIG_SOC_COEX_HW_PTI=y
CONFIG_SOC_PHY_DIG_REGS_MEM_SIZE=21
CONFIG_SOC_WIFI_LIGHT_SLEEP_CLK_WIDTH=12
CONFIG_SOC_PM_SUPPORT_EXT1_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_EXT1_WAKEUP_MODE_PER_PIN=y
CONFIG_SOC_PM_EXT1_WAKEUP_BY_PMU=y
CONFIG_SOC_PM_SUPPORT_WIFI_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_XTAL32K_PD=y
CONFIG_SOC_PM_SUPPORT_RC32K_PD=y
CONFIG_SOC_PM_SUPPORT_RC_FAST_PD=y
CONFIG_SOC_PM_SUPPORT_VDDSDIO_PD=y
CONFIG_SOC_PM_SUPPORT_TOP_PD=y
CONFIG_SOC_PM_SUPPORT_CNNT_PD=y
CONFIG_SOC_PM_SUPPORT_RTC_PERIPH_PD=y
CONFIG_SOC_PM_SUPPORT_DEEPSLEEP_CHECK_STUB_ONLY=y
CONFIG_SOC_PM_CPU_RETENTION_BY_SW=y
CONFIG_SOC_PM_PAU_LINK_NUM=4
CONFIG_SOC_PM_PAU_REGDMA_LINK_MULTI_ADDR=y
CONFIG_SOC_PAU_IN_TOP_DOMAIN=y
CONFIG_SOC_CPU_IN_TOP_DOMAIN=y
CONFIG_SOC_PM_PAU_REGDMA_UPDATE_CACHE_BEFORE_WAIT_COMPARE=y
CONFIG_SOC_SLEEP_SYSTIMER_STALL_WORKAROUND=y
CONFIG_SOC_SLEEP_TGWDT_STOP_WORKAROUND=y
CONFIG_SOC_PM_RETENTION_MODULE_NUM=64
CONFIG_SOC_PSRAM_VDD_POWER_MPLL=y
CONFIG_SOC_CLK_RC_FAST_SUPPORT_CALIBRATION=y
CONFIG_SOC_CLK_APLL_SUPPORTED=y
CONFIG_SOC_CLK_MPLL_SUPPORTED=y
CONFIG_SOC_CLK_SDIO_PLL_SUPPORTED=y
CONFIG_SOC_CLK_XTAL32K_SUPPORTED=y
CONFIG_SOC_CLK_RC32K_SUPPORTED=y
CONFIG_SOC_CLK_LP_FAST_SUPPORT_LP_PLL=y
CONFIG_SOC_CLK_LP_FAST_SUPPORT_XTAL=y
CONFIG_SOC_PERIPH_CLK_CTRL_SHARED=y
CONFIG_SOC_TEMPERATURE_SENSOR_LP_PLL_SUPPORT=y
CONFIG_SOC_TEMPERATURE_SENSOR_INTR_SUPPORT=y
CONFIG_SOC_TSENS_IS_INDEPENDENT_FROM_ADC=y
CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_ETM=y
CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_MEM_TCM_SUPPORTED=y
CONFIG_SOC_MEM_NON_CONTIGUOUS_SRAM=y
CONFIG_SOC_ASYNCHRONOUS_BUS_ERROR_MODE=y
CONFIG_SOC_EMAC_IEEE_1588_SUPPORT=y
CONFIG_SOC_EMAC_USE_MULTI_IO_MUX=y
CONFIG_SOC_EMAC_MII_USE_GPIO_MATRIX=y
CONFIG_SOC_JPEG_CODEC_SUPPORTED=y
CONFIG_SOC_JPEG_DECODE_SUPPORTED=y
CONFIG_SOC_JPEG_ENCODE_SUPPORTED=y
CONFIG_SOC_LCDCAM_CAM_SUPPORT_RGB_YUV_CONV=y
CONFIG_SOC_LCDCAM_CAM_PERIPH_NUM=1
CONFIG_SOC_LCDCAM_CAM_DATA_WIDTH_MAX=16
CONFIG_SOC_LP_CORE_SUPPORT_ETM=y
CONFIG_SOC_LP_CORE_SUPPORT_LP_ADC=y
CONFIG_SOC_LP_CORE_SUPPORT_LP_VAD=y
CONFIG_IDF_CMAKE=y
CONFIG_IDF_TOOLCHAIN="gcc"
CONFIG_IDF_TOOLCHAIN_GCC=y
CONFIG_IDF_TARGET_ARCH_RISCV=y
CONFIG_IDF_TARGET_ARCH="riscv"
CONFIG_IDF_TARGET="esp32p4"
CONFIG_IDF_INIT_VERSION="5.4.0"
CONFIG_IDF_TARGET_ESP32P4=y
CONFIG_IDF_FIRMWARE_CHIP_ID=0x0012
#
# Build type
#
CONFIG_APP_BUILD_TYPE_APP_2NDBOOT=y
# CONFIG_APP_BUILD_TYPE_RAM is not set
CONFIG_APP_BUILD_GENERATE_BINARIES=y
CONFIG_APP_BUILD_BOOTLOADER=y
CONFIG_APP_BUILD_USE_FLASH_SECTIONS=y
# CONFIG_APP_REPRODUCIBLE_BUILD is not set
# CONFIG_APP_NO_BLOBS is not set
# end of Build type
#
# Bootloader config
#
#
# Bootloader manager
#
CONFIG_BOOTLOADER_COMPILE_TIME_DATE=y
CONFIG_BOOTLOADER_PROJECT_VER=1
# end of Bootloader manager
CONFIG_BOOTLOADER_OFFSET_IN_FLASH=0x2000
CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y
# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG is not set
# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_PERF is not set
#
# Log
#
# CONFIG_BOOTLOADER_LOG_LEVEL_NONE is not set
# CONFIG_BOOTLOADER_LOG_LEVEL_ERROR is not set
# CONFIG_BOOTLOADER_LOG_LEVEL_WARN is not set
CONFIG_BOOTLOADER_LOG_LEVEL_INFO=y
# CONFIG_BOOTLOADER_LOG_LEVEL_DEBUG is not set
# CONFIG_BOOTLOADER_LOG_LEVEL_VERBOSE is not set
CONFIG_BOOTLOADER_LOG_LEVEL=3
#
# Format
#
# CONFIG_BOOTLOADER_LOG_COLORS is not set
CONFIG_BOOTLOADER_LOG_TIMESTAMP_SOURCE_CPU_TICKS=y
# end of Format
# end of Log
#
# Serial Flash Configurations
#
# CONFIG_BOOTLOADER_FLASH_DC_AWARE is not set
CONFIG_BOOTLOADER_FLASH_XMC_SUPPORT=y
# end of Serial Flash Configurations
# CONFIG_BOOTLOADER_FACTORY_RESET is not set
# CONFIG_BOOTLOADER_APP_TEST is not set
CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE=y
CONFIG_BOOTLOADER_WDT_ENABLE=y
# CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE is not set
CONFIG_BOOTLOADER_WDT_TIME_MS=9000
# CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE is not set
# CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP is not set
# CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON is not set
# CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS is not set
CONFIG_BOOTLOADER_RESERVE_RTC_SIZE=0
# CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC is not set
# end of Bootloader config
#
# Security features
#
CONFIG_SECURE_BOOT_V2_RSA_SUPPORTED=y
CONFIG_SECURE_BOOT_V2_ECC_SUPPORTED=y
CONFIG_SECURE_BOOT_V2_PREFERRED=y
# CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT is not set
# CONFIG_SECURE_BOOT is not set
# CONFIG_SECURE_FLASH_ENC_ENABLED is not set
CONFIG_SECURE_ROM_DL_MODE_ENABLED=y
# end of Security features
#
# Application manager
#
CONFIG_APP_COMPILE_TIME_DATE=y
# CONFIG_APP_EXCLUDE_PROJECT_VER_VAR is not set
# CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR is not set
# CONFIG_APP_PROJECT_VER_FROM_CONFIG is not set
CONFIG_APP_RETRIEVE_LEN_ELF_SHA=9
# end of Application manager
CONFIG_ESP_ROM_HAS_CRC_LE=y
CONFIG_ESP_ROM_HAS_CRC_BE=y
CONFIG_ESP_ROM_UART_CLK_IS_XTAL=y
CONFIG_ESP_ROM_USB_SERIAL_DEVICE_NUM=6
CONFIG_ESP_ROM_USB_OTG_NUM=5
CONFIG_ESP_ROM_HAS_RETARGETABLE_LOCKING=y
CONFIG_ESP_ROM_GET_CLK_FREQ=y
CONFIG_ESP_ROM_HAS_RVFPLIB=y
CONFIG_ESP_ROM_HAS_HAL_WDT=y
CONFIG_ESP_ROM_HAS_HAL_SYSTIMER=y
CONFIG_ESP_ROM_HAS_LAYOUT_TABLE=y
CONFIG_ESP_ROM_WDT_INIT_PATCH=y
CONFIG_ESP_ROM_HAS_LP_ROM=y
CONFIG_ESP_ROM_WITHOUT_REGI2C=y
CONFIG_ESP_ROM_HAS_NEWLIB=y
CONFIG_ESP_ROM_HAS_NEWLIB_NANO_FORMAT=y
CONFIG_ESP_ROM_HAS_NEWLIB_NANO_PRINTF_FLOAT_BUG=y
CONFIG_ESP_ROM_HAS_VERSION=y
CONFIG_ESP_ROM_CLIC_INT_TYPE_PATCH=y
CONFIG_ESP_ROM_HAS_OUTPUT_PUTC_FUNC=y
#
# Boot ROM Behavior
#
CONFIG_BOOT_ROM_LOG_ALWAYS_ON=y
# CONFIG_BOOT_ROM_LOG_ALWAYS_OFF is not set
# CONFIG_BOOT_ROM_LOG_ON_GPIO_HIGH is not set
# CONFIG_BOOT_ROM_LOG_ON_GPIO_LOW is not set
# end of Boot ROM Behavior
#
# Serial flasher config
#
# CONFIG_ESPTOOLPY_NO_STUB is not set
CONFIG_ESPTOOLPY_FLASHMODE_QIO=y
# CONFIG_ESPTOOLPY_FLASHMODE_QOUT is not set
# CONFIG_ESPTOOLPY_FLASHMODE_DIO is not set
# CONFIG_ESPTOOLPY_FLASHMODE_DOUT is not set
CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_STR=y
CONFIG_ESPTOOLPY_FLASHMODE="dio"
CONFIG_ESPTOOLPY_FLASHFREQ_80M=y
# CONFIG_ESPTOOLPY_FLASHFREQ_40M is not set
# CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set
CONFIG_ESPTOOLPY_FLASHFREQ="80m"
# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y
# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE="16MB"
# CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set
CONFIG_ESPTOOLPY_BEFORE_RESET=y
# CONFIG_ESPTOOLPY_BEFORE_NORESET is not set
CONFIG_ESPTOOLPY_BEFORE="default_reset"
CONFIG_ESPTOOLPY_AFTER_RESET=y
# CONFIG_ESPTOOLPY_AFTER_NORESET is not set
CONFIG_ESPTOOLPY_AFTER="hard_reset"
CONFIG_ESPTOOLPY_MONITOR_BAUD=115200
# end of Serial flasher config
#
# Partition Table
#
# CONFIG_PARTITION_TABLE_SINGLE_APP is not set
# CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set
# CONFIG_PARTITION_TABLE_TWO_OTA is not set
# CONFIG_PARTITION_TABLE_TWO_OTA_LARGE is not set
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_OFFSET=0x8000
CONFIG_PARTITION_TABLE_MD5=y
# end of Partition Table
#
# Compiler options
#
# CONFIG_COMPILER_OPTIMIZATION_DEBUG is not set
# CONFIG_COMPILER_OPTIMIZATION_SIZE is not set
CONFIG_COMPILER_OPTIMIZATION_PERF=y
# CONFIG_COMPILER_OPTIMIZATION_NONE is not set
CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE=y
# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT is not set
# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE is not set
CONFIG_COMPILER_ASSERT_NDEBUG_EVALUATE=y
# CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB is not set
CONFIG_COMPILER_FLOAT_LIB_FROM_RVFPLIB=y
CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL=2
# CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT is not set
CONFIG_COMPILER_HIDE_PATHS_MACROS=y
# CONFIG_COMPILER_CXX_EXCEPTIONS is not set
# CONFIG_COMPILER_CXX_RTTI is not set
CONFIG_COMPILER_STACK_CHECK_MODE_NONE=y
# CONFIG_COMPILER_STACK_CHECK_MODE_NORM is not set
# CONFIG_COMPILER_STACK_CHECK_MODE_STRONG is not set
# CONFIG_COMPILER_STACK_CHECK_MODE_ALL is not set
# CONFIG_COMPILER_NO_MERGE_CONSTANTS is not set
# CONFIG_COMPILER_WARN_WRITE_STRINGS is not set
# CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS is not set
CONFIG_COMPILER_DISABLE_DEFAULT_ERRORS=y
# CONFIG_COMPILER_DISABLE_GCC12_WARNINGS is not set
# CONFIG_COMPILER_DISABLE_GCC13_WARNINGS is not set
# CONFIG_COMPILER_DISABLE_GCC14_WARNINGS is not set
# CONFIG_COMPILER_DUMP_RTL_FILES is not set
CONFIG_COMPILER_RT_LIB_GCCLIB=y
CONFIG_COMPILER_RT_LIB_NAME="gcc"
# CONFIG_COMPILER_ORPHAN_SECTIONS_WARNING is not set
CONFIG_COMPILER_ORPHAN_SECTIONS_PLACE=y
# CONFIG_COMPILER_STATIC_ANALYZER is not set
# end of Compiler options
#
# Component config
#
#
# Application Level Tracing
#
# CONFIG_APPTRACE_DEST_JTAG is not set
CONFIG_APPTRACE_DEST_NONE=y
# CONFIG_APPTRACE_DEST_UART1 is not set
# CONFIG_APPTRACE_DEST_UART2 is not set
CONFIG_APPTRACE_DEST_UART_NONE=y
CONFIG_APPTRACE_UART_TASK_PRIO=1
CONFIG_APPTRACE_LOCK_ENABLE=y
# end of Application Level Tracing
#
# Bluetooth
#
# CONFIG_BT_ENABLED is not set
CONFIG_BT_ALARM_MAX_NUM=50
# end of Bluetooth
#
# Console Library
#
# CONFIG_CONSOLE_SORTED_HELP is not set
# end of Console Library
#
# Driver Configurations
#
#
# TWAI Configuration
#
# CONFIG_TWAI_ISR_IN_IRAM is not set
# end of TWAI Configuration
#
# Legacy ADC Driver Configuration
#
# CONFIG_ADC_SUPPRESS_DEPRECATE_WARN is not set
#
# Legacy ADC Calibration Configuration
#
# CONFIG_ADC_CALI_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy ADC Calibration Configuration
# end of Legacy ADC Driver Configuration
#
# Legacy MCPWM Driver Configurations
#
# CONFIG_MCPWM_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy MCPWM Driver Configurations
#
# Legacy Timer Group Driver Configurations
#
# CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy Timer Group Driver Configurations
#
# Legacy RMT Driver Configurations
#
# CONFIG_RMT_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy RMT Driver Configurations
#
# Legacy I2S Driver Configurations
#
# CONFIG_I2S_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy I2S Driver Configurations
#
# Legacy PCNT Driver Configurations
#
# CONFIG_PCNT_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy PCNT Driver Configurations
#
# Legacy SDM Driver Configurations
#
# CONFIG_SDM_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy SDM Driver Configurations
#
# Legacy Temperature Sensor Driver Configurations
#
# CONFIG_TEMP_SENSOR_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy Temperature Sensor Driver Configurations
# end of Driver Configurations
#
# eFuse Bit Manager
#
# CONFIG_EFUSE_CUSTOM_TABLE is not set
# CONFIG_EFUSE_VIRTUAL is not set
CONFIG_EFUSE_MAX_BLK_LEN=256
# end of eFuse Bit Manager
#
# ESP-TLS
#
CONFIG_ESP_TLS_USING_MBEDTLS=y
CONFIG_ESP_TLS_USE_DS_PERIPHERAL=y
# CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is not set
# CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is not set
# CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK is not set
# CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL is not set
# CONFIG_ESP_TLS_PSK_VERIFICATION is not set
# CONFIG_ESP_TLS_INSECURE is not set
# end of ESP-TLS
#
# ADC and ADC Calibration
#
# CONFIG_ADC_ONESHOT_CTRL_FUNC_IN_IRAM is not set
# CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is not set
# CONFIG_ADC_ENABLE_DEBUG_LOG is not set
# end of ADC and ADC Calibration
#
# Wireless Coexistence
#
# CONFIG_ESP_COEX_GPIO_DEBUG is not set
# end of Wireless Coexistence
#
# Common ESP-related
#
CONFIG_ESP_ERR_TO_NAME_LOOKUP=y
# end of Common ESP-related
#
# ESP-Driver:Analog Comparator Configurations
#
# CONFIG_ANA_CMPR_ISR_IRAM_SAFE is not set
# CONFIG_ANA_CMPR_CTRL_FUNC_IN_IRAM is not set
# CONFIG_ANA_CMPR_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:Analog Comparator Configurations
#
# ESP-Driver:Camera Controller Configurations
#
# CONFIG_CAM_CTLR_MIPI_CSI_ISR_IRAM_SAFE is not set
# CONFIG_CAM_CTLR_ISP_DVP_ISR_IRAM_SAFE is not set
# CONFIG_CAM_CTLR_DVP_CAM_ISR_IRAM_SAFE is not set
# end of ESP-Driver:Camera Controller Configurations
#
# ESP-Driver:GPIO Configurations
#
# CONFIG_GPIO_CTRL_FUNC_IN_IRAM is not set
# end of ESP-Driver:GPIO Configurations
#
# ESP-Driver:GPTimer Configurations
#
CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y
# CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is not set
# CONFIG_GPTIMER_ISR_IRAM_SAFE is not set
# CONFIG_GPTIMER_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:GPTimer Configurations
#
# ESP-Driver:I2C Configurations
#
# CONFIG_I2C_ISR_IRAM_SAFE is not set
# CONFIG_I2C_ENABLE_DEBUG_LOG is not set
# CONFIG_I2C_ENABLE_SLAVE_DRIVER_VERSION_2 is not set
# end of ESP-Driver:I2C Configurations
#
# ESP-Driver:I2S Configurations
#
# CONFIG_I2S_ISR_IRAM_SAFE is not set
# CONFIG_I2S_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:I2S Configurations
#
# ESP-Driver:ISP Configurations
#
# CONFIG_ISP_ISR_IRAM_SAFE is not set
# CONFIG_ISP_CTRL_FUNC_IN_IRAM is not set
# end of ESP-Driver:ISP Configurations
#
# ESP-Driver:JPEG-Codec Configurations
#
# CONFIG_JPEG_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:JPEG-Codec Configurations
#
# ESP-Driver:LEDC Configurations
#
# CONFIG_LEDC_CTRL_FUNC_IN_IRAM is not set
# end of ESP-Driver:LEDC Configurations
#
# ESP-Driver:MCPWM Configurations
#
# CONFIG_MCPWM_ISR_IRAM_SAFE is not set
# CONFIG_MCPWM_CTRL_FUNC_IN_IRAM is not set
# CONFIG_MCPWM_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:MCPWM Configurations
#
# ESP-Driver:Parallel IO Configurations
#
# CONFIG_PARLIO_ENABLE_DEBUG_LOG is not set
# CONFIG_PARLIO_ISR_IRAM_SAFE is not set
# end of ESP-Driver:Parallel IO Configurations
#
# ESP-Driver:PCNT Configurations
#
# CONFIG_PCNT_CTRL_FUNC_IN_IRAM is not set
# CONFIG_PCNT_ISR_IRAM_SAFE is not set
# CONFIG_PCNT_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:PCNT Configurations
#
# ESP-Driver:RMT Configurations
#
# CONFIG_RMT_ISR_IRAM_SAFE is not set
# CONFIG_RMT_RECV_FUNC_IN_IRAM is not set
# CONFIG_RMT_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:RMT Configurations
#
# ESP-Driver:Sigma Delta Modulator Configurations
#
# CONFIG_SDM_CTRL_FUNC_IN_IRAM is not set
# CONFIG_SDM_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:Sigma Delta Modulator Configurations
#
# ESP-Driver:SPI Configurations
#
# CONFIG_SPI_MASTER_IN_IRAM is not set
CONFIG_SPI_MASTER_ISR_IN_IRAM=y
# CONFIG_SPI_SLAVE_IN_IRAM is not set
CONFIG_SPI_SLAVE_ISR_IN_IRAM=y
# end of ESP-Driver:SPI Configurations
#
# ESP-Driver:Touch Sensor Configurations
#
# CONFIG_TOUCH_CTRL_FUNC_IN_IRAM is not set
# CONFIG_TOUCH_ISR_IRAM_SAFE is not set
# CONFIG_TOUCH_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:Touch Sensor Configurations
#
# ESP-Driver:Temperature Sensor Configurations
#
# CONFIG_TEMP_SENSOR_ENABLE_DEBUG_LOG is not set
# CONFIG_TEMP_SENSOR_ISR_IRAM_SAFE is not set
# end of ESP-Driver:Temperature Sensor Configurations
#
# ESP-Driver:UART Configurations
#
# CONFIG_UART_ISR_IN_IRAM is not set
# end of ESP-Driver:UART Configurations
#
# ESP-Driver:USB Serial/JTAG Configuration
#
CONFIG_USJ_ENABLE_USB_SERIAL_JTAG=y
# end of ESP-Driver:USB Serial/JTAG Configuration
#
# Ethernet
#
CONFIG_ETH_ENABLED=y
CONFIG_ETH_USE_ESP32_EMAC=y
CONFIG_ETH_PHY_INTERFACE_RMII=y
CONFIG_ETH_DMA_BUFFER_SIZE=512
CONFIG_ETH_DMA_RX_BUFFER_NUM=20
CONFIG_ETH_DMA_TX_BUFFER_NUM=10
# CONFIG_ETH_SOFT_FLOW_CONTROL is not set
# CONFIG_ETH_IRAM_OPTIMIZATION is not set
CONFIG_ETH_USE_SPI_ETHERNET=y
# CONFIG_ETH_SPI_ETHERNET_DM9051 is not set
# CONFIG_ETH_SPI_ETHERNET_W5500 is not set
# CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL is not set
# CONFIG_ETH_USE_OPENETH is not set
# CONFIG_ETH_TRANSMIT_MUTEX is not set
# end of Ethernet
#
# Event Loop Library
#
# CONFIG_ESP_EVENT_LOOP_PROFILING is not set
CONFIG_ESP_EVENT_POST_FROM_ISR=y
CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR=y
# end of Event Loop Library
#
# GDB Stub
#
CONFIG_ESP_GDBSTUB_ENABLED=y
# CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME is not set
CONFIG_ESP_GDBSTUB_SUPPORT_TASKS=y
CONFIG_ESP_GDBSTUB_MAX_TASKS=32
# end of GDB Stub
#
# ESP HTTP client
#
CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y
# CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH is not set
# CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH is not set
# CONFIG_ESP_HTTP_CLIENT_ENABLE_CUSTOM_TRANSPORT is not set
CONFIG_ESP_HTTP_CLIENT_EVENT_POST_TIMEOUT=2000
# end of ESP HTTP client
#
# HTTP Server
#
CONFIG_HTTPD_MAX_REQ_HDR_LEN=512
CONFIG_HTTPD_MAX_URI_LEN=512
CONFIG_HTTPD_ERR_RESP_NO_DELAY=y
CONFIG_HTTPD_PURGE_BUF_LEN=32
# CONFIG_HTTPD_LOG_PURGE_DATA is not set
# CONFIG_HTTPD_WS_SUPPORT is not set
# CONFIG_HTTPD_QUEUE_WORK_BLOCKING is not set
CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT=2000
# end of HTTP Server
#
# ESP HTTPS OTA
#
# CONFIG_ESP_HTTPS_OTA_DECRYPT_CB is not set
# CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP is not set
CONFIG_ESP_HTTPS_OTA_EVENT_POST_TIMEOUT=2000
# end of ESP HTTPS OTA
#
# ESP HTTPS server
#
# CONFIG_ESP_HTTPS_SERVER_ENABLE is not set
CONFIG_ESP_HTTPS_SERVER_EVENT_POST_TIMEOUT=2000
# end of ESP HTTPS server
#
# Hardware Settings
#
#
# Chip revision
#
# CONFIG_ESP32P4_REV_MIN_0 is not set
CONFIG_ESP32P4_REV_MIN_1=y
# CONFIG_ESP32P4_REV_MIN_100 is not set
CONFIG_ESP32P4_REV_MIN_FULL=1
CONFIG_ESP_REV_MIN_FULL=1
#
# Maximum Supported ESP32-P4 Revision (Rev v1.99)
#
CONFIG_ESP32P4_REV_MAX_FULL=199
CONFIG_ESP_REV_MAX_FULL=199
CONFIG_ESP_EFUSE_BLOCK_REV_MIN_FULL=0
CONFIG_ESP_EFUSE_BLOCK_REV_MAX_FULL=99
#
# Maximum Supported ESP32-P4 eFuse Block Revision (eFuse Block Rev v0.99)
#
# end of Chip revision
#
# MAC Config
#
CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH=y
CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES_ONE=y
CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES=1
CONFIG_ESP32P4_UNIVERSAL_MAC_ADDRESSES_ONE=y
CONFIG_ESP32P4_UNIVERSAL_MAC_ADDRESSES=1
# CONFIG_ESP_MAC_USE_CUSTOM_MAC_AS_BASE_MAC is not set
# end of MAC Config
#
# Sleep Config
#
CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND=y
CONFIG_ESP_SLEEP_PSRAM_LEAKAGE_WORKAROUND=y
# CONFIG_ESP_SLEEP_MSPI_NEED_ALL_IO_PU is not set
# CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND is not set
CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY=0
# CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION is not set
# CONFIG_ESP_SLEEP_DEBUG is not set
CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS=y
# end of Sleep Config
#
# RTC Clock Config
#
CONFIG_RTC_CLK_SRC_INT_RC=y
# CONFIG_RTC_CLK_SRC_EXT_CRYS is not set
CONFIG_RTC_CLK_CAL_CYCLES=1024
CONFIG_RTC_FAST_CLK_SRC_RC_FAST=y
# CONFIG_RTC_FAST_CLK_SRC_XTAL is not set
# end of RTC Clock Config
#
# Peripheral Control
#
CONFIG_PERIPH_CTRL_FUNC_IN_IRAM=y
# end of Peripheral Control
#
# ETM Configuration
#
# CONFIG_ETM_ENABLE_DEBUG_LOG is not set
# end of ETM Configuration
#
# GDMA Configurations
#
CONFIG_GDMA_CTRL_FUNC_IN_IRAM=y
# CONFIG_GDMA_ISR_IRAM_SAFE is not set
# CONFIG_GDMA_ENABLE_DEBUG_LOG is not set
# end of GDMA Configurations
#
# DW_GDMA Configurations
#
# CONFIG_DW_GDMA_ENABLE_DEBUG_LOG is not set
# end of DW_GDMA Configurations
#
# 2D-DMA Configurations
#
# CONFIG_DMA2D_OPERATION_FUNC_IN_IRAM is not set
# CONFIG_DMA2D_ISR_IRAM_SAFE is not set
# end of 2D-DMA Configurations
#
# Main XTAL Config
#
CONFIG_XTAL_FREQ_40=y
CONFIG_XTAL_FREQ=40
# end of Main XTAL Config
#
# DCDC Regulator Configurations
#
CONFIG_ESP_SLEEP_KEEP_DCDC_ALWAYS_ON=y
CONFIG_ESP_SLEEP_DCM_VSET_VAL_IN_SLEEP=14
# end of DCDC Regulator Configurations
#
# LDO Regulator Configurations
#
CONFIG_ESP_LDO_RESERVE_SPI_NOR_FLASH=y
CONFIG_ESP_LDO_CHAN_SPI_NOR_FLASH_DOMAIN=1
CONFIG_ESP_LDO_VOLTAGE_SPI_NOR_FLASH_3300_MV=y
CONFIG_ESP_LDO_VOLTAGE_SPI_NOR_FLASH_DOMAIN=3300
CONFIG_ESP_LDO_RESERVE_PSRAM=y
CONFIG_ESP_LDO_CHAN_PSRAM_DOMAIN=2
CONFIG_ESP_LDO_VOLTAGE_PSRAM_1900_MV=y
CONFIG_ESP_LDO_VOLTAGE_PSRAM_DOMAIN=1900
# end of LDO Regulator Configurations
CONFIG_ESP_SPI_BUS_LOCK_ISR_FUNCS_IN_IRAM=y
# end of Hardware Settings
#
# ESP-Driver:LCD Controller Configurations
#
# CONFIG_LCD_ENABLE_DEBUG_LOG is not set
# CONFIG_LCD_RGB_ISR_IRAM_SAFE is not set
# CONFIG_LCD_RGB_RESTART_IN_VSYNC is not set
# CONFIG_LCD_DSI_ISR_IRAM_SAFE is not set
# end of ESP-Driver:LCD Controller Configurations
#
# ESP-MM: Memory Management Configurations
#
# CONFIG_ESP_MM_CACHE_MSYNC_C2M_CHUNKED_OPS is not set
# end of ESP-MM: Memory Management Configurations
#
# ESP NETIF Adapter
#
CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL=120
# CONFIG_ESP_NETIF_PROVIDE_CUSTOM_IMPLEMENTATION is not set
CONFIG_ESP_NETIF_TCPIP_LWIP=y
# CONFIG_ESP_NETIF_LOOPBACK is not set
CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y
CONFIG_ESP_NETIF_REPORT_DATA_TRAFFIC=y
# CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS is not set
# CONFIG_ESP_NETIF_L2_TAP is not set
# CONFIG_ESP_NETIF_BRIDGE_EN is not set
# CONFIG_ESP_NETIF_SET_DNS_PER_DEFAULT_NETIF is not set
# end of ESP NETIF Adapter
#
# Partition API Configuration
#
# end of Partition API Configuration
#
# PHY
#
# end of PHY
#
# Power Management
#
# CONFIG_PM_ENABLE is not set
# CONFIG_PM_SLP_IRAM_OPT is not set
# CONFIG_PM_POWER_DOWN_PERIPHERAL_IN_LIGHT_SLEEP is not set
# end of Power Management
#
# ESP PSRAM
#
CONFIG_SPIRAM=y
#
# PSRAM config
#
CONFIG_SPIRAM_MODE_HEX=y
CONFIG_SPIRAM_SPEED_200M=y
# CONFIG_SPIRAM_SPEED_20M is not set
CONFIG_SPIRAM_SPEED=200
CONFIG_SPIRAM_FETCH_INSTRUCTIONS=y
CONFIG_SPIRAM_RODATA=y
CONFIG_SPIRAM_XIP_FROM_PSRAM=y
CONFIG_SPIRAM_FLASH_LOAD_TO_PSRAM=y
# CONFIG_SPIRAM_ECC_ENABLE is not set
CONFIG_SPIRAM_BOOT_INIT=y
# CONFIG_SPIRAM_IGNORE_NOTFOUND is not set
# CONFIG_SPIRAM_USE_MEMMAP is not set
# CONFIG_SPIRAM_USE_CAPS_ALLOC is not set
CONFIG_SPIRAM_USE_MALLOC=y
CONFIG_SPIRAM_MEMTEST=y
CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=16384
# CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP is not set
CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL=32768
# CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY is not set
# CONFIG_SPIRAM_ALLOW_NOINIT_SEG_EXTERNAL_MEMORY is not set
# end of PSRAM config
# end of ESP PSRAM
#
# ESP Ringbuf
#
# CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH is not set
# end of ESP Ringbuf
#
# ESP Security Specific
#
# end of ESP Security Specific
#
# ESP System Settings
#
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_360=y
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=360
#
# Cache config
#
# CONFIG_CACHE_L2_CACHE_128KB is not set
CONFIG_CACHE_L2_CACHE_256KB=y
# CONFIG_CACHE_L2_CACHE_512KB is not set
CONFIG_CACHE_L2_CACHE_SIZE=0x40000
# CONFIG_CACHE_L2_CACHE_LINE_64B is not set
CONFIG_CACHE_L2_CACHE_LINE_128B=y
CONFIG_CACHE_L2_CACHE_LINE_SIZE=128
CONFIG_CACHE_L1_CACHE_LINE_SIZE=64
# end of Cache config
# CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT is not set
CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT=y
# CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT is not set
# CONFIG_ESP_SYSTEM_PANIC_GDBSTUB is not set
CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS=0
CONFIG_ESP_SYSTEM_RTC_FAST_MEM_AS_HEAP_DEPCHECK=y
CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP=y
# CONFIG_ESP_SYSTEM_USE_EH_FRAME is not set
#
# Memory protection
#
CONFIG_ESP_SYSTEM_PMP_IDRAM_SPLIT=y
# CONFIG_ESP_SYSTEM_PMP_LP_CORE_RESERVE_MEM_EXECUTABLE is not set
# end of Memory protection
CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE=32
CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=2304
CONFIG_ESP_MAIN_TASK_STACK_SIZE=12288
CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0=y
# CONFIG_ESP_MAIN_TASK_AFFINITY_CPU1 is not set
# CONFIG_ESP_MAIN_TASK_AFFINITY_NO_AFFINITY is not set
CONFIG_ESP_MAIN_TASK_AFFINITY=0x0
CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE=2048
CONFIG_ESP_CONSOLE_UART_DEFAULT=y
# CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG is not set
# CONFIG_ESP_CONSOLE_UART_CUSTOM is not set
# CONFIG_ESP_CONSOLE_NONE is not set
# CONFIG_ESP_CONSOLE_SECONDARY_NONE is not set
CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED=y
CONFIG_ESP_CONSOLE_UART=y
CONFIG_ESP_CONSOLE_UART_NUM=0
CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=0
CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200
CONFIG_ESP_INT_WDT=y
CONFIG_ESP_INT_WDT_TIMEOUT_MS=300
CONFIG_ESP_INT_WDT_CHECK_CPU1=y
CONFIG_ESP_TASK_WDT_EN=y
CONFIG_ESP_TASK_WDT_INIT=y
# CONFIG_ESP_TASK_WDT_PANIC is not set
CONFIG_ESP_TASK_WDT_TIMEOUT_S=5
CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0=y
CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1=y
# CONFIG_ESP_PANIC_HANDLER_IRAM is not set
# CONFIG_ESP_DEBUG_STUBS_ENABLE is not set
CONFIG_ESP_DEBUG_OCDAWARE=y
CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4=y
#
# Brownout Detector
#
CONFIG_ESP_BROWNOUT_DET=y
CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7=y
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6 is not set
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5 is not set
CONFIG_ESP_BROWNOUT_DET_LVL=7
# end of Brownout Detector
CONFIG_ESP_SYSTEM_BROWNOUT_INTR=y
CONFIG_ESP_SYSTEM_HW_STACK_GUARD=y
CONFIG_ESP_SYSTEM_HW_PC_RECORD=y
# end of ESP System Settings
#
# IPC (Inter-Processor Call)
#
CONFIG_ESP_IPC_TASK_STACK_SIZE=1024
CONFIG_ESP_IPC_USES_CALLERS_PRIORITY=y
CONFIG_ESP_IPC_ISR_ENABLE=y
# end of IPC (Inter-Processor Call)
#
# ESP Timer (High Resolution Timer)
#
# CONFIG_ESP_TIMER_PROFILING is not set
CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER=y
CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER=y
CONFIG_ESP_TIMER_TASK_STACK_SIZE=3584
CONFIG_ESP_TIMER_INTERRUPT_LEVEL=1
# CONFIG_ESP_TIMER_SHOW_EXPERIMENTAL is not set
CONFIG_ESP_TIMER_TASK_AFFINITY=0x0
CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0=y
CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0=y
# CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD is not set
CONFIG_ESP_TIMER_IMPL_SYSTIMER=y
# end of ESP Timer (High Resolution Timer)
#
# Wi-Fi
#
# CONFIG_ESP_HOST_WIFI_ENABLED is not set
# end of Wi-Fi
#
# Core dump
#
# CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH is not set
# CONFIG_ESP_COREDUMP_ENABLE_TO_UART is not set
CONFIG_ESP_COREDUMP_ENABLE_TO_NONE=y
# end of Core dump
#
# FAT Filesystem support
#
CONFIG_FATFS_VOLUME_COUNT=2
CONFIG_FATFS_LFN_NONE=y
# CONFIG_FATFS_LFN_HEAP is not set
# CONFIG_FATFS_LFN_STACK is not set
# CONFIG_FATFS_SECTOR_512 is not set
CONFIG_FATFS_SECTOR_4096=y
# CONFIG_FATFS_CODEPAGE_DYNAMIC is not set
CONFIG_FATFS_CODEPAGE_437=y
# CONFIG_FATFS_CODEPAGE_720 is not set
# CONFIG_FATFS_CODEPAGE_737 is not set
# CONFIG_FATFS_CODEPAGE_771 is not set
# CONFIG_FATFS_CODEPAGE_775 is not set
# CONFIG_FATFS_CODEPAGE_850 is not set
# CONFIG_FATFS_CODEPAGE_852 is not set
# CONFIG_FATFS_CODEPAGE_855 is not set
# CONFIG_FATFS_CODEPAGE_857 is not set
# CONFIG_FATFS_CODEPAGE_860 is not set
# CONFIG_FATFS_CODEPAGE_861 is not set
# CONFIG_FATFS_CODEPAGE_862 is not set
# CONFIG_FATFS_CODEPAGE_863 is not set
# CONFIG_FATFS_CODEPAGE_864 is not set
# CONFIG_FATFS_CODEPAGE_865 is not set
# CONFIG_FATFS_CODEPAGE_866 is not set
# CONFIG_FATFS_CODEPAGE_869 is not set
# CONFIG_FATFS_CODEPAGE_932 is not set
# CONFIG_FATFS_CODEPAGE_936 is not set
# CONFIG_FATFS_CODEPAGE_949 is not set
# CONFIG_FATFS_CODEPAGE_950 is not set
CONFIG_FATFS_CODEPAGE=437
CONFIG_FATFS_FS_LOCK=0
CONFIG_FATFS_TIMEOUT_MS=10000
CONFIG_FATFS_PER_FILE_CACHE=y
CONFIG_FATFS_ALLOC_PREFER_EXTRAM=y
# CONFIG_FATFS_USE_FASTSEEK is not set
CONFIG_FATFS_USE_STRFUNC_NONE=y
# CONFIG_FATFS_USE_STRFUNC_WITHOUT_CRLF_CONV is not set
# CONFIG_FATFS_USE_STRFUNC_WITH_CRLF_CONV is not set
CONFIG_FATFS_VFS_FSTAT_BLKSIZE=0
# CONFIG_FATFS_IMMEDIATE_FSYNC is not set
# CONFIG_FATFS_USE_LABEL is not set
CONFIG_FATFS_LINK_LOCK=y
# end of FAT Filesystem support
#
# FreeRTOS
#
#
# Kernel
#
# CONFIG_FREERTOS_UNICORE is not set
CONFIG_FREERTOS_HZ=1000
# CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE is not set
# CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL is not set
CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY=y
CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS=1
CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=1536
# CONFIG_FREERTOS_USE_IDLE_HOOK is not set
# CONFIG_FREERTOS_USE_TICK_HOOK is not set
CONFIG_FREERTOS_MAX_TASK_NAME_LEN=16
# CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY is not set
CONFIG_FREERTOS_USE_TIMERS=y
CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME="Tmr Svc"
# CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU0 is not set
# CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU1 is not set
CONFIG_FREERTOS_TIMER_TASK_NO_AFFINITY=y
CONFIG_FREERTOS_TIMER_SERVICE_TASK_CORE_AFFINITY=0x7FFFFFFF
CONFIG_FREERTOS_TIMER_TASK_PRIORITY=1
CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=2048
CONFIG_FREERTOS_TIMER_QUEUE_LENGTH=10
CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE=0
CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES=1
CONFIG_FREERTOS_USE_TRACE_FACILITY=y
CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS=y
# CONFIG_FREERTOS_USE_LIST_DATA_INTEGRITY_CHECK_BYTES is not set
CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID=y
CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS=y
CONFIG_FREERTOS_RUN_TIME_COUNTER_TYPE_U32=y
# CONFIG_FREERTOS_RUN_TIME_COUNTER_TYPE_U64 is not set
# CONFIG_FREERTOS_USE_APPLICATION_TASK_TAG is not set
# end of Kernel
#
# Port
#
# CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK is not set
CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS=y
# CONFIG_FREERTOS_TASK_PRE_DELETION_HOOK is not set
# CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP is not set
CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER=y
CONFIG_FREERTOS_ISR_STACKSIZE=1536
CONFIG_FREERTOS_INTERRUPT_BACKTRACE=y
CONFIG_FREERTOS_TICK_SUPPORT_SYSTIMER=y
CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL1=y
# CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL3 is not set
CONFIG_FREERTOS_SYSTICK_USES_SYSTIMER=y
CONFIG_FREERTOS_RUN_TIME_STATS_USING_ESP_TIMER=y
# CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH is not set
# CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE is not set
# end of Port
#
# Extra
#
CONFIG_FREERTOS_TASK_CREATE_ALLOW_EXT_MEM=y
# end of Extra
CONFIG_FREERTOS_PORT=y
CONFIG_FREERTOS_NO_AFFINITY=0x7FFFFFFF
CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION=y
CONFIG_FREERTOS_DEBUG_OCDAWARE=y
CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT=y
CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH=y
CONFIG_FREERTOS_NUMBER_OF_CORES=2
# end of FreeRTOS
#
# Hardware Abstraction Layer (HAL) and Low Level (LL)
#
CONFIG_HAL_ASSERTION_EQUALS_SYSTEM=y
# CONFIG_HAL_ASSERTION_DISABLE is not set
# CONFIG_HAL_ASSERTION_SILENT is not set
# CONFIG_HAL_ASSERTION_ENABLE is not set
CONFIG_HAL_DEFAULT_ASSERTION_LEVEL=2
CONFIG_HAL_SYSTIMER_USE_ROM_IMPL=y
CONFIG_HAL_WDT_USE_ROM_IMPL=y
CONFIG_HAL_SPI_MASTER_FUNC_IN_IRAM=y
CONFIG_HAL_SPI_SLAVE_FUNC_IN_IRAM=y
# CONFIG_HAL_ECDSA_GEN_SIG_CM is not set
# end of Hardware Abstraction Layer (HAL) and Low Level (LL)
#
# Heap memory debugging
#
CONFIG_HEAP_POISONING_DISABLED=y
# CONFIG_HEAP_POISONING_LIGHT is not set
# CONFIG_HEAP_POISONING_COMPREHENSIVE is not set
CONFIG_HEAP_TRACING_OFF=y
# CONFIG_HEAP_TRACING_STANDALONE is not set
# CONFIG_HEAP_TRACING_TOHOST is not set
# CONFIG_HEAP_USE_HOOKS is not set
# CONFIG_HEAP_TASK_TRACKING is not set
# CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS is not set
# CONFIG_HEAP_PLACE_FUNCTION_INTO_FLASH is not set
# end of Heap memory debugging
#
# Log
#
#
# Log Level
#
# CONFIG_LOG_DEFAULT_LEVEL_NONE is not set
# CONFIG_LOG_DEFAULT_LEVEL_ERROR is not set
# CONFIG_LOG_DEFAULT_LEVEL_WARN is not set
CONFIG_LOG_DEFAULT_LEVEL_INFO=y
# CONFIG_LOG_DEFAULT_LEVEL_DEBUG is not set
# CONFIG_LOG_DEFAULT_LEVEL_VERBOSE is not set
CONFIG_LOG_DEFAULT_LEVEL=3
CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT=y
# CONFIG_LOG_MAXIMUM_LEVEL_DEBUG is not set
# CONFIG_LOG_MAXIMUM_LEVEL_VERBOSE is not set
CONFIG_LOG_MAXIMUM_LEVEL=3
#
# Level Settings
#
# CONFIG_LOG_MASTER_LEVEL is not set
CONFIG_LOG_DYNAMIC_LEVEL_CONTROL=y
# CONFIG_LOG_TAG_LEVEL_IMPL_NONE is not set
# CONFIG_LOG_TAG_LEVEL_IMPL_LINKED_LIST is not set
CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_AND_LINKED_LIST=y
# CONFIG_LOG_TAG_LEVEL_CACHE_ARRAY is not set
CONFIG_LOG_TAG_LEVEL_CACHE_BINARY_MIN_HEAP=y
CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_SIZE=31
# end of Level Settings
# end of Log Level
#
# Format
#
CONFIG_LOG_COLORS=y
CONFIG_LOG_TIMESTAMP_SOURCE_RTOS=y
# CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM is not set
# end of Format
# end of Log
#
# LWIP
#
CONFIG_LWIP_ENABLE=y
CONFIG_LWIP_LOCAL_HOSTNAME="espressif"
# CONFIG_LWIP_NETIF_API is not set
CONFIG_LWIP_TCPIP_TASK_PRIO=18
# CONFIG_LWIP_TCPIP_CORE_LOCKING is not set
# CONFIG_LWIP_CHECK_THREAD_SAFETY is not set
CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y
# CONFIG_LWIP_L2_TO_L3_COPY is not set
# CONFIG_LWIP_IRAM_OPTIMIZATION is not set
# CONFIG_LWIP_EXTRA_IRAM_OPTIMIZATION is not set
CONFIG_LWIP_TIMERS_ONDEMAND=y
CONFIG_LWIP_ND6=y
# CONFIG_LWIP_FORCE_ROUTER_FORWARDING is not set
CONFIG_LWIP_MAX_SOCKETS=10
# CONFIG_LWIP_USE_ONLY_LWIP_SELECT is not set
# CONFIG_LWIP_SO_LINGER is not set
CONFIG_LWIP_SO_REUSE=y
CONFIG_LWIP_SO_REUSE_RXTOALL=y
# CONFIG_LWIP_SO_RCVBUF is not set
# CONFIG_LWIP_NETBUF_RECVINFO is not set
CONFIG_LWIP_IP_DEFAULT_TTL=64
CONFIG_LWIP_IP4_FRAG=y
CONFIG_LWIP_IP6_FRAG=y
# CONFIG_LWIP_IP4_REASSEMBLY is not set
# CONFIG_LWIP_IP6_REASSEMBLY is not set
CONFIG_LWIP_IP_REASS_MAX_PBUFS=10
# CONFIG_LWIP_IP_FORWARD is not set
# CONFIG_LWIP_STATS is not set
CONFIG_LWIP_ESP_GRATUITOUS_ARP=y
CONFIG_LWIP_GARP_TMR_INTERVAL=60
CONFIG_LWIP_ESP_MLDV6_REPORT=y
CONFIG_LWIP_MLDV6_TMR_INTERVAL=40
CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32
CONFIG_LWIP_DHCP_DOES_ARP_CHECK=y
# CONFIG_LWIP_DHCP_DOES_ACD_CHECK is not set
# CONFIG_LWIP_DHCP_DOES_NOT_CHECK_OFFERED_IP is not set
# CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID is not set
CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID=y
# CONFIG_LWIP_DHCP_RESTORE_LAST_IP is not set
CONFIG_LWIP_DHCP_OPTIONS_LEN=68
CONFIG_LWIP_NUM_NETIF_CLIENT_DATA=0
CONFIG_LWIP_DHCP_COARSE_TIMER_SECS=1
#
# DHCP server
#
CONFIG_LWIP_DHCPS=y
CONFIG_LWIP_DHCPS_LEASE_UNIT=60
CONFIG_LWIP_DHCPS_MAX_STATION_NUM=8
CONFIG_LWIP_DHCPS_STATIC_ENTRIES=y
CONFIG_LWIP_DHCPS_ADD_DNS=y
# end of DHCP server
# CONFIG_LWIP_AUTOIP is not set
CONFIG_LWIP_IPV4=y
CONFIG_LWIP_IPV6=y
# CONFIG_LWIP_IPV6_AUTOCONFIG is not set
CONFIG_LWIP_IPV6_NUM_ADDRESSES=3
# CONFIG_LWIP_IPV6_FORWARD is not set
# CONFIG_LWIP_NETIF_STATUS_CALLBACK is not set
CONFIG_LWIP_NETIF_LOOPBACK=y
CONFIG_LWIP_LOOPBACK_MAX_PBUFS=8
#
# TCP
#
CONFIG_LWIP_MAX_ACTIVE_TCP=16
CONFIG_LWIP_MAX_LISTENING_TCP=16
CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION=y
CONFIG_LWIP_TCP_MAXRTX=12
CONFIG_LWIP_TCP_SYNMAXRTX=12
CONFIG_LWIP_TCP_MSS=1440
CONFIG_LWIP_TCP_TMR_INTERVAL=250
CONFIG_LWIP_TCP_MSL=60000
CONFIG_LWIP_TCP_FIN_WAIT_TIMEOUT=20000
CONFIG_LWIP_TCP_SND_BUF_DEFAULT=5760
CONFIG_LWIP_TCP_WND_DEFAULT=5760
CONFIG_LWIP_TCP_RECVMBOX_SIZE=6
CONFIG_LWIP_TCP_ACCEPTMBOX_SIZE=6
CONFIG_LWIP_TCP_QUEUE_OOSEQ=y
CONFIG_LWIP_TCP_OOSEQ_TIMEOUT=6
CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS=4
# CONFIG_LWIP_TCP_SACK_OUT is not set
CONFIG_LWIP_TCP_OVERSIZE_MSS=y
# CONFIG_LWIP_TCP_OVERSIZE_QUARTER_MSS is not set
# CONFIG_LWIP_TCP_OVERSIZE_DISABLE is not set
CONFIG_LWIP_TCP_RTO_TIME=1500
# end of TCP
#
# UDP
#
CONFIG_LWIP_MAX_UDP_PCBS=16
CONFIG_LWIP_UDP_RECVMBOX_SIZE=6
# end of UDP
#
# Checksums
#
# CONFIG_LWIP_CHECKSUM_CHECK_IP is not set
# CONFIG_LWIP_CHECKSUM_CHECK_UDP is not set
CONFIG_LWIP_CHECKSUM_CHECK_ICMP=y
# end of Checksums
CONFIG_LWIP_TCPIP_TASK_STACK_SIZE=3072
CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY=y
# CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0 is not set
# CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU1 is not set
CONFIG_LWIP_TCPIP_TASK_AFFINITY=0x7FFFFFFF
CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE=3
CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS=5
CONFIG_LWIP_IPV6_ND6_NUM_PREFIXES=5
CONFIG_LWIP_IPV6_ND6_NUM_ROUTERS=3
CONFIG_LWIP_IPV6_ND6_NUM_DESTINATIONS=10
# CONFIG_LWIP_PPP_SUPPORT is not set
# CONFIG_LWIP_SLIP_SUPPORT is not set
#
# ICMP
#
CONFIG_LWIP_ICMP=y
# CONFIG_LWIP_MULTICAST_PING is not set
# CONFIG_LWIP_BROADCAST_PING is not set
# end of ICMP
#
# LWIP RAW API
#
CONFIG_LWIP_MAX_RAW_PCBS=16
# end of LWIP RAW API
#
# SNTP
#
CONFIG_LWIP_SNTP_MAX_SERVERS=1
# CONFIG_LWIP_DHCP_GET_NTP_SRV is not set
CONFIG_LWIP_SNTP_UPDATE_DELAY=3600000
CONFIG_LWIP_SNTP_STARTUP_DELAY=y
CONFIG_LWIP_SNTP_MAXIMUM_STARTUP_DELAY=5000
# end of SNTP
#
# DNS
#
CONFIG_LWIP_DNS_MAX_HOST_IP=1
CONFIG_LWIP_DNS_MAX_SERVERS=3
# CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT is not set
# CONFIG_LWIP_DNS_SETSERVER_WITH_NETIF is not set
# end of DNS
CONFIG_LWIP_BRIDGEIF_MAX_PORTS=7
CONFIG_LWIP_ESP_LWIP_ASSERT=y
#
# Hooks
#
# CONFIG_LWIP_HOOK_TCP_ISN_NONE is not set
CONFIG_LWIP_HOOK_TCP_ISN_DEFAULT=y
# CONFIG_LWIP_HOOK_TCP_ISN_CUSTOM is not set
CONFIG_LWIP_HOOK_IP6_ROUTE_NONE=y
# CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT is not set
# CONFIG_LWIP_HOOK_IP6_ROUTE_CUSTOM is not set
CONFIG_LWIP_HOOK_ND6_GET_GW_NONE=y
# CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT is not set
# CONFIG_LWIP_HOOK_ND6_GET_GW_CUSTOM is not set
CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE=y
# CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_DEFAULT is not set
# CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_CUSTOM is not set
CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE=y
# CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_DEFAULT is not set
# CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM is not set
CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_NONE=y
# CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_CUSTOM is not set
# CONFIG_LWIP_HOOK_IP6_INPUT_NONE is not set
CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT=y
# CONFIG_LWIP_HOOK_IP6_INPUT_CUSTOM is not set
# end of Hooks
# CONFIG_LWIP_DEBUG is not set
# end of LWIP
#
# mbedTLS
#
CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y
# CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC is not set
# CONFIG_MBEDTLS_DEFAULT_MEM_ALLOC is not set
# CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC is not set
CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y
CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=16384
CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096
# CONFIG_MBEDTLS_DYNAMIC_BUFFER is not set
# CONFIG_MBEDTLS_DEBUG is not set
#
# mbedTLS v3.x related
#
# CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 is not set
# CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH is not set
# CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK is not set
# CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set
CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y
CONFIG_MBEDTLS_PKCS7_C=y
# end of mbedTLS v3.x related
#
# Certificate Bundle
#
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL=y
# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN is not set
# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE is not set
# CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE is not set
# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEPRECATED_LIST is not set
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS=200
# end of Certificate Bundle
# CONFIG_MBEDTLS_ECP_RESTARTABLE is not set
# CONFIG_MBEDTLS_CMAC_C is not set
CONFIG_MBEDTLS_HARDWARE_AES=y
CONFIG_MBEDTLS_AES_USE_INTERRUPT=y
CONFIG_MBEDTLS_AES_INTERRUPT_LEVEL=0
CONFIG_MBEDTLS_HARDWARE_GCM=y
CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER=y
CONFIG_MBEDTLS_HARDWARE_MPI=y
# CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI is not set
CONFIG_MBEDTLS_MPI_USE_INTERRUPT=y
CONFIG_MBEDTLS_MPI_INTERRUPT_LEVEL=0
CONFIG_MBEDTLS_HARDWARE_SHA=y
CONFIG_MBEDTLS_HARDWARE_ECC=y
CONFIG_MBEDTLS_ECC_OTHER_CURVES_SOFT_FALLBACK=y
CONFIG_MBEDTLS_ROM_MD5=y
# CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set
# CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set
CONFIG_MBEDTLS_HAVE_TIME=y
# CONFIG_MBEDTLS_PLATFORM_TIME_ALT is not set
# CONFIG_MBEDTLS_HAVE_TIME_DATE is not set
CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y
CONFIG_MBEDTLS_SHA512_C=y
# CONFIG_MBEDTLS_SHA3_C is not set
CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT=y
# CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set
# CONFIG_MBEDTLS_TLS_CLIENT_ONLY is not set
# CONFIG_MBEDTLS_TLS_DISABLED is not set
CONFIG_MBEDTLS_TLS_SERVER=y
CONFIG_MBEDTLS_TLS_CLIENT=y
CONFIG_MBEDTLS_TLS_ENABLED=y
#
# TLS Key Exchange Methods
#
# CONFIG_MBEDTLS_PSK_MODES is not set
CONFIG_MBEDTLS_KEY_EXCHANGE_RSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA=y
# end of TLS Key Exchange Methods
CONFIG_MBEDTLS_SSL_RENEGOTIATION=y
CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y
# CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set
# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set
CONFIG_MBEDTLS_SSL_ALPN=y
CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS=y
CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS=y
#
# Symmetric Ciphers
#
CONFIG_MBEDTLS_AES_C=y
# CONFIG_MBEDTLS_CAMELLIA_C is not set
# CONFIG_MBEDTLS_DES_C is not set
# CONFIG_MBEDTLS_BLOWFISH_C is not set
# CONFIG_MBEDTLS_XTEA_C is not set
CONFIG_MBEDTLS_CCM_C=y
CONFIG_MBEDTLS_GCM_C=y
# CONFIG_MBEDTLS_NIST_KW_C is not set
# end of Symmetric Ciphers
# CONFIG_MBEDTLS_RIPEMD160_C is not set
#
# Certificates
#
CONFIG_MBEDTLS_PEM_PARSE_C=y
CONFIG_MBEDTLS_PEM_WRITE_C=y
CONFIG_MBEDTLS_X509_CRL_PARSE_C=y
CONFIG_MBEDTLS_X509_CSR_PARSE_C=y
# end of Certificates
CONFIG_MBEDTLS_ECP_C=y
CONFIG_MBEDTLS_PK_PARSE_EC_EXTENDED=y
CONFIG_MBEDTLS_PK_PARSE_EC_COMPRESSED=y
# CONFIG_MBEDTLS_DHM_C is not set
CONFIG_MBEDTLS_ECDH_C=y
CONFIG_MBEDTLS_ECDSA_C=y
# CONFIG_MBEDTLS_ECJPAKE_C is not set
CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED=y
CONFIG_MBEDTLS_ECP_NIST_OPTIM=y
# CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM is not set
# CONFIG_MBEDTLS_POLY1305_C is not set
# CONFIG_MBEDTLS_CHACHA20_C is not set
# CONFIG_MBEDTLS_HKDF_C is not set
# CONFIG_MBEDTLS_THREADING_C is not set
CONFIG_MBEDTLS_ERROR_STRINGS=y
CONFIG_MBEDTLS_FS_IO=y
# end of mbedTLS
#
# ESP-MQTT Configurations
#
CONFIG_MQTT_PROTOCOL_311=y
# CONFIG_MQTT_PROTOCOL_5 is not set
CONFIG_MQTT_TRANSPORT_SSL=y
CONFIG_MQTT_TRANSPORT_WEBSOCKET=y
CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y
# CONFIG_MQTT_MSG_ID_INCREMENTAL is not set
# CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED is not set
# CONFIG_MQTT_REPORT_DELETED_MESSAGES is not set
# CONFIG_MQTT_USE_CUSTOM_CONFIG is not set
# CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED is not set
# CONFIG_MQTT_CUSTOM_OUTBOX is not set
# end of ESP-MQTT Configurations
#
# Newlib
#
CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF=y
# CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF is not set
# CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR is not set
# CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF is not set
# CONFIG_NEWLIB_STDIN_LINE_ENDING_LF is not set
CONFIG_NEWLIB_STDIN_LINE_ENDING_CR=y
# CONFIG_NEWLIB_NANO_FORMAT is not set
CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y
# CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC is not set
# CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT is not set
# CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE is not set
# end of Newlib
#
# NVS
#
# CONFIG_NVS_ENCRYPTION is not set
# CONFIG_NVS_ASSERT_ERROR_CHECK is not set
# CONFIG_NVS_LEGACY_DUP_KEYS_COMPATIBILITY is not set
# CONFIG_NVS_ALLOCATE_CACHE_IN_SPIRAM is not set
# end of NVS
#
# OpenThread
#
# CONFIG_OPENTHREAD_ENABLED is not set
#
# OpenThread Spinel
#
# CONFIG_OPENTHREAD_SPINEL_ONLY is not set
# end of OpenThread Spinel
# end of OpenThread
#
# Protocomm
#
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0=y
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1=y
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2=y
# end of Protocomm
#
# PThreads
#
CONFIG_PTHREAD_TASK_PRIO_DEFAULT=5
CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072
CONFIG_PTHREAD_STACK_MIN=768
CONFIG_PTHREAD_DEFAULT_CORE_NO_AFFINITY=y
# CONFIG_PTHREAD_DEFAULT_CORE_0 is not set
# CONFIG_PTHREAD_DEFAULT_CORE_1 is not set
CONFIG_PTHREAD_TASK_CORE_DEFAULT=-1
CONFIG_PTHREAD_TASK_NAME_DEFAULT="pthread"
# end of PThreads
#
# MMU Config
#
CONFIG_MMU_PAGE_SIZE_64KB=y
CONFIG_MMU_PAGE_MODE="64KB"
CONFIG_MMU_PAGE_SIZE=0x10000
# end of MMU Config
#
# Main Flash configuration
#
#
# SPI Flash behavior when brownout
#
CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC=y
CONFIG_SPI_FLASH_BROWNOUT_RESET=y
# end of SPI Flash behavior when brownout
#
# Optional and Experimental Features (READ DOCS FIRST)
#
#
# Features here require specific hardware (READ DOCS FIRST!)
#
# CONFIG_SPI_FLASH_AUTO_SUSPEND is not set
CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US=50
# CONFIG_SPI_FLASH_FORCE_ENABLE_XMC_C_SUSPEND is not set
# end of Optional and Experimental Features (READ DOCS FIRST)
# end of Main Flash configuration
#
# SPI Flash driver
#
# CONFIG_SPI_FLASH_VERIFY_WRITE is not set
# CONFIG_SPI_FLASH_ENABLE_COUNTERS is not set
CONFIG_SPI_FLASH_ROM_DRIVER_PATCH=y
CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS=y
# CONFIG_SPI_FLASH_DANGEROUS_WRITE_FAILS is not set
# CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED is not set
# CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE is not set
CONFIG_SPI_FLASH_YIELD_DURING_ERASE=y
CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS=20
CONFIG_SPI_FLASH_ERASE_YIELD_TICKS=1
CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE=8192
# CONFIG_SPI_FLASH_SIZE_OVERRIDE is not set
# CONFIG_SPI_FLASH_CHECK_ERASE_TIMEOUT_DISABLED is not set
# CONFIG_SPI_FLASH_OVERRIDE_CHIP_DRIVER_LIST is not set
#
# Auto-detect flash chips
#
CONFIG_SPI_FLASH_VENDOR_XMC_SUPPORTED=y
# CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP is not set
# CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP is not set
# CONFIG_SPI_FLASH_SUPPORT_GD_CHIP is not set
# CONFIG_SPI_FLASH_SUPPORT_WINBOND_CHIP is not set
# CONFIG_SPI_FLASH_SUPPORT_BOYA_CHIP is not set
# CONFIG_SPI_FLASH_SUPPORT_TH_CHIP is not set
# end of Auto-detect flash chips
CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE=y
# end of SPI Flash driver
#
# SPIFFS Configuration
#
CONFIG_SPIFFS_MAX_PARTITIONS=3
#
# SPIFFS Cache Configuration
#
CONFIG_SPIFFS_CACHE=y
CONFIG_SPIFFS_CACHE_WR=y
# CONFIG_SPIFFS_CACHE_STATS is not set
# end of SPIFFS Cache Configuration
CONFIG_SPIFFS_PAGE_CHECK=y
CONFIG_SPIFFS_GC_MAX_RUNS=10
# CONFIG_SPIFFS_GC_STATS is not set
CONFIG_SPIFFS_PAGE_SIZE=256
CONFIG_SPIFFS_OBJ_NAME_LEN=32
# CONFIG_SPIFFS_FOLLOW_SYMLINKS is not set
CONFIG_SPIFFS_USE_MAGIC=y
CONFIG_SPIFFS_USE_MAGIC_LENGTH=y
CONFIG_SPIFFS_META_LENGTH=4
CONFIG_SPIFFS_USE_MTIME=y
#
# Debug Configuration
#
# CONFIG_SPIFFS_DBG is not set
# CONFIG_SPIFFS_API_DBG is not set
# CONFIG_SPIFFS_GC_DBG is not set
# CONFIG_SPIFFS_CACHE_DBG is not set
# CONFIG_SPIFFS_CHECK_DBG is not set
# CONFIG_SPIFFS_TEST_VISUALISATION is not set
# end of Debug Configuration
# end of SPIFFS Configuration
#
# TCP Transport
#
#
# Websocket
#
CONFIG_WS_TRANSPORT=y
CONFIG_WS_BUFFER_SIZE=1024
# CONFIG_WS_DYNAMIC_BUFFER is not set
# end of Websocket
# end of TCP Transport
#
# Ultra Low Power (ULP) Co-processor
#
# CONFIG_ULP_COPROC_ENABLED is not set
#
# ULP Debugging Options
#
# end of ULP Debugging Options
# end of Ultra Low Power (ULP) Co-processor
#
# Unity unit testing library
#
CONFIG_UNITY_ENABLE_FLOAT=y
CONFIG_UNITY_ENABLE_DOUBLE=y
# CONFIG_UNITY_ENABLE_64BIT is not set
# CONFIG_UNITY_ENABLE_COLOR is not set
CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER=y
# CONFIG_UNITY_ENABLE_FIXTURE is not set
# CONFIG_UNITY_ENABLE_BACKTRACE_ON_FAIL is not set
# end of Unity unit testing library
#
# USB-OTG
#
CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE=256
CONFIG_USB_HOST_HW_BUFFER_BIAS_BALANCED=y
# CONFIG_USB_HOST_HW_BUFFER_BIAS_IN is not set
# CONFIG_USB_HOST_HW_BUFFER_BIAS_PERIODIC_OUT is not set
#
# Hub Driver Configuration
#
#
# Root Port configuration
#
CONFIG_USB_HOST_DEBOUNCE_DELAY_MS=250
CONFIG_USB_HOST_RESET_HOLD_MS=30
CONFIG_USB_HOST_RESET_RECOVERY_MS=30
CONFIG_USB_HOST_SET_ADDR_RECOVERY_MS=10
# end of Root Port configuration
# CONFIG_USB_HOST_HUBS_SUPPORTED is not set
# end of Hub Driver Configuration
# CONFIG_USB_HOST_ENABLE_ENUM_FILTER_CALLBACK is not set
CONFIG_USB_OTG_SUPPORTED=y
# end of USB-OTG
#
# Virtual file system
#
CONFIG_VFS_SUPPORT_IO=y
CONFIG_VFS_SUPPORT_DIR=y
CONFIG_VFS_SUPPORT_SELECT=y
CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT=y
# CONFIG_VFS_SELECT_IN_RAM is not set
CONFIG_VFS_SUPPORT_TERMIOS=y
CONFIG_VFS_MAX_COUNT=8
#
# Host File System I/O (Semihosting)
#
CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS=1
# end of Host File System I/O (Semihosting)
CONFIG_VFS_INITIALIZE_DEV_NULL=y
# end of Virtual file system
#
# Wear Levelling
#
# CONFIG_WL_SECTOR_SIZE_512 is not set
CONFIG_WL_SECTOR_SIZE_4096=y
CONFIG_WL_SECTOR_SIZE=4096
# end of Wear Levelling
#
# Wi-Fi Provisioning Manager
#
CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES=16
CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT=30
CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y
# CONFIG_WIFI_PROV_STA_FAST_SCAN is not set
# end of Wi-Fi Provisioning Manager
#
# CMake Utilities
#
# CONFIG_CU_RELINKER_ENABLE is not set
# CONFIG_CU_DIAGNOSTICS_COLOR_NEVER is not set
CONFIG_CU_DIAGNOSTICS_COLOR_ALWAYS=y
# CONFIG_CU_DIAGNOSTICS_COLOR_AUTO is not set
# CONFIG_CU_GCC_LTO_ENABLE is not set
# CONFIG_CU_GCC_STRING_1BYTE_ALIGN is not set
# end of CMake Utilities
#
# Audio Codec Device Configuration
#
CONFIG_CODEC_ES8311_SUPPORT=y
CONFIG_CODEC_ES7210_SUPPORT=y
CONFIG_CODEC_ES7243_SUPPORT=y
CONFIG_CODEC_ES7243E_SUPPORT=y
CONFIG_CODEC_ES8156_SUPPORT=y
CONFIG_CODEC_AW88298_SUPPORT=y
CONFIG_CODEC_ES8374_SUPPORT=y
CONFIG_CODEC_ES8388_SUPPORT=y
CONFIG_CODEC_TAS5805M_SUPPORT=y
# CONFIG_CODEC_ZL38063_SUPPORT is not set
# end of Audio Codec Device Configuration
#
# ESP LCD TOUCH
#
CONFIG_ESP_LCD_TOUCH_MAX_POINTS=5
CONFIG_ESP_LCD_TOUCH_MAX_BUTTONS=1
# end of ESP LCD TOUCH
#
# Bus Options
#
#
# I2C Bus Options
#
CONFIG_I2C_BUS_DYNAMIC_CONFIG=y
CONFIG_I2C_MS_TO_WAIT=200
# CONFIG_I2C_BUS_BACKWARD_CONFIG is not set
# CONFIG_I2C_BUS_SUPPORT_SOFTWARE is not set
# end of I2C Bus Options
# end of Bus Options
#
# LVGL configuration
#
CONFIG_LV_CONF_SKIP=y
# CONFIG_LV_CONF_MINIMAL is not set
#
# Color Settings
#
# CONFIG_LV_COLOR_DEPTH_32 is not set
# CONFIG_LV_COLOR_DEPTH_24 is not set
CONFIG_LV_COLOR_DEPTH_16=y
# CONFIG_LV_COLOR_DEPTH_8 is not set
# CONFIG_LV_COLOR_DEPTH_1 is not set
CONFIG_LV_COLOR_DEPTH=16
# end of Color Settings
#
# Memory Settings
#
# CONFIG_LV_USE_BUILTIN_MALLOC is not set
CONFIG_LV_USE_CLIB_MALLOC=y
# CONFIG_LV_USE_MICROPYTHON_MALLOC is not set
# CONFIG_LV_USE_RTTHREAD_MALLOC is not set
# CONFIG_LV_USE_CUSTOM_MALLOC is not set
# CONFIG_LV_USE_BUILTIN_STRING is not set
CONFIG_LV_USE_CLIB_STRING=y
# CONFIG_LV_USE_CUSTOM_STRING is not set
# CONFIG_LV_USE_BUILTIN_SPRINTF is not set
CONFIG_LV_USE_CLIB_SPRINTF=y
# CONFIG_LV_USE_CUSTOM_SPRINTF is not set
# end of Memory Settings
#
# HAL Settings
#
CONFIG_LV_DEF_REFR_PERIOD=15
CONFIG_LV_DPI_DEF=130
# end of HAL Settings
#
# Operating System (OS)
#
# CONFIG_LV_OS_NONE is not set
# CONFIG_LV_OS_PTHREAD is not set
CONFIG_LV_OS_FREERTOS=y
# CONFIG_LV_OS_CMSIS_RTOS2 is not set
# CONFIG_LV_OS_RTTHREAD is not set
# CONFIG_LV_OS_WINDOWS is not set
# CONFIG_LV_OS_MQX is not set
# CONFIG_LV_OS_CUSTOM is not set
CONFIG_LV_USE_OS=2
CONFIG_LV_USE_FREERTOS_TASK_NOTIFY=y
# end of Operating System (OS)
#
# Rendering Configuration
#
CONFIG_LV_DRAW_BUF_STRIDE_ALIGN=1
CONFIG_LV_DRAW_BUF_ALIGN=4
CONFIG_LV_DRAW_LAYER_SIMPLE_BUF_SIZE=24576
CONFIG_LV_DRAW_THREAD_STACK_SIZE=8192
CONFIG_LV_USE_DRAW_SW=y
CONFIG_LV_DRAW_SW_SUPPORT_RGB565=y
CONFIG_LV_DRAW_SW_SUPPORT_RGB565A8=y
CONFIG_LV_DRAW_SW_SUPPORT_RGB888=y
CONFIG_LV_DRAW_SW_SUPPORT_XRGB8888=y
CONFIG_LV_DRAW_SW_SUPPORT_ARGB8888=y
CONFIG_LV_DRAW_SW_SUPPORT_L8=y
CONFIG_LV_DRAW_SW_SUPPORT_AL88=y
CONFIG_LV_DRAW_SW_SUPPORT_A8=y
CONFIG_LV_DRAW_SW_SUPPORT_I1=y
CONFIG_LV_DRAW_SW_DRAW_UNIT_CNT=2
# CONFIG_LV_USE_DRAW_ARM2D_SYNC is not set
# CONFIG_LV_USE_NATIVE_HELIUM_ASM is not set
CONFIG_LV_DRAW_SW_COMPLEX=y
# CONFIG_LV_USE_DRAW_SW_COMPLEX_GRADIENTS is not set
CONFIG_LV_DRAW_SW_SHADOW_CACHE_SIZE=0
CONFIG_LV_DRAW_SW_CIRCLE_CACHE_SIZE=4
CONFIG_LV_DRAW_SW_ASM_NONE=y
# CONFIG_LV_DRAW_SW_ASM_NEON is not set
# CONFIG_LV_DRAW_SW_ASM_HELIUM is not set
# CONFIG_LV_DRAW_SW_ASM_CUSTOM is not set
CONFIG_LV_USE_DRAW_SW_ASM=0
# CONFIG_LV_USE_DRAW_VGLITE is not set
# CONFIG_LV_USE_PXP is not set
# CONFIG_LV_USE_DRAW_DAVE2D is not set
# CONFIG_LV_USE_DRAW_SDL is not set
# CONFIG_LV_USE_DRAW_VG_LITE is not set
# CONFIG_LV_USE_VECTOR_GRAPHIC is not set
# end of Rendering Configuration
#
# Feature Configuration
#
#
# Logging
#
# CONFIG_LV_USE_LOG is not set
# end of Logging
#
# Asserts
#
CONFIG_LV_USE_ASSERT_NULL=y
CONFIG_LV_USE_ASSERT_MALLOC=y
# CONFIG_LV_USE_ASSERT_STYLE is not set
# CONFIG_LV_USE_ASSERT_MEM_INTEGRITY is not set
# CONFIG_LV_USE_ASSERT_OBJ is not set
CONFIG_LV_ASSERT_HANDLER_INCLUDE="assert.h"
# end of Asserts
#
# Debug
#
# CONFIG_LV_USE_REFR_DEBUG is not set
# CONFIG_LV_USE_LAYER_DEBUG is not set
# CONFIG_LV_USE_PARALLEL_DRAW_DEBUG is not set
# end of Debug
#
# Others
#
# CONFIG_LV_ENABLE_GLOBAL_CUSTOM is not set
CONFIG_LV_CACHE_DEF_SIZE=0
CONFIG_LV_IMAGE_HEADER_CACHE_DEF_CNT=0
CONFIG_LV_GRADIENT_MAX_STOPS=2
CONFIG_LV_COLOR_MIX_ROUND_OFS=128
# CONFIG_LV_OBJ_STYLE_CACHE is not set
# CONFIG_LV_USE_OBJ_ID is not set
# CONFIG_LV_USE_OBJ_PROPERTY is not set
# end of Others
# end of Feature Configuration
#
# Compiler Settings
#
# CONFIG_LV_BIG_ENDIAN_SYSTEM is not set
CONFIG_LV_ATTRIBUTE_MEM_ALIGN_SIZE=1
CONFIG_LV_ATTRIBUTE_FAST_MEM_USE_IRAM=y
# CONFIG_LV_USE_FLOAT is not set
# CONFIG_LV_USE_MATRIX is not set
# CONFIG_LV_USE_PRIVATE_API is not set
# end of Compiler Settings
#
# Font Usage
#
#
# Enable built-in fonts
#
# CONFIG_LV_FONT_MONTSERRAT_8 is not set
# CONFIG_LV_FONT_MONTSERRAT_10 is not set
CONFIG_LV_FONT_MONTSERRAT_12=y
CONFIG_LV_FONT_MONTSERRAT_14=y
CONFIG_LV_FONT_MONTSERRAT_16=y
CONFIG_LV_FONT_MONTSERRAT_18=y
CONFIG_LV_FONT_MONTSERRAT_20=y
CONFIG_LV_FONT_MONTSERRAT_22=y
CONFIG_LV_FONT_MONTSERRAT_24=y
CONFIG_LV_FONT_MONTSERRAT_26=y
# CONFIG_LV_FONT_MONTSERRAT_28 is not set
# CONFIG_LV_FONT_MONTSERRAT_30 is not set
# CONFIG_LV_FONT_MONTSERRAT_32 is not set
# CONFIG_LV_FONT_MONTSERRAT_34 is not set
# CONFIG_LV_FONT_MONTSERRAT_36 is not set
# CONFIG_LV_FONT_MONTSERRAT_38 is not set
# CONFIG_LV_FONT_MONTSERRAT_40 is not set
# CONFIG_LV_FONT_MONTSERRAT_42 is not set
# CONFIG_LV_FONT_MONTSERRAT_44 is not set
# CONFIG_LV_FONT_MONTSERRAT_46 is not set
# CONFIG_LV_FONT_MONTSERRAT_48 is not set
# CONFIG_LV_FONT_MONTSERRAT_28_COMPRESSED is not set
# CONFIG_LV_FONT_DEJAVU_16_PERSIAN_HEBREW is not set
# CONFIG_LV_FONT_SIMSUN_14_CJK is not set
# CONFIG_LV_FONT_SIMSUN_16_CJK is not set
# CONFIG_LV_FONT_UNSCII_8 is not set
# CONFIG_LV_FONT_UNSCII_16 is not set
# end of Enable built-in fonts
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_8 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_10 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_12 is not set
CONFIG_LV_FONT_DEFAULT_MONTSERRAT_14=y
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_16 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_18 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_20 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_22 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_24 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_26 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_30 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_32 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_34 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_36 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_38 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_40 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_42 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_44 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_46 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_48 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28_COMPRESSED is not set
# CONFIG_LV_FONT_DEFAULT_DEJAVU_16_PERSIAN_HEBREW is not set
# CONFIG_LV_FONT_DEFAULT_SIMSUN_14_CJK is not set
# CONFIG_LV_FONT_DEFAULT_SIMSUN_16_CJK is not set
# CONFIG_LV_FONT_DEFAULT_UNSCII_8 is not set
# CONFIG_LV_FONT_DEFAULT_UNSCII_16 is not set
# CONFIG_LV_FONT_FMT_TXT_LARGE is not set
CONFIG_LV_USE_FONT_COMPRESSED=y
CONFIG_LV_USE_FONT_PLACEHOLDER=y
# end of Font Usage
#
# Text Settings
#
CONFIG_LV_TXT_ENC_UTF8=y
# CONFIG_LV_TXT_ENC_ASCII is not set
CONFIG_LV_TXT_BREAK_CHARS=" ,.;:-_"
CONFIG_LV_TXT_LINE_BREAK_LONG_LEN=0
# CONFIG_LV_USE_BIDI is not set
# CONFIG_LV_USE_ARABIC_PERSIAN_CHARS is not set
# end of Text Settings
#
# Widget Usage
#
CONFIG_LV_WIDGETS_HAS_DEFAULT_VALUE=y
CONFIG_LV_USE_ANIMIMG=y
CONFIG_LV_USE_ARC=y
CONFIG_LV_USE_BAR=y
CONFIG_LV_USE_BUTTON=y
CONFIG_LV_USE_BUTTONMATRIX=y
CONFIG_LV_USE_CALENDAR=y
# CONFIG_LV_CALENDAR_WEEK_STARTS_MONDAY is not set
CONFIG_LV_USE_CALENDAR_HEADER_ARROW=y
CONFIG_LV_USE_CALENDAR_HEADER_DROPDOWN=y
# CONFIG_LV_USE_CALENDAR_CHINESE is not set
CONFIG_LV_USE_CANVAS=y
CONFIG_LV_USE_CHART=y
CONFIG_LV_USE_CHECKBOX=y
CONFIG_LV_USE_DROPDOWN=y
CONFIG_LV_USE_IMAGE=y
CONFIG_LV_USE_IMAGEBUTTON=y
CONFIG_LV_USE_KEYBOARD=y
CONFIG_LV_USE_LABEL=y
CONFIG_LV_LABEL_TEXT_SELECTION=y
CONFIG_LV_LABEL_LONG_TXT_HINT=y
CONFIG_LV_LABEL_WAIT_CHAR_COUNT=3
CONFIG_LV_USE_LED=y
CONFIG_LV_USE_LINE=y
CONFIG_LV_USE_LIST=y
CONFIG_LV_USE_MENU=y
CONFIG_LV_USE_MSGBOX=y
CONFIG_LV_USE_ROLLER=y
CONFIG_LV_USE_SCALE=y
CONFIG_LV_USE_SLIDER=y
CONFIG_LV_USE_SPAN=y
CONFIG_LV_SPAN_SNIPPET_STACK_SIZE=64
CONFIG_LV_USE_SPINBOX=y
CONFIG_LV_USE_SPINNER=y
CONFIG_LV_USE_SWITCH=y
CONFIG_LV_USE_TEXTAREA=y
CONFIG_LV_TEXTAREA_DEF_PWD_SHOW_TIME=1500
CONFIG_LV_USE_TABLE=y
CONFIG_LV_USE_TABVIEW=y
CONFIG_LV_USE_TILEVIEW=y
CONFIG_LV_USE_WIN=y
# end of Widget Usage
#
# Themes
#
CONFIG_LV_USE_THEME_DEFAULT=y
# CONFIG_LV_THEME_DEFAULT_DARK is not set
CONFIG_LV_THEME_DEFAULT_GROW=y
CONFIG_LV_THEME_DEFAULT_TRANSITION_TIME=80
CONFIG_LV_USE_THEME_SIMPLE=y
# CONFIG_LV_USE_THEME_MONO is not set
# end of Themes
#
# Layouts
#
CONFIG_LV_USE_FLEX=y
CONFIG_LV_USE_GRID=y
# end of Layouts
#
# 3rd Party Libraries
#
CONFIG_LV_FS_DEFAULT_DRIVE_LETTER=0
# CONFIG_LV_USE_FS_STDIO is not set
# CONFIG_LV_USE_FS_POSIX is not set
# CONFIG_LV_USE_FS_WIN32 is not set
# CONFIG_LV_USE_FS_FATFS is not set
# CONFIG_LV_USE_FS_MEMFS is not set
# CONFIG_LV_USE_FS_LITTLEFS is not set
# CONFIG_LV_USE_FS_ARDUINO_ESP_LITTLEFS is not set
# CONFIG_LV_USE_FS_ARDUINO_SD is not set
# CONFIG_LV_USE_LODEPNG is not set
# CONFIG_LV_USE_LIBPNG is not set
# CONFIG_LV_USE_BMP is not set
# CONFIG_LV_USE_TJPGD is not set
# CONFIG_LV_USE_LIBJPEG_TURBO is not set
# CONFIG_LV_USE_GIF is not set
# CONFIG_LV_BIN_DECODER_RAM_LOAD is not set
# CONFIG_LV_USE_RLE is not set
# CONFIG_LV_USE_QRCODE is not set
# CONFIG_LV_USE_BARCODE is not set
# CONFIG_LV_USE_FREETYPE is not set
# CONFIG_LV_USE_TINY_TTF is not set
# CONFIG_LV_USE_RLOTTIE is not set
# CONFIG_LV_USE_THORVG is not set
# CONFIG_LV_USE_LZ4 is not set
# CONFIG_LV_USE_FFMPEG is not set
# end of 3rd Party Libraries
#
# Others
#
# CONFIG_LV_USE_SNAPSHOT is not set
CONFIG_LV_USE_SYSMON=y
CONFIG_LV_USE_PERF_MONITOR=y
# CONFIG_LV_PERF_MONITOR_ALIGN_TOP_LEFT is not set
# CONFIG_LV_PERF_MONITOR_ALIGN_TOP_MID is not set
# CONFIG_LV_PERF_MONITOR_ALIGN_TOP_RIGHT is not set
# CONFIG_LV_PERF_MONITOR_ALIGN_BOTTOM_LEFT is not set
# CONFIG_LV_PERF_MONITOR_ALIGN_BOTTOM_MID is not set
CONFIG_LV_PERF_MONITOR_ALIGN_BOTTOM_RIGHT=y
# CONFIG_LV_PERF_MONITOR_ALIGN_LEFT_MID is not set
# CONFIG_LV_PERF_MONITOR_ALIGN_RIGHT_MID is not set
# CONFIG_LV_PERF_MONITOR_ALIGN_CENTER is not set
# CONFIG_LV_USE_PERF_MONITOR_LOG_MODE is not set
# CONFIG_LV_USE_PROFILER is not set
# CONFIG_LV_USE_MONKEY is not set
# CONFIG_LV_USE_GRIDNAV is not set
# CONFIG_LV_USE_FRAGMENT is not set
CONFIG_LV_USE_IMGFONT=y
CONFIG_LV_USE_OBSERVER=y
# CONFIG_LV_USE_IME_PINYIN is not set
# CONFIG_LV_USE_FILE_EXPLORER is not set
CONFIG_LVGL_VERSION_MAJOR=9
CONFIG_LVGL_VERSION_MINOR=2
CONFIG_LVGL_VERSION_PATCH=2
# end of Others
#
# Devices
#
# CONFIG_LV_USE_SDL is not set
# CONFIG_LV_USE_X11 is not set
# CONFIG_LV_USE_WAYLAND is not set
# CONFIG_LV_USE_LINUX_FBDEV is not set
# CONFIG_LV_USE_NUTTX is not set
# CONFIG_LV_USE_LINUX_DRM is not set
# CONFIG_LV_USE_TFT_ESPI is not set
# CONFIG_LV_USE_EVDEV is not set
# CONFIG_LV_USE_LIBINPUT is not set
# CONFIG_LV_USE_ST7735 is not set
# CONFIG_LV_USE_ST7789 is not set
# CONFIG_LV_USE_ST7796 is not set
# CONFIG_LV_USE_ILI9341 is not set
# CONFIG_LV_USE_GENERIC_MIPI is not set
# CONFIG_LV_USE_RENESAS_GLCDC is not set
# CONFIG_LV_USE_OPENGLES is not set
# CONFIG_LV_USE_QNX is not set
# end of Devices
#
# Examples
#
CONFIG_LV_BUILD_EXAMPLES=y
# end of Examples
#
# Demos
#
CONFIG_LV_USE_DEMO_WIDGETS=y
# CONFIG_LV_USE_DEMO_KEYPAD_AND_ENCODER is not set
CONFIG_LV_USE_DEMO_BENCHMARK=y
CONFIG_LV_USE_DEMO_RENDER=y
CONFIG_LV_USE_DEMO_SCROLL=y
CONFIG_LV_USE_DEMO_STRESS=y
CONFIG_LV_USE_DEMO_TRANSFORM=y
CONFIG_LV_USE_DEMO_MUSIC=y
# CONFIG_LV_DEMO_MUSIC_SQUARE is not set
# CONFIG_LV_DEMO_MUSIC_LANDSCAPE is not set
# CONFIG_LV_DEMO_MUSIC_ROUND is not set
# CONFIG_LV_DEMO_MUSIC_LARGE is not set
CONFIG_LV_DEMO_MUSIC_AUTO_PLAY=y
CONFIG_LV_USE_DEMO_FLEX_LAYOUT=y
CONFIG_LV_USE_DEMO_MULTILANG=y
# end of Demos
# end of LVGL configuration
#
# Board Support Package(ESP32-P4)
#
CONFIG_BSP_ERROR_CHECK=y
#
# I2C
#
CONFIG_BSP_I2C_NUM=1
CONFIG_BSP_I2C_FAST_MODE=y
CONFIG_BSP_I2C_CLK_SPEED_HZ=400000
# end of I2C
#
# I2S
#
CONFIG_BSP_I2S_NUM=1
# end of I2S
#
# uSD card - Virtual File System
#
# CONFIG_BSP_SD_FORMAT_ON_MOUNT_FAIL is not set
CONFIG_BSP_SD_MOUNT_POINT="/sdcard"
# end of uSD card - Virtual File System
#
# SPIFFS - Virtual File System
#
# CONFIG_BSP_SPIFFS_FORMAT_ON_MOUNT_FAIL is not set
CONFIG_BSP_SPIFFS_MOUNT_POINT="/spiffs"
CONFIG_BSP_SPIFFS_PARTITION_LABEL="storage"
CONFIG_BSP_SPIFFS_MAX_FILES=5
# end of SPIFFS - Virtual File System
#
# Display
#
CONFIG_BSP_LCD_DPI_BUFFER_NUMS=1
CONFIG_BSP_DISPLAY_BRIGHTNESS_LEDC_CH=1
CONFIG_BSP_LCD_COLOR_FORMAT_RGB565=y
# CONFIG_BSP_LCD_COLOR_FORMAT_RGB888 is not set
CONFIG_BSP_LCD_TYPE_800_1280_10_1_INCH=y
# CONFIG_BSP_LCD_TYPE_800_1280_10_1_INCH_A is not set
# CONFIG_BSP_LCD_TYPE_800_1280_8_INCH_A is not set
# CONFIG_BSP_LCD_TYPE_720_1280_7_INCH_A is not set
# CONFIG_BSP_LCD_TYPE_480_640_2_8_INCH is not set
# CONFIG_BSP_LCD_TYPE_800_800_3_4_INCH_C is not set
# CONFIG_BSP_LCD_TYPE_720_720_4_INCH_C is not set
# CONFIG_BSP_LCD_TYPE_480_800_4_INCH is not set
# CONFIG_BSP_LCD_TYPE_720_1280_5_INCH_D is not set
# CONFIG_BSP_LCD_TYPE_720_1560_6_25_INCH is not set
# CONFIG_BSP_LCD_TYPE_1024_600_5_INCH_C is not set
# CONFIG_BSP_LCD_TYPE_1024_600_7_INCH_C is not set
# CONFIG_BSP_LCD_TYPE_400_1280_7_9_INCH is not set
# CONFIG_BSP_LCD_TYPE_1280_800_7_INCH_E is not set
# CONFIG_BSP_LCD_TYPE_1280_800_8_INCH_C is not set
# CONFIG_BSP_LCD_TYPE_1280_800_10_1_INCH_C is not set
# CONFIG_BSP_LCD_TYPE_480_1920_8_8_INCH is not set
# CONFIG_BSP_LCD_TYPE_320_1480_11_9_INCH is not set
CONFIG_BSP_LCD_MIPI_DSI_LANE_BITRATE_MBPS=1500
# end of Display
# end of Board Support Package(ESP32-P4)
# end of Component config
CONFIG_IDF_EXPERIMENTAL_FEATURES=y
# Deprecated options for backward compatibility
# CONFIG_APP_BUILD_TYPE_ELF_RAM is not set
# CONFIG_NO_BLOBS is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_NONE is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_ERROR is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_WARN is not set
CONFIG_LOG_BOOTLOADER_LEVEL_INFO=y
# CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE is not set
CONFIG_LOG_BOOTLOADER_LEVEL=3
# CONFIG_APP_ROLLBACK_ENABLE is not set
# CONFIG_FLASH_ENCRYPTION_ENABLED is not set
CONFIG_FLASHMODE_QIO=y
# CONFIG_FLASHMODE_QOUT is not set
# CONFIG_FLASHMODE_DIO is not set
# CONFIG_FLASHMODE_DOUT is not set
CONFIG_MONITOR_BAUD=115200
# CONFIG_OPTIMIZATION_LEVEL_DEBUG is not set
# CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG is not set
# CONFIG_COMPILER_OPTIMIZATION_DEFAULT is not set
# CONFIG_OPTIMIZATION_LEVEL_RELEASE is not set
# CONFIG_COMPILER_OPTIMIZATION_LEVEL_RELEASE is not set
CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED=y
# CONFIG_OPTIMIZATION_ASSERTIONS_SILENT is not set
# CONFIG_OPTIMIZATION_ASSERTIONS_DISABLED is not set
CONFIG_OPTIMIZATION_ASSERTION_LEVEL=2
# CONFIG_CXX_EXCEPTIONS is not set
CONFIG_STACK_CHECK_NONE=y
# CONFIG_STACK_CHECK_NORM is not set
# CONFIG_STACK_CHECK_STRONG is not set
# CONFIG_STACK_CHECK_ALL is not set
# CONFIG_WARN_WRITE_STRINGS is not set
# CONFIG_ESP32_APPTRACE_DEST_TRAX is not set
CONFIG_ESP32_APPTRACE_DEST_NONE=y
CONFIG_ESP32_APPTRACE_LOCK_ENABLE=y
# CONFIG_MCPWM_ISR_IN_IRAM is not set
# CONFIG_EVENT_LOOP_PROFILING is not set
CONFIG_POST_EVENTS_FROM_ISR=y
CONFIG_POST_EVENTS_FROM_IRAM_ISR=y
CONFIG_GDBSTUB_SUPPORT_TASKS=y
CONFIG_GDBSTUB_MAX_TASKS=32
# CONFIG_OTA_ALLOW_HTTP is not set
CONFIG_SYSTEM_EVENT_QUEUE_SIZE=32
CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE=2304
CONFIG_MAIN_TASK_STACK_SIZE=12288
CONFIG_CONSOLE_UART_DEFAULT=y
# CONFIG_CONSOLE_UART_CUSTOM is not set
# CONFIG_CONSOLE_UART_NONE is not set
# CONFIG_ESP_CONSOLE_UART_NONE is not set
CONFIG_CONSOLE_UART=y
CONFIG_CONSOLE_UART_NUM=0
CONFIG_CONSOLE_UART_BAUDRATE=115200
CONFIG_INT_WDT=y
CONFIG_INT_WDT_TIMEOUT_MS=300
CONFIG_INT_WDT_CHECK_CPU1=y
CONFIG_TASK_WDT=y
CONFIG_ESP_TASK_WDT=y
# CONFIG_TASK_WDT_PANIC is not set
CONFIG_TASK_WDT_TIMEOUT_S=5
CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0=y
CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1=y
# CONFIG_ESP32_DEBUG_STUBS_ENABLE is not set
CONFIG_BROWNOUT_DET=y
CONFIG_BROWNOUT_DET_LVL_SEL_7=y
# CONFIG_BROWNOUT_DET_LVL_SEL_6 is not set
# CONFIG_BROWNOUT_DET_LVL_SEL_5 is not set
CONFIG_BROWNOUT_DET_LVL=7
CONFIG_IPC_TASK_STACK_SIZE=1024
CONFIG_TIMER_TASK_STACK_SIZE=3584
# CONFIG_ESP32_ENABLE_COREDUMP_TO_FLASH is not set
# CONFIG_ESP32_ENABLE_COREDUMP_TO_UART is not set
CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE=y
CONFIG_TIMER_TASK_PRIORITY=1
CONFIG_TIMER_TASK_STACK_DEPTH=2048
CONFIG_TIMER_QUEUE_LENGTH=10
# CONFIG_ENABLE_STATIC_TASK_CLEAN_UP_HOOK is not set
CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY=y
# CONFIG_HAL_ASSERTION_SILIENT is not set
# CONFIG_L2_TO_L3_COPY is not set
CONFIG_ESP_GRATUITOUS_ARP=y
CONFIG_GARP_TMR_INTERVAL=60
CONFIG_TCPIP_RECVMBOX_SIZE=32
CONFIG_TCP_MAXRTX=12
CONFIG_TCP_SYNMAXRTX=12
CONFIG_TCP_MSS=1440
CONFIG_TCP_MSL=60000
CONFIG_TCP_SND_BUF_DEFAULT=5760
CONFIG_TCP_WND_DEFAULT=5760
CONFIG_TCP_RECVMBOX_SIZE=6
CONFIG_TCP_QUEUE_OOSEQ=y
CONFIG_TCP_OVERSIZE_MSS=y
# CONFIG_TCP_OVERSIZE_QUARTER_MSS is not set
# CONFIG_TCP_OVERSIZE_DISABLE is not set
CONFIG_UDP_RECVMBOX_SIZE=6
CONFIG_TCPIP_TASK_STACK_SIZE=3072
CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY=y
# CONFIG_TCPIP_TASK_AFFINITY_CPU0 is not set
# CONFIG_TCPIP_TASK_AFFINITY_CPU1 is not set
CONFIG_TCPIP_TASK_AFFINITY=0x7FFFFFFF
# CONFIG_PPP_SUPPORT is not set
CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT=5
CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072
CONFIG_ESP32_PTHREAD_STACK_MIN=768
CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY=y
# CONFIG_ESP32_DEFAULT_PTHREAD_CORE_0 is not set
# CONFIG_ESP32_DEFAULT_PTHREAD_CORE_1 is not set
CONFIG_ESP32_PTHREAD_TASK_CORE_DEFAULT=-1
CONFIG_ESP32_PTHREAD_TASK_NAME_DEFAULT="pthread"
CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS=y
# CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_FAILS is not set
# CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED is not set
CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT=y
CONFIG_SUPPORT_TERMIOS=y
CONFIG_SEMIHOSTFS_MAX_MOUNT_POINTS=1
# End of deprecated options
|
0015/StickiNote
| 4,136 |
Readme.md
|
## **StickiNote – ESP32-P4 Digital Sticky Notes App**
<div align="center">

</div>
**StickiNote** is a **modern, e-paper-styled digital sticky note app** designed specifically for high-performance **ESP32-P4-based embedded systems**. This project leverages the **fast clock speed of the ESP32-P4** and the **MIPI DSI interface for a 10-inch display**, ensuring smooth animations, fluid UI interactions, and an optimal user experience.
---
## **Features**
**Designed for ESP32-P4** – Optimized for **ESP32-P4’s high-performance CPU and memory**.
**MIPI DSI 10-Inch Display Support** – **Hardware-accelerated** rendering for large screens.
**Digital Sticky Notes** – Add, move, resize, and edit post-its effortlessly.
**Persistent Storage (NVS)** – Saves notes as JSON in ESP32's flash memory.
**Animated Splash Screen** – Smooth startup animation for an engaging experience.
**E-Paper-Like UI** – Minimalist notebook-style background.
**Floating Action Button (FAB)** – Quickly create new sticky notes.
**Keyboard Integration** – Pop-up keyboard for text input on sticky notes.
**Touch & Drag Support** – Move and resize post-its with intuitive gestures.
**Low Memory Consumption** – Optimized **LVGL v9 implementation** for high FPS.
[](https://youtu.be/b1jTc1RyG3s)
*(Waveshare ESP32-P4 Nano & 10-Inch DSI Display)*
---
## **⚡ Why ESP32-P4 & MIPI DSI?**
This project is designed **exclusively for ESP32-P4**, taking advantage of:
**Higher Clock Speed** – Ensures smooth animations and fast UI updates.
**MIPI DSI Interface** – Supports **10-inch high-resolution displays** with optimal performance.
**Hardware Acceleration** – Optimized graphics rendering for fluid user interactions.
⚠️ This project is **not** designed for standard ESP32 boards._ Using **ESP32-P4 is essential** to achieve the required performance levels.
---
## **Getting Started**
### **Requirements**
- **ESP32-P4** (Fast clock + MIPI DSI support)
- **10-inch MIPI DSI Display**
- **ESP-IDF v5.3+**
- **LVGL v9**
---
## **Dependencies**
This project requires the following **ESP-IDF components**:
```yaml
dependencies:
lvgl/lvgl:
version: 9.2.*
public: true
waveshare/esp_lcd_jd9365_10_1: ^1.0.1
waveshare/esp32_p4_nano: ^1.1.5
```
💡 **Ensure you have these dependencies installed in your ESP-IDF project before building.**
---
## **How to Use**
**Create a Note** – Tap the **FAB button** to create a sticky note.
**Edit a Note** – Long-press on a note to open the **keyboard**.
**Move a Note** – Drag and drop notes anywhere on the screen.
**Resize a Note** – Tap the **corner triangle** and drag to resize.
**Delete a Note** – Tap the `(X)` button inside a note.
**Persistence** – All notes are saved automatically and restored on reboot.
---
## **Project Structure**
```
StickiNote/
│── main/
│ ├── include/ # header files
│ ├── main.cpp # App entry point
│ ├── LVGL_WidgetManager.cpp # Manages UI widgets
│ ├── SplashScreen.cpp # Animated splash screen logic
│ ├── NVSManager.cpp # Handles saving/loading notes in NVS
│ ├── ui_resources/ # UI assets (icons, images, fonts)
│ ├── CMakeLists.txt # Build configuration
│── CMakeLists.txt # Project build file
│── README.md # Documentation
│── LICENSE # Open-source license (MIT recommended)
```
---
## **Contributing**
**Fork the repo** and submit pull requests with new features or bug fixes.
**Report issues** via the [GitHub Issues](https://github.com/0015/StickiNote/issues) tab.
**Feature Requests** – Suggest improvements via discussions!
---
## **License**
This project is **open-source** under the **MIT License**. Feel free to use, modify, and distribute it!
---
## **Support & Community**
💬 Have questions or ideas? Join our discussions!
📢 **Follow us on [YouTube](https://youtube.com/ThatProject) for tutorials!**
|
0015/StickiNote
| 1,523 |
sdkconfig.defaults
|
# This file was generated using idf.py save-defconfig. It can be edited manually.
# Espressif IoT Development Framework (ESP-IDF) 5.4.0 Project Minimal Configuration
#
CONFIG_IDF_TARGET="esp32p4"
CONFIG_ESPTOOLPY_FLASHMODE_QIO=y
CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_COMPILER_OPTIMIZATION_PERF=y
CONFIG_SPIRAM=y
CONFIG_SPIRAM_SPEED_200M=y
CONFIG_SPIRAM_XIP_FROM_PSRAM=y
CONFIG_CACHE_L2_CACHE_256KB=y
CONFIG_CACHE_L2_CACHE_LINE_128B=y
CONFIG_ESP_MAIN_TASK_STACK_SIZE=10240
CONFIG_FREERTOS_HZ=1000
CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID=y
CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS=y
CONFIG_LV_USE_CLIB_MALLOC=y
CONFIG_LV_USE_CLIB_STRING=y
CONFIG_LV_USE_CLIB_SPRINTF=y
CONFIG_LV_DEF_REFR_PERIOD=15
CONFIG_LV_OS_FREERTOS=y
CONFIG_LV_DRAW_SW_DRAW_UNIT_CNT=2
CONFIG_LV_ATTRIBUTE_FAST_MEM_USE_IRAM=y
CONFIG_LV_FONT_MONTSERRAT_12=y
CONFIG_LV_FONT_MONTSERRAT_16=y
CONFIG_LV_FONT_MONTSERRAT_18=y
CONFIG_LV_FONT_MONTSERRAT_20=y
CONFIG_LV_FONT_MONTSERRAT_22=y
CONFIG_LV_FONT_MONTSERRAT_24=y
CONFIG_LV_FONT_MONTSERRAT_26=y
CONFIG_LV_USE_FONT_COMPRESSED=y
CONFIG_LV_TXT_BREAK_CHARS=" ,.;:-_"
CONFIG_LV_USE_SYSMON=y
CONFIG_LV_USE_PERF_MONITOR=y
CONFIG_LV_USE_IMGFONT=y
CONFIG_LV_USE_DEMO_WIDGETS=y
CONFIG_LV_USE_DEMO_BENCHMARK=y
CONFIG_LV_USE_DEMO_RENDER=y
CONFIG_LV_USE_DEMO_SCROLL=y
CONFIG_LV_USE_DEMO_STRESS=y
CONFIG_LV_USE_DEMO_TRANSFORM=y
CONFIG_LV_USE_DEMO_MUSIC=y
CONFIG_LV_DEMO_MUSIC_AUTO_PLAY=y
CONFIG_LV_USE_DEMO_FLEX_LAYOUT=y
CONFIG_LV_USE_DEMO_MULTILANG=y
CONFIG_IDF_EXPERIMENTAL_FEATURES=y
|
000haoji/deep-student
| 16,878 |
src/components/SubjectConfig.tsx
|
import React, { useState, useEffect } from 'react';
import { TauriAPI } from '../utils/tauriApi';
import { useSubject } from '../contexts/SubjectContext';
import { Target, Plus, RefreshCcw, Edit, Trash2, CheckCircle, XCircle, Lightbulb, FileText, Tag, X } from 'lucide-react';
interface SubjectConfig {
id: string;
subject_name: string;
display_name: string;
description: string;
is_enabled: boolean;
prompts: SubjectPrompts;
mistake_types: string[];
default_tags: string[];
created_at: string;
updated_at: string;
}
interface SubjectPrompts {
analysis_prompt: string;
review_prompt: string;
chat_prompt: string;
ocr_prompt: string;
classification_prompt: string;
consolidated_review_prompt: string;
anki_generation_prompt: string;
}
interface SubjectConfigProps {}
export const SubjectConfig: React.FC<SubjectConfigProps> = () => {
const { refreshSubjects } = useSubject();
const [configs, setConfigs] = useState<SubjectConfig[]>([]);
const [selectedConfig, setSelectedConfig] = useState<SubjectConfig | null>(null);
const [isEditing, setIsEditing] = useState(false);
const [isCreating, setIsCreating] = useState(false);
const [loading, setLoading] = useState(false);
// LaTeX数学公式输出规范
const latexRules = `\n\n【LaTeX 数学公式输出规范】
1. 所有数学公式、符号、变量等都必须使用LaTeX格式包裹。
2. 行内公式使用 \`$...$\` 包裹,例如:\`$E=mc^2$\`。
3. 独立展示的公式或方程组使用 \`$$...$$\` 包裹。
4. 对于矩阵,请务必使用 \`bmatrix\` 环境,例如:\`$$\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}$$\`。在 \`bmatrix\` 环境中,使用 \`&\` 分隔列元素,使用 \`\\\\\` (单个反斜杠,在JSON字符串中可能需要转义为 \`\\\\\\\\\`) 换行。
5. 确保所有LaTeX环境(如 \`bmatrix\`)和括号都正确配对和闭合。
6. 避免使用不常见或自定义的LaTeX宏包或命令,尽量使用标准KaTeX支持的命令。`;
// 新建/编辑表单状态
const [formData, setFormData] = useState<Partial<SubjectConfig>>({
subject_name: '',
display_name: '',
description: '',
is_enabled: true,
prompts: {
analysis_prompt: `请仔细分析这道{subject}错题,提供详细的解题思路和知识点讲解。${latexRules}`,
review_prompt: `请分析这些{subject}错题的共同问题和改进建议。${latexRules}`,
chat_prompt: `基于这道{subject}题目,请回答学生的问题。${latexRules}`,
ocr_prompt: '请识别这张{subject}题目图片中的文字内容。',
classification_prompt: '请分析这道{subject}题目的类型和相关知识点标签。',
consolidated_review_prompt: `请对这些{subject}错题进行统一分析,提供综合性的学习建议和知识点总结。${latexRules}`,
anki_generation_prompt: `请根据这道{subject}错题生成Anki卡片,包含问题、答案和关键知识点。${latexRules}`,
},
mistake_types: ['计算错误', '概念理解', '方法应用', '知识遗忘', '审题不清'],
default_tags: ['基础知识', '重点难点', '易错点'],
});
useEffect(() => {
loadConfigs();
}, []);
const loadConfigs = async () => {
setLoading(true);
try {
const allConfigs = await TauriAPI.getAllSubjectConfigs(false);
setConfigs(allConfigs);
// 同时刷新全局科目状态
await refreshSubjects();
} catch (error) {
console.error('加载科目配置失败:', error);
alert('加载科目配置失败: ' + error);
} finally {
setLoading(false);
}
};
const handleEdit = (config: SubjectConfig) => {
setSelectedConfig(config);
setFormData(config);
setIsEditing(true);
setIsCreating(false);
};
const handleCreate = () => {
setSelectedConfig(null);
setFormData({
subject_name: '',
display_name: '',
description: '',
is_enabled: true,
prompts: {
analysis_prompt: `请仔细分析这道{subject}错题,提供详细的解题思路和知识点讲解。${latexRules}`,
review_prompt: `请分析这些{subject}错题的共同问题和改进建议。${latexRules}`,
chat_prompt: `基于这道{subject}题目,请回答学生的问题。${latexRules}`,
ocr_prompt: '请识别这张{subject}题目图片中的文字内容。',
classification_prompt: '请分析这道{subject}题目的类型和相关知识点标签。',
consolidated_review_prompt: `请对这些{subject}错题进行统一分析,提供综合性的学习建议和知识点总结。${latexRules}`,
anki_generation_prompt: `请根据这道{subject}错题生成Anki卡片,包含问题、答案和关键知识点。${latexRules}`,
},
mistake_types: ['计算错误', '概念理解', '方法应用', '知识遗忘', '审题不清'],
default_tags: ['基础知识', '重点难点', '易错点'],
});
setIsCreating(true);
setIsEditing(false);
};
const handleSave = async () => {
if (!formData.subject_name || !formData.display_name) {
alert('请填写科目名称和显示名称');
return;
}
setLoading(true);
try {
if (isCreating) {
await TauriAPI.createSubjectConfig({
subject_name: formData.subject_name!,
display_name: formData.display_name!,
description: formData.description,
prompts: formData.prompts,
mistake_types: formData.mistake_types,
default_tags: formData.default_tags,
});
} else if (selectedConfig) {
await TauriAPI.updateSubjectConfig({
id: selectedConfig.id,
display_name: formData.display_name,
description: formData.description,
is_enabled: formData.is_enabled,
prompts: formData.prompts,
mistake_types: formData.mistake_types,
default_tags: formData.default_tags,
});
}
alert(isCreating ? '创建成功!' : '更新成功!');
setIsEditing(false);
setIsCreating(false);
setSelectedConfig(null);
await loadConfigs();
// 刷新全局科目状态,以更新标题栏的科目下拉栏
await refreshSubjects();
} catch (error) {
console.error('保存失败:', error);
alert('保存失败: ' + error);
} finally {
setLoading(false);
}
};
const handleDelete = async (config: SubjectConfig) => {
if (!confirm(`确定要删除科目配置 "${config.display_name}" 吗?`)) {
return;
}
setLoading(true);
try {
await TauriAPI.deleteSubjectConfig(config.id);
alert('删除成功!');
await loadConfigs();
// 刷新全局科目状态,以更新标题栏的科目下拉栏
await refreshSubjects();
} catch (error) {
console.error('删除失败:', error);
alert('删除失败: ' + error);
} finally {
setLoading(false);
}
};
const handleCancel = () => {
setIsEditing(false);
setIsCreating(false);
setSelectedConfig(null);
};
const updateFormField = (field: string, value: any) => {
setFormData(prev => ({
...prev,
[field]: value
}));
};
const updatePromptField = (field: string, value: string) => {
setFormData(prev => ({
...prev,
prompts: {
...prev.prompts!,
[field]: value
}
}));
};
const updateArrayField = (field: 'mistake_types' | 'default_tags', value: string) => {
const items = value.split(',').map(item => item.trim()).filter(item => item);
setFormData(prev => ({
...prev,
[field]: items
}));
};
return (
<>
<div className="subject-config">
<div className="settings-section">
<h3 style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Target size={20} />
科目配置管理
</h3>
<div className="toolbar">
<button onClick={handleCreate} className="create-button" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Plus size={16} />
新建科目
</button>
<button onClick={loadConfigs} disabled={loading} className="refresh-button" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<RefreshCcw size={16} />
刷新
</button>
</div>
{loading ? (
<div className="loading">加载中...</div>
) : (
<div className="config-list">
{configs.length === 0 ? (
<div className="empty-state">
<p>暂无科目配置</p>
<button onClick={handleCreate}>创建第一个科目配置</button>
</div>
) : (
configs.map(config => (
<div key={config.id} className={`config-item ${!config.is_enabled ? 'disabled' : ''}`}>
<div className="config-header">
<h4>{config.display_name}</h4>
<div className="config-actions">
<button onClick={() => handleEdit(config)} className="edit-button" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Edit size={14} />
编辑
</button>
<button onClick={() => handleDelete(config)} className="delete-button" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Trash2 size={14} />
删除
</button>
</div>
</div>
<div className="config-info">
<p><strong>科目名称:</strong> {config.subject_name}</p>
<p><strong>描述:</strong> {config.description}</p>
<p style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<strong>状态:</strong>
{config.is_enabled ? (
<span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<CheckCircle size={16} color="green" />
启用
</span>
) : (
<span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<XCircle size={16} color="red" />
禁用
</span>
)}
</p>
<p><strong>错题类型:</strong> {config.mistake_types.join(', ')}</p>
<p><strong>默认标签:</strong> {config.default_tags.join(', ')}</p>
<p><strong>更新时间:</strong> {new Date(config.updated_at).toLocaleString('zh-CN')}</p>
</div>
</div>
))
)}
</div>
)}
<div className="tips">
<h5 style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Lightbulb size={16} />
使用提示:
</h5>
<ul>
<li>科目名称创建后不可修改,请谨慎填写</li>
<li>提示词中可使用 {'{subject}'} 作为科目名称占位符</li>
<li>禁用的科目在前端选择器中不会显示</li>
<li>修改提示词会影响后续的AI分析结果</li>
</ul>
</div>
</div>
</div>
{(isEditing || isCreating) && (
<div className="modal-overlay">
<div className="modal-dialog">
<div className="modal-header">
<h3 style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Target size={20} />
{isCreating ? '新建科目配置' : '编辑科目配置'}
</h3>
<button onClick={handleCancel} className="close-button">
<X size={16} />
</button>
</div>
<div className="modal-content">
<div className="form-section">
<div className="form-group">
<label>科目名称:</label>
<input
type="text"
value={formData.subject_name || ''}
onChange={(e) => updateFormField('subject_name', e.target.value)}
disabled={!isCreating}
placeholder="如:数学、物理"
/>
{!isCreating && <small>科目名称创建后不可修改</small>}
</div>
<div className="form-group">
<label>显示名称:</label>
<input
type="text"
value={formData.display_name || ''}
onChange={(e) => updateFormField('display_name', e.target.value)}
placeholder="如:高中数学、初中物理"
/>
</div>
<div className="form-group">
<label>描述:</label>
<textarea
value={formData.description || ''}
onChange={(e) => updateFormField('description', e.target.value)}
placeholder="科目的详细描述"
rows={2}
/>
</div>
<div className="form-group checkbox-group">
<div className="checkbox-container">
<span>启用此科目</span>
<input
type="checkbox"
checked={formData.is_enabled}
onChange={(e) => updateFormField('is_enabled', e.target.checked)}
/>
</div>
</div>
</div>
<div className="form-section">
<h4 style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<FileText size={16} />
提示词配置
</h4>
<small>使用 {'{subject}'} 作为科目名称的占位符</small>
<div className="form-group">
<label>错题分析提示词:</label>
<textarea
value={formData.prompts?.analysis_prompt || ''}
onChange={(e) => updatePromptField('analysis_prompt', e.target.value)}
rows={3}
placeholder="用于分析错题的提示词"
/>
</div>
<div className="form-group">
<label>回顾分析提示词:</label>
<textarea
value={formData.prompts?.review_prompt || ''}
onChange={(e) => updatePromptField('review_prompt', e.target.value)}
rows={3}
placeholder="用于回顾分析的提示词"
/>
</div>
<div className="form-group">
<label>对话追问提示词:</label>
<textarea
value={formData.prompts?.chat_prompt || ''}
onChange={(e) => updatePromptField('chat_prompt', e.target.value)}
rows={3}
placeholder="用于对话追问的提示词"
/>
</div>
<div className="form-group">
<label>OCR识别提示词:</label>
<textarea
value={formData.prompts?.ocr_prompt || ''}
onChange={(e) => updatePromptField('ocr_prompt', e.target.value)}
rows={2}
placeholder="用于OCR图片识别的提示词"
/>
</div>
<div className="form-group">
<label>分类标记提示词:</label>
<textarea
value={formData.prompts?.classification_prompt || ''}
onChange={(e) => updatePromptField('classification_prompt', e.target.value)}
rows={2}
placeholder="用于分类和标记的提示词"
/>
</div>
<div className="form-group">
<label>统一回顾分析提示词:</label>
<textarea
value={formData.prompts?.consolidated_review_prompt || ''}
onChange={(e) => updatePromptField('consolidated_review_prompt', e.target.value)}
rows={3}
placeholder="用于统一回顾分析的提示词"
/>
</div>
<div className="form-group">
<label>Anki卡片生成提示词:</label>
<textarea
value={formData.prompts?.anki_generation_prompt || ''}
onChange={(e) => updatePromptField('anki_generation_prompt', e.target.value)}
rows={3}
placeholder="用于生成Anki卡片的提示词"
/>
</div>
</div>
<div className="form-section">
<h4 style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Tag size={16} />
默认配置
</h4>
<div className="form-group">
<label>错题类型 (逗号分隔):</label>
<input
type="text"
value={formData.mistake_types?.join(', ') || ''}
onChange={(e) => updateArrayField('mistake_types', e.target.value)}
placeholder="计算错误, 概念理解, 方法应用"
/>
</div>
<div className="form-group">
<label>默认标签 (逗号分隔):</label>
<input
type="text"
value={formData.default_tags?.join(', ') || ''}
onChange={(e) => updateArrayField('default_tags', e.target.value)}
placeholder="基础知识, 重点难点, 易错点"
/>
</div>
</div>
</div>
<div className="modal-footer">
<button onClick={handleCancel} className="cancel-button">取消</button>
<button onClick={handleSave} disabled={loading} className="save-button">
{loading ? '保存中...' : '保存'}
</button>
</div>
</div>
</div>
)}
</>
);
};
|
0000cd/wolf-set
| 2,646 |
content/achrive/2024-12.md
|
---
author: 逊狼
title: 2024-12
date: 2024-12-26
draft: false
---
```yaml
- title: Button Stealer
hex: "#ff5100"
tags:
- 网页
- 有趣
- 开源
date: "2024/12"
description: 从路过的每个网页“窃取”按钮,欣赏你的按钮藏品。
links:
- name: 官网
url: https://anatolyzenkov.com/stolen-buttons/button-stealer
- name: GitHub
url: https://github.com/anatolyzenkov/button-stealer
- name: 藏品?
url: https://anatolyzenkov.com/stolen-buttons
- title: cobalt
hex: "#000000"
tags:
- 网页
- 工具
- 开源
date: "2024/12"
description: 一键下载网页上的媒体文件。
links:
- name: 官网
url: https://cobalt.tools/
- name: GitHub
url: https://github.com/imputnet/cobalt
- name: 赞助
url: https://liberapay.com/imput
- title: GOODY-2
hex: "#EBF38D"
tags:
- 网页
- AI
- 有趣
date: "2024/12"
description: 与世界上“最负责”的 AI 聊天。
links: https://www.goody2.ai/chat
- title: SONOTELLER.AI
hex: "#fcac45"
tags:
- 网页
- 声音
- AI
date: "2024/12"
description: 听懂歌的 AI,分析曲风情绪歌词等音乐的一切。
links: https://sonoteller.ai/
- title: Wappalyzer
hex: "#4608AD"
tags:
- 网页
- 开发
date: "2024/12"
description: 识别任意网页的技术栈。
links: https://www.wappalyzer.com/
- title: Neal.fun
hex: "#ffc7c7"
tags:
- 网页
- 有趣
date: "2024/12"
description: 希望你有美好的一天… 游戏互动可视化等其他奇怪的东西。
links:
- name: 官网
url: https://neal.fun/
- name: 设置密码?
url: https://neal.fun/password-game/
- name: 赞助
url: https://buymeacoffee.com/neal
- title: Wild West
hex: "#BBF7D0"
tags:
- 网页
- 有趣
- AI
date: "2024/12"
description: 由 AI 驱动的游戏,剪刀石头布。
links:
- name: 官网
url: https://www.wildwest.gg/
- name: 击败石头?
url: https://www.whatbeatsrock.com/
- title: UniGetUI
hex: "#707070"
tags:
- 桌面
- 开源
- 开发
date: "2024/12"
description: 图形化 Windows 全能包管理器。
links:
- name: 官网
url: https://www.marticliment.com/unigetui/
- name: GitHub
url: https://github.com/marticliment/UniGetUI
- name: 赞助
url: https://ko-fi.com/s/290486d079
- title: PowerToys
hex: "#666666"
tags:
- 桌面
- 开源
- 工具
date: "2024/12"
description: 一组实用工具,可帮助高级用户调整和简化其 Windows 体验,从而提高工作效率。
links:
- name: 官网
url: https://learn.microsoft.com/zh-cn/windows/powertoys/
- name: GitHub
url: https://github.com/microsoft/PowerToys
- name: 微软商店
url: https://apps.microsoft.com/detail/xp89dcgq3k6vld?hl=zh-cn&gl=CN
- title: LocalSend
hex: "#008080"
tags:
- 桌面
- 移动
- 开源
date: "2024/12"
description: 全平台 WIFI 分享文件。
links:
- name: 官网
url: https://localsend.org/zh-CN
- name: GitHub
url: https://github.com/localsend/localsend
- name: 赞助
url: https://github.com/sponsors/Tienisto
```
|
0000cd/wolf-set
| 2,449 |
content/achrive/legacy.md
|
---
author: 逊狼
title: Legacy
date: 2024-04-04
draft: false
---
```yaml
- title: Unsplash
hex: "#000000"
tags:
- 推荐
- 网页
- 图片
date: "2024/04"
description: 全球摄影师 300万 高清免费图片。
links:
- name: 官网
url: https://unsplash.com
- name: 背景
url: https://unsplash.com/backgrounds
- name: 壁纸
url: https://unsplash.com/wallpapers
- title: The Useless Web
hex: "#ff1493"
tags:
- 推荐
- 网页
- 有趣
date: "2024/04"
description: 随机打开网上有趣而无用的网站。
links: https://theuselessweb.com
- title: i Hate Regex
hex: "#e53e3e"
tags:
- 网页
- 开源
- 开发
date: "2024/04"
description: 帮助讨厌复杂正则表达式的人理解和使用它们,现在你有两个问题了。
links:
- name: 官网
url: https://ihateregex.io/
- name: GitHub
url: https://github.com/geongeorge/i-hate-regex
- name: 赞助
url: https://opencollective.com/ihateregex
- title: Msgif
hex: "#7880dd"
tags:
- 网页
- 动图
- 有趣
date: "2024/04"
description: 打字过程转换成动图,见字如面。
links: https://msgif.net/
- title: Marked.cc
hex: "#fecf28"
tags:
- 网页
- 图片
- 有趣
date: "2024/04"
description: 简单的制作一张便签图片。
links:
- name: 官网
url: https://marked.cc/
- name: GitHub
url: https://github.com/msjaber/marked.cc
- title: Exploding Topics
hex: "#2e5ce5"
tags:
- 网页
- 搜索
- 想法
date: "2024/04"
description: 寻找快速增长与有潜力的科技话题。
links: https://explodingtopics.com/
- title: 100font.com
hex: "#f7c601"
tags:
- 推荐
- 网页
- 字体
date: "2024/04"
description: 一个专门收集整理“免费商用字体”的网站,有大量中文字体。
links: https://www.100font.com
- title: Recompressor
hex: "#3755dc"
tags:
- 推荐
- 网页
- 工具
- 图片
date: "2024/04"
description: 智能压缩技术,优化图片质量与尺寸,多种图像工具。
links:
- name: 压缩
url: https://zh.recompressor.com/
- name: 修复
url: https://zh.pixfix.com/
- name: 检查
url: https://zh.pixspy.com/
- title: No More Ransom
hex: "#102a87"
tags:
- 网页
- 安全
date: "2024/04"
description: 提供数十种免费的解密工具,从勒索病毒中恢复数据。
links:
- name: 官网
url: https://www.nomoreransom.org/zh/index.html
- name: 知识
url: https://www.nomoreransom.org/zh/ransomware-qa.html
- name: 建议
url: https://www.nomoreransom.org/zh/prevention-advice-for-users.html
- title: IconKitchen
hex: "#6a3de8"
tags:
- 网页
- 图标
- 开发
date: "2024/04"
description: 轻松生成标准的全平台应用图标。
links: https://icon.kitchen
- title: Game-icons.net
hex: "#000000"
tags:
- 网页
- 图标
date: "2024/04"
description: 4千 CC 授权免费矢量游戏图标。
links: https://game-icons.net/
```
|
000haoji/deep-student
| 18,869 |
src/components/ReviewAnalysis.tsx
|
/**
* DEPRECATED COMPONENT - 已废弃的组件
*
* 废弃日期: 2024年6月5日
* 废弃原因: 单次回顾功能已被统一回顾模块替代,为简化用户体验而停用
* 替代方案: 请使用 ReviewAnalysisDashboard 和相关的统一回顾功能
*
* 注意: 此组件已从主界面隐藏,但保留代码以供将来可能的恢复需要
* 如需重新启用,请修改 App.tsx 中的相关注释
*/
import { useState, useEffect } from 'react';
import { TauriAPI, MistakeItem } from '../utils/tauriApi';
import { StreamingMarkdownRenderer } from '../chat-core';
interface ReviewSession {
id: string;
subject: string;
selectedMistakes: MistakeItem[];
analysis: string;
created_at: string;
chatHistory: ChatMessage[];
}
interface ChatMessage {
role: string;
content: string;
timestamp: string;
thinking_content?: string;
}
interface ReviewAnalysisProps {
onBack: () => void;
}
/**
* @deprecated 此组件已废弃 - 请使用统一回顾功能替代
*/
export const ReviewAnalysis: React.FC<ReviewAnalysisProps> = ({ onBack }) => {
const [selectedSubject, setSelectedSubject] = useState('');
const [selectedMistakes, setSelectedMistakes] = useState<MistakeItem[]>([]);
const [currentReview, setCurrentReview] = useState<ReviewSession | null>(null);
const [isAnalyzing, setIsAnalyzing] = useState(false);
const [chatHistory, setChatHistory] = useState<ChatMessage[]>([]);
const [currentMessage, setCurrentMessage] = useState('');
const [isChatting, setIsChatting] = useState(false);
const [subjectMistakes, setSubjectMistakes] = useState<MistakeItem[]>([]);
const [loading, setLoading] = useState(false);
const [availableSubjects, setAvailableSubjects] = useState<string[]>([]);
const [isLoadingSubjects, setIsLoadingSubjects] = useState(true);
// 流式处理相关状态
const [streamingMessageIndex, setStreamingMessageIndex] = useState<number | null>(null);
const [thinkingContent, setThinkingContent] = useState<Map<number, string>>(new Map());
// 获取当前科目的错题
const getSubjectMistakes = () => {
return subjectMistakes;
};
// 加载科目错题
const loadSubjectMistakes = async (subject: string) => {
setLoading(true);
try {
const mistakes = await TauriAPI.getMistakes({ subject });
setSubjectMistakes(mistakes);
} catch (error) {
console.error('加载错题失败:', error);
alert('加载错题失败: ' + error);
} finally {
setLoading(false);
}
};
// 加载支持的科目
useEffect(() => {
const loadSubjects = async () => {
try {
const subjects = await TauriAPI.getSupportedSubjects();
setAvailableSubjects(subjects);
// 设置默认科目为第一个
if (subjects.length > 0) {
setSelectedSubject(subjects[0]);
}
} catch (error) {
console.error('加载科目失败:', error);
// 如果API失败,使用备用科目列表
const fallbackSubjects = ['数学', '物理', '化学', '英语'];
setAvailableSubjects(fallbackSubjects);
setSelectedSubject(fallbackSubjects[0]);
} finally {
setIsLoadingSubjects(false);
}
};
loadSubjects();
}, []);
// 组件加载时和科目变化时加载错题
useEffect(() => {
if (selectedSubject) {
loadSubjectMistakes(selectedSubject);
}
}, [selectedSubject]);
// 切换错题选择
const toggleMistakeSelection = (mistake: MistakeItem) => {
setSelectedMistakes(prev => {
const isSelected = prev.some(m => m.id === mistake.id);
if (isSelected) {
return prev.filter(m => m.id !== mistake.id);
} else {
return [...prev, mistake];
}
});
};
// 全选/取消全选
const toggleSelectAll = () => {
const subjectMistakes = getSubjectMistakes();
if (selectedMistakes.length === subjectMistakes.length) {
setSelectedMistakes([]);
} else {
setSelectedMistakes(subjectMistakes);
}
};
// 开始回顾分析 - 流式版本
const startReviewAnalysis = async () => {
if (selectedMistakes.length === 0) {
alert('请至少选择一道错题进行分析');
return;
}
setIsAnalyzing(true);
setStreamingMessageIndex(null);
setChatHistory([]);
setThinkingContent(new Map());
try {
const mistakeIds = selectedMistakes.map(m => m.id);
console.log('🚀 开始流式回顾分析:', mistakeIds);
// 创建空的助手消息等待流式填充
const initialMessage: ChatMessage = {
role: 'assistant',
content: '',
timestamp: new Date().toISOString(),
};
setChatHistory([initialMessage]);
setStreamingMessageIndex(0);
// 设置流式事件监听
const streamEvent = 'review_analysis_stream';
let fullContent = '';
let fullThinkingContent = '';
let contentListenerActive = true;
let thinkingListenerActive = true;
// 使用Tauri的listen API
const { listen } = await import('@tauri-apps/api/event');
// 监听主内容流
const unlistenContent = await listen(streamEvent, (event: any) => {
if (!contentListenerActive) return;
console.log(`💬 收到回顾分析流式内容:`, event.payload);
if (event.payload) {
// 先检查是否完成
if (event.payload.is_complete) {
console.log('🎉 流式回顾分析完成,总长度:', fullContent.length);
contentListenerActive = false;
// 如果思维链监听器也不活跃了,则设置整体完成状态
if (!thinkingListenerActive) {
console.log('🎉 所有流式内容完成');
setStreamingMessageIndex(null);
}
return;
}
// 如果有内容,则累积
if (event.payload.content) {
fullContent += event.payload.content;
console.log(`📝 回顾分析累积内容长度: ${fullContent.length} 字符`);
// 更新聊天历史
setChatHistory(prev => {
const newHistory = [...prev];
if (newHistory[0]) {
newHistory[0] = {
...newHistory[0],
content: fullContent
};
}
return newHistory;
});
}
}
});
// 监听思维链事件(回顾分析通常需要深度思考)
const reasoningEvent = `${streamEvent}_reasoning`;
console.log(`🧠 监听回顾分析思维链事件: ${reasoningEvent}`);
const unlistenThinking = await listen(reasoningEvent, (event: any) => {
if (!thinkingListenerActive) return;
console.log(`🧠 回顾分析思维链内容:`, event.payload);
if (event.payload) {
// 先检查是否完成
if (event.payload.is_complete) {
console.log('🎉 回顾分析思维链完成,总长度:', fullThinkingContent.length);
thinkingListenerActive = false;
// 如果主内容监听器也不活跃了,则设置整体完成状态
if (!contentListenerActive) {
console.log('🎉 所有流式内容完成');
setStreamingMessageIndex(null);
}
return;
}
// 如果有内容,则累积
if (event.payload.content) {
fullThinkingContent += event.payload.content;
// 更新思维链内容
setThinkingContent(prev => {
const newMap = new Map(prev);
newMap.set(0, fullThinkingContent);
return newMap;
});
console.log(`🧠 回顾分析思维链累积长度: ${fullThinkingContent.length} 字符`);
}
}
});
// 调用后端流式回顾分析API
const response = await TauriAPI.analyzeReviewSessionStream(selectedSubject, mistakeIds);
// 创建回顾会话对象
const reviewSession: ReviewSession = {
id: response.review_id,
subject: selectedSubject,
selectedMistakes: [...selectedMistakes],
analysis: '', // 将通过流式更新
created_at: new Date().toISOString(),
chatHistory: []
};
setCurrentReview(reviewSession);
} catch (error) {
console.error('❌ 回顾分析失败:', error);
alert('回顾分析失败: ' + error);
setStreamingMessageIndex(null);
setChatHistory([]);
} finally {
setIsAnalyzing(false);
}
};
// 发送聊天消息 - 流式版本
const handleSendMessage = async () => {
if (!currentMessage.trim() || !currentReview) return;
const newUserMessage: ChatMessage = {
role: 'user',
content: currentMessage,
timestamp: new Date().toISOString(),
};
const updatedHistory = [...chatHistory, newUserMessage];
setChatHistory(updatedHistory);
setCurrentMessage('');
setIsChatting(true);
try {
console.log('💬 开始流式回顾分析追问...');
// 创建空的助手消息等待流式填充
const assistantMessage: ChatMessage = {
role: 'assistant',
content: '',
timestamp: new Date().toISOString(),
};
const streamingHistory = [...updatedHistory, assistantMessage];
setChatHistory(streamingHistory);
setStreamingMessageIndex(streamingHistory.length - 1);
// 设置流式事件监听
const streamEvent = `review_chat_stream_${currentReview.id}`;
let fullContent = '';
let fullThinkingContent = '';
let contentListenerActive = true;
let thinkingListenerActive = true;
// 使用Tauri的listen API
const { listen } = await import('@tauri-apps/api/event');
// 监听主内容流
const unlistenContent = await listen(streamEvent, (event: any) => {
if (!contentListenerActive) return;
console.log(`💬 收到回顾追问流式内容:`, event.payload);
if (event.payload) {
// 先检查是否完成
if (event.payload.is_complete) {
console.log('🎉 流式回顾追问完成,总长度:', fullContent.length);
contentListenerActive = false;
// 如果思维链监听器也不活跃了,则设置整体完成状态
if (!thinkingListenerActive) {
console.log('🎉 所有追问流式内容完成');
setStreamingMessageIndex(null);
}
return;
}
// 如果有内容,则累积
if (event.payload.content) {
fullContent += event.payload.content;
console.log(`📝 回顾追问累积内容长度: ${fullContent.length} 字符`);
// 更新聊天历史中的最后一条助手消息
setChatHistory(prev => {
const newHistory = [...prev];
const lastIndex = newHistory.length - 1;
if (newHistory[lastIndex] && newHistory[lastIndex].role === 'assistant') {
newHistory[lastIndex] = {
...newHistory[lastIndex],
content: fullContent
};
}
return newHistory;
});
}
}
});
// 监听思维链事件
const reasoningEvent = `${streamEvent}_reasoning`;
console.log(`🧠 监听回顾追问思维链事件: ${reasoningEvent}`);
const unlistenThinking = await listen(reasoningEvent, (event: any) => {
if (!thinkingListenerActive) return;
console.log(`🧠 回顾追问思维链内容:`, event.payload);
if (event.payload) {
// 先检查是否完成
if (event.payload.is_complete) {
console.log('🎉 回顾追问思维链完成,总长度:', fullThinkingContent.length);
thinkingListenerActive = false;
// 如果主内容监听器也不活跃了,则设置整体完成状态
if (!contentListenerActive) {
console.log('🎉 所有追问流式内容完成');
setStreamingMessageIndex(null);
}
return;
}
// 如果有内容,则累积
if (event.payload.content) {
fullThinkingContent += event.payload.content;
// 更新思维链内容(使用最后一条消息的索引)
const lastMessageIndex = streamingHistory.length - 1;
setThinkingContent(prev => {
const newMap = new Map(prev);
newMap.set(lastMessageIndex, fullThinkingContent);
return newMap;
});
console.log(`🧠 回顾追问思维链累积长度: ${fullThinkingContent.length} 字符`);
}
}
});
// 调用后端流式追问API
await TauriAPI.continueReviewChatStream(currentReview.id, updatedHistory);
} catch (error) {
console.error('❌ 回顾追问失败:', error);
alert('聊天失败: ' + error);
setStreamingMessageIndex(null);
} finally {
setIsChatting(false);
}
};
// 重新开始分析
const resetAnalysis = () => {
setCurrentReview(null);
setChatHistory([]);
setSelectedMistakes([]);
setStreamingMessageIndex(null);
setThinkingContent(new Map());
};
return (
<div className="review-analysis">
<div className="review-header">
<button onClick={onBack} className="back-button">
← 返回
</button>
<h2>回顾分析</h2>
{currentReview && (
<button onClick={resetAnalysis} className="reset-button">
🔄 重新分析
</button>
)}
</div>
{!currentReview ? (
// 选择错题界面
<div className="mistake-selection">
<div className="selection-controls">
<div className="subject-selector">
<label>选择科目:</label>
<select
value={selectedSubject}
onChange={(e) => {
setSelectedSubject(e.target.value);
setSelectedMistakes([]);
}}
disabled={isLoadingSubjects}
>
{isLoadingSubjects ? (
<option value="">加载中...</option>
) : (
availableSubjects.map(subject => (
<option key={subject} value={subject}>{subject}</option>
))
)}
</select>
</div>
<div className="selection-info">
<span>已选择 {selectedMistakes.length} / {getSubjectMistakes().length} 道题目</span>
<button onClick={toggleSelectAll} className="select-all-button">
{selectedMistakes.length === getSubjectMistakes().length ? '取消全选' : '全选'}
</button>
</div>
</div>
{loading ? (
<div className="loading">加载错题中...</div>
) : (
<div className="mistakes-grid">
{getSubjectMistakes().map((mistake) => (
<div
key={mistake.id}
className={`mistake-card ${selectedMistakes.some(m => m.id === mistake.id) ? 'selected' : ''}`}
onClick={() => toggleMistakeSelection(mistake)}
>
<div className="mistake-header">
<input
type="checkbox"
checked={selectedMistakes.some(m => m.id === mistake.id)}
onChange={() => toggleMistakeSelection(mistake)}
onClick={(e) => e.stopPropagation()}
/>
<span className="mistake-type">{mistake.mistake_type}</span>
<span className="mistake-date">
{new Date(mistake.created_at).toLocaleDateString('zh-CN')}
</span>
</div>
<div className="mistake-content">
<h4>{mistake.user_question}</h4>
<p className="ocr-preview">{mistake.ocr_text}</p>
<div className="tags">
{mistake.tags.map((tag, index) => (
<span key={index} className="tag">{tag}</span>
))}
</div>
</div>
</div>
))}
</div>
)}
{!loading && getSubjectMistakes().length === 0 && (
<div className="empty-mistakes">
<p>当前科目还没有错题记录</p>
<p>请先在分析页面添加一些错题</p>
</div>
)}
<div className="analysis-controls">
<div style={{ padding: '0.5rem', backgroundColor: '#f0f8ff', borderRadius: '4px', fontSize: '0.9rem', color: '#666', marginBottom: '1rem' }}>
ℹ️ 回顾分析将使用流式输出和思维链,为您提供深度分析
</div>
<button
onClick={startReviewAnalysis}
disabled={selectedMistakes.length === 0 || isAnalyzing}
className="start-analysis-button"
>
{isAnalyzing ? '分析中...' : `开始分析 (${selectedMistakes.length}道题目)`}
</button>
</div>
</div>
) : (
// 分析结果界面
<div className="analysis-result">
<div className="result-header">
<h3>分析结果 - {currentReview.subject}</h3>
<div className="result-info">
<span>分析题目: {currentReview.selectedMistakes.length} 道</span>
<span>分析时间: {new Date(currentReview.created_at).toLocaleString('zh-CN')}</span>
<span className="stream-indicator">🌊 流式输出 🧠 思维链</span>
</div>
</div>
<div className="chat-container">
<div className="chat-history">
{chatHistory.map((message, index) => {
const isStreaming = streamingMessageIndex === index;
const thinking = thinkingContent.get(index);
return (
<div key={index} className={`message ${message.role}`}>
<div className="message-content">
<StreamingMarkdownRenderer
content={message.content}
isStreaming={isStreaming}
chainOfThought={{
enabled: !!thinking,
details: thinking || ''
}}
/>
</div>
<div className="message-time">
{new Date(message.timestamp).toLocaleTimeString()}
</div>
</div>
);
})}
{(isAnalyzing || isChatting) && streamingMessageIndex === null && (
<div className="message assistant">
<div className="message-content typing">
<span className="typing-indicator">
<span></span>
<span></span>
<span></span>
</span>
{isAnalyzing ? 'AI正在深度分析多道错题...' : '正在思考中...'}
</div>
</div>
)}
</div>
{/* 只有在分析完成后才显示输入框 */}
{!isAnalyzing && currentReview && (
<div className="chat-input">
<input
type="text"
value={currentMessage}
onChange={(e) => setCurrentMessage(e.target.value)}
placeholder="对分析结果有疑问?继续提问..."
onKeyDown={(e) => e.key === 'Enter' && handleSendMessage()}
disabled={isChatting}
/>
<button
onClick={handleSendMessage}
disabled={isChatting || !currentMessage.trim()}
className="send-button"
>
{isChatting ? '⏳' : '📤'}
</button>
</div>
)}
</div>
</div>
)}
</div>
);
};
|
0015/StickiNote
| 82,172 |
sdkconfig.esp32-p4-nano
|
#
# Automatically generated file. DO NOT EDIT.
# Espressif IoT Development Framework (ESP-IDF) 5.4.0 Project Configuration
#
CONFIG_SOC_ADC_SUPPORTED=y
CONFIG_SOC_ANA_CMPR_SUPPORTED=y
CONFIG_SOC_DEDICATED_GPIO_SUPPORTED=y
CONFIG_SOC_UART_SUPPORTED=y
CONFIG_SOC_GDMA_SUPPORTED=y
CONFIG_SOC_AHB_GDMA_SUPPORTED=y
CONFIG_SOC_AXI_GDMA_SUPPORTED=y
CONFIG_SOC_DW_GDMA_SUPPORTED=y
CONFIG_SOC_DMA2D_SUPPORTED=y
CONFIG_SOC_GPTIMER_SUPPORTED=y
CONFIG_SOC_PCNT_SUPPORTED=y
CONFIG_SOC_LCDCAM_SUPPORTED=y
CONFIG_SOC_LCDCAM_CAM_SUPPORTED=y
CONFIG_SOC_LCDCAM_I80_LCD_SUPPORTED=y
CONFIG_SOC_LCDCAM_RGB_LCD_SUPPORTED=y
CONFIG_SOC_MIPI_CSI_SUPPORTED=y
CONFIG_SOC_MIPI_DSI_SUPPORTED=y
CONFIG_SOC_MCPWM_SUPPORTED=y
CONFIG_SOC_TWAI_SUPPORTED=y
CONFIG_SOC_ETM_SUPPORTED=y
CONFIG_SOC_PARLIO_SUPPORTED=y
CONFIG_SOC_ASYNC_MEMCPY_SUPPORTED=y
CONFIG_SOC_EMAC_SUPPORTED=y
CONFIG_SOC_USB_OTG_SUPPORTED=y
CONFIG_SOC_WIRELESS_HOST_SUPPORTED=y
CONFIG_SOC_USB_SERIAL_JTAG_SUPPORTED=y
CONFIG_SOC_TEMP_SENSOR_SUPPORTED=y
CONFIG_SOC_SUPPORTS_SECURE_DL_MODE=y
CONFIG_SOC_ULP_SUPPORTED=y
CONFIG_SOC_LP_CORE_SUPPORTED=y
CONFIG_SOC_EFUSE_KEY_PURPOSE_FIELD=y
CONFIG_SOC_EFUSE_SUPPORTED=y
CONFIG_SOC_RTC_FAST_MEM_SUPPORTED=y
CONFIG_SOC_RTC_MEM_SUPPORTED=y
CONFIG_SOC_RMT_SUPPORTED=y
CONFIG_SOC_I2S_SUPPORTED=y
CONFIG_SOC_SDM_SUPPORTED=y
CONFIG_SOC_GPSPI_SUPPORTED=y
CONFIG_SOC_LEDC_SUPPORTED=y
CONFIG_SOC_ISP_SUPPORTED=y
CONFIG_SOC_I2C_SUPPORTED=y
CONFIG_SOC_SYSTIMER_SUPPORTED=y
CONFIG_SOC_AES_SUPPORTED=y
CONFIG_SOC_MPI_SUPPORTED=y
CONFIG_SOC_SHA_SUPPORTED=y
CONFIG_SOC_HMAC_SUPPORTED=y
CONFIG_SOC_DIG_SIGN_SUPPORTED=y
CONFIG_SOC_ECC_SUPPORTED=y
CONFIG_SOC_ECC_EXTENDED_MODES_SUPPORTED=y
CONFIG_SOC_FLASH_ENC_SUPPORTED=y
CONFIG_SOC_SECURE_BOOT_SUPPORTED=y
CONFIG_SOC_BOD_SUPPORTED=y
CONFIG_SOC_APM_SUPPORTED=y
CONFIG_SOC_PMU_SUPPORTED=y
CONFIG_SOC_DCDC_SUPPORTED=y
CONFIG_SOC_PAU_SUPPORTED=y
CONFIG_SOC_LP_TIMER_SUPPORTED=y
CONFIG_SOC_ULP_LP_UART_SUPPORTED=y
CONFIG_SOC_LP_GPIO_MATRIX_SUPPORTED=y
CONFIG_SOC_LP_PERIPHERALS_SUPPORTED=y
CONFIG_SOC_LP_I2C_SUPPORTED=y
CONFIG_SOC_LP_I2S_SUPPORTED=y
CONFIG_SOC_LP_SPI_SUPPORTED=y
CONFIG_SOC_LP_ADC_SUPPORTED=y
CONFIG_SOC_LP_VAD_SUPPORTED=y
CONFIG_SOC_SPIRAM_SUPPORTED=y
CONFIG_SOC_PSRAM_DMA_CAPABLE=y
CONFIG_SOC_SDMMC_HOST_SUPPORTED=y
CONFIG_SOC_CLK_TREE_SUPPORTED=y
CONFIG_SOC_ASSIST_DEBUG_SUPPORTED=y
CONFIG_SOC_DEBUG_PROBE_SUPPORTED=y
CONFIG_SOC_WDT_SUPPORTED=y
CONFIG_SOC_SPI_FLASH_SUPPORTED=y
CONFIG_SOC_TOUCH_SENSOR_SUPPORTED=y
CONFIG_SOC_RNG_SUPPORTED=y
CONFIG_SOC_GP_LDO_SUPPORTED=y
CONFIG_SOC_PPA_SUPPORTED=y
CONFIG_SOC_LIGHT_SLEEP_SUPPORTED=y
CONFIG_SOC_DEEP_SLEEP_SUPPORTED=y
CONFIG_SOC_PM_SUPPORTED=y
CONFIG_SOC_XTAL_SUPPORT_40M=y
CONFIG_SOC_AES_SUPPORT_DMA=y
CONFIG_SOC_AES_SUPPORT_GCM=y
CONFIG_SOC_AES_GDMA=y
CONFIG_SOC_AES_SUPPORT_AES_128=y
CONFIG_SOC_AES_SUPPORT_AES_256=y
CONFIG_SOC_ADC_RTC_CTRL_SUPPORTED=y
CONFIG_SOC_ADC_DIG_CTRL_SUPPORTED=y
CONFIG_SOC_ADC_DMA_SUPPORTED=y
CONFIG_SOC_ADC_PERIPH_NUM=2
CONFIG_SOC_ADC_MAX_CHANNEL_NUM=8
CONFIG_SOC_ADC_ATTEN_NUM=4
CONFIG_SOC_ADC_DIGI_CONTROLLER_NUM=2
CONFIG_SOC_ADC_PATT_LEN_MAX=16
CONFIG_SOC_ADC_DIGI_MAX_BITWIDTH=12
CONFIG_SOC_ADC_DIGI_MIN_BITWIDTH=12
CONFIG_SOC_ADC_DIGI_IIR_FILTER_NUM=2
CONFIG_SOC_ADC_DIGI_MONITOR_NUM=2
CONFIG_SOC_ADC_DIGI_RESULT_BYTES=4
CONFIG_SOC_ADC_DIGI_DATA_BYTES_PER_CONV=4
CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_HIGH=83333
CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_LOW=611
CONFIG_SOC_ADC_RTC_MIN_BITWIDTH=12
CONFIG_SOC_ADC_RTC_MAX_BITWIDTH=12
CONFIG_SOC_ADC_SHARED_POWER=y
CONFIG_SOC_BROWNOUT_RESET_SUPPORTED=y
CONFIG_SOC_SHARED_IDCACHE_SUPPORTED=y
CONFIG_SOC_CACHE_WRITEBACK_SUPPORTED=y
CONFIG_SOC_CACHE_FREEZE_SUPPORTED=y
CONFIG_SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE=y
CONFIG_SOC_CPU_CORES_NUM=2
CONFIG_SOC_CPU_INTR_NUM=32
CONFIG_SOC_CPU_HAS_FLEXIBLE_INTC=y
CONFIG_SOC_INT_CLIC_SUPPORTED=y
CONFIG_SOC_INT_HW_NESTED_SUPPORTED=y
CONFIG_SOC_BRANCH_PREDICTOR_SUPPORTED=y
CONFIG_SOC_CPU_COPROC_NUM=3
CONFIG_SOC_CPU_HAS_FPU=y
CONFIG_SOC_CPU_HAS_FPU_EXT_ILL_BUG=y
CONFIG_SOC_CPU_HAS_HWLOOP=y
CONFIG_SOC_CPU_HAS_PIE=y
CONFIG_SOC_HP_CPU_HAS_MULTIPLE_CORES=y
CONFIG_SOC_CPU_BREAKPOINTS_NUM=3
CONFIG_SOC_CPU_WATCHPOINTS_NUM=3
CONFIG_SOC_CPU_WATCHPOINT_MAX_REGION_SIZE=0x100
CONFIG_SOC_CPU_HAS_PMA=y
CONFIG_SOC_CPU_IDRAM_SPLIT_USING_PMP=y
CONFIG_SOC_CPU_PMP_REGION_GRANULARITY=128
CONFIG_SOC_CPU_HAS_LOCKUP_RESET=y
CONFIG_SOC_DS_SIGNATURE_MAX_BIT_LEN=4096
CONFIG_SOC_DS_KEY_PARAM_MD_IV_LENGTH=16
CONFIG_SOC_DS_KEY_CHECK_MAX_WAIT_US=1100
CONFIG_SOC_DMA_CAN_ACCESS_FLASH=y
CONFIG_SOC_AHB_GDMA_VERSION=2
CONFIG_SOC_GDMA_SUPPORT_CRC=y
CONFIG_SOC_GDMA_NUM_GROUPS_MAX=2
CONFIG_SOC_GDMA_PAIRS_PER_GROUP_MAX=3
CONFIG_SOC_AXI_GDMA_SUPPORT_PSRAM=y
CONFIG_SOC_GDMA_SUPPORT_ETM=y
CONFIG_SOC_GDMA_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_AXI_DMA_EXT_MEM_ENC_ALIGNMENT=16
CONFIG_SOC_DMA2D_GROUPS=1
CONFIG_SOC_DMA2D_TX_CHANNELS_PER_GROUP=3
CONFIG_SOC_DMA2D_RX_CHANNELS_PER_GROUP=2
CONFIG_SOC_ETM_GROUPS=1
CONFIG_SOC_ETM_CHANNELS_PER_GROUP=50
CONFIG_SOC_ETM_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_GPIO_PORT=1
CONFIG_SOC_GPIO_PIN_COUNT=55
CONFIG_SOC_GPIO_SUPPORT_PIN_GLITCH_FILTER=y
CONFIG_SOC_GPIO_FLEX_GLITCH_FILTER_NUM=8
CONFIG_SOC_GPIO_SUPPORT_PIN_HYS_FILTER=y
CONFIG_SOC_GPIO_SUPPORT_ETM=y
CONFIG_SOC_GPIO_SUPPORT_RTC_INDEPENDENT=y
CONFIG_SOC_GPIO_S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C_ISP_HIST_SEGMENT_NUMS=16
CONFIG_SOC_ISP_HIST_INTERVAL_NUMS=15
CONFIG_SOC_ISP_LSC_GRAD_RATIO_INT_BITS=2
CONFIG_SOC_ISP_LSC_GRAD_RATIO_DEC_BITS=8
CONFIG_SOC_ISP_LSC_GRAD_RATIO_RES_BITS=22
CONFIG_SOC_LEDC_SUPPORT_PLL_DIV_CLOCK=y
CONFIG_SOC_LEDC_SUPPORT_XTAL_CLOCK=y
CONFIG_SOC_LEDC_TIMER_NUM=4
CONFIG_SOC_LEDC_CHANNEL_NUM=8
CONFIG_SOC_LEDC_TIMER_BIT_WIDTH=20
CONFIG_SOC_LEDC_GAMMA_CURVE_FADE_SUPPORTED=y
CONFIG_SOC_LEDC_GAMMA_CURVE_FADE_RANGE_MAX=16
CONFIG_SOC_LEDC_SUPPORT_FADE_STOP=y
CONFIG_SOC_LEDC_FADE_PARAMS_BIT_WIDTH=10
CONFIG_SOC_LEDC_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_MMU_PERIPH_NUM=2
CONFIG_SOC_MMU_LINEAR_ADDRESS_REGION_NUM=2
CONFIG_SOC_MMU_DI_VADDR_SHARED=y
CONFIG_SOC_MMU_PER_EXT_MEM_TARGET=y
CONFIG_SOC_MPU_MIN_REGION_SIZE=0x20000000
CONFIG_SOC_MPU_REGIONS_MAX_NUM=8
CONFIG_SOC_PCNT_GROUPS=1
CONFIG_SOC_PCNT_UNITS_PER_GROUP=4
CONFIG_SOC_PCNT_CHANNELS_PER_UNIT=2
CONFIG_SOC_PCNT_THRES_POINT_PER_UNIT=2
CONFIG_SOC_PCNT_SUPPORT_RUNTIME_THRES_UPDATE=y
CONFIG_SOC_PCNT_SUPPORT_CLEAR_SIGNAL=y
CONFIG_SOC_RMT_GROUPS=1
CONFIG_SOC_RMT_TX_CANDIDATES_PER_GROUP=4
CONFIG_SOC_RMT_RX_CANDIDATES_PER_GROUP=4
CONFIG_SOC_RMT_CHANNELS_PER_GROUP=8
CONFIG_SOC_RMT_MEM_WORDS_PER_CHANNEL=48
CONFIG_SOC_RMT_SUPPORT_RX_PINGPONG=y
CONFIG_SOC_RMT_SUPPORT_RX_DEMODULATION=y
CONFIG_SOC_RMT_SUPPORT_TX_ASYNC_STOP=y
CONFIG_SOC_RMT_SUPPORT_TX_LOOP_COUNT=y
CONFIG_SOC_RMT_SUPPORT_TX_LOOP_AUTO_STOP=y
CONFIG_SOC_RMT_SUPPORT_TX_SYNCHRO=y
CONFIG_SOC_RMT_SUPPORT_TX_CARRIER_DATA_ONLY=y
CONFIG_SOC_RMT_SUPPORT_XTAL=y
CONFIG_SOC_RMT_SUPPORT_RC_FAST=y
CONFIG_SOC_RMT_SUPPORT_DMA=y
CONFIG_SOC_RMT_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_LCD_I80_SUPPORTED=y
CONFIG_SOC_LCD_RGB_SUPPORTED=y
CONFIG_SOC_LCDCAM_I80_NUM_BUSES=1
CONFIG_SOC_LCDCAM_I80_BUS_WIDTH=24
CONFIG_SOC_LCDCAM_RGB_NUM_PANELS=1
CONFIG_SOC_LCDCAM_RGB_DATA_WIDTH=24
CONFIG_SOC_LCD_SUPPORT_RGB_YUV_CONV=y
CONFIG_SOC_MCPWM_GROUPS=2
CONFIG_SOC_MCPWM_TIMERS_PER_GROUP=3
CONFIG_SOC_MCPWM_OPERATORS_PER_GROUP=3
CONFIG_SOC_MCPWM_COMPARATORS_PER_OPERATOR=2
CONFIG_SOC_MCPWM_EVENT_COMPARATORS_PER_OPERATOR=2
CONFIG_SOC_MCPWM_GENERATORS_PER_OPERATOR=2
CONFIG_SOC_MCPWM_TRIGGERS_PER_OPERATOR=2
CONFIG_SOC_MCPWM_GPIO_FAULTS_PER_GROUP=3
CONFIG_SOC_MCPWM_CAPTURE_TIMERS_PER_GROUP=y
CONFIG_SOC_MCPWM_CAPTURE_CHANNELS_PER_TIMER=3
CONFIG_SOC_MCPWM_GPIO_SYNCHROS_PER_GROUP=3
CONFIG_SOC_MCPWM_SWSYNC_CAN_PROPAGATE=y
CONFIG_SOC_MCPWM_SUPPORT_ETM=y
CONFIG_SOC_MCPWM_SUPPORT_EVENT_COMPARATOR=y
CONFIG_SOC_MCPWM_CAPTURE_CLK_FROM_GROUP=y
CONFIG_SOC_USB_OTG_PERIPH_NUM=2
CONFIG_SOC_USB_UTMI_PHY_NUM=1
CONFIG_SOC_PARLIO_GROUPS=1
CONFIG_SOC_PARLIO_TX_UNITS_PER_GROUP=1
CONFIG_SOC_PARLIO_RX_UNITS_PER_GROUP=1
CONFIG_SOC_PARLIO_TX_UNIT_MAX_DATA_WIDTH=16
CONFIG_SOC_PARLIO_RX_UNIT_MAX_DATA_WIDTH=16
CONFIG_SOC_PARLIO_TX_CLK_SUPPORT_GATING=y
CONFIG_SOC_PARLIO_RX_CLK_SUPPORT_GATING=y
CONFIG_SOC_PARLIO_RX_CLK_SUPPORT_OUTPUT=y
CONFIG_SOC_PARLIO_TRANS_BIT_ALIGN=y
CONFIG_SOC_PARLIO_TX_SIZE_BY_DMA=y
CONFIG_SOC_PARLIO_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_MPI_MEM_BLOCKS_NUM=4
CONFIG_SOC_MPI_OPERATIONS_NUM=3
CONFIG_SOC_RSA_MAX_BIT_LEN=4096
CONFIG_SOC_SDMMC_USE_IOMUX=y
CONFIG_SOC_SDMMC_USE_GPIO_MATRIX=y
CONFIG_SOC_SDMMC_NUM_SLOTS=2
CONFIG_SOC_SDMMC_DELAY_PHASE_NUM=4
CONFIG_SOC_SDMMC_IO_POWER_EXTERNAL=y
CONFIG_SOC_SDMMC_PSRAM_DMA_CAPABLE=y
CONFIG_SOC_SDMMC_UHS_I_SUPPORTED=y
CONFIG_SOC_SHA_DMA_MAX_BUFFER_SIZE=3968
CONFIG_SOC_SHA_SUPPORT_DMA=y
CONFIG_SOC_SHA_SUPPORT_RESUME=y
CONFIG_SOC_SHA_GDMA=y
CONFIG_SOC_SHA_SUPPORT_SHA1=y
CONFIG_SOC_SHA_SUPPORT_SHA224=y
CONFIG_SOC_SHA_SUPPORT_SHA256=y
CONFIG_SOC_SHA_SUPPORT_SHA384=y
CONFIG_SOC_SHA_SUPPORT_SHA512=y
CONFIG_SOC_SHA_SUPPORT_SHA512_224=y
CONFIG_SOC_SHA_SUPPORT_SHA512_256=y
CONFIG_SOC_SHA_SUPPORT_SHA512_T=y
CONFIG_SOC_ECDSA_SUPPORT_EXPORT_PUBKEY=y
CONFIG_SOC_ECDSA_SUPPORT_DETERMINISTIC_MODE=y
CONFIG_SOC_ECDSA_USES_MPI=y
CONFIG_SOC_SDM_GROUPS=1
CONFIG_SOC_SDM_CHANNELS_PER_GROUP=8
CONFIG_SOC_SDM_CLK_SUPPORT_PLL_F80M=y
CONFIG_SOC_SDM_CLK_SUPPORT_XTAL=y
CONFIG_SOC_SPI_PERIPH_NUM=3
CONFIG_SOC_SPI_MAX_CS_NUM=6
CONFIG_SOC_SPI_MAXIMUM_BUFFER_SIZE=64
CONFIG_SOC_SPI_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_SPI_SUPPORT_SLAVE_HD_VER2=y
CONFIG_SOC_SPI_SLAVE_SUPPORT_SEG_TRANS=y
CONFIG_SOC_SPI_SUPPORT_DDRCLK=y
CONFIG_SOC_SPI_SUPPORT_CD_SIG=y
CONFIG_SOC_SPI_SUPPORT_OCT=y
CONFIG_SOC_SPI_SUPPORT_CLK_XTAL=y
CONFIG_SOC_SPI_SUPPORT_CLK_RC_FAST=y
CONFIG_SOC_SPI_SUPPORT_CLK_SPLL=y
CONFIG_SOC_MEMSPI_IS_INDEPENDENT=y
CONFIG_SOC_SPI_MAX_PRE_DIVIDER=16
CONFIG_SOC_LP_SPI_PERIPH_NUM=y
CONFIG_SOC_LP_SPI_MAXIMUM_BUFFER_SIZE=64
CONFIG_SOC_SPIRAM_XIP_SUPPORTED=y
CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_WAIT_IDLE=y
CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_SUSPEND=y
CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_RESUME=y
CONFIG_SOC_SPI_MEM_SUPPORT_IDLE_INTR=y
CONFIG_SOC_SPI_MEM_SUPPORT_SW_SUSPEND=y
CONFIG_SOC_SPI_MEM_SUPPORT_CHECK_SUS=y
CONFIG_SOC_SPI_MEM_SUPPORT_TIMING_TUNING=y
CONFIG_SOC_MEMSPI_TIMING_TUNING_BY_DQS=y
CONFIG_SOC_SPI_MEM_SUPPORT_CACHE_32BIT_ADDR_MAP=y
CONFIG_SOC_SPI_PERIPH_SUPPORT_CONTROL_DUMMY_OUT=y
CONFIG_SOC_MEMSPI_SRC_FREQ_80M_SUPPORTED=y
CONFIG_SOC_MEMSPI_SRC_FREQ_40M_SUPPORTED=y
CONFIG_SOC_MEMSPI_SRC_FREQ_20M_SUPPORTED=y
CONFIG_SOC_MEMSPI_FLASH_PSRAM_INDEPENDENT=y
CONFIG_SOC_SYSTIMER_COUNTER_NUM=2
CONFIG_SOC_SYSTIMER_ALARM_NUM=3
CONFIG_SOC_SYSTIMER_BIT_WIDTH_LO=32
CONFIG_SOC_SYSTIMER_BIT_WIDTH_HI=20
CONFIG_SOC_SYSTIMER_FIXED_DIVIDER=y
CONFIG_SOC_SYSTIMER_SUPPORT_RC_FAST=y
CONFIG_SOC_SYSTIMER_INT_LEVEL=y
CONFIG_SOC_SYSTIMER_ALARM_MISS_COMPENSATE=y
CONFIG_SOC_SYSTIMER_SUPPORT_ETM=y
CONFIG_SOC_LP_TIMER_BIT_WIDTH_LO=32
CONFIG_SOC_LP_TIMER_BIT_WIDTH_HI=16
CONFIG_SOC_TIMER_GROUPS=2
CONFIG_SOC_TIMER_GROUP_TIMERS_PER_GROUP=2
CONFIG_SOC_TIMER_GROUP_COUNTER_BIT_WIDTH=54
CONFIG_SOC_TIMER_GROUP_SUPPORT_XTAL=y
CONFIG_SOC_TIMER_GROUP_SUPPORT_RC_FAST=y
CONFIG_SOC_TIMER_G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OT_KEY_DIGESTS=y
CONFIG_SOC_SUPPORT_SECURE_BOOT_REVOKE_KEY=y
CONFIG_SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX=64
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES=y
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_OPTIONS=y
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_128=y
CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_256=y
CONFIG_SOC_UART_NUM=6
CONFIG_SOC_UART_HP_NUM=5
CONFIG_SOC_UART_LP_NUM=1
CONFIG_SOC_UART_FIFO_LEN=128
CONFIG_SOC_LP_UART_FIFO_LEN=16
CONFIG_SOC_UART_BITRATE_MAX=5000000
CONFIG_SOC_UART_SUPPORT_PLL_F80M_CLK=y
CONFIG_SOC_UART_SUPPORT_RTC_CLK=y
CONFIG_SOC_UART_SUPPORT_XTAL_CLK=y
CONFIG_SOC_UART_SUPPORT_WAKEUP_INT=y
CONFIG_SOC_UART_HAS_LP_UART=y
CONFIG_SOC_UART_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_UART_SUPPORT_FSM_TX_WAIT_SEND=y
CONFIG_SOC_LP_I2S_SUPPORT_VAD=y
CONFIG_SOC_COEX_HW_PTI=y
CONFIG_SOC_PHY_DIG_REGS_MEM_SIZE=21
CONFIG_SOC_WIFI_LIGHT_SLEEP_CLK_WIDTH=12
CONFIG_SOC_PM_SUPPORT_EXT1_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_EXT1_WAKEUP_MODE_PER_PIN=y
CONFIG_SOC_PM_EXT1_WAKEUP_BY_PMU=y
CONFIG_SOC_PM_SUPPORT_WIFI_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP=y
CONFIG_SOC_PM_SUPPORT_XTAL32K_PD=y
CONFIG_SOC_PM_SUPPORT_RC32K_PD=y
CONFIG_SOC_PM_SUPPORT_RC_FAST_PD=y
CONFIG_SOC_PM_SUPPORT_VDDSDIO_PD=y
CONFIG_SOC_PM_SUPPORT_TOP_PD=y
CONFIG_SOC_PM_SUPPORT_CNNT_PD=y
CONFIG_SOC_PM_SUPPORT_RTC_PERIPH_PD=y
CONFIG_SOC_PM_SUPPORT_DEEPSLEEP_CHECK_STUB_ONLY=y
CONFIG_SOC_PM_CPU_RETENTION_BY_SW=y
CONFIG_SOC_PM_PAU_LINK_NUM=4
CONFIG_SOC_PM_PAU_REGDMA_LINK_MULTI_ADDR=y
CONFIG_SOC_PAU_IN_TOP_DOMAIN=y
CONFIG_SOC_CPU_IN_TOP_DOMAIN=y
CONFIG_SOC_PM_PAU_REGDMA_UPDATE_CACHE_BEFORE_WAIT_COMPARE=y
CONFIG_SOC_SLEEP_SYSTIMER_STALL_WORKAROUND=y
CONFIG_SOC_SLEEP_TGWDT_STOP_WORKAROUND=y
CONFIG_SOC_PM_RETENTION_MODULE_NUM=64
CONFIG_SOC_PSRAM_VDD_POWER_MPLL=y
CONFIG_SOC_CLK_RC_FAST_SUPPORT_CALIBRATION=y
CONFIG_SOC_CLK_APLL_SUPPORTED=y
CONFIG_SOC_CLK_MPLL_SUPPORTED=y
CONFIG_SOC_CLK_SDIO_PLL_SUPPORTED=y
CONFIG_SOC_CLK_XTAL32K_SUPPORTED=y
CONFIG_SOC_CLK_RC32K_SUPPORTED=y
CONFIG_SOC_CLK_LP_FAST_SUPPORT_LP_PLL=y
CONFIG_SOC_CLK_LP_FAST_SUPPORT_XTAL=y
CONFIG_SOC_PERIPH_CLK_CTRL_SHARED=y
CONFIG_SOC_TEMPERATURE_SENSOR_LP_PLL_SUPPORT=y
CONFIG_SOC_TEMPERATURE_SENSOR_INTR_SUPPORT=y
CONFIG_SOC_TSENS_IS_INDEPENDENT_FROM_ADC=y
CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_ETM=y
CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_SLEEP_RETENTION=y
CONFIG_SOC_MEM_TCM_SUPPORTED=y
CONFIG_SOC_MEM_NON_CONTIGUOUS_SRAM=y
CONFIG_SOC_ASYNCHRONOUS_BUS_ERROR_MODE=y
CONFIG_SOC_EMAC_IEEE_1588_SUPPORT=y
CONFIG_SOC_EMAC_USE_MULTI_IO_MUX=y
CONFIG_SOC_EMAC_MII_USE_GPIO_MATRIX=y
CONFIG_SOC_JPEG_CODEC_SUPPORTED=y
CONFIG_SOC_JPEG_DECODE_SUPPORTED=y
CONFIG_SOC_JPEG_ENCODE_SUPPORTED=y
CONFIG_SOC_LCDCAM_CAM_SUPPORT_RGB_YUV_CONV=y
CONFIG_SOC_LCDCAM_CAM_PERIPH_NUM=1
CONFIG_SOC_LCDCAM_CAM_DATA_WIDTH_MAX=16
CONFIG_SOC_LP_CORE_SUPPORT_ETM=y
CONFIG_SOC_LP_CORE_SUPPORT_LP_ADC=y
CONFIG_SOC_LP_CORE_SUPPORT_LP_VAD=y
CONFIG_IDF_CMAKE=y
CONFIG_IDF_TOOLCHAIN="gcc"
CONFIG_IDF_TOOLCHAIN_GCC=y
CONFIG_IDF_TARGET_ARCH_RISCV=y
CONFIG_IDF_TARGET_ARCH="riscv"
CONFIG_IDF_TARGET="esp32p4"
CONFIG_IDF_INIT_VERSION="5.4.0"
CONFIG_IDF_TARGET_ESP32P4=y
CONFIG_IDF_FIRMWARE_CHIP_ID=0x0012
#
# Build type
#
CONFIG_APP_BUILD_TYPE_APP_2NDBOOT=y
# CONFIG_APP_BUILD_TYPE_RAM is not set
CONFIG_APP_BUILD_GENERATE_BINARIES=y
CONFIG_APP_BUILD_BOOTLOADER=y
CONFIG_APP_BUILD_USE_FLASH_SECTIONS=y
# CONFIG_APP_REPRODUCIBLE_BUILD is not set
# CONFIG_APP_NO_BLOBS is not set
# end of Build type
#
# Bootloader config
#
#
# Bootloader manager
#
CONFIG_BOOTLOADER_COMPILE_TIME_DATE=y
CONFIG_BOOTLOADER_PROJECT_VER=1
# end of Bootloader manager
CONFIG_BOOTLOADER_OFFSET_IN_FLASH=0x2000
CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y
# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG is not set
# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_PERF is not set
#
# Log
#
# CONFIG_BOOTLOADER_LOG_LEVEL_NONE is not set
# CONFIG_BOOTLOADER_LOG_LEVEL_ERROR is not set
# CONFIG_BOOTLOADER_LOG_LEVEL_WARN is not set
CONFIG_BOOTLOADER_LOG_LEVEL_INFO=y
# CONFIG_BOOTLOADER_LOG_LEVEL_DEBUG is not set
# CONFIG_BOOTLOADER_LOG_LEVEL_VERBOSE is not set
CONFIG_BOOTLOADER_LOG_LEVEL=3
#
# Format
#
# CONFIG_BOOTLOADER_LOG_COLORS is not set
CONFIG_BOOTLOADER_LOG_TIMESTAMP_SOURCE_CPU_TICKS=y
# end of Format
# end of Log
#
# Serial Flash Configurations
#
# CONFIG_BOOTLOADER_FLASH_DC_AWARE is not set
CONFIG_BOOTLOADER_FLASH_XMC_SUPPORT=y
# end of Serial Flash Configurations
# CONFIG_BOOTLOADER_FACTORY_RESET is not set
# CONFIG_BOOTLOADER_APP_TEST is not set
CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE=y
CONFIG_BOOTLOADER_WDT_ENABLE=y
# CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE is not set
CONFIG_BOOTLOADER_WDT_TIME_MS=9000
# CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE is not set
# CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP is not set
# CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON is not set
# CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS is not set
CONFIG_BOOTLOADER_RESERVE_RTC_SIZE=0
# CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC is not set
# end of Bootloader config
#
# Security features
#
CONFIG_SECURE_BOOT_V2_RSA_SUPPORTED=y
CONFIG_SECURE_BOOT_V2_ECC_SUPPORTED=y
CONFIG_SECURE_BOOT_V2_PREFERRED=y
# CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT is not set
# CONFIG_SECURE_BOOT is not set
# CONFIG_SECURE_FLASH_ENC_ENABLED is not set
CONFIG_SECURE_ROM_DL_MODE_ENABLED=y
# end of Security features
#
# Application manager
#
CONFIG_APP_COMPILE_TIME_DATE=y
# CONFIG_APP_EXCLUDE_PROJECT_VER_VAR is not set
# CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR is not set
# CONFIG_APP_PROJECT_VER_FROM_CONFIG is not set
CONFIG_APP_RETRIEVE_LEN_ELF_SHA=9
# end of Application manager
CONFIG_ESP_ROM_HAS_CRC_LE=y
CONFIG_ESP_ROM_HAS_CRC_BE=y
CONFIG_ESP_ROM_UART_CLK_IS_XTAL=y
CONFIG_ESP_ROM_USB_SERIAL_DEVICE_NUM=6
CONFIG_ESP_ROM_USB_OTG_NUM=5
CONFIG_ESP_ROM_HAS_RETARGETABLE_LOCKING=y
CONFIG_ESP_ROM_GET_CLK_FREQ=y
CONFIG_ESP_ROM_HAS_RVFPLIB=y
CONFIG_ESP_ROM_HAS_HAL_WDT=y
CONFIG_ESP_ROM_HAS_HAL_SYSTIMER=y
CONFIG_ESP_ROM_HAS_LAYOUT_TABLE=y
CONFIG_ESP_ROM_WDT_INIT_PATCH=y
CONFIG_ESP_ROM_HAS_LP_ROM=y
CONFIG_ESP_ROM_WITHOUT_REGI2C=y
CONFIG_ESP_ROM_HAS_NEWLIB=y
CONFIG_ESP_ROM_HAS_NEWLIB_NANO_FORMAT=y
CONFIG_ESP_ROM_HAS_NEWLIB_NANO_PRINTF_FLOAT_BUG=y
CONFIG_ESP_ROM_HAS_VERSION=y
CONFIG_ESP_ROM_CLIC_INT_TYPE_PATCH=y
CONFIG_ESP_ROM_HAS_OUTPUT_PUTC_FUNC=y
#
# Boot ROM Behavior
#
CONFIG_BOOT_ROM_LOG_ALWAYS_ON=y
# CONFIG_BOOT_ROM_LOG_ALWAYS_OFF is not set
# CONFIG_BOOT_ROM_LOG_ON_GPIO_HIGH is not set
# CONFIG_BOOT_ROM_LOG_ON_GPIO_LOW is not set
# end of Boot ROM Behavior
#
# Serial flasher config
#
# CONFIG_ESPTOOLPY_NO_STUB is not set
CONFIG_ESPTOOLPY_FLASHMODE_QIO=y
# CONFIG_ESPTOOLPY_FLASHMODE_QOUT is not set
# CONFIG_ESPTOOLPY_FLASHMODE_DIO is not set
# CONFIG_ESPTOOLPY_FLASHMODE_DOUT is not set
CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_STR=y
CONFIG_ESPTOOLPY_FLASHMODE="dio"
CONFIG_ESPTOOLPY_FLASHFREQ_80M=y
# CONFIG_ESPTOOLPY_FLASHFREQ_40M is not set
# CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set
CONFIG_ESPTOOLPY_FLASHFREQ="80m"
# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y
# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE="16MB"
# CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set
CONFIG_ESPTOOLPY_BEFORE_RESET=y
# CONFIG_ESPTOOLPY_BEFORE_NORESET is not set
CONFIG_ESPTOOLPY_BEFORE="default_reset"
CONFIG_ESPTOOLPY_AFTER_RESET=y
# CONFIG_ESPTOOLPY_AFTER_NORESET is not set
CONFIG_ESPTOOLPY_AFTER="hard_reset"
CONFIG_ESPTOOLPY_MONITOR_BAUD=115200
# end of Serial flasher config
#
# Partition Table
#
# CONFIG_PARTITION_TABLE_SINGLE_APP is not set
# CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set
# CONFIG_PARTITION_TABLE_TWO_OTA is not set
# CONFIG_PARTITION_TABLE_TWO_OTA_LARGE is not set
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_OFFSET=0x8000
CONFIG_PARTITION_TABLE_MD5=y
# end of Partition Table
#
# Compiler options
#
# CONFIG_COMPILER_OPTIMIZATION_DEBUG is not set
# CONFIG_COMPILER_OPTIMIZATION_SIZE is not set
CONFIG_COMPILER_OPTIMIZATION_PERF=y
# CONFIG_COMPILER_OPTIMIZATION_NONE is not set
CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE=y
# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT is not set
# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE is not set
CONFIG_COMPILER_ASSERT_NDEBUG_EVALUATE=y
# CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB is not set
CONFIG_COMPILER_FLOAT_LIB_FROM_RVFPLIB=y
CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL=2
# CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT is not set
CONFIG_COMPILER_HIDE_PATHS_MACROS=y
# CONFIG_COMPILER_CXX_EXCEPTIONS is not set
# CONFIG_COMPILER_CXX_RTTI is not set
CONFIG_COMPILER_STACK_CHECK_MODE_NONE=y
# CONFIG_COMPILER_STACK_CHECK_MODE_NORM is not set
# CONFIG_COMPILER_STACK_CHECK_MODE_STRONG is not set
# CONFIG_COMPILER_STACK_CHECK_MODE_ALL is not set
# CONFIG_COMPILER_NO_MERGE_CONSTANTS is not set
# CONFIG_COMPILER_WARN_WRITE_STRINGS is not set
# CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS is not set
CONFIG_COMPILER_DISABLE_DEFAULT_ERRORS=y
# CONFIG_COMPILER_DISABLE_GCC12_WARNINGS is not set
# CONFIG_COMPILER_DISABLE_GCC13_WARNINGS is not set
# CONFIG_COMPILER_DISABLE_GCC14_WARNINGS is not set
# CONFIG_COMPILER_DUMP_RTL_FILES is not set
CONFIG_COMPILER_RT_LIB_GCCLIB=y
CONFIG_COMPILER_RT_LIB_NAME="gcc"
# CONFIG_COMPILER_ORPHAN_SECTIONS_WARNING is not set
CONFIG_COMPILER_ORPHAN_SECTIONS_PLACE=y
# CONFIG_COMPILER_STATIC_ANALYZER is not set
# end of Compiler options
#
# Component config
#
#
# Application Level Tracing
#
# CONFIG_APPTRACE_DEST_JTAG is not set
CONFIG_APPTRACE_DEST_NONE=y
# CONFIG_APPTRACE_DEST_UART1 is not set
# CONFIG_APPTRACE_DEST_UART2 is not set
CONFIG_APPTRACE_DEST_UART_NONE=y
CONFIG_APPTRACE_UART_TASK_PRIO=1
CONFIG_APPTRACE_LOCK_ENABLE=y
# end of Application Level Tracing
#
# Bluetooth
#
# CONFIG_BT_ENABLED is not set
CONFIG_BT_ALARM_MAX_NUM=50
# end of Bluetooth
#
# Console Library
#
# CONFIG_CONSOLE_SORTED_HELP is not set
# end of Console Library
#
# Driver Configurations
#
#
# TWAI Configuration
#
# CONFIG_TWAI_ISR_IN_IRAM is not set
# end of TWAI Configuration
#
# Legacy ADC Driver Configuration
#
# CONFIG_ADC_SUPPRESS_DEPRECATE_WARN is not set
#
# Legacy ADC Calibration Configuration
#
# CONFIG_ADC_CALI_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy ADC Calibration Configuration
# end of Legacy ADC Driver Configuration
#
# Legacy MCPWM Driver Configurations
#
# CONFIG_MCPWM_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy MCPWM Driver Configurations
#
# Legacy Timer Group Driver Configurations
#
# CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy Timer Group Driver Configurations
#
# Legacy RMT Driver Configurations
#
# CONFIG_RMT_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy RMT Driver Configurations
#
# Legacy I2S Driver Configurations
#
# CONFIG_I2S_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy I2S Driver Configurations
#
# Legacy PCNT Driver Configurations
#
# CONFIG_PCNT_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy PCNT Driver Configurations
#
# Legacy SDM Driver Configurations
#
# CONFIG_SDM_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy SDM Driver Configurations
#
# Legacy Temperature Sensor Driver Configurations
#
# CONFIG_TEMP_SENSOR_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy Temperature Sensor Driver Configurations
# end of Driver Configurations
#
# eFuse Bit Manager
#
# CONFIG_EFUSE_CUSTOM_TABLE is not set
# CONFIG_EFUSE_VIRTUAL is not set
CONFIG_EFUSE_MAX_BLK_LEN=256
# end of eFuse Bit Manager
#
# ESP-TLS
#
CONFIG_ESP_TLS_USING_MBEDTLS=y
CONFIG_ESP_TLS_USE_DS_PERIPHERAL=y
# CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is not set
# CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is not set
# CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK is not set
# CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL is not set
# CONFIG_ESP_TLS_PSK_VERIFICATION is not set
# CONFIG_ESP_TLS_INSECURE is not set
# end of ESP-TLS
#
# ADC and ADC Calibration
#
# CONFIG_ADC_ONESHOT_CTRL_FUNC_IN_IRAM is not set
# CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is not set
# CONFIG_ADC_ENABLE_DEBUG_LOG is not set
# end of ADC and ADC Calibration
#
# Wireless Coexistence
#
# CONFIG_ESP_COEX_GPIO_DEBUG is not set
# end of Wireless Coexistence
#
# Common ESP-related
#
CONFIG_ESP_ERR_TO_NAME_LOOKUP=y
# end of Common ESP-related
#
# ESP-Driver:Analog Comparator Configurations
#
# CONFIG_ANA_CMPR_ISR_IRAM_SAFE is not set
# CONFIG_ANA_CMPR_CTRL_FUNC_IN_IRAM is not set
# CONFIG_ANA_CMPR_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:Analog Comparator Configurations
#
# ESP-Driver:Camera Controller Configurations
#
# CONFIG_CAM_CTLR_MIPI_CSI_ISR_IRAM_SAFE is not set
# CONFIG_CAM_CTLR_ISP_DVP_ISR_IRAM_SAFE is not set
# CONFIG_CAM_CTLR_DVP_CAM_ISR_IRAM_SAFE is not set
# end of ESP-Driver:Camera Controller Configurations
#
# ESP-Driver:GPIO Configurations
#
# CONFIG_GPIO_CTRL_FUNC_IN_IRAM is not set
# end of ESP-Driver:GPIO Configurations
#
# ESP-Driver:GPTimer Configurations
#
CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y
# CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is not set
# CONFIG_GPTIMER_ISR_IRAM_SAFE is not set
# CONFIG_GPTIMER_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:GPTimer Configurations
#
# ESP-Driver:I2C Configurations
#
# CONFIG_I2C_ISR_IRAM_SAFE is not set
# CONFIG_I2C_ENABLE_DEBUG_LOG is not set
# CONFIG_I2C_ENABLE_SLAVE_DRIVER_VERSION_2 is not set
# end of ESP-Driver:I2C Configurations
#
# ESP-Driver:I2S Configurations
#
# CONFIG_I2S_ISR_IRAM_SAFE is not set
# CONFIG_I2S_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:I2S Configurations
#
# ESP-Driver:ISP Configurations
#
# CONFIG_ISP_ISR_IRAM_SAFE is not set
# CONFIG_ISP_CTRL_FUNC_IN_IRAM is not set
# end of ESP-Driver:ISP Configurations
#
# ESP-Driver:JPEG-Codec Configurations
#
# CONFIG_JPEG_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:JPEG-Codec Configurations
#
# ESP-Driver:LEDC Configurations
#
# CONFIG_LEDC_CTRL_FUNC_IN_IRAM is not set
# end of ESP-Driver:LEDC Configurations
#
# ESP-Driver:MCPWM Configurations
#
# CONFIG_MCPWM_ISR_IRAM_SAFE is not set
# CONFIG_MCPWM_CTRL_FUNC_IN_IRAM is not set
# CONFIG_MCPWM_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:MCPWM Configurations
#
# ESP-Driver:Parallel IO Configurations
#
# CONFIG_PARLIO_ENABLE_DEBUG_LOG is not set
# CONFIG_PARLIO_ISR_IRAM_SAFE is not set
# end of ESP-Driver:Parallel IO Configurations
#
# ESP-Driver:PCNT Configurations
#
# CONFIG_PCNT_CTRL_FUNC_IN_IRAM is not set
# CONFIG_PCNT_ISR_IRAM_SAFE is not set
# CONFIG_PCNT_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:PCNT Configurations
#
# ESP-Driver:RMT Configurations
#
# CONFIG_RMT_ISR_IRAM_SAFE is not set
# CONFIG_RMT_RECV_FUNC_IN_IRAM is not set
# CONFIG_RMT_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:RMT Configurations
#
# ESP-Driver:Sigma Delta Modulator Configurations
#
# CONFIG_SDM_CTRL_FUNC_IN_IRAM is not set
# CONFIG_SDM_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:Sigma Delta Modulator Configurations
#
# ESP-Driver:SPI Configurations
#
# CONFIG_SPI_MASTER_IN_IRAM is not set
CONFIG_SPI_MASTER_ISR_IN_IRAM=y
# CONFIG_SPI_SLAVE_IN_IRAM is not set
CONFIG_SPI_SLAVE_ISR_IN_IRAM=y
# end of ESP-Driver:SPI Configurations
#
# ESP-Driver:Touch Sensor Configurations
#
# CONFIG_TOUCH_CTRL_FUNC_IN_IRAM is not set
# CONFIG_TOUCH_ISR_IRAM_SAFE is not set
# CONFIG_TOUCH_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:Touch Sensor Configurations
#
# ESP-Driver:Temperature Sensor Configurations
#
# CONFIG_TEMP_SENSOR_ENABLE_DEBUG_LOG is not set
# CONFIG_TEMP_SENSOR_ISR_IRAM_SAFE is not set
# end of ESP-Driver:Temperature Sensor Configurations
#
# ESP-Driver:UART Configurations
#
# CONFIG_UART_ISR_IN_IRAM is not set
# end of ESP-Driver:UART Configurations
#
# ESP-Driver:USB Serial/JTAG Configuration
#
CONFIG_USJ_ENABLE_USB_SERIAL_JTAG=y
# end of ESP-Driver:USB Serial/JTAG Configuration
#
# Ethernet
#
CONFIG_ETH_ENABLED=y
CONFIG_ETH_USE_ESP32_EMAC=y
CONFIG_ETH_PHY_INTERFACE_RMII=y
CONFIG_ETH_DMA_BUFFER_SIZE=512
CONFIG_ETH_DMA_RX_BUFFER_NUM=20
CONFIG_ETH_DMA_TX_BUFFER_NUM=10
# CONFIG_ETH_SOFT_FLOW_CONTROL is not set
# CONFIG_ETH_IRAM_OPTIMIZATION is not set
CONFIG_ETH_USE_SPI_ETHERNET=y
# CONFIG_ETH_SPI_ETHERNET_DM9051 is not set
# CONFIG_ETH_SPI_ETHERNET_W5500 is not set
# CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL is not set
# CONFIG_ETH_USE_OPENETH is not set
# CONFIG_ETH_TRANSMIT_MUTEX is not set
# end of Ethernet
#
# Event Loop Library
#
# CONFIG_ESP_EVENT_LOOP_PROFILING is not set
CONFIG_ESP_EVENT_POST_FROM_ISR=y
CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR=y
# end of Event Loop Library
#
# GDB Stub
#
CONFIG_ESP_GDBSTUB_ENABLED=y
# CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME is not set
CONFIG_ESP_GDBSTUB_SUPPORT_TASKS=y
CONFIG_ESP_GDBSTUB_MAX_TASKS=32
# end of GDB Stub
#
# ESP HTTP client
#
CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y
# CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH is not set
# CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH is not set
# CONFIG_ESP_HTTP_CLIENT_ENABLE_CUSTOM_TRANSPORT is not set
CONFIG_ESP_HTTP_CLIENT_EVENT_POST_TIMEOUT=2000
# end of ESP HTTP client
#
# HTTP Server
#
CONFIG_HTTPD_MAX_REQ_HDR_LEN=512
CONFIG_HTTPD_MAX_URI_LEN=512
CONFIG_HTTPD_ERR_RESP_NO_DELAY=y
CONFIG_HTTPD_PURGE_BUF_LEN=32
# CONFIG_HTTPD_LOG_PURGE_DATA is not set
# CONFIG_HTTPD_WS_SUPPORT is not set
# CONFIG_HTTPD_QUEUE_WORK_BLOCKING is not set
CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT=2000
# end of HTTP Server
#
# ESP HTTPS OTA
#
# CONFIG_ESP_HTTPS_OTA_DECRYPT_CB is not set
# CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP is not set
CONFIG_ESP_HTTPS_OTA_EVENT_POST_TIMEOUT=2000
# end of ESP HTTPS OTA
#
# ESP HTTPS server
#
# CONFIG_ESP_HTTPS_SERVER_ENABLE is not set
CONFIG_ESP_HTTPS_SERVER_EVENT_POST_TIMEOUT=2000
# end of ESP HTTPS server
#
# Hardware Settings
#
#
# Chip revision
#
# CONFIG_ESP32P4_REV_MIN_0 is not set
CONFIG_ESP32P4_REV_MIN_1=y
# CONFIG_ESP32P4_REV_MIN_100 is not set
CONFIG_ESP32P4_REV_MIN_FULL=1
CONFIG_ESP_REV_MIN_FULL=1
#
# Maximum Supported ESP32-P4 Revision (Rev v1.99)
#
CONFIG_ESP32P4_REV_MAX_FULL=199
CONFIG_ESP_REV_MAX_FULL=199
CONFIG_ESP_EFUSE_BLOCK_REV_MIN_FULL=0
CONFIG_ESP_EFUSE_BLOCK_REV_MAX_FULL=99
#
# Maximum Supported ESP32-P4 eFuse Block Revision (eFuse Block Rev v0.99)
#
# end of Chip revision
#
# MAC Config
#
CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH=y
CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES_ONE=y
CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES=1
CONFIG_ESP32P4_UNIVERSAL_MAC_ADDRESSES_ONE=y
CONFIG_ESP32P4_UNIVERSAL_MAC_ADDRESSES=1
# CONFIG_ESP_MAC_USE_CUSTOM_MAC_AS_BASE_MAC is not set
# end of MAC Config
#
# Sleep Config
#
CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND=y
CONFIG_ESP_SLEEP_PSRAM_LEAKAGE_WORKAROUND=y
# CONFIG_ESP_SLEEP_MSPI_NEED_ALL_IO_PU is not set
# CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND is not set
CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY=0
# CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION is not set
# CONFIG_ESP_SLEEP_DEBUG is not set
CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS=y
# end of Sleep Config
#
# RTC Clock Config
#
CONFIG_RTC_CLK_SRC_INT_RC=y
# CONFIG_RTC_CLK_SRC_EXT_CRYS is not set
CONFIG_RTC_CLK_CAL_CYCLES=1024
CONFIG_RTC_FAST_CLK_SRC_RC_FAST=y
# CONFIG_RTC_FAST_CLK_SRC_XTAL is not set
# end of RTC Clock Config
#
# Peripheral Control
#
CONFIG_PERIPH_CTRL_FUNC_IN_IRAM=y
# end of Peripheral Control
#
# ETM Configuration
#
# CONFIG_ETM_ENABLE_DEBUG_LOG is not set
# end of ETM Configuration
#
# GDMA Configurations
#
CONFIG_GDMA_CTRL_FUNC_IN_IRAM=y
# CONFIG_GDMA_ISR_IRAM_SAFE is not set
# CONFIG_GDMA_ENABLE_DEBUG_LOG is not set
# end of GDMA Configurations
#
# DW_GDMA Configurations
#
# CONFIG_DW_GDMA_ENABLE_DEBUG_LOG is not set
# end of DW_GDMA Configurations
#
# 2D-DMA Configurations
#
# CONFIG_DMA2D_OPERATION_FUNC_IN_IRAM is not set
# CONFIG_DMA2D_ISR_IRAM_SAFE is not set
# end of 2D-DMA Configurations
#
# Main XTAL Config
#
CONFIG_XTAL_FREQ_40=y
CONFIG_XTAL_FREQ=40
# end of Main XTAL Config
#
# DCDC Regulator Configurations
#
CONFIG_ESP_SLEEP_KEEP_DCDC_ALWAYS_ON=y
CONFIG_ESP_SLEEP_DCM_VSET_VAL_IN_SLEEP=14
# end of DCDC Regulator Configurations
#
# LDO Regulator Configurations
#
CONFIG_ESP_LDO_RESERVE_SPI_NOR_FLASH=y
CONFIG_ESP_LDO_CHAN_SPI_NOR_FLASH_DOMAIN=1
CONFIG_ESP_LDO_VOLTAGE_SPI_NOR_FLASH_3300_MV=y
CONFIG_ESP_LDO_VOLTAGE_SPI_NOR_FLASH_DOMAIN=3300
CONFIG_ESP_LDO_RESERVE_PSRAM=y
CONFIG_ESP_LDO_CHAN_PSRAM_DOMAIN=2
CONFIG_ESP_LDO_VOLTAGE_PSRAM_1900_MV=y
CONFIG_ESP_LDO_VOLTAGE_PSRAM_DOMAIN=1900
# end of LDO Regulator Configurations
CONFIG_ESP_SPI_BUS_LOCK_ISR_FUNCS_IN_IRAM=y
# end of Hardware Settings
#
# ESP-Driver:LCD Controller Configurations
#
# CONFIG_LCD_ENABLE_DEBUG_LOG is not set
# CONFIG_LCD_RGB_ISR_IRAM_SAFE is not set
# CONFIG_LCD_RGB_RESTART_IN_VSYNC is not set
# CONFIG_LCD_DSI_ISR_IRAM_SAFE is not set
# end of ESP-Driver:LCD Controller Configurations
#
# ESP-MM: Memory Management Configurations
#
# CONFIG_ESP_MM_CACHE_MSYNC_C2M_CHUNKED_OPS is not set
# end of ESP-MM: Memory Management Configurations
#
# ESP NETIF Adapter
#
CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL=120
# CONFIG_ESP_NETIF_PROVIDE_CUSTOM_IMPLEMENTATION is not set
CONFIG_ESP_NETIF_TCPIP_LWIP=y
# CONFIG_ESP_NETIF_LOOPBACK is not set
CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y
CONFIG_ESP_NETIF_REPORT_DATA_TRAFFIC=y
# CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS is not set
# CONFIG_ESP_NETIF_L2_TAP is not set
# CONFIG_ESP_NETIF_BRIDGE_EN is not set
# CONFIG_ESP_NETIF_SET_DNS_PER_DEFAULT_NETIF is not set
# end of ESP NETIF Adapter
#
# Partition API Configuration
#
# end of Partition API Configuration
#
# PHY
#
# end of PHY
#
# Power Management
#
# CONFIG_PM_ENABLE is not set
# CONFIG_PM_SLP_IRAM_OPT is not set
# CONFIG_PM_POWER_DOWN_PERIPHERAL_IN_LIGHT_SLEEP is not set
# end of Power Management
#
# ESP PSRAM
#
CONFIG_SPIRAM=y
#
# PSRAM config
#
CONFIG_SPIRAM_MODE_HEX=y
CONFIG_SPIRAM_SPEED_200M=y
# CONFIG_SPIRAM_SPEED_20M is not set
CONFIG_SPIRAM_SPEED=200
CONFIG_SPIRAM_FETCH_INSTRUCTIONS=y
CONFIG_SPIRAM_RODATA=y
CONFIG_SPIRAM_XIP_FROM_PSRAM=y
CONFIG_SPIRAM_FLASH_LOAD_TO_PSRAM=y
# CONFIG_SPIRAM_ECC_ENABLE is not set
CONFIG_SPIRAM_BOOT_INIT=y
# CONFIG_SPIRAM_IGNORE_NOTFOUND is not set
# CONFIG_SPIRAM_USE_MEMMAP is not set
# CONFIG_SPIRAM_USE_CAPS_ALLOC is not set
CONFIG_SPIRAM_USE_MALLOC=y
CONFIG_SPIRAM_MEMTEST=y
CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=16384
# CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP is not set
CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL=32768
# CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY is not set
# CONFIG_SPIRAM_ALLOW_NOINIT_SEG_EXTERNAL_MEMORY is not set
# end of PSRAM config
# end of ESP PSRAM
#
# ESP Ringbuf
#
# CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH is not set
# end of ESP Ringbuf
#
# ESP Security Specific
#
# end of ESP Security Specific
#
# ESP System Settings
#
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_360=y
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=360
#
# Cache config
#
# CONFIG_CACHE_L2_CACHE_128KB is not set
CONFIG_CACHE_L2_CACHE_256KB=y
# CONFIG_CACHE_L2_CACHE_512KB is not set
CONFIG_CACHE_L2_CACHE_SIZE=0x40000
# CONFIG_CACHE_L2_CACHE_LINE_64B is not set
CONFIG_CACHE_L2_CACHE_LINE_128B=y
CONFIG_CACHE_L2_CACHE_LINE_SIZE=128
CONFIG_CACHE_L1_CACHE_LINE_SIZE=64
# end of Cache config
# CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT is not set
CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT=y
# CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT is not set
# CONFIG_ESP_SYSTEM_PANIC_GDBSTUB is not set
CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS=0
CONFIG_ESP_SYSTEM_RTC_FAST_MEM_AS_HEAP_DEPCHECK=y
CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP=y
# CONFIG_ESP_SYSTEM_USE_EH_FRAME is not set
#
# Memory protection
#
CONFIG_ESP_SYSTEM_PMP_IDRAM_SPLIT=y
# CONFIG_ESP_SYSTEM_PMP_LP_CORE_RESERVE_MEM_EXECUTABLE is not set
# end of Memory protection
CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE=32
CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=2304
CONFIG_ESP_MAIN_TASK_STACK_SIZE=12288
CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0=y
# CONFIG_ESP_MAIN_TASK_AFFINITY_CPU1 is not set
# CONFIG_ESP_MAIN_TASK_AFFINITY_NO_AFFINITY is not set
CONFIG_ESP_MAIN_TASK_AFFINITY=0x0
CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE=2048
CONFIG_ESP_CONSOLE_UART_DEFAULT=y
# CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG is not set
# CONFIG_ESP_CONSOLE_UART_CUSTOM is not set
# CONFIG_ESP_CONSOLE_NONE is not set
# CONFIG_ESP_CONSOLE_SECONDARY_NONE is not set
CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED=y
CONFIG_ESP_CONSOLE_UART=y
CONFIG_ESP_CONSOLE_UART_NUM=0
CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=0
CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200
CONFIG_ESP_INT_WDT=y
CONFIG_ESP_INT_WDT_TIMEOUT_MS=300
CONFIG_ESP_INT_WDT_CHECK_CPU1=y
CONFIG_ESP_TASK_WDT_EN=y
CONFIG_ESP_TASK_WDT_INIT=y
# CONFIG_ESP_TASK_WDT_PANIC is not set
CONFIG_ESP_TASK_WDT_TIMEOUT_S=5
CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0=y
CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1=y
# CONFIG_ESP_PANIC_HANDLER_IRAM is not set
# CONFIG_ESP_DEBUG_STUBS_ENABLE is not set
CONFIG_ESP_DEBUG_OCDAWARE=y
CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4=y
#
# Brownout Detector
#
CONFIG_ESP_BROWNOUT_DET=y
CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7=y
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6 is not set
# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5 is not set
CONFIG_ESP_BROWNOUT_DET_LVL=7
# end of Brownout Detector
CONFIG_ESP_SYSTEM_BROWNOUT_INTR=y
CONFIG_ESP_SYSTEM_HW_STACK_GUARD=y
CONFIG_ESP_SYSTEM_HW_PC_RECORD=y
# end of ESP System Settings
#
# IPC (Inter-Processor Call)
#
CONFIG_ESP_IPC_TASK_STACK_SIZE=1024
CONFIG_ESP_IPC_USES_CALLERS_PRIORITY=y
CONFIG_ESP_IPC_ISR_ENABLE=y
# end of IPC (Inter-Processor Call)
#
# ESP Timer (High Resolution Timer)
#
# CONFIG_ESP_TIMER_PROFILING is not set
CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER=y
CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER=y
CONFIG_ESP_TIMER_TASK_STACK_SIZE=3584
CONFIG_ESP_TIMER_INTERRUPT_LEVEL=1
# CONFIG_ESP_TIMER_SHOW_EXPERIMENTAL is not set
CONFIG_ESP_TIMER_TASK_AFFINITY=0x0
CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0=y
CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0=y
# CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD is not set
CONFIG_ESP_TIMER_IMPL_SYSTIMER=y
# end of ESP Timer (High Resolution Timer)
#
# Wi-Fi
#
# CONFIG_ESP_HOST_WIFI_ENABLED is not set
# end of Wi-Fi
#
# Core dump
#
# CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH is not set
# CONFIG_ESP_COREDUMP_ENABLE_TO_UART is not set
CONFIG_ESP_COREDUMP_ENABLE_TO_NONE=y
# end of Core dump
#
# FAT Filesystem support
#
CONFIG_FATFS_VOLUME_COUNT=2
CONFIG_FATFS_LFN_NONE=y
# CONFIG_FATFS_LFN_HEAP is not set
# CONFIG_FATFS_LFN_STACK is not set
# CONFIG_FATFS_SECTOR_512 is not set
CONFIG_FATFS_SECTOR_4096=y
# CONFIG_FATFS_CODEPAGE_DYNAMIC is not set
CONFIG_FATFS_CODEPAGE_437=y
# CONFIG_FATFS_CODEPAGE_720 is not set
# CONFIG_FATFS_CODEPAGE_737 is not set
# CONFIG_FATFS_CODEPAGE_771 is not set
# CONFIG_FATFS_CODEPAGE_775 is not set
# CONFIG_FATFS_CODEPAGE_850 is not set
# CONFIG_FATFS_CODEPAGE_852 is not set
# CONFIG_FATFS_CODEPAGE_855 is not set
# CONFIG_FATFS_CODEPAGE_857 is not set
# CONFIG_FATFS_CODEPAGE_860 is not set
# CONFIG_FATFS_CODEPAGE_861 is not set
# CONFIG_FATFS_CODEPAGE_862 is not set
# CONFIG_FATFS_CODEPAGE_863 is not set
# CONFIG_FATFS_CODEPAGE_864 is not set
# CONFIG_FATFS_CODEPAGE_865 is not set
# CONFIG_FATFS_CODEPAGE_866 is not set
# CONFIG_FATFS_CODEPAGE_869 is not set
# CONFIG_FATFS_CODEPAGE_932 is not set
# CONFIG_FATFS_CODEPAGE_936 is not set
# CONFIG_FATFS_CODEPAGE_949 is not set
# CONFIG_FATFS_CODEPAGE_950 is not set
CONFIG_FATFS_CODEPAGE=437
CONFIG_FATFS_FS_LOCK=0
CONFIG_FATFS_TIMEOUT_MS=10000
CONFIG_FATFS_PER_FILE_CACHE=y
CONFIG_FATFS_ALLOC_PREFER_EXTRAM=y
# CONFIG_FATFS_USE_FASTSEEK is not set
CONFIG_FATFS_USE_STRFUNC_NONE=y
# CONFIG_FATFS_USE_STRFUNC_WITHOUT_CRLF_CONV is not set
# CONFIG_FATFS_USE_STRFUNC_WITH_CRLF_CONV is not set
CONFIG_FATFS_VFS_FSTAT_BLKSIZE=0
# CONFIG_FATFS_IMMEDIATE_FSYNC is not set
# CONFIG_FATFS_USE_LABEL is not set
CONFIG_FATFS_LINK_LOCK=y
# end of FAT Filesystem support
#
# FreeRTOS
#
#
# Kernel
#
# CONFIG_FREERTOS_UNICORE is not set
CONFIG_FREERTOS_HZ=1000
# CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE is not set
# CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL is not set
CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY=y
CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS=1
CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=1536
# CONFIG_FREERTOS_USE_IDLE_HOOK is not set
# CONFIG_FREERTOS_USE_TICK_HOOK is not set
CONFIG_FREERTOS_MAX_TASK_NAME_LEN=16
# CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY is not set
CONFIG_FREERTOS_USE_TIMERS=y
CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME="Tmr Svc"
# CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU0 is not set
# CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU1 is not set
CONFIG_FREERTOS_TIMER_TASK_NO_AFFINITY=y
CONFIG_FREERTOS_TIMER_SERVICE_TASK_CORE_AFFINITY=0x7FFFFFFF
CONFIG_FREERTOS_TIMER_TASK_PRIORITY=1
CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=2048
CONFIG_FREERTOS_TIMER_QUEUE_LENGTH=10
CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE=0
CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES=1
CONFIG_FREERTOS_USE_TRACE_FACILITY=y
CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS=y
# CONFIG_FREERTOS_USE_LIST_DATA_INTEGRITY_CHECK_BYTES is not set
CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID=y
CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS=y
CONFIG_FREERTOS_RUN_TIME_COUNTER_TYPE_U32=y
# CONFIG_FREERTOS_RUN_TIME_COUNTER_TYPE_U64 is not set
# CONFIG_FREERTOS_USE_APPLICATION_TASK_TAG is not set
# end of Kernel
#
# Port
#
# CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK is not set
CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS=y
# CONFIG_FREERTOS_TASK_PRE_DELETION_HOOK is not set
# CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP is not set
CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER=y
CONFIG_FREERTOS_ISR_STACKSIZE=1536
CONFIG_FREERTOS_INTERRUPT_BACKTRACE=y
CONFIG_FREERTOS_TICK_SUPPORT_SYSTIMER=y
CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL1=y
# CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL3 is not set
CONFIG_FREERTOS_SYSTICK_USES_SYSTIMER=y
CONFIG_FREERTOS_RUN_TIME_STATS_USING_ESP_TIMER=y
# CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH is not set
# CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE is not set
# end of Port
#
# Extra
#
CONFIG_FREERTOS_TASK_CREATE_ALLOW_EXT_MEM=y
# end of Extra
CONFIG_FREERTOS_PORT=y
CONFIG_FREERTOS_NO_AFFINITY=0x7FFFFFFF
CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION=y
CONFIG_FREERTOS_DEBUG_OCDAWARE=y
CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT=y
CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH=y
CONFIG_FREERTOS_NUMBER_OF_CORES=2
# end of FreeRTOS
#
# Hardware Abstraction Layer (HAL) and Low Level (LL)
#
CONFIG_HAL_ASSERTION_EQUALS_SYSTEM=y
# CONFIG_HAL_ASSERTION_DISABLE is not set
# CONFIG_HAL_ASSERTION_SILENT is not set
# CONFIG_HAL_ASSERTION_ENABLE is not set
CONFIG_HAL_DEFAULT_ASSERTION_LEVEL=2
CONFIG_HAL_SYSTIMER_USE_ROM_IMPL=y
CONFIG_HAL_WDT_USE_ROM_IMPL=y
CONFIG_HAL_SPI_MASTER_FUNC_IN_IRAM=y
CONFIG_HAL_SPI_SLAVE_FUNC_IN_IRAM=y
# CONFIG_HAL_ECDSA_GEN_SIG_CM is not set
# end of Hardware Abstraction Layer (HAL) and Low Level (LL)
#
# Heap memory debugging
#
CONFIG_HEAP_POISONING_DISABLED=y
# CONFIG_HEAP_POISONING_LIGHT is not set
# CONFIG_HEAP_POISONING_COMPREHENSIVE is not set
CONFIG_HEAP_TRACING_OFF=y
# CONFIG_HEAP_TRACING_STANDALONE is not set
# CONFIG_HEAP_TRACING_TOHOST is not set
# CONFIG_HEAP_USE_HOOKS is not set
# CONFIG_HEAP_TASK_TRACKING is not set
# CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS is not set
# CONFIG_HEAP_PLACE_FUNCTION_INTO_FLASH is not set
# end of Heap memory debugging
#
# Log
#
#
# Log Level
#
# CONFIG_LOG_DEFAULT_LEVEL_NONE is not set
# CONFIG_LOG_DEFAULT_LEVEL_ERROR is not set
# CONFIG_LOG_DEFAULT_LEVEL_WARN is not set
CONFIG_LOG_DEFAULT_LEVEL_INFO=y
# CONFIG_LOG_DEFAULT_LEVEL_DEBUG is not set
# CONFIG_LOG_DEFAULT_LEVEL_VERBOSE is not set
CONFIG_LOG_DEFAULT_LEVEL=3
CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT=y
# CONFIG_LOG_MAXIMUM_LEVEL_DEBUG is not set
# CONFIG_LOG_MAXIMUM_LEVEL_VERBOSE is not set
CONFIG_LOG_MAXIMUM_LEVEL=3
#
# Level Settings
#
# CONFIG_LOG_MASTER_LEVEL is not set
CONFIG_LOG_DYNAMIC_LEVEL_CONTROL=y
# CONFIG_LOG_TAG_LEVEL_IMPL_NONE is not set
# CONFIG_LOG_TAG_LEVEL_IMPL_LINKED_LIST is not set
CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_AND_LINKED_LIST=y
# CONFIG_LOG_TAG_LEVEL_CACHE_ARRAY is not set
CONFIG_LOG_TAG_LEVEL_CACHE_BINARY_MIN_HEAP=y
CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_SIZE=31
# end of Level Settings
# end of Log Level
#
# Format
#
CONFIG_LOG_COLORS=y
CONFIG_LOG_TIMESTAMP_SOURCE_RTOS=y
# CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM is not set
# end of Format
# end of Log
#
# LWIP
#
CONFIG_LWIP_ENABLE=y
CONFIG_LWIP_LOCAL_HOSTNAME="espressif"
# CONFIG_LWIP_NETIF_API is not set
CONFIG_LWIP_TCPIP_TASK_PRIO=18
# CONFIG_LWIP_TCPIP_CORE_LOCKING is not set
# CONFIG_LWIP_CHECK_THREAD_SAFETY is not set
CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y
# CONFIG_LWIP_L2_TO_L3_COPY is not set
# CONFIG_LWIP_IRAM_OPTIMIZATION is not set
# CONFIG_LWIP_EXTRA_IRAM_OPTIMIZATION is not set
CONFIG_LWIP_TIMERS_ONDEMAND=y
CONFIG_LWIP_ND6=y
# CONFIG_LWIP_FORCE_ROUTER_FORWARDING is not set
CONFIG_LWIP_MAX_SOCKETS=10
# CONFIG_LWIP_USE_ONLY_LWIP_SELECT is not set
# CONFIG_LWIP_SO_LINGER is not set
CONFIG_LWIP_SO_REUSE=y
CONFIG_LWIP_SO_REUSE_RXTOALL=y
# CONFIG_LWIP_SO_RCVBUF is not set
# CONFIG_LWIP_NETBUF_RECVINFO is not set
CONFIG_LWIP_IP_DEFAULT_TTL=64
CONFIG_LWIP_IP4_FRAG=y
CONFIG_LWIP_IP6_FRAG=y
# CONFIG_LWIP_IP4_REASSEMBLY is not set
# CONFIG_LWIP_IP6_REASSEMBLY is not set
CONFIG_LWIP_IP_REASS_MAX_PBUFS=10
# CONFIG_LWIP_IP_FORWARD is not set
# CONFIG_LWIP_STATS is not set
CONFIG_LWIP_ESP_GRATUITOUS_ARP=y
CONFIG_LWIP_GARP_TMR_INTERVAL=60
CONFIG_LWIP_ESP_MLDV6_REPORT=y
CONFIG_LWIP_MLDV6_TMR_INTERVAL=40
CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32
CONFIG_LWIP_DHCP_DOES_ARP_CHECK=y
# CONFIG_LWIP_DHCP_DOES_ACD_CHECK is not set
# CONFIG_LWIP_DHCP_DOES_NOT_CHECK_OFFERED_IP is not set
# CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID is not set
CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID=y
# CONFIG_LWIP_DHCP_RESTORE_LAST_IP is not set
CONFIG_LWIP_DHCP_OPTIONS_LEN=68
CONFIG_LWIP_NUM_NETIF_CLIENT_DATA=0
CONFIG_LWIP_DHCP_COARSE_TIMER_SECS=1
#
# DHCP server
#
CONFIG_LWIP_DHCPS=y
CONFIG_LWIP_DHCPS_LEASE_UNIT=60
CONFIG_LWIP_DHCPS_MAX_STATION_NUM=8
CONFIG_LWIP_DHCPS_STATIC_ENTRIES=y
CONFIG_LWIP_DHCPS_ADD_DNS=y
# end of DHCP server
# CONFIG_LWIP_AUTOIP is not set
CONFIG_LWIP_IPV4=y
CONFIG_LWIP_IPV6=y
# CONFIG_LWIP_IPV6_AUTOCONFIG is not set
CONFIG_LWIP_IPV6_NUM_ADDRESSES=3
# CONFIG_LWIP_IPV6_FORWARD is not set
# CONFIG_LWIP_NETIF_STATUS_CALLBACK is not set
CONFIG_LWIP_NETIF_LOOPBACK=y
CONFIG_LWIP_LOOPBACK_MAX_PBUFS=8
#
# TCP
#
CONFIG_LWIP_MAX_ACTIVE_TCP=16
CONFIG_LWIP_MAX_LISTENING_TCP=16
CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION=y
CONFIG_LWIP_TCP_MAXRTX=12
CONFIG_LWIP_TCP_SYNMAXRTX=12
CONFIG_LWIP_TCP_MSS=1440
CONFIG_LWIP_TCP_TMR_INTERVAL=250
CONFIG_LWIP_TCP_MSL=60000
CONFIG_LWIP_TCP_FIN_WAIT_TIMEOUT=20000
CONFIG_LWIP_TCP_SND_BUF_DEFAULT=5760
CONFIG_LWIP_TCP_WND_DEFAULT=5760
CONFIG_LWIP_TCP_RECVMBOX_SIZE=6
CONFIG_LWIP_TCP_ACCEPTMBOX_SIZE=6
CONFIG_LWIP_TCP_QUEUE_OOSEQ=y
CONFIG_LWIP_TCP_OOSEQ_TIMEOUT=6
CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS=4
# CONFIG_LWIP_TCP_SACK_OUT is not set
CONFIG_LWIP_TCP_OVERSIZE_MSS=y
# CONFIG_LWIP_TCP_OVERSIZE_QUARTER_MSS is not set
# CONFIG_LWIP_TCP_OVERSIZE_DISABLE is not set
CONFIG_LWIP_TCP_RTO_TIME=1500
# end of TCP
#
# UDP
#
CONFIG_LWIP_MAX_UDP_PCBS=16
CONFIG_LWIP_UDP_RECVMBOX_SIZE=6
# end of UDP
#
# Checksums
#
# CONFIG_LWIP_CHECKSUM_CHECK_IP is not set
# CONFIG_LWIP_CHECKSUM_CHECK_UDP is not set
CONFIG_LWIP_CHECKSUM_CHECK_ICMP=y
# end of Checksums
CONFIG_LWIP_TCPIP_TASK_STACK_SIZE=3072
CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY=y
# CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0 is not set
# CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU1 is not set
CONFIG_LWIP_TCPIP_TASK_AFFINITY=0x7FFFFFFF
CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE=3
CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS=5
CONFIG_LWIP_IPV6_ND6_NUM_PREFIXES=5
CONFIG_LWIP_IPV6_ND6_NUM_ROUTERS=3
CONFIG_LWIP_IPV6_ND6_NUM_DESTINATIONS=10
# CONFIG_LWIP_PPP_SUPPORT is not set
# CONFIG_LWIP_SLIP_SUPPORT is not set
#
# ICMP
#
CONFIG_LWIP_ICMP=y
# CONFIG_LWIP_MULTICAST_PING is not set
# CONFIG_LWIP_BROADCAST_PING is not set
# end of ICMP
#
# LWIP RAW API
#
CONFIG_LWIP_MAX_RAW_PCBS=16
# end of LWIP RAW API
#
# SNTP
#
CONFIG_LWIP_SNTP_MAX_SERVERS=1
# CONFIG_LWIP_DHCP_GET_NTP_SRV is not set
CONFIG_LWIP_SNTP_UPDATE_DELAY=3600000
CONFIG_LWIP_SNTP_STARTUP_DELAY=y
CONFIG_LWIP_SNTP_MAXIMUM_STARTUP_DELAY=5000
# end of SNTP
#
# DNS
#
CONFIG_LWIP_DNS_MAX_HOST_IP=1
CONFIG_LWIP_DNS_MAX_SERVERS=3
# CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT is not set
# CONFIG_LWIP_DNS_SETSERVER_WITH_NETIF is not set
# end of DNS
CONFIG_LWIP_BRIDGEIF_MAX_PORTS=7
CONFIG_LWIP_ESP_LWIP_ASSERT=y
#
# Hooks
#
# CONFIG_LWIP_HOOK_TCP_ISN_NONE is not set
CONFIG_LWIP_HOOK_TCP_ISN_DEFAULT=y
# CONFIG_LWIP_HOOK_TCP_ISN_CUSTOM is not set
CONFIG_LWIP_HOOK_IP6_ROUTE_NONE=y
# CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT is not set
# CONFIG_LWIP_HOOK_IP6_ROUTE_CUSTOM is not set
CONFIG_LWIP_HOOK_ND6_GET_GW_NONE=y
# CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT is not set
# CONFIG_LWIP_HOOK_ND6_GET_GW_CUSTOM is not set
CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE=y
# CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_DEFAULT is not set
# CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_CUSTOM is not set
CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE=y
# CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_DEFAULT is not set
# CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM is not set
CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_NONE=y
# CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_CUSTOM is not set
# CONFIG_LWIP_HOOK_IP6_INPUT_NONE is not set
CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT=y
# CONFIG_LWIP_HOOK_IP6_INPUT_CUSTOM is not set
# end of Hooks
# CONFIG_LWIP_DEBUG is not set
# end of LWIP
#
# mbedTLS
#
CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y
# CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC is not set
# CONFIG_MBEDTLS_DEFAULT_MEM_ALLOC is not set
# CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC is not set
CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y
CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=16384
CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096
# CONFIG_MBEDTLS_DYNAMIC_BUFFER is not set
# CONFIG_MBEDTLS_DEBUG is not set
#
# mbedTLS v3.x related
#
# CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 is not set
# CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH is not set
# CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK is not set
# CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set
CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y
CONFIG_MBEDTLS_PKCS7_C=y
# end of mbedTLS v3.x related
#
# Certificate Bundle
#
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL=y
# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN is not set
# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE is not set
# CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE is not set
# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEPRECATED_LIST is not set
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS=200
# end of Certificate Bundle
# CONFIG_MBEDTLS_ECP_RESTARTABLE is not set
# CONFIG_MBEDTLS_CMAC_C is not set
CONFIG_MBEDTLS_HARDWARE_AES=y
CONFIG_MBEDTLS_AES_USE_INTERRUPT=y
CONFIG_MBEDTLS_AES_INTERRUPT_LEVEL=0
CONFIG_MBEDTLS_HARDWARE_GCM=y
CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER=y
CONFIG_MBEDTLS_HARDWARE_MPI=y
# CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI is not set
CONFIG_MBEDTLS_MPI_USE_INTERRUPT=y
CONFIG_MBEDTLS_MPI_INTERRUPT_LEVEL=0
CONFIG_MBEDTLS_HARDWARE_SHA=y
CONFIG_MBEDTLS_HARDWARE_ECC=y
CONFIG_MBEDTLS_ECC_OTHER_CURVES_SOFT_FALLBACK=y
CONFIG_MBEDTLS_ROM_MD5=y
# CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set
# CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set
CONFIG_MBEDTLS_HAVE_TIME=y
# CONFIG_MBEDTLS_PLATFORM_TIME_ALT is not set
# CONFIG_MBEDTLS_HAVE_TIME_DATE is not set
CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y
CONFIG_MBEDTLS_SHA512_C=y
# CONFIG_MBEDTLS_SHA3_C is not set
CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT=y
# CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set
# CONFIG_MBEDTLS_TLS_CLIENT_ONLY is not set
# CONFIG_MBEDTLS_TLS_DISABLED is not set
CONFIG_MBEDTLS_TLS_SERVER=y
CONFIG_MBEDTLS_TLS_CLIENT=y
CONFIG_MBEDTLS_TLS_ENABLED=y
#
# TLS Key Exchange Methods
#
# CONFIG_MBEDTLS_PSK_MODES is not set
CONFIG_MBEDTLS_KEY_EXCHANGE_RSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA=y
# end of TLS Key Exchange Methods
CONFIG_MBEDTLS_SSL_RENEGOTIATION=y
CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y
# CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set
# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set
CONFIG_MBEDTLS_SSL_ALPN=y
CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS=y
CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS=y
#
# Symmetric Ciphers
#
CONFIG_MBEDTLS_AES_C=y
# CONFIG_MBEDTLS_CAMELLIA_C is not set
# CONFIG_MBEDTLS_DES_C is not set
# CONFIG_MBEDTLS_BLOWFISH_C is not set
# CONFIG_MBEDTLS_XTEA_C is not set
CONFIG_MBEDTLS_CCM_C=y
CONFIG_MBEDTLS_GCM_C=y
# CONFIG_MBEDTLS_NIST_KW_C is not set
# end of Symmetric Ciphers
# CONFIG_MBEDTLS_RIPEMD160_C is not set
#
# Certificates
#
CONFIG_MBEDTLS_PEM_PARSE_C=y
CONFIG_MBEDTLS_PEM_WRITE_C=y
CONFIG_MBEDTLS_X509_CRL_PARSE_C=y
CONFIG_MBEDTLS_X509_CSR_PARSE_C=y
# end of Certificates
CONFIG_MBEDTLS_ECP_C=y
CONFIG_MBEDTLS_PK_PARSE_EC_EXTENDED=y
CONFIG_MBEDTLS_PK_PARSE_EC_COMPRESSED=y
# CONFIG_MBEDTLS_DHM_C is not set
CONFIG_MBEDTLS_ECDH_C=y
CONFIG_MBEDTLS_ECDSA_C=y
# CONFIG_MBEDTLS_ECJPAKE_C is not set
CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED=y
CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED=y
CONFIG_MBEDTLS_ECP_NIST_OPTIM=y
# CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM is not set
# CONFIG_MBEDTLS_POLY1305_C is not set
# CONFIG_MBEDTLS_CHACHA20_C is not set
# CONFIG_MBEDTLS_HKDF_C is not set
# CONFIG_MBEDTLS_THREADING_C is not set
CONFIG_MBEDTLS_ERROR_STRINGS=y
CONFIG_MBEDTLS_FS_IO=y
# end of mbedTLS
#
# ESP-MQTT Configurations
#
CONFIG_MQTT_PROTOCOL_311=y
# CONFIG_MQTT_PROTOCOL_5 is not set
CONFIG_MQTT_TRANSPORT_SSL=y
CONFIG_MQTT_TRANSPORT_WEBSOCKET=y
CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y
# CONFIG_MQTT_MSG_ID_INCREMENTAL is not set
# CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED is not set
# CONFIG_MQTT_REPORT_DELETED_MESSAGES is not set
# CONFIG_MQTT_USE_CUSTOM_CONFIG is not set
# CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED is not set
# CONFIG_MQTT_CUSTOM_OUTBOX is not set
# end of ESP-MQTT Configurations
#
# Newlib
#
CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF=y
# CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF is not set
# CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR is not set
# CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF is not set
# CONFIG_NEWLIB_STDIN_LINE_ENDING_LF is not set
CONFIG_NEWLIB_STDIN_LINE_ENDING_CR=y
# CONFIG_NEWLIB_NANO_FORMAT is not set
CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y
# CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC is not set
# CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT is not set
# CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE is not set
# end of Newlib
#
# NVS
#
# CONFIG_NVS_ENCRYPTION is not set
# CONFIG_NVS_ASSERT_ERROR_CHECK is not set
# CONFIG_NVS_LEGACY_DUP_KEYS_COMPATIBILITY is not set
# CONFIG_NVS_ALLOCATE_CACHE_IN_SPIRAM is not set
# end of NVS
#
# OpenThread
#
# CONFIG_OPENTHREAD_ENABLED is not set
#
# OpenThread Spinel
#
# CONFIG_OPENTHREAD_SPINEL_ONLY is not set
# end of OpenThread Spinel
# end of OpenThread
#
# Protocomm
#
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0=y
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1=y
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2=y
# end of Protocomm
#
# PThreads
#
CONFIG_PTHREAD_TASK_PRIO_DEFAULT=5
CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072
CONFIG_PTHREAD_STACK_MIN=768
CONFIG_PTHREAD_DEFAULT_CORE_NO_AFFINITY=y
# CONFIG_PTHREAD_DEFAULT_CORE_0 is not set
# CONFIG_PTHREAD_DEFAULT_CORE_1 is not set
CONFIG_PTHREAD_TASK_CORE_DEFAULT=-1
CONFIG_PTHREAD_TASK_NAME_DEFAULT="pthread"
# end of PThreads
#
# MMU Config
#
CONFIG_MMU_PAGE_SIZE_64KB=y
CONFIG_MMU_PAGE_MODE="64KB"
CONFIG_MMU_PAGE_SIZE=0x10000
# end of MMU Config
#
# Main Flash configuration
#
#
# SPI Flash behavior when brownout
#
CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC=y
CONFIG_SPI_FLASH_BROWNOUT_RESET=y
# end of SPI Flash behavior when brownout
#
# Optional and Experimental Features (READ DOCS FIRST)
#
#
# Features here require specific hardware (READ DOCS FIRST!)
#
# CONFIG_SPI_FLASH_AUTO_SUSPEND is not set
CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US=50
# CONFIG_SPI_FLASH_FORCE_ENABLE_XMC_C_SUSPEND is not set
# end of Optional and Experimental Features (READ DOCS FIRST)
# end of Main Flash configuration
#
# SPI Flash driver
#
# CONFIG_SPI_FLASH_VERIFY_WRITE is not set
# CONFIG_SPI_FLASH_ENABLE_COUNTERS is not set
CONFIG_SPI_FLASH_ROM_DRIVER_PATCH=y
CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS=y
# CONFIG_SPI_FLASH_DANGEROUS_WRITE_FAILS is not set
# CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED is not set
# CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE is not set
CONFIG_SPI_FLASH_YIELD_DURING_ERASE=y
CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS=20
CONFIG_SPI_FLASH_ERASE_YIELD_TICKS=1
CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE=8192
# CONFIG_SPI_FLASH_SIZE_OVERRIDE is not set
# CONFIG_SPI_FLASH_CHECK_ERASE_TIMEOUT_DISABLED is not set
# CONFIG_SPI_FLASH_OVERRIDE_CHIP_DRIVER_LIST is not set
#
# Auto-detect flash chips
#
CONFIG_SPI_FLASH_VENDOR_XMC_SUPPORTED=y
# CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP is not set
# CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP is not set
# CONFIG_SPI_FLASH_SUPPORT_GD_CHIP is not set
# CONFIG_SPI_FLASH_SUPPORT_WINBOND_CHIP is not set
# CONFIG_SPI_FLASH_SUPPORT_BOYA_CHIP is not set
# CONFIG_SPI_FLASH_SUPPORT_TH_CHIP is not set
# end of Auto-detect flash chips
CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE=y
# end of SPI Flash driver
#
# SPIFFS Configuration
#
CONFIG_SPIFFS_MAX_PARTITIONS=3
#
# SPIFFS Cache Configuration
#
CONFIG_SPIFFS_CACHE=y
CONFIG_SPIFFS_CACHE_WR=y
# CONFIG_SPIFFS_CACHE_STATS is not set
# end of SPIFFS Cache Configuration
CONFIG_SPIFFS_PAGE_CHECK=y
CONFIG_SPIFFS_GC_MAX_RUNS=10
# CONFIG_SPIFFS_GC_STATS is not set
CONFIG_SPIFFS_PAGE_SIZE=256
CONFIG_SPIFFS_OBJ_NAME_LEN=32
# CONFIG_SPIFFS_FOLLOW_SYMLINKS is not set
CONFIG_SPIFFS_USE_MAGIC=y
CONFIG_SPIFFS_USE_MAGIC_LENGTH=y
CONFIG_SPIFFS_META_LENGTH=4
CONFIG_SPIFFS_USE_MTIME=y
#
# Debug Configuration
#
# CONFIG_SPIFFS_DBG is not set
# CONFIG_SPIFFS_API_DBG is not set
# CONFIG_SPIFFS_GC_DBG is not set
# CONFIG_SPIFFS_CACHE_DBG is not set
# CONFIG_SPIFFS_CHECK_DBG is not set
# CONFIG_SPIFFS_TEST_VISUALISATION is not set
# end of Debug Configuration
# end of SPIFFS Configuration
#
# TCP Transport
#
#
# Websocket
#
CONFIG_WS_TRANSPORT=y
CONFIG_WS_BUFFER_SIZE=1024
# CONFIG_WS_DYNAMIC_BUFFER is not set
# end of Websocket
# end of TCP Transport
#
# Ultra Low Power (ULP) Co-processor
#
# CONFIG_ULP_COPROC_ENABLED is not set
#
# ULP Debugging Options
#
# end of ULP Debugging Options
# end of Ultra Low Power (ULP) Co-processor
#
# Unity unit testing library
#
CONFIG_UNITY_ENABLE_FLOAT=y
CONFIG_UNITY_ENABLE_DOUBLE=y
# CONFIG_UNITY_ENABLE_64BIT is not set
# CONFIG_UNITY_ENABLE_COLOR is not set
CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER=y
# CONFIG_UNITY_ENABLE_FIXTURE is not set
# CONFIG_UNITY_ENABLE_BACKTRACE_ON_FAIL is not set
# end of Unity unit testing library
#
# USB-OTG
#
CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE=256
CONFIG_USB_HOST_HW_BUFFER_BIAS_BALANCED=y
# CONFIG_USB_HOST_HW_BUFFER_BIAS_IN is not set
# CONFIG_USB_HOST_HW_BUFFER_BIAS_PERIODIC_OUT is not set
#
# Hub Driver Configuration
#
#
# Root Port configuration
#
CONFIG_USB_HOST_DEBOUNCE_DELAY_MS=250
CONFIG_USB_HOST_RESET_HOLD_MS=30
CONFIG_USB_HOST_RESET_RECOVERY_MS=30
CONFIG_USB_HOST_SET_ADDR_RECOVERY_MS=10
# end of Root Port configuration
# CONFIG_USB_HOST_HUBS_SUPPORTED is not set
# end of Hub Driver Configuration
# CONFIG_USB_HOST_ENABLE_ENUM_FILTER_CALLBACK is not set
CONFIG_USB_OTG_SUPPORTED=y
# end of USB-OTG
#
# Virtual file system
#
CONFIG_VFS_SUPPORT_IO=y
CONFIG_VFS_SUPPORT_DIR=y
CONFIG_VFS_SUPPORT_SELECT=y
CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT=y
# CONFIG_VFS_SELECT_IN_RAM is not set
CONFIG_VFS_SUPPORT_TERMIOS=y
CONFIG_VFS_MAX_COUNT=8
#
# Host File System I/O (Semihosting)
#
CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS=1
# end of Host File System I/O (Semihosting)
CONFIG_VFS_INITIALIZE_DEV_NULL=y
# end of Virtual file system
#
# Wear Levelling
#
# CONFIG_WL_SECTOR_SIZE_512 is not set
CONFIG_WL_SECTOR_SIZE_4096=y
CONFIG_WL_SECTOR_SIZE=4096
# end of Wear Levelling
#
# Wi-Fi Provisioning Manager
#
CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES=16
CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT=30
CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y
# CONFIG_WIFI_PROV_STA_FAST_SCAN is not set
# end of Wi-Fi Provisioning Manager
#
# CMake Utilities
#
# CONFIG_CU_RELINKER_ENABLE is not set
# CONFIG_CU_DIAGNOSTICS_COLOR_NEVER is not set
CONFIG_CU_DIAGNOSTICS_COLOR_ALWAYS=y
# CONFIG_CU_DIAGNOSTICS_COLOR_AUTO is not set
# CONFIG_CU_GCC_LTO_ENABLE is not set
# CONFIG_CU_GCC_STRING_1BYTE_ALIGN is not set
# end of CMake Utilities
#
# Audio Codec Device Configuration
#
CONFIG_CODEC_ES8311_SUPPORT=y
CONFIG_CODEC_ES7210_SUPPORT=y
CONFIG_CODEC_ES7243_SUPPORT=y
CONFIG_CODEC_ES7243E_SUPPORT=y
CONFIG_CODEC_ES8156_SUPPORT=y
CONFIG_CODEC_AW88298_SUPPORT=y
CONFIG_CODEC_ES8374_SUPPORT=y
CONFIG_CODEC_ES8388_SUPPORT=y
CONFIG_CODEC_TAS5805M_SUPPORT=y
# CONFIG_CODEC_ZL38063_SUPPORT is not set
# end of Audio Codec Device Configuration
#
# ESP LCD TOUCH
#
CONFIG_ESP_LCD_TOUCH_MAX_POINTS=5
CONFIG_ESP_LCD_TOUCH_MAX_BUTTONS=1
# end of ESP LCD TOUCH
#
# Bus Options
#
#
# I2C Bus Options
#
CONFIG_I2C_BUS_DYNAMIC_CONFIG=y
CONFIG_I2C_MS_TO_WAIT=200
# CONFIG_I2C_BUS_BACKWARD_CONFIG is not set
# CONFIG_I2C_BUS_SUPPORT_SOFTWARE is not set
# end of I2C Bus Options
# end of Bus Options
#
# LVGL configuration
#
CONFIG_LV_CONF_SKIP=y
# CONFIG_LV_CONF_MINIMAL is not set
#
# Color Settings
#
# CONFIG_LV_COLOR_DEPTH_32 is not set
# CONFIG_LV_COLOR_DEPTH_24 is not set
CONFIG_LV_COLOR_DEPTH_16=y
# CONFIG_LV_COLOR_DEPTH_8 is not set
# CONFIG_LV_COLOR_DEPTH_1 is not set
CONFIG_LV_COLOR_DEPTH=16
# end of Color Settings
#
# Memory Settings
#
# CONFIG_LV_USE_BUILTIN_MALLOC is not set
CONFIG_LV_USE_CLIB_MALLOC=y
# CONFIG_LV_USE_MICROPYTHON_MALLOC is not set
# CONFIG_LV_USE_RTTHREAD_MALLOC is not set
# CONFIG_LV_USE_CUSTOM_MALLOC is not set
# CONFIG_LV_USE_BUILTIN_STRING is not set
CONFIG_LV_USE_CLIB_STRING=y
# CONFIG_LV_USE_CUSTOM_STRING is not set
# CONFIG_LV_USE_BUILTIN_SPRINTF is not set
CONFIG_LV_USE_CLIB_SPRINTF=y
# CONFIG_LV_USE_CUSTOM_SPRINTF is not set
# end of Memory Settings
#
# HAL Settings
#
CONFIG_LV_DEF_REFR_PERIOD=15
CONFIG_LV_DPI_DEF=130
# end of HAL Settings
#
# Operating System (OS)
#
# CONFIG_LV_OS_NONE is not set
# CONFIG_LV_OS_PTHREAD is not set
CONFIG_LV_OS_FREERTOS=y
# CONFIG_LV_OS_CMSIS_RTOS2 is not set
# CONFIG_LV_OS_RTTHREAD is not set
# CONFIG_LV_OS_WINDOWS is not set
# CONFIG_LV_OS_MQX is not set
# CONFIG_LV_OS_CUSTOM is not set
CONFIG_LV_USE_OS=2
CONFIG_LV_USE_FREERTOS_TASK_NOTIFY=y
# end of Operating System (OS)
#
# Rendering Configuration
#
CONFIG_LV_DRAW_BUF_STRIDE_ALIGN=1
CONFIG_LV_DRAW_BUF_ALIGN=4
CONFIG_LV_DRAW_LAYER_SIMPLE_BUF_SIZE=24576
CONFIG_LV_DRAW_THREAD_STACK_SIZE=8192
CONFIG_LV_USE_DRAW_SW=y
CONFIG_LV_DRAW_SW_SUPPORT_RGB565=y
CONFIG_LV_DRAW_SW_SUPPORT_RGB565A8=y
CONFIG_LV_DRAW_SW_SUPPORT_RGB888=y
CONFIG_LV_DRAW_SW_SUPPORT_XRGB8888=y
CONFIG_LV_DRAW_SW_SUPPORT_ARGB8888=y
CONFIG_LV_DRAW_SW_SUPPORT_L8=y
CONFIG_LV_DRAW_SW_SUPPORT_AL88=y
CONFIG_LV_DRAW_SW_SUPPORT_A8=y
CONFIG_LV_DRAW_SW_SUPPORT_I1=y
CONFIG_LV_DRAW_SW_DRAW_UNIT_CNT=2
# CONFIG_LV_USE_DRAW_ARM2D_SYNC is not set
# CONFIG_LV_USE_NATIVE_HELIUM_ASM is not set
CONFIG_LV_DRAW_SW_COMPLEX=y
# CONFIG_LV_USE_DRAW_SW_COMPLEX_GRADIENTS is not set
CONFIG_LV_DRAW_SW_SHADOW_CACHE_SIZE=0
CONFIG_LV_DRAW_SW_CIRCLE_CACHE_SIZE=4
CONFIG_LV_DRAW_SW_ASM_NONE=y
# CONFIG_LV_DRAW_SW_ASM_NEON is not set
# CONFIG_LV_DRAW_SW_ASM_HELIUM is not set
# CONFIG_LV_DRAW_SW_ASM_CUSTOM is not set
CONFIG_LV_USE_DRAW_SW_ASM=0
# CONFIG_LV_USE_DRAW_VGLITE is not set
# CONFIG_LV_USE_PXP is not set
# CONFIG_LV_USE_DRAW_DAVE2D is not set
# CONFIG_LV_USE_DRAW_SDL is not set
# CONFIG_LV_USE_DRAW_VG_LITE is not set
# CONFIG_LV_USE_VECTOR_GRAPHIC is not set
# end of Rendering Configuration
#
# Feature Configuration
#
#
# Logging
#
# CONFIG_LV_USE_LOG is not set
# end of Logging
#
# Asserts
#
CONFIG_LV_USE_ASSERT_NULL=y
CONFIG_LV_USE_ASSERT_MALLOC=y
# CONFIG_LV_USE_ASSERT_STYLE is not set
# CONFIG_LV_USE_ASSERT_MEM_INTEGRITY is not set
# CONFIG_LV_USE_ASSERT_OBJ is not set
CONFIG_LV_ASSERT_HANDLER_INCLUDE="assert.h"
# end of Asserts
#
# Debug
#
# CONFIG_LV_USE_REFR_DEBUG is not set
# CONFIG_LV_USE_LAYER_DEBUG is not set
# CONFIG_LV_USE_PARALLEL_DRAW_DEBUG is not set
# end of Debug
#
# Others
#
# CONFIG_LV_ENABLE_GLOBAL_CUSTOM is not set
CONFIG_LV_CACHE_DEF_SIZE=0
CONFIG_LV_IMAGE_HEADER_CACHE_DEF_CNT=0
CONFIG_LV_GRADIENT_MAX_STOPS=2
CONFIG_LV_COLOR_MIX_ROUND_OFS=128
# CONFIG_LV_OBJ_STYLE_CACHE is not set
# CONFIG_LV_USE_OBJ_ID is not set
# CONFIG_LV_USE_OBJ_PROPERTY is not set
# end of Others
# end of Feature Configuration
#
# Compiler Settings
#
# CONFIG_LV_BIG_ENDIAN_SYSTEM is not set
CONFIG_LV_ATTRIBUTE_MEM_ALIGN_SIZE=1
CONFIG_LV_ATTRIBUTE_FAST_MEM_USE_IRAM=y
# CONFIG_LV_USE_FLOAT is not set
# CONFIG_LV_USE_MATRIX is not set
# CONFIG_LV_USE_PRIVATE_API is not set
# end of Compiler Settings
#
# Font Usage
#
#
# Enable built-in fonts
#
# CONFIG_LV_FONT_MONTSERRAT_8 is not set
# CONFIG_LV_FONT_MONTSERRAT_10 is not set
CONFIG_LV_FONT_MONTSERRAT_12=y
CONFIG_LV_FONT_MONTSERRAT_14=y
CONFIG_LV_FONT_MONTSERRAT_16=y
CONFIG_LV_FONT_MONTSERRAT_18=y
CONFIG_LV_FONT_MONTSERRAT_20=y
CONFIG_LV_FONT_MONTSERRAT_22=y
CONFIG_LV_FONT_MONTSERRAT_24=y
CONFIG_LV_FONT_MONTSERRAT_26=y
# CONFIG_LV_FONT_MONTSERRAT_28 is not set
# CONFIG_LV_FONT_MONTSERRAT_30 is not set
# CONFIG_LV_FONT_MONTSERRAT_32 is not set
# CONFIG_LV_FONT_MONTSERRAT_34 is not set
# CONFIG_LV_FONT_MONTSERRAT_36 is not set
# CONFIG_LV_FONT_MONTSERRAT_38 is not set
# CONFIG_LV_FONT_MONTSERRAT_40 is not set
# CONFIG_LV_FONT_MONTSERRAT_42 is not set
# CONFIG_LV_FONT_MONTSERRAT_44 is not set
# CONFIG_LV_FONT_MONTSERRAT_46 is not set
# CONFIG_LV_FONT_MONTSERRAT_48 is not set
# CONFIG_LV_FONT_MONTSERRAT_28_COMPRESSED is not set
# CONFIG_LV_FONT_DEJAVU_16_PERSIAN_HEBREW is not set
# CONFIG_LV_FONT_SIMSUN_14_CJK is not set
# CONFIG_LV_FONT_SIMSUN_16_CJK is not set
# CONFIG_LV_FONT_UNSCII_8 is not set
# CONFIG_LV_FONT_UNSCII_16 is not set
# end of Enable built-in fonts
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_8 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_10 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_12 is not set
CONFIG_LV_FONT_DEFAULT_MONTSERRAT_14=y
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_16 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_18 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_20 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_22 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_24 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_26 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_30 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_32 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_34 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_36 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_38 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_40 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_42 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_44 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_46 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_48 is not set
# CONFIG_LV_FONT_DEFAULT_MONTSERRAT_28_COMPRESSED is not set
# CONFIG_LV_FONT_DEFAULT_DEJAVU_16_PERSIAN_HEBREW is not set
# CONFIG_LV_FONT_DEFAULT_SIMSUN_14_CJK is not set
# CONFIG_LV_FONT_DEFAULT_SIMSUN_16_CJK is not set
# CONFIG_LV_FONT_DEFAULT_UNSCII_8 is not set
# CONFIG_LV_FONT_DEFAULT_UNSCII_16 is not set
# CONFIG_LV_FONT_FMT_TXT_LARGE is not set
CONFIG_LV_USE_FONT_COMPRESSED=y
CONFIG_LV_USE_FONT_PLACEHOLDER=y
# end of Font Usage
#
# Text Settings
#
CONFIG_LV_TXT_ENC_UTF8=y
# CONFIG_LV_TXT_ENC_ASCII is not set
CONFIG_LV_TXT_BREAK_CHARS=" ,.;:-_"
CONFIG_LV_TXT_LINE_BREAK_LONG_LEN=0
# CONFIG_LV_USE_BIDI is not set
# CONFIG_LV_USE_ARABIC_PERSIAN_CHARS is not set
# end of Text Settings
#
# Widget Usage
#
CONFIG_LV_WIDGETS_HAS_DEFAULT_VALUE=y
CONFIG_LV_USE_ANIMIMG=y
CONFIG_LV_USE_ARC=y
CONFIG_LV_USE_BAR=y
CONFIG_LV_USE_BUTTON=y
CONFIG_LV_USE_BUTTONMATRIX=y
CONFIG_LV_USE_CALENDAR=y
# CONFIG_LV_CALENDAR_WEEK_STARTS_MONDAY is not set
CONFIG_LV_USE_CALENDAR_HEADER_ARROW=y
CONFIG_LV_USE_CALENDAR_HEADER_DROPDOWN=y
# CONFIG_LV_USE_CALENDAR_CHINESE is not set
CONFIG_LV_USE_CANVAS=y
CONFIG_LV_USE_CHART=y
CONFIG_LV_USE_CHECKBOX=y
CONFIG_LV_USE_DROPDOWN=y
CONFIG_LV_USE_IMAGE=y
CONFIG_LV_USE_IMAGEBUTTON=y
CONFIG_LV_USE_KEYBOARD=y
CONFIG_LV_USE_LABEL=y
CONFIG_LV_LABEL_TEXT_SELECTION=y
CONFIG_LV_LABEL_LONG_TXT_HINT=y
CONFIG_LV_LABEL_WAIT_CHAR_COUNT=3
CONFIG_LV_USE_LED=y
CONFIG_LV_USE_LINE=y
CONFIG_LV_USE_LIST=y
CONFIG_LV_USE_MENU=y
CONFIG_LV_USE_MSGBOX=y
CONFIG_LV_USE_ROLLER=y
CONFIG_LV_USE_SCALE=y
CONFIG_LV_USE_SLIDER=y
CONFIG_LV_USE_SPAN=y
CONFIG_LV_SPAN_SNIPPET_STACK_SIZE=64
CONFIG_LV_USE_SPINBOX=y
CONFIG_LV_USE_SPINNER=y
CONFIG_LV_USE_SWITCH=y
CONFIG_LV_USE_TEXTAREA=y
CONFIG_LV_TEXTAREA_DEF_PWD_SHOW_TIME=1500
CONFIG_LV_USE_TABLE=y
CONFIG_LV_USE_TABVIEW=y
CONFIG_LV_USE_TILEVIEW=y
CONFIG_LV_USE_WIN=y
# end of Widget Usage
#
# Themes
#
CONFIG_LV_USE_THEME_DEFAULT=y
# CONFIG_LV_THEME_DEFAULT_DARK is not set
CONFIG_LV_THEME_DEFAULT_GROW=y
CONFIG_LV_THEME_DEFAULT_TRANSITION_TIME=80
CONFIG_LV_USE_THEME_SIMPLE=y
# CONFIG_LV_USE_THEME_MONO is not set
# end of Themes
#
# Layouts
#
CONFIG_LV_USE_FLEX=y
CONFIG_LV_USE_GRID=y
# end of Layouts
#
# 3rd Party Libraries
#
CONFIG_LV_FS_DEFAULT_DRIVE_LETTER=0
# CONFIG_LV_USE_FS_STDIO is not set
# CONFIG_LV_USE_FS_POSIX is not set
# CONFIG_LV_USE_FS_WIN32 is not set
# CONFIG_LV_USE_FS_FATFS is not set
# CONFIG_LV_USE_FS_MEMFS is not set
# CONFIG_LV_USE_FS_LITTLEFS is not set
# CONFIG_LV_USE_FS_ARDUINO_ESP_LITTLEFS is not set
# CONFIG_LV_USE_FS_ARDUINO_SD is not set
# CONFIG_LV_USE_LODEPNG is not set
# CONFIG_LV_USE_LIBPNG is not set
# CONFIG_LV_USE_BMP is not set
# CONFIG_LV_USE_TJPGD is not set
# CONFIG_LV_USE_LIBJPEG_TURBO is not set
# CONFIG_LV_USE_GIF is not set
# CONFIG_LV_BIN_DECODER_RAM_LOAD is not set
# CONFIG_LV_USE_RLE is not set
# CONFIG_LV_USE_QRCODE is not set
# CONFIG_LV_USE_BARCODE is not set
# CONFIG_LV_USE_FREETYPE is not set
# CONFIG_LV_USE_TINY_TTF is not set
# CONFIG_LV_USE_RLOTTIE is not set
# CONFIG_LV_USE_THORVG is not set
# CONFIG_LV_USE_LZ4 is not set
# CONFIG_LV_USE_FFMPEG is not set
# end of 3rd Party Libraries
#
# Others
#
# CONFIG_LV_USE_SNAPSHOT is not set
CONFIG_LV_USE_SYSMON=y
CONFIG_LV_USE_PERF_MONITOR=y
# CONFIG_LV_PERF_MONITOR_ALIGN_TOP_LEFT is not set
# CONFIG_LV_PERF_MONITOR_ALIGN_TOP_MID is not set
# CONFIG_LV_PERF_MONITOR_ALIGN_TOP_RIGHT is not set
# CONFIG_LV_PERF_MONITOR_ALIGN_BOTTOM_LEFT is not set
# CONFIG_LV_PERF_MONITOR_ALIGN_BOTTOM_MID is not set
CONFIG_LV_PERF_MONITOR_ALIGN_BOTTOM_RIGHT=y
# CONFIG_LV_PERF_MONITOR_ALIGN_LEFT_MID is not set
# CONFIG_LV_PERF_MONITOR_ALIGN_RIGHT_MID is not set
# CONFIG_LV_PERF_MONITOR_ALIGN_CENTER is not set
# CONFIG_LV_USE_PERF_MONITOR_LOG_MODE is not set
# CONFIG_LV_USE_PROFILER is not set
# CONFIG_LV_USE_MONKEY is not set
# CONFIG_LV_USE_GRIDNAV is not set
# CONFIG_LV_USE_FRAGMENT is not set
CONFIG_LV_USE_IMGFONT=y
CONFIG_LV_USE_OBSERVER=y
# CONFIG_LV_USE_IME_PINYIN is not set
# CONFIG_LV_USE_FILE_EXPLORER is not set
CONFIG_LVGL_VERSION_MAJOR=9
CONFIG_LVGL_VERSION_MINOR=2
CONFIG_LVGL_VERSION_PATCH=2
# end of Others
#
# Devices
#
# CONFIG_LV_USE_SDL is not set
# CONFIG_LV_USE_X11 is not set
# CONFIG_LV_USE_WAYLAND is not set
# CONFIG_LV_USE_LINUX_FBDEV is not set
# CONFIG_LV_USE_NUTTX is not set
# CONFIG_LV_USE_LINUX_DRM is not set
# CONFIG_LV_USE_TFT_ESPI is not set
# CONFIG_LV_USE_EVDEV is not set
# CONFIG_LV_USE_LIBINPUT is not set
# CONFIG_LV_USE_ST7735 is not set
# CONFIG_LV_USE_ST7789 is not set
# CONFIG_LV_USE_ST7796 is not set
# CONFIG_LV_USE_ILI9341 is not set
# CONFIG_LV_USE_GENERIC_MIPI is not set
# CONFIG_LV_USE_RENESAS_GLCDC is not set
# CONFIG_LV_USE_OPENGLES is not set
# CONFIG_LV_USE_QNX is not set
# end of Devices
#
# Examples
#
CONFIG_LV_BUILD_EXAMPLES=y
# end of Examples
#
# Demos
#
CONFIG_LV_USE_DEMO_WIDGETS=y
# CONFIG_LV_USE_DEMO_KEYPAD_AND_ENCODER is not set
CONFIG_LV_USE_DEMO_BENCHMARK=y
CONFIG_LV_USE_DEMO_RENDER=y
CONFIG_LV_USE_DEMO_SCROLL=y
CONFIG_LV_USE_DEMO_STRESS=y
CONFIG_LV_USE_DEMO_TRANSFORM=y
CONFIG_LV_USE_DEMO_MUSIC=y
# CONFIG_LV_DEMO_MUSIC_SQUARE is not set
# CONFIG_LV_DEMO_MUSIC_LANDSCAPE is not set
# CONFIG_LV_DEMO_MUSIC_ROUND is not set
# CONFIG_LV_DEMO_MUSIC_LARGE is not set
CONFIG_LV_DEMO_MUSIC_AUTO_PLAY=y
CONFIG_LV_USE_DEMO_FLEX_LAYOUT=y
CONFIG_LV_USE_DEMO_MULTILANG=y
# end of Demos
# end of LVGL configuration
#
# Board Support Package(ESP32-P4)
#
CONFIG_BSP_ERROR_CHECK=y
#
# I2C
#
CONFIG_BSP_I2C_NUM=1
CONFIG_BSP_I2C_FAST_MODE=y
CONFIG_BSP_I2C_CLK_SPEED_HZ=400000
# end of I2C
#
# I2S
#
CONFIG_BSP_I2S_NUM=1
# end of I2S
#
# uSD card - Virtual File System
#
# CONFIG_BSP_SD_FORMAT_ON_MOUNT_FAIL is not set
CONFIG_BSP_SD_MOUNT_POINT="/sdcard"
# end of uSD card - Virtual File System
#
# SPIFFS - Virtual File System
#
# CONFIG_BSP_SPIFFS_FORMAT_ON_MOUNT_FAIL is not set
CONFIG_BSP_SPIFFS_MOUNT_POINT="/spiffs"
CONFIG_BSP_SPIFFS_PARTITION_LABEL="storage"
CONFIG_BSP_SPIFFS_MAX_FILES=5
# end of SPIFFS - Virtual File System
#
# Display
#
CONFIG_BSP_LCD_DPI_BUFFER_NUMS=1
CONFIG_BSP_DISPLAY_BRIGHTNESS_LEDC_CH=1
CONFIG_BSP_LCD_COLOR_FORMAT_RGB565=y
# CONFIG_BSP_LCD_COLOR_FORMAT_RGB888 is not set
CONFIG_BSP_LCD_TYPE_800_1280_10_1_INCH=y
# CONFIG_BSP_LCD_TYPE_800_1280_10_1_INCH_A is not set
# CONFIG_BSP_LCD_TYPE_800_1280_8_INCH_A is not set
# CONFIG_BSP_LCD_TYPE_720_1280_7_INCH_A is not set
# CONFIG_BSP_LCD_TYPE_480_640_2_8_INCH is not set
# CONFIG_BSP_LCD_TYPE_800_800_3_4_INCH_C is not set
# CONFIG_BSP_LCD_TYPE_720_720_4_INCH_C is not set
# CONFIG_BSP_LCD_TYPE_480_800_4_INCH is not set
# CONFIG_BSP_LCD_TYPE_720_1280_5_INCH_D is not set
# CONFIG_BSP_LCD_TYPE_720_1560_6_25_INCH is not set
# CONFIG_BSP_LCD_TYPE_1024_600_5_INCH_C is not set
# CONFIG_BSP_LCD_TYPE_1024_600_7_INCH_C is not set
# CONFIG_BSP_LCD_TYPE_400_1280_7_9_INCH is not set
# CONFIG_BSP_LCD_TYPE_1280_800_7_INCH_E is not set
# CONFIG_BSP_LCD_TYPE_1280_800_8_INCH_C is not set
# CONFIG_BSP_LCD_TYPE_1280_800_10_1_INCH_C is not set
# CONFIG_BSP_LCD_TYPE_480_1920_8_8_INCH is not set
# CONFIG_BSP_LCD_TYPE_320_1480_11_9_INCH is not set
CONFIG_BSP_LCD_MIPI_DSI_LANE_BITRATE_MBPS=1500
# end of Display
# end of Board Support Package(ESP32-P4)
# end of Component config
CONFIG_IDF_EXPERIMENTAL_FEATURES=y
# Deprecated options for backward compatibility
# CONFIG_APP_BUILD_TYPE_ELF_RAM is not set
# CONFIG_NO_BLOBS is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_NONE is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_ERROR is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_WARN is not set
CONFIG_LOG_BOOTLOADER_LEVEL_INFO=y
# CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG is not set
# CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE is not set
CONFIG_LOG_BOOTLOADER_LEVEL=3
# CONFIG_APP_ROLLBACK_ENABLE is not set
# CONFIG_FLASH_ENCRYPTION_ENABLED is not set
CONFIG_FLASHMODE_QIO=y
# CONFIG_FLASHMODE_QOUT is not set
# CONFIG_FLASHMODE_DIO is not set
# CONFIG_FLASHMODE_DOUT is not set
CONFIG_MONITOR_BAUD=115200
# CONFIG_OPTIMIZATION_LEVEL_DEBUG is not set
# CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG is not set
# CONFIG_COMPILER_OPTIMIZATION_DEFAULT is not set
# CONFIG_OPTIMIZATION_LEVEL_RELEASE is not set
# CONFIG_COMPILER_OPTIMIZATION_LEVEL_RELEASE is not set
CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED=y
# CONFIG_OPTIMIZATION_ASSERTIONS_SILENT is not set
# CONFIG_OPTIMIZATION_ASSERTIONS_DISABLED is not set
CONFIG_OPTIMIZATION_ASSERTION_LEVEL=2
# CONFIG_CXX_EXCEPTIONS is not set
CONFIG_STACK_CHECK_NONE=y
# CONFIG_STACK_CHECK_NORM is not set
# CONFIG_STACK_CHECK_STRONG is not set
# CONFIG_STACK_CHECK_ALL is not set
# CONFIG_WARN_WRITE_STRINGS is not set
# CONFIG_ESP32_APPTRACE_DEST_TRAX is not set
CONFIG_ESP32_APPTRACE_DEST_NONE=y
CONFIG_ESP32_APPTRACE_LOCK_ENABLE=y
# CONFIG_MCPWM_ISR_IN_IRAM is not set
# CONFIG_EVENT_LOOP_PROFILING is not set
CONFIG_POST_EVENTS_FROM_ISR=y
CONFIG_POST_EVENTS_FROM_IRAM_ISR=y
CONFIG_GDBSTUB_SUPPORT_TASKS=y
CONFIG_GDBSTUB_MAX_TASKS=32
# CONFIG_OTA_ALLOW_HTTP is not set
CONFIG_SYSTEM_EVENT_QUEUE_SIZE=32
CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE=2304
CONFIG_MAIN_TASK_STACK_SIZE=12288
CONFIG_CONSOLE_UART_DEFAULT=y
# CONFIG_CONSOLE_UART_CUSTOM is not set
# CONFIG_CONSOLE_UART_NONE is not set
# CONFIG_ESP_CONSOLE_UART_NONE is not set
CONFIG_CONSOLE_UART=y
CONFIG_CONSOLE_UART_NUM=0
CONFIG_CONSOLE_UART_BAUDRATE=115200
CONFIG_INT_WDT=y
CONFIG_INT_WDT_TIMEOUT_MS=300
CONFIG_INT_WDT_CHECK_CPU1=y
CONFIG_TASK_WDT=y
CONFIG_ESP_TASK_WDT=y
# CONFIG_TASK_WDT_PANIC is not set
CONFIG_TASK_WDT_TIMEOUT_S=5
CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0=y
CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1=y
# CONFIG_ESP32_DEBUG_STUBS_ENABLE is not set
CONFIG_BROWNOUT_DET=y
CONFIG_BROWNOUT_DET_LVL_SEL_7=y
# CONFIG_BROWNOUT_DET_LVL_SEL_6 is not set
# CONFIG_BROWNOUT_DET_LVL_SEL_5 is not set
CONFIG_BROWNOUT_DET_LVL=7
CONFIG_IPC_TASK_STACK_SIZE=1024
CONFIG_TIMER_TASK_STACK_SIZE=3584
# CONFIG_ESP32_ENABLE_COREDUMP_TO_FLASH is not set
# CONFIG_ESP32_ENABLE_COREDUMP_TO_UART is not set
CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE=y
CONFIG_TIMER_TASK_PRIORITY=1
CONFIG_TIMER_TASK_STACK_DEPTH=2048
CONFIG_TIMER_QUEUE_LENGTH=10
# CONFIG_ENABLE_STATIC_TASK_CLEAN_UP_HOOK is not set
CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY=y
# CONFIG_HAL_ASSERTION_SILIENT is not set
# CONFIG_L2_TO_L3_COPY is not set
CONFIG_ESP_GRATUITOUS_ARP=y
CONFIG_GARP_TMR_INTERVAL=60
CONFIG_TCPIP_RECVMBOX_SIZE=32
CONFIG_TCP_MAXRTX=12
CONFIG_TCP_SYNMAXRTX=12
CONFIG_TCP_MSS=1440
CONFIG_TCP_MSL=60000
CONFIG_TCP_SND_BUF_DEFAULT=5760
CONFIG_TCP_WND_DEFAULT=5760
CONFIG_TCP_RECVMBOX_SIZE=6
CONFIG_TCP_QUEUE_OOSEQ=y
CONFIG_TCP_OVERSIZE_MSS=y
# CONFIG_TCP_OVERSIZE_QUARTER_MSS is not set
# CONFIG_TCP_OVERSIZE_DISABLE is not set
CONFIG_UDP_RECVMBOX_SIZE=6
CONFIG_TCPIP_TASK_STACK_SIZE=3072
CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY=y
# CONFIG_TCPIP_TASK_AFFINITY_CPU0 is not set
# CONFIG_TCPIP_TASK_AFFINITY_CPU1 is not set
CONFIG_TCPIP_TASK_AFFINITY=0x7FFFFFFF
# CONFIG_PPP_SUPPORT is not set
CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT=5
CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072
CONFIG_ESP32_PTHREAD_STACK_MIN=768
CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY=y
# CONFIG_ESP32_DEFAULT_PTHREAD_CORE_0 is not set
# CONFIG_ESP32_DEFAULT_PTHREAD_CORE_1 is not set
CONFIG_ESP32_PTHREAD_TASK_CORE_DEFAULT=-1
CONFIG_ESP32_PTHREAD_TASK_NAME_DEFAULT="pthread"
CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS=y
# CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_FAILS is not set
# CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED is not set
CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT=y
CONFIG_SUPPORT_TERMIOS=y
CONFIG_SEMIHOSTFS_MAX_MOUNT_POINTS=1
# End of deprecated options
|
000haoji/deep-student
| 25,719 |
src/components/KnowledgeBaseManagement.css
|
/* Knowledge Base Management 组件专用样式 */
.knowledge-base-container {
min-height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
position: relative;
overflow-x: hidden;
overflow-y: auto;
transition: all 0.3s ease;
}
.knowledge-base-container.drag-over {
background: linear-gradient(135deg, #4299e1 0%, #3182ce 100%);
box-shadow: inset 0 0 50px rgba(66, 153, 225, 0.3);
}
/* 拖拽覆盖层 */
.kb-drag-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(66, 153, 225, 0.9);
backdrop-filter: blur(10px);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
animation: fadeIn 0.3s ease;
}
.kb-drag-overlay-content {
text-align: center;
color: white;
padding: 3rem;
border-radius: 20px;
background: rgba(255, 255, 255, 0.1);
border: 2px dashed rgba(255, 255, 255, 0.5);
backdrop-filter: blur(20px);
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
}
.kb-drag-icon {
font-size: 4rem;
margin-bottom: 1rem;
animation: bounce 1s infinite;
}
.kb-drag-title {
font-size: 2rem;
font-weight: 700;
margin-bottom: 0.5rem;
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}
.kb-drag-subtitle {
font-size: 1.25rem;
opacity: 0.9;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-10px); }
}
/* 背景装饰效果 */
.knowledge-base-container::before {
content: '';
position: absolute;
top: -40%;
right: -40%;
width: 80%;
height: 80%;
background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 50%, transparent 70%);
border-radius: 50%;
animation: float 20s infinite ease-in-out;
}
.knowledge-base-container::after {
content: '';
position: absolute;
bottom: -40%;
left: -40%;
width: 80%;
height: 80%;
background: radial-gradient(circle, rgba(255, 255, 255, 0.08) 0%, rgba(255, 255, 255, 0.03) 50%, transparent 70%);
border-radius: 50%;
animation: float 25s infinite ease-in-out reverse;
}
@keyframes float {
0%, 100% { transform: translate(0, 0) rotate(0deg); }
33% { transform: translate(30px, -30px) rotate(120deg); }
66% { transform: translate(-20px, 20px) rotate(240deg); }
}
.knowledge-base-content {
position: relative;
z-index: 1;
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
min-height: calc(100vh - 4rem);
display: flex;
flex-direction: column;
}
/* 页面标题区域 */
.kb-header {
text-align: center;
margin-bottom: 3rem;
}
.kb-title-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 80px;
height: 80px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 20px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
margin-bottom: 1.5rem;
transition: transform 0.3s ease;
}
.kb-title-icon:hover {
transform: scale(1.05);
}
.kb-title-icon span {
font-size: 2rem;
}
.kb-title {
font-size: 3rem;
font-weight: 800;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
margin-bottom: 1rem;
}
.kb-subtitle {
font-size: 1.25rem;
color: #ffffff;
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
max-width: 600px;
margin: 0 auto;
line-height: 1.6;
opacity: 0.9;
}
/* 统计卡片 */
.kb-stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 2rem;
margin-bottom: 3rem;
}
.kb-stat-card {
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(20px);
border-radius: 20px;
padding: 2rem;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
transition: all 0.3s ease;
position: relative;
overflow: hidden;
}
.kb-stat-card::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(135deg, transparent 0%, rgba(255, 255, 255, 0.1) 100%);
opacity: 0;
transition: opacity 0.3s ease;
}
.kb-stat-card:hover {
transform: translateY(-8px);
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
}
.kb-stat-card:hover::before {
opacity: 1;
}
.kb-stat-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 1rem;
}
.kb-stat-icon {
width: 60px;
height: 60px;
border-radius: 15px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.5rem;
color: white;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.kb-stat-icon.blue { background: linear-gradient(135deg, #4299e1, #3182ce); }
.kb-stat-icon.green { background: linear-gradient(135deg, #48bb78, #38a169); }
.kb-stat-icon.purple { background: linear-gradient(135deg, #9f7aea, #805ad5); }
.kb-stat-icon.orange { background: linear-gradient(135deg, #ed8936, #dd6b20); }
.kb-stat-value {
font-size: 2.5rem;
font-weight: 800;
color: #2d3748;
margin-bottom: 0.5rem;
}
.kb-stat-label {
font-size: 0.9rem;
color: #4a5568;
font-weight: 500;
}
.kb-stat-progress {
width: 100%;
height: 6px;
background: #e2e8f0;
border-radius: 3px;
margin-top: 1rem;
overflow: hidden;
}
.kb-stat-progress-bar {
height: 100%;
background: linear-gradient(90deg, #4299e1, #3182ce);
border-radius: 3px;
transition: width 1s ease;
}
.kb-stat-status {
display: flex;
align-items: center;
gap: 0.5rem;
margin-top: 0.75rem;
font-size: 0.8rem;
color: #4a5568;
}
.kb-status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
animation: pulse 2s infinite;
}
.kb-status-dot.green { background: #48bb78; }
.kb-status-dot.red { background: #f56565; }
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
/* 上传区域 */
.kb-upload-section {
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(20px);
border-radius: 20px;
padding: 2.5rem;
margin-bottom: 3rem;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
}
.kb-upload-header {
display: flex;
align-items: center;
gap: 1rem;
margin-bottom: 2rem;
}
.kb-upload-icon {
width: 60px;
height: 60px;
background: linear-gradient(135deg, #48bb78, #38a169);
border-radius: 15px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.5rem;
color: white;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.kb-upload-title {
font-size: 1.5rem;
font-weight: 700;
color: #2d3748;
margin-bottom: 0.25rem;
}
.kb-upload-subtitle {
color: #718096;
font-size: 0.9rem;
}
.kb-format-tags {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
margin-bottom: 2rem;
}
.kb-format-tag {
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 1rem;
border-radius: 25px;
font-size: 0.85rem;
font-weight: 600;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
cursor: pointer;
}
.kb-format-tag:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.kb-format-tag.txt { background: linear-gradient(135deg, #e3f2fd, #bbdefb); color: #1565c0; }
.kb-format-tag.md { background: linear-gradient(135deg, #e8f5e8, #c8e6c9); color: #2e7d32; }
.kb-format-tag.pdf { background: linear-gradient(135deg, #ffebee, #ffcdd2); color: #c62828; }
.kb-format-tag.docx { background: linear-gradient(135deg, #f3e5f5, #e1bee7); color: #7b1fa2; }
.kb-upload-zone {
border: 3px dashed #cbd5e0;
border-radius: 20px;
padding: 3rem;
text-align: center;
background: linear-gradient(135deg, #f7fafc, #edf2f7);
transition: all 0.3s ease;
cursor: pointer;
position: relative;
overflow: hidden;
}
.kb-upload-zone::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(135deg, rgba(66, 153, 225, 0.1), rgba(129, 140, 248, 0.1));
opacity: 0;
transition: opacity 0.3s ease;
}
.kb-upload-zone:hover {
border-color: #4299e1;
background: linear-gradient(135deg, #ebf8ff, #e6fffa);
transform: scale(1.02);
}
.kb-upload-zone:hover::before {
opacity: 1;
}
.kb-upload-zone-icon {
width: 80px;
height: 80px;
background: linear-gradient(135deg, #4299e1, #3182ce);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 2rem;
color: white;
margin: 0 auto 1.5rem;
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}
.kb-upload-zone:hover .kb-upload-zone-icon {
transform: scale(1.1) rotate(5deg);
}
.kb-upload-zone-title {
font-size: 1.25rem;
font-weight: 600;
color: #2d3748;
margin-bottom: 0.5rem;
}
.kb-upload-zone-subtitle {
color: #718096;
margin-bottom: 1.5rem;
}
.kb-upload-zone-button {
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.75rem 1.5rem;
background: linear-gradient(135deg, #4299e1, #3182ce);
color: white;
border: none;
border-radius: 12px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.kb-upload-zone-button:hover {
transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}
/* 选中文件列表 */
.kb-selected-files {
background: linear-gradient(135deg, #f0fff4, #e6fffa);
border-radius: 20px;
padding: 1.5rem;
margin-top: 2rem;
border: 2px solid #48bb78;
}
.kb-selected-header {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1.5rem;
}
.kb-selected-icon {
width: 32px;
height: 32px;
background: linear-gradient(135deg, #48bb78, #38a169);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 0.9rem;
font-weight: bold;
}
.kb-selected-title {
font-size: 1.1rem;
font-weight: 600;
color: #22543d;
}
.kb-selected-badge {
margin-left: auto;
padding: 0.25rem 0.75rem;
background: #c6f6d5;
color: #22543d;
border-radius: 12px;
font-size: 0.8rem;
font-weight: 600;
}
.kb-file-list {
display: grid;
gap: 1rem;
}
.kb-file-item {
background: rgba(255, 255, 255, 0.8);
backdrop-filter: blur(10px);
border-radius: 12px;
padding: 1rem;
display: flex;
align-items: center;
gap: 1rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
border: 1px solid rgba(255, 255, 255, 0.3);
transition: all 0.3s ease;
}
.kb-file-item:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.kb-file-icon {
width: 48px;
height: 48px;
background: linear-gradient(135deg, #4299e1, #3182ce);
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.25rem;
color: white;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.kb-file-info {
flex: 1;
min-width: 0;
}
.kb-file-name {
font-weight: 600;
color: #2d3748;
margin-bottom: 0.25rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.kb-file-meta {
display: flex;
gap: 0.75rem;
}
.kb-file-size {
font-size: 0.8rem;
color: #718096;
background: #e2e8f0;
padding: 0.25rem 0.5rem;
border-radius: 6px;
}
.kb-file-status {
font-size: 0.8rem;
color: #22543d;
background: #c6f6d5;
padding: 0.25rem 0.5rem;
border-radius: 6px;
font-weight: 600;
}
.kb-file-check {
width: 32px;
height: 32px;
background: #c6f6d5;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: #22543d;
font-size: 0.9rem;
font-weight: bold;
}
/* 操作按钮 */
.kb-action-buttons {
display: flex;
flex-wrap: wrap;
gap: 1rem;
margin-top: 2rem;
}
.kb-button {
display: inline-flex;
align-items: center;
gap: 0.75rem;
padding: 1rem 2rem;
border: none;
border-radius: 12px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
font-size: 1rem;
position: relative;
overflow: hidden;
}
.kb-button::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(135deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.1));
opacity: 0;
transition: opacity 0.3s ease;
}
.kb-button:hover::before {
opacity: 1;
}
.kb-button:hover {
transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}
.kb-button:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none !important;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important;
}
.kb-button.primary {
background: linear-gradient(135deg, #4299e1, #3182ce);
color: white;
}
.kb-button.secondary {
background: linear-gradient(135deg, #718096, #4a5568);
color: white;
}
.kb-button.danger {
background: linear-gradient(135deg, #f56565, #e53e3e);
color: white;
}
/* 文档列表 */
.kb-documents-section {
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(20px);
border-radius: 20px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
overflow-x: auto;
overflow-y: visible;
}
.kb-documents-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 2rem 2.5rem;
border-bottom: 1px solid #e2e8f0;
}
.kb-documents-title-group {
display: flex;
align-items: center;
gap: 1rem;
}
.kb-documents-icon {
width: 60px;
height: 60px;
background: linear-gradient(135deg, #9f7aea, #805ad5);
border-radius: 15px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.5rem;
color: white;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.kb-documents-title {
font-size: 1.5rem;
font-weight: 700;
color: #2d3748;
margin-bottom: 0.25rem;
}
.kb-documents-subtitle {
color: #718096;
font-size: 0.9rem;
}
/* 加载状态 */
.kb-loading {
text-align: center;
padding: 4rem;
}
.kb-loading-icon {
width: 80px;
height: 80px;
margin: 0 auto 2rem;
position: relative;
}
.kb-loading-spinner {
width: 100%;
height: 100%;
border: 4px solid #e2e8f0;
border-top: 4px solid #4299e1;
border-radius: 50%;
animation: spin 1s linear infinite;
}
.kb-loading-inner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 32px;
height: 32px;
background: linear-gradient(135deg, #4299e1, #3182ce);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 1rem;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.kb-loading-title {
font-size: 1.5rem;
font-weight: 600;
color: #2d3748;
margin-bottom: 0.5rem;
}
.kb-loading-subtitle {
color: #718096;
margin-bottom: 1.5rem;
}
.kb-loading-dots {
display: flex;
justify-content: center;
gap: 0.5rem;
}
.kb-loading-dot {
width: 8px;
height: 8px;
border-radius: 50%;
animation: bounce 1.4s infinite ease-in-out both;
}
.kb-loading-dot:nth-child(1) { background: #4299e1; animation-delay: -0.32s; }
.kb-loading-dot:nth-child(2) { background: #9f7aea; animation-delay: -0.16s; }
.kb-loading-dot:nth-child(3) { background: #f56565; }
@keyframes bounce {
0%, 80%, 100% {
transform: scale(0);
} 40% {
transform: scale(1);
}
}
/* 空状态 */
.kb-empty {
text-align: center;
padding: 5rem 2rem;
}
.kb-empty-icon {
width: 120px;
height: 120px;
margin: 0 auto 2rem;
position: relative;
}
.kb-empty-circle {
width: 100%;
height: 100%;
background: linear-gradient(135deg, #e6fffa, #b2f5ea);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
animation: pulse-soft 3s infinite ease-in-out;
}
.kb-empty-circle span {
font-size: 3rem;
animation: bounce-soft 2s infinite ease-in-out;
}
@keyframes pulse-soft {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.05); }
}
@keyframes bounce-soft {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-10px); }
}
.kb-empty-title {
font-size: 2rem;
font-weight: 700;
color: #2d3748;
margin-bottom: 1rem;
}
.kb-empty-subtitle {
font-size: 1.25rem;
color: #718096;
margin-bottom: 2rem;
max-width: 600px;
margin-left: auto;
margin-right: auto;
line-height: 1.6;
}
.kb-empty-formats {
display: flex;
flex-wrap: wrap;
gap: 1rem;
justify-content: center;
margin-bottom: 2rem;
}
.kb-empty-cta {
display: inline-flex;
align-items: center;
gap: 0.75rem;
padding: 1rem 2rem;
background: linear-gradient(135deg, #4299e1, #3182ce);
color: white;
text-decoration: none;
border-radius: 12px;
font-weight: 600;
font-size: 1.1rem;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}
.kb-empty-cta:hover {
transform: translateY(-2px);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.15);
}
.kb-empty-cta span:first-child {
font-size: 1.25rem;
animation: bounce-soft 2s infinite ease-in-out;
}
/* 文档表格容器 */
.kb-table-container {
max-height: 60vh;
overflow-y: auto;
overflow-x: auto;
border-radius: 8px;
background: #ffffff;
}
.kb-table-container::-webkit-scrollbar {
width: 8px;
height: 8px;
}
.kb-table-container::-webkit-scrollbar-track {
background: #f8f9fa;
border-radius: 4px;
}
.kb-table-container::-webkit-scrollbar-thumb {
background: #cbd5e1;
border-radius: 4px;
}
.kb-table-container::-webkit-scrollbar-thumb:hover {
background: #94a3b8;
}
.kb-table-container::-webkit-scrollbar-corner {
background: #f8f9fa;
}
/* 文档表格 */
.kb-table {
width: 100%;
border-collapse: collapse;
min-width: 800px;
}
.kb-table thead {
background: linear-gradient(135deg, #f7fafc, #edf2f7);
position: sticky;
top: 0;
z-index: 10;
}
.kb-table th {
padding: 1.5rem;
text-align: left;
font-weight: 600;
color: #4a5568;
font-size: 0.9rem;
text-transform: uppercase;
letter-spacing: 0.05em;
border-bottom: 2px solid #e2e8f0;
}
.kb-table th:first-child { text-align: left; }
.kb-table th:not(:first-child) { text-align: center; }
.kb-table tbody tr {
border-bottom: 1px solid #e2e8f0;
transition: all 0.3s ease;
}
.kb-table tbody tr:hover {
background: linear-gradient(135deg, #f7fafc, #edf2f7);
transform: scale(1.01);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.kb-table td {
padding: 2rem 1.5rem;
vertical-align: middle;
}
.kb-doc-cell {
display: flex;
align-items: center;
gap: 1.5rem;
}
.kb-doc-icon-wrapper {
position: relative;
}
.kb-doc-icon {
width: 64px;
height: 64px;
background: linear-gradient(135deg, #4299e1, #3182ce);
border-radius: 15px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.5rem;
color: white;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
transition: transform 0.3s ease;
}
.kb-table tbody tr:hover .kb-doc-icon {
transform: scale(1.1) rotate(5deg);
}
.kb-doc-number {
position: absolute;
top: -4px;
right: -4px;
width: 20px;
height: 20px;
background: linear-gradient(135deg, #48bb78, #38a169);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 0.7rem;
font-weight: bold;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.kb-doc-info {
flex: 1;
min-width: 0;
}
.kb-doc-name {
font-size: 1.1rem;
font-weight: 600;
color: #2d3748;
margin-bottom: 0.5rem;
transition: color 0.3s ease;
}
.kb-table tbody tr:hover .kb-doc-name {
color: #4299e1;
}
.kb-doc-meta {
display: flex;
gap: 0.75rem;
}
.kb-doc-id {
font-size: 0.8rem;
color: #718096;
background: #e2e8f0;
padding: 0.25rem 0.5rem;
border-radius: 6px;
font-family: monospace;
}
.kb-doc-status {
font-size: 0.8rem;
color: #22543d;
background: #c6f6d5;
padding: 0.25rem 0.5rem;
border-radius: 6px;
font-weight: 600;
}
.kb-cell-center {
text-align: center;
}
.kb-file-size-display {
font-size: 1.1rem;
font-weight: 600;
color: #2d3748;
margin-bottom: 0.25rem;
}
.kb-file-size-label {
font-size: 0.8rem;
color: #718096;
}
.kb-chunks-badge {
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 1rem;
background: linear-gradient(135deg, #e6fffa, #b2f5ea);
color: #234e52;
border-radius: 20px;
font-weight: 600;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
transition: all 0.3s ease;
}
.kb-table tbody tr:hover .kb-chunks-badge {
background: linear-gradient(135deg, #b2f5ea, #9ae6b4);
transform: scale(1.05);
}
.kb-chunks-dot {
width: 8px;
height: 8px;
background: #48bb78;
border-radius: 50%;
animation: pulse 2s infinite;
}
.kb-date-display {
font-weight: 600;
color: #4a5568;
margin-bottom: 0.25rem;
}
.kb-date-label {
font-size: 0.8rem;
color: #718096;
}
.kb-delete-button {
position: relative;
padding: 0.75rem 1rem;
background: linear-gradient(135deg, #fed7d7, #feb2b2);
color: #c53030;
border: 2px solid #fed7d7;
border-radius: 12px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
overflow: hidden;
}
.kb-delete-button::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(135deg, #f56565, #e53e3e);
opacity: 0;
transition: opacity 0.3s ease;
}
.kb-delete-button:hover {
color: white;
border-color: #f56565;
transform: scale(1.05);
}
.kb-delete-button:hover::before {
opacity: 1;
}
.kb-delete-content {
position: relative;
z-index: 1;
display: flex;
align-items: center;
gap: 0.5rem;
}
.kb-delete-content span:first-child {
font-size: 1.1rem;
transition: transform 0.3s ease;
}
.kb-delete-button:hover .kb-delete-content span:first-child {
animation: bounce-soft 0.6s ease-in-out;
}
/* 处理状态显示 */
.kb-processing-status {
margin-top: 1rem;
padding: 1.5rem;
border-radius: 15px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
border: 2px solid;
}
.kb-processing-status.pending {
background: linear-gradient(135deg, #fef5e7, #fed7aa);
border-color: #f6ad55;
color: #744210;
}
.kb-processing-status.reading {
background: linear-gradient(135deg, #e6fffa, #b2f5ea);
border-color: #4299e1;
color: #1e4a8c;
}
.kb-processing-status.completed {
background: linear-gradient(135deg, #f0fff4, #c6f6d5);
border-color: #48bb78;
color: #22543d;
}
.kb-processing-status.failed {
background: linear-gradient(135deg, #fed7d7, #feb2b2);
border-color: #f56565;
color: #c53030;
}
.kb-processing-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 1rem;
}
.kb-processing-title {
font-weight: 600;
font-size: 0.9rem;
}
.kb-processing-percentage {
font-weight: 600;
font-size: 0.9rem;
background: rgba(255, 255, 255, 0.5);
padding: 0.25rem 0.75rem;
border-radius: 20px;
}
.kb-processing-bar {
width: 100%;
height: 8px;
background: rgba(255, 255, 255, 0.3);
border-radius: 4px;
overflow: hidden;
margin-bottom: 0.75rem;
}
.kb-processing-progress {
height: 100%;
background: linear-gradient(90deg, #4299e1, #3182ce);
border-radius: 4px;
transition: width 0.5s ease;
box-shadow: 0 0 8px rgba(66, 153, 225, 0.4);
}
.kb-processing-chunks {
font-size: 0.8rem;
font-weight: 600;
background: rgba(255, 255, 255, 0.4);
padding: 0.5rem 0.75rem;
border-radius: 12px;
display: inline-block;
}
.kb-chunks-info {
margin-bottom: 0.5rem;
}
.kb-chunks-progress {
height: 6px;
background: rgba(255, 255, 255, 0.3);
border-radius: 3px;
overflow: hidden;
}
.kb-chunks-progress-bar {
height: 100%;
background: linear-gradient(90deg, #4299e1, #3182ce);
border-radius: 3px;
transition: width 0.3s ease;
box-shadow: 0 0 8px rgba(66, 153, 225, 0.6);
}
/* 知识库滚动条美化 */
.knowledge-base-container::-webkit-scrollbar {
width: 8px;
}
.knowledge-base-container::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.1);
border-radius: 4px;
}
.knowledge-base-container::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 4px;
transition: background 0.3s ease;
}
.knowledge-base-container::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.5);
}
.kb-documents-section::-webkit-scrollbar {
height: 6px;
}
.kb-documents-section::-webkit-scrollbar-track {
background: #f1f5f9;
border-radius: 3px;
}
.kb-documents-section::-webkit-scrollbar-thumb {
background: #cbd5e1;
border-radius: 3px;
transition: background 0.3s ease;
}
.kb-documents-section::-webkit-scrollbar-thumb:hover {
background: #94a3b8;
}
/* 响应式设计 */
@media (max-width: 768px) {
.knowledge-base-content {
padding: 1rem;
min-height: calc(100vh - 2rem);
}
.kb-title {
font-size: 2rem;
}
.kb-stats-grid {
grid-template-columns: 1fr;
gap: 1rem;
}
.kb-stat-card,
.kb-upload-section,
.kb-documents-section {
padding: 1.5rem;
}
.kb-action-buttons {
flex-direction: column;
}
.kb-button {
justify-content: center;
}
.kb-table-container {
max-height: 50vh;
}
.kb-table {
font-size: 0.9rem;
min-width: 600px;
}
.kb-table th,
.kb-table td {
padding: 1rem 0.75rem;
}
.kb-doc-icon {
width: 48px;
height: 48px;
font-size: 1.25rem;
}
.kb-doc-cell {
gap: 1rem;
}
}
@media (max-width: 480px) {
.knowledge-base-content {
padding: 0.75rem;
min-height: calc(100vh - 1.5rem);
}
.kb-title {
font-size: 1.5rem;
}
.kb-subtitle {
font-size: 1rem;
}
.kb-upload-zone {
padding: 2rem 1rem;
}
.kb-format-tags {
justify-content: center;
}
.kb-table-container {
max-height: 45vh;
}
.kb-table {
min-width: 500px;
font-size: 0.8rem;
}
.kb-documents-header {
flex-direction: column;
gap: 1rem;
text-align: center;
}
}
|
0015/StickiNote
| 4,186 |
main/NVSManager.cpp
|
#include "NVSManager.hpp"
#include "esp_log.h"
#include "esp_random.h"
#include <cstdlib>
#include <cstdio>
std::string NVSManager::generateUUID() {
char uuid[9];
sprintf(uuid, "%08X", esp_random());
ESP_LOGI("NVS", "ID: %s", uuid);
return std::string(uuid);
}
void NVSManager::init() {
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
nvs_flash_erase();
nvs_flash_init();
}
}
void NVSManager::updateSinglePostIt(const PostItData& postIt) {
if (postIt.id.empty()) return;
std::vector<PostItData> postIts = loadPostIts();
bool found = false;
for (auto& p : postIts) {
if (p.id == postIt.id) {
p = postIt;
found = true;
break;
}
}
if (!found) {
ESP_LOGW("NVS", "Post-it with ID %s not found, adding a new one.", postIt.id.c_str());
postIts.push_back(postIt);
}
cJSON *root = cJSON_CreateArray();
for (const auto& p : postIts) {
cJSON *postit_obj = cJSON_CreateObject();
cJSON_AddStringToObject(postit_obj, "id", p.id.c_str());
cJSON_AddNumberToObject(postit_obj, "x", p.x);
cJSON_AddNumberToObject(postit_obj, "y", p.y);
cJSON_AddNumberToObject(postit_obj, "width", p.width);
cJSON_AddNumberToObject(postit_obj, "height", p.height);
cJSON_AddStringToObject(postit_obj, "text", p.text.c_str());
cJSON_AddItemToArray(root, postit_obj);
}
char *json_str = cJSON_Print(root);
ESP_LOGI("NVS", "Updated JSON: %s", json_str);
cJSON_Delete(root);
nvs_handle_t nvs_handle;
esp_err_t err = nvs_open("storage", NVS_READWRITE, &nvs_handle);
if (err != ESP_OK) {
ESP_LOGE("NVS", "Failed to open NVS for writing!");
free(json_str);
return;
}
err = nvs_set_str(nvs_handle, "postits", json_str);
if (err == ESP_OK) {
ESP_LOGI("NVS", "Post-its successfully updated in NVS.");
} else {
ESP_LOGE("NVS", "Failed to write Post-its to NVS.");
}
err = nvs_commit(nvs_handle);
if (err != ESP_OK) {
ESP_LOGE("NVS", "Failed to commit data to NVS!");
} else {
ESP_LOGI("NVS", "NVS commit successful.");
}
nvs_close(nvs_handle);
free(json_str);
}
std::vector<PostItData> NVSManager::loadPostIts() {
std::vector<PostItData> postIts;
nvs_handle_t nvs_handle;
esp_err_t err = nvs_open("storage", NVS_READONLY, &nvs_handle);
if (err != ESP_OK) {
ESP_LOGW("NVS", "Failed to open NVS for reading.");
return postIts;
}
size_t required_size = 0;
err = nvs_get_str(nvs_handle, "postits", NULL, &required_size);
if (err != ESP_OK || required_size == 0) {
ESP_LOGW("NVS", "No saved Post-its in NVS.");
nvs_close(nvs_handle);
return postIts;
}
char *json_str = (char*)malloc(required_size);
err = nvs_get_str(nvs_handle, "postits", json_str, &required_size);
nvs_close(nvs_handle);
if (err != ESP_OK) {
ESP_LOGE("NVS", "Failed to read Post-its from NVS.");
free(json_str);
return postIts;
}
ESP_LOGI("NVS", "Loaded JSON from NVS: %s", json_str);
cJSON *root = cJSON_Parse(json_str);
free(json_str);
if (!root) {
ESP_LOGE("NVS", "Failed to parse JSON from NVS.");
return postIts;
}
int count = cJSON_GetArraySize(root);
ESP_LOGI("NVS", "Restoring %d Post-it notes", count);
for (int i = 0; i < count; i++) {
cJSON *postit_obj = cJSON_GetArrayItem(root, i);
if (!postit_obj) continue;
PostItData data;
data.id = cJSON_GetObjectItem(postit_obj, "id")->valuestring;
data.x = cJSON_GetObjectItem(postit_obj, "x")->valueint;
data.y = cJSON_GetObjectItem(postit_obj, "y")->valueint;
data.width = cJSON_GetObjectItem(postit_obj, "width")->valueint;
data.height = cJSON_GetObjectItem(postit_obj, "height")->valueint;
data.text = cJSON_GetObjectItem(postit_obj, "text")->valuestring;
postIts.push_back(data);
}
cJSON_Delete(root);
return postIts;
}
|
0015/StickiNote
| 12,950 |
main/LVGL_WidgetManager.cpp
|
#include "LVGL_WidgetManager.hpp"
#include "esp_log.h"
#include <algorithm>
#include "esp_timer.h"
#define DOUBLE_TAP_TIME 300
#define MAX_POSTITS 10
LV_IMG_DECLARE(icon_resize);
LV_FONT_DECLARE(sticky_font_32)
lv_obj_t *LVGL_WidgetManager::screen_ = nullptr;
lv_obj_t *LVGL_WidgetManager::kb_ = nullptr;
LVGL_WidgetManager *LVGL_WidgetManager::instance = nullptr;
int LVGL_WidgetManager::screen_width_ = 0;
int LVGL_WidgetManager::screen_height_ = 0;
std::vector<lv_obj_t *> LVGL_WidgetManager::widgets_;
LVGL_WidgetManager::LVGL_WidgetManager(lv_obj_t *screen, lv_obj_t *kb)
{
instance = this;
screen_ = screen;
kb_ = kb;
widgets_.reserve(MAX_POSTITS);
printf("LVGL_WidgetManager Initialized - Parent: %p, Keyboard: %p\n", screen_, kb_);
screen_width_ = lv_obj_get_width(lv_screen_active());
screen_height_ = lv_obj_get_height(lv_screen_active());
printf("LVGL_WidgetManager Initialized - screen_width_: %d, screen_height_: %d\n", screen_width_, screen_height_);
static lv_style_t style_fab;
lv_style_init(&style_fab);
lv_style_set_radius(&style_fab, LV_RADIUS_CIRCLE);
lv_style_set_bg_opa(&style_fab, LV_OPA_COVER);
lv_style_set_bg_color(&style_fab, lv_palette_main(LV_PALETTE_GREY));
lv_style_set_shadow_width(&style_fab, 10);
lv_style_set_shadow_color(&style_fab, lv_palette_darken(LV_PALETTE_GREY, 2));
lv_style_set_text_color(&style_fab, lv_color_white());
lv_obj_t *fab_btn = lv_btn_create(screen_);
lv_obj_set_size(fab_btn, 80, 80);
lv_obj_add_style(fab_btn, &style_fab, LV_PART_MAIN);
lv_obj_align(fab_btn, LV_ALIGN_BOTTOM_RIGHT, 20, 20);
lv_obj_set_style_bg_image_src(fab_btn, LV_SYMBOL_PLUS, 0);
lv_obj_add_event_cb(fab_btn, [](lv_event_t *e)
{
if (instance)
{
ESP_LOGE("LVGL", "fab_btn_event_cb");
instance->createPostIt(20, 20, 300, 300, "", NVSManager::generateUUID());
}
}, LV_EVENT_CLICKED, nullptr);
}
void LVGL_WidgetManager::createPostIt(int x, int y, int width, int height, const char* text, std::string id)
{
if (widgets_.size() >= MAX_POSTITS)
{
ESP_LOGW("LVGL", "Maximum Post-it limit reached (%d). Cannot create more.", MAX_POSTITS);
return;
}
if (!screen_)
{
ESP_LOGE("LVGL", "Error: Parent object is NULL!");
return;
}
if (!kb_)
{
printf("Warning: kb_ is NULL. Creating a default keyboard.\n");
return;
}
static lv_style_t style_postit;
lv_style_init(&style_postit);
lv_style_set_bg_opa(&style_postit, LV_OPA_COVER);
lv_style_set_bg_color(&style_postit, lv_color_make(230, 230, 230));
lv_style_set_border_color(&style_postit, lv_color_black());
lv_style_set_border_width(&style_postit, 2);
lv_style_set_radius(&style_postit, 5);
lv_obj_t *postit = lv_obj_create(screen_);
if (!postit)
{
ESP_LOGE("LVGL", "Error: Failed to create Post-it object!");
return;
}
lv_obj_add_style(postit, &style_postit, LV_PART_MAIN);
lv_obj_clear_flag(postit, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_pos(postit, x, y);
lv_obj_set_size(postit, width, height);
static lv_style_t style_textarea;
lv_style_init(&style_textarea);
lv_style_set_bg_opa(&style_textarea, LV_OPA_COVER);
lv_style_set_bg_color(&style_textarea, lv_color_white());
lv_style_set_border_color(&style_textarea, lv_color_black());
lv_style_set_border_width(&style_textarea, 1);
lv_style_set_text_color(&style_textarea, lv_color_black());
lv_style_set_pad_all(&style_textarea, 5);
lv_style_set_text_font(&style_textarea, &sticky_font_32);
lv_obj_t *textarea = lv_textarea_create(postit);
lv_obj_set_size(textarea, width - 20, height - 30);
lv_obj_align(textarea, LV_ALIGN_TOP_LEFT, 10, 10);
lv_obj_add_style(textarea, &style_textarea, LV_PART_MAIN);
lv_obj_clear_flag(textarea, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_event_cb(textarea, textarea_event_handler, LV_EVENT_PRESSING, nullptr);
lv_obj_add_event_cb(textarea, textarea_event_handler, LV_EVENT_RELEASED, nullptr);
lv_obj_add_event_cb(textarea, textarea_kb_event_handler, LV_EVENT_CLICKED, kb_);
lv_obj_add_event_cb(textarea, textarea_kb_event_handler, LV_EVENT_DEFOCUSED, kb_);
lv_keyboard_set_textarea(kb_, textarea);
if (text == nullptr || text[0] == '\0') {
lv_textarea_set_placeholder_text(textarea, "Enter text here...");
}else{
lv_textarea_set_text(textarea, text);
lv_textarea_set_cursor_pos(textarea, 0);
}
lv_obj_t *close_btn = lv_btn_create(postit);
lv_obj_set_size(close_btn, 30, 30);
lv_obj_align(close_btn, LV_ALIGN_TOP_RIGHT, 20, -20);
lv_obj_set_style_bg_color(close_btn, lv_palette_main(LV_PALETTE_RED), LV_PART_MAIN);
lv_obj_t *close_label = lv_label_create(close_btn);
lv_label_set_text(close_label, "X");
lv_obj_center(close_label);
lv_obj_add_event_cb(close_btn, [](lv_event_t *e)
{
lv_obj_t* btn = (lv_obj_t*)lv_event_get_target(e);
lv_obj_t* postIt = (lv_obj_t*)lv_obj_get_parent(btn);
LVGL_WidgetManager::instance->removePostIt(postIt); }, LV_EVENT_CLICKED, nullptr);
lv_obj_t *resize_btn = lv_button_create(postit);
lv_obj_set_size(resize_btn, 40, 40);
lv_obj_align(resize_btn, LV_ALIGN_BOTTOM_RIGHT, 20, 20);
lv_obj_set_style_bg_opa(resize_btn, LV_OPA_TRANSP, LV_PART_MAIN);
lv_obj_set_style_border_color(resize_btn, lv_palette_main(LV_PALETTE_GREY), LV_PART_MAIN);
lv_obj_set_style_border_width(resize_btn, 2, LV_PART_MAIN);
lv_obj_t *resize_icon = lv_img_create(resize_btn);
lv_img_set_src(resize_icon, &icon_resize);
lv_obj_center(resize_icon);
lv_obj_add_event_cb(resize_btn, drag_event_handler, LV_EVENT_PRESSING, textarea);
lv_obj_add_event_cb(resize_btn, drag_event_handler, LV_EVENT_RELEASED, textarea);
lv_obj_set_user_data(postit, (void *)new std::string(id));
widgets_.push_back(postit);
ESP_LOGE("LVGL", "Post-it created. Total count: %d\n", (int)widgets_.size());
PostItData postItData = {id, x, y, width, height, text};
NVSManager::updateSinglePostIt(postItData);
}
void LVGL_WidgetManager::removePostIt(lv_obj_t *postit)
{
if (!postit) return;
std::string *id_ptr = static_cast<std::string *>(lv_obj_get_user_data(postit));
if (!id_ptr) {
ESP_LOGE("LVGL", "Failed to get Post-it ID for deletion.");
return;
}
std::string postItID = *id_ptr;
delete id_ptr;
lv_obj_del(postit);
auto it = std::find(widgets_.begin(), widgets_.end(), postit);
if (it != widgets_.end()) {
widgets_.erase(it);
}
NVSManager::removePostItFromNVS(postItID);
ESP_LOGI("LVGL", "Post-it removed successfully. ID: %s", postItID.c_str());
}
void LVGL_WidgetManager::deleteAllWidgets()
{
for (auto widget : widgets_)
{
lv_obj_del(widget);
}
widgets_.clear();
}
int LVGL_WidgetManager::getWidgetCount() const
{
return widgets_.size();
}
void LVGL_WidgetManager::btn_event_cb(lv_event_t *e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t *btn = (lv_obj_t *)lv_event_get_target(e);
if (code == LV_EVENT_CLICKED)
{
static uint8_t cnt = 0;
cnt++;
/*Get the first child of the button which is the label and change its text*/
lv_obj_t *label = lv_obj_get_child(btn, 0);
lv_label_set_text_fmt(label, "Button: %d", cnt);
}
}
void LVGL_WidgetManager::drag_event_handler(lv_event_t *e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t *obj = (lv_obj_t *)lv_event_get_target(e);
lv_obj_t *postit = (lv_obj_t *)lv_obj_get_parent(obj);
if (postit == NULL) return;
if (code == LV_EVENT_RELEASED) {
ESP_LOGI("LVGL", "Post-it resize finalized and saved.");
instance->saveSinglePostItToNVS(postit);
return;
}
lv_indev_t *indev = lv_indev_active();
if (indev == NULL) return;
lv_point_t vect;
lv_indev_get_vect(indev, &vect);
if (vect.x == 0 && vect.y == 0) return;
lv_obj_move_foreground(postit);
int32_t x = lv_obj_get_width(postit) + vect.x;
int32_t y = lv_obj_get_height(postit) + vect.y;
lv_obj_set_size(postit, x, y);
lv_obj_t *textarea = (lv_obj_t *)lv_event_get_user_data(e);
if (textarea == NULL) return;
x = lv_obj_get_width(textarea) + vect.x;
y = lv_obj_get_height(textarea) + vect.y;
lv_obj_set_size(textarea, x, y);
}
void LVGL_WidgetManager::textarea_event_handler(lv_event_t *e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t *textarea = (lv_obj_t *)lv_event_get_target(e);
lv_obj_t *postit = (lv_obj_t *)lv_obj_get_parent(textarea);
if (!postit || !screen_) return;
lv_obj_move_foreground(postit);
if (code == LV_EVENT_PRESSING){
lv_indev_t *indev = lv_indev_active();
if (indev == NULL)
return;
lv_point_t vect;
lv_indev_get_vect(indev, &vect);
int32_t x = lv_obj_get_x_aligned(postit) + vect.x;
int32_t y = lv_obj_get_y_aligned(postit) + vect.y;
lv_obj_set_pos(postit, x, y);
}else if (code == LV_EVENT_RELEASED){
instance->saveSinglePostItToNVS(postit);
}
}
void LVGL_WidgetManager::textarea_kb_event_handler(lv_event_t *e) {
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t *textarea = (lv_obj_t *)lv_event_get_target(e);
lv_obj_t *kb = (lv_obj_t *)lv_event_get_user_data(e);
lv_obj_t *postit = (lv_obj_t *)lv_obj_get_parent(textarea);
if (!postit || !screen_)
return;
int screen_mid = screen_height_ / 2;
int postit_y = lv_obj_get_y_aligned(postit);
int kb_height = screen_height_ / 3;
static int original_screen_y = 0;
static int64_t last_tap_time = 0;
int64_t current_time = esp_timer_get_time() / 1000;
if (code == LV_EVENT_CLICKED) {
if (current_time - last_tap_time < DOUBLE_TAP_TIME) {
ESP_LOGI("LVGL", "Double-tap detected! Opening keyboard.");
lv_obj_move_foreground(postit);
lv_keyboard_set_textarea(kb, textarea);
lv_obj_remove_flag(kb, LV_OBJ_FLAG_HIDDEN);
if (postit_y > screen_mid)
{
original_screen_y = lv_obj_get_y_aligned(screen_);
lv_obj_set_y(screen_, original_screen_y - kb_height);
}
}
last_tap_time = current_time;
}else if (code == LV_EVENT_DEFOCUSED)
{
lv_keyboard_set_textarea(kb, NULL);
lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
lv_obj_set_y(screen_, original_screen_y);
instance->saveSinglePostItToNVS(postit);
}
}
void LVGL_WidgetManager::saveSinglePostItToNVS(lv_obj_t *postit)
{
std::string *id_ptr = static_cast<std::string *>(lv_obj_get_user_data(postit));
ESP_LOGI("LVGL", "saveSinglePostItToNVS: Post-it ID: %s", *id_ptr);
if (!id_ptr)
return;
PostItData postIt;
postIt.id = *id_ptr;
postIt.x = lv_obj_get_x(postit);
postIt.y = lv_obj_get_y(postit);
postIt.width = lv_obj_get_width(postit);
postIt.height = lv_obj_get_height(postit);
postIt.text = lv_textarea_get_text(lv_obj_get_child(postit, 0));
NVSManager::updateSinglePostIt(postIt);
}
void LVGL_WidgetManager::loadPostItsFromNVS() {
std::vector<PostItData> postIts = NVSManager::loadPostIts();
if (postIts.empty()) {
ESP_LOGW("LVGL", "No Post-its found in NVS.");
return;
}
for (const auto& postIt : postIts) {
ESP_LOGI("LVGL", "Creating Post-it ID: %s at (%d, %d)", postIt.id.c_str(), postIt.x, postIt.y);
createPostIt(postIt.x, postIt.y, postIt.width, postIt.height, postIt.text.c_str(), postIt.id);
}
}
void NVSManager::removePostItFromNVS(const std::string &postItID) {
std::vector<PostItData> postIts = loadPostIts();
auto it = std::remove_if(postIts.begin(), postIts.end(),
[&](const PostItData &p) { return p.id == postItID; });
if (it == postIts.end()) {
ESP_LOGW("NVS", "Post-it with ID %s not found in NVS.", postItID.c_str());
return;
}
postIts.erase(it, postIts.end());
cJSON *root = cJSON_CreateArray();
for (const auto &p : postIts) {
cJSON *postit_obj = cJSON_CreateObject();
cJSON_AddStringToObject(postit_obj, "id", p.id.c_str());
cJSON_AddNumberToObject(postit_obj, "x", p.x);
cJSON_AddNumberToObject(postit_obj, "y", p.y);
cJSON_AddNumberToObject(postit_obj, "width", p.width);
cJSON_AddNumberToObject(postit_obj, "height", p.height);
cJSON_AddStringToObject(postit_obj, "text", p.text.c_str());
cJSON_AddItemToArray(root, postit_obj);
}
char *json_str = cJSON_Print(root);
cJSON_Delete(root);
nvs_handle_t nvs_handle;
esp_err_t err = nvs_open("storage", NVS_READWRITE, &nvs_handle);
if (err != ESP_OK) {
ESP_LOGE("NVS", "Failed to open NVS for deletion!");
free(json_str);
return;
}
err = nvs_set_str(nvs_handle, "postits", json_str);
if (err == ESP_OK) {
ESP_LOGI("NVS", "Post-it successfully deleted from NVS.");
} else {
ESP_LOGE("NVS", "Failed to update NVS after deletion.");
}
err = nvs_commit(nvs_handle);
if (err != ESP_OK) {
ESP_LOGE("NVS", "Failed to commit NVS after deletion!");
} else {
ESP_LOGI("NVS", "NVS commit successful after deletion.");
}
nvs_close(nvs_handle);
free(json_str);
}
|
0000cd/wolf-set
| 1,917 |
content/posts/about.md
|
---
author: 狼
title: 关于狼集
date: 2024-04-04
draft: false
---
- [这是开源项目,你也可以快速创建**属于你自己的**网址导航。](https://github.com/0000cd/wolf-set)
- [点我访问【**首页**】,浏览共 {{< total >}} 个有趣网址导航,和 {{< total "开源" >}} 个开源项目!](/)
## 狼集 Wolf Set
[](https://sonarcloud.io/summary/new_code?id=0000cd_wolf-set)
宇宙总需要些航天器,“📀各位都好吧?” 让我们路过些互联网小行星。
狼集 Wolf Set,源自“狼牌工作网址导航”。集万千兴趣,再次发现分享互联网的新乐趣!
### 灵感
Wolf(狼)+ Set(集合),音同“狼藉”(杂乱不堪,糟透了!),一个聚合发现与分享的地方。
Wolf Set 则更常见于游戏,是指“狼套装”,一身盔甲或装备,你冒险可靠的家伙。

## 特别感谢
- 静态生成:[Hugo](https://gohugo.io/) - The world’s fastest framework for building websites.
- 网站统计:[Umami](https://umami.is/) - The modern analytics platform
for effortless insights.
- 友链接力:[travellings](https://www.travellings.cn/) - 让流量相互流动,让网络开放起来。
- 内容分发:[Cloudflare](https://www.cloudflare.com/) - 随时随地连接、保护和构建。
- AI 助手:[Gpt-4 & Claude 3.5](https://poe.com/) - 部分代码由 AI 协助。
- JS 库:[Isotope](https://isotope.metafizzy.co/) - Filter & sort magical layouts.
---
## Bluf theme
Bluf 是一款简明扼要的**瀑布流**卡片式 Hugo 主题,非常适合脑暴、作品集、链接导航、等需要**收集分享**的场景。作者是逊狼,部分代码由 GPT-4 与 Claude AI 协助。
### 用法
Bluf 是一款单页 Hugo 主题,这意味着你应该将数据放置在 data 目录中,而**不**是按照传统方式在 content 目录下编写文章。你需要在 data 目录下准备以下三个配置文件(以下示例为 yaml):
- cards.yaml:包含主页瀑布流所有卡片的核心数据。
- navbar.yaml:包括顶部导航栏的标签筛选和外链数据。
- tag_classes.yaml:配置标签和标签样式之间的映射关系。
### 灵感
Blue + Wolf = Bluf
- BLUF (bottom line up front) is the practice of beginning a message with its key information (the "bottom line"). This provides the reader with the most important information first.
- BLUF(先行底行)是一种沟通方式,即在信息的开始部分先给出关键信息(即“底行”)。这样做可以让读者首先了解到最重要的信息。
---
## License
- content 与 data 目录下的内容遵循 **[CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh-hans)** 许可协议共享。
- **Bluf** 主题因集成 **[Isotope](https://isotope.metafizzy.co/license)**,遵循 **GPLv3** 许可协议。
|
0000cd/wolf-set
| 770 |
content/posts/example.md
|
---
author: 逊狼
title: 网红狼求生之路引热议
date: 2024-04-04
draft: false
---
## BLUF (Bottom Line Up Front)
一只青海可可西里的野狼因被游客频繁投喂而成为“网红”,其行为模式从野生狼转变为类似家犬的依赖,引起网友热议与专家担忧。
## 新闻报道
近日,一头青海可可西里的野狼意外成为网络红星。最初,这只野狼因不明原因被狼群赶出,瘦弱到皮包骨。然而,自从今年7月一位过路的网友在国道附近给它投喂了两个蛋黄派后,它的命运戏剧性地改变了。
这只野狼开始每天在公路上讨食,游客们被它那瘦骨嶙峋的模样所吸引,纷纷投喂食物。经过一段时间,这头狼与人类变得亲近,不再仅是被动等待投喂,而是积极迎接过往的车辆,并跟随车辆以示亲昵,以获取食物。
随着时间的流逝,这只曾经饥饿的野狼已经变得身体健壮,甚至开始挑食,偏爱高热量食物如炸鸡和蛋黄派。有趣的是,这只狼被保护站的工作人员转移到戈壁深处,但它又坚持不懈地回到了求食的道路上,并且似乎还吸引了其他狼加入,形成了一种“师徒”关系。
值得注意的是,这只狼由于长时间接触车辆,甚至学会了识别不同的车标。这一现象引发了人们对于动物生存意义的思考,同时也激起了网友们对这只狼的同情与喜爱,有人赞其可爱,有人担心它过度依赖人类投喂,可能会失去捕猎能力,或者过于亲近人类而引发危险。
专家们则警告不应随意投喂野生动物,认为这种行为虽出于善意,但缺乏理性,可能导致不良后果。他们强调死亡是自然界的一部分,而这只狼不需要救助,而是需要人们停止投喂。
尽管这个话题有多种看法,但大家普遍认为应适度投喂,避免影响该狼及其环境的自然秩序。这只网红狼通过独特的适应方式,从濒临死亡的境地中存活下来,也许正是自然选择的一种体现。
|
0000cd/wolf-set
| 3,809 |
themes/bluf/layouts/404.html
|
<!DOCTYPE html>
<html lang="{{ .Site.LanguageCode }}">
<head>
<!--https://github.com/vicevolf/retro-404-->
<!-- https://github.com/gaoryrt/retro-404 -->
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, viewport-fit=cover">
<title>404 Not Found</title>
{{ if .Site.Params.enableUmami }}
<script defer src="{{ .Site.Params.UmamiLink }}" data-website-id="{{ .Site.Params.UmamiID }}"></script>
{{ end }}
<style type="text/css">
html {
overflow: hidden;
font-family: Courier New, serif;
font-style: normal;
font-stretch: normal;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
vertical-align: baseline;
-webkit-tap-highlight-color: transparent;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
text-size-adjust: 100%;
background: #0000cd;
color: #fafafa;
font-size: 16px
}
body,
html {
width: 100%;
height: 100%
}
body {
display: -webkit-flex;
display: flex;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
position: relative;
filter: contrast(150%) brightness(120%) saturate(100%);
image-rendering: pixelated;
overflow: hidden;
}
body::before {
content: "";
position: absolute;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
background: radial-gradient(circle at center, transparent 30%, black 250%);
transform: scale(0.5);
z-index: 1;
pointer-events: none;
}
body a {
color: #fafafa;
text-decoration: none;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box
}
.container {
width: 550px;
text-align: center
}
p {
margin: 30px 0;
text-align: left
}
.title {
background: #ccc;
color: #0000cd;
padding: 2px 6px
}
@keyframes blink {
0%,
49% {
visibility: visible;
}
50%,
100% {
visibility: hidden;
}
}
.blink {
animation: blink 1s step-start infinite;
}
h1,
p {
position: relative;
z-index: 2;
}
</style>
</head>
<body>
<div class="container">
<span class="title">404 Not Found</span>
<p>
░▒▓ A wild <strong>404-PAGE</strong> appeared! ▓▒░<br>
✦<em>Thank you!</em> But the page is in another path~✧<br><br>
* <em>Don't Panic!</em> adventurer. The quest isn't over yet.<br>
* Pro tip: <strong>DONT</strong> Forget to <a href="/feed.xml">Feed the Wolf</a>. ▓▒░<br>
------
</p>
<div><a href="/">✦ Press any key to continue </a><span class="blink">_</span></div>
</div>
</div>
<script type="text/javascript">
window.onload = function () {
document.body.addEventListener('keydown', function () {
window.location.href = '{{ .Site.BaseURL }}';
});
}
</script>
</body>
</html>
|
0000cd/wolf-set
| 19,618 |
themes/bluf/layouts/index.html
|
<!DOCTYPE html>
<html lang="{{ .Site.LanguageCode }}">
<head>
{{ partial "head.html" . }}
<title>{{ .Site.Title }}</title>
<meta name="description" content="{{ .Site.Params.description }}" />
<meta name="keywords" content="{{ range .Site.Params.keywords }}{{ . }},{{ end }}" />
</head>
<body>
<div class="top-bar">
<div class="top-bar-inner">
<div class="top-bar-title">
<a href="{{ .Site.BaseURL }}">
<img class="top-bar-logo" src="/logo.webp" alt="Logo">
</a>
<h1 class="top-title" style="font-size: 1em;">{{ .Site.Params.pagename }}</h1>
<noscript>{{ .Site.Params.alias }}</noscript>
</div>
<nav class="top-bar-nav">
<div class="menu-container">
<button class="theme-toggle" id="themeToggle" title="切换深浅配色">
深色模式
</button>
</div>
{{ with .Site.Data.navbar.external_links }}
<div class="menu-container external_links">
{{ range . }}
<a href="{{ .url | safeURL }}" target="_blank" class="menu-toggle exlink" rel="noopener"
{{ if $.Site.Params.enableUmami }}data-umami-event="NAV-{{ .name }}" {{ end }}>
{{ .name }}
</a>
{{ end }}
</div>
{{ end }}
{{ range .Site.Data.navbar.categories }}
<div class="menu-container categories">
<div class="menu-toggle" id="menu-toggle-{{ .id }}">{{ .name }}</div>
<div class="nav-button filter-button-group" id="filter-group-{{ .id }}">
{{ range .tags }}
<button class="menu-toggle-btn filter-btn" data-filter=".{{ index $.Site.Data.tag_classes . }}">{{ . }}</button>
{{ end }}
</div>
</div>
{{ end }}
{{ with .Site.Data.navbar.hot_tags }}
<div class="hot-tags-container filter-button-group">
{{ range . }}
<button class="hot-tag filter-btn" data-filter=".{{ index $.Site.Data.tag_classes . }}">{{ . }}</button>
{{ end }}
</div>
{{ end }}
</nav>
</div>
</div>
<div class="grid" id="myGrid">
{{ range $index, $element := .Site.Data.cards }}
{{ $title := .title }}
<article id="{{ .title }}">
<div class="grid-item {{ range .tags }}{{ index $.Site.Data.tag_classes . }} {{ end }}
{{- with .hex -}}
{{ partial "getColorCategory" . }}
{{- end -}}">
{{/* 处理链接变量 */}}
{{ $link0 := false }}
{{ with .links }}
{{ if reflect.IsSlice . }}
{{ $link0 = (index . 0).url | safeURL }}
{{ else }}
{{ $link0 = . | safeURL }}
{{ end }}
{{ end }}
{{ $media := .media | default false }}
<div class="grid-item-head">
{{ $extensions := slice "jpg" "jpeg" "png" "gif" "webp" "mp4" "webm" }}
{{ $galleryPath := "assets/gallery" }}
{{ $galleryPublicPath := "gallery" }}
{{ $folders := readDir $galleryPath }}
{{ range $ext := $extensions }}
{{ $imgPath := printf "img/%s.%s" $title $ext }}
{{ if (resources.Get $imgPath) }}
{{ $image := resources.Get $imgPath }}
{{ $displayWidth := 255 }}
{{ $ratio := div (float $image.Height) $image.Width }}
{{ $displayHeight := math.Round (mul $displayWidth $ratio) }}
{{ if $.Site.Params.gallery }}
{{/* 查找是否存在对应的画廊文件夹 */}}
{{ $matchedFolder := false }}
{{ range $folder := $folders }}
{{- if and $folder.IsDir (eq (lower $folder.Name) (lower $title)) -}}
{{ $matchedFolder = true }}
{{ $folderName := $folder.Name }}
<div class="gallery" {{ if $.Site.Params.enableUmami}}data-umami-event="GALLERY-{{ $title }}"{{ end }}>
<a href="{{ $image.RelPermalink | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" id="cover" aria-label="{{ $title }}-cover">
<img class="grid-item-img cover-img"
src="{{ $image.RelPermalink }}"
width="{{ $displayWidth }}"
height="{{ $displayHeight }}"
alt=""
{{ if ge $index 10 }}loading="lazy"{{ end }}
onload="this.classList.add('loaded')"
title="查看画廊">
<div class="cover-line"></div>
</a>
{{ if $media }}
{{ if reflect.IsSlice $media }}
{{ range $media }}
<a href="{{ .url | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" style="display: none;"></a>
{{ end }}
{{ else }}
<a href="{{ $media | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" style="display: none;"></a>
{{ end }}
{{ end }}
{{ $galleryImagesPath := printf "%s/%s" $galleryPath $folderName }}
{{ $galleryImageFiles := readDir $galleryImagesPath }}
{{- range $galleryImage := $galleryImageFiles -}}
{{- $galleryImageExt := path.Ext $galleryImage.Name -}}
{{- $galleryImageExt := strings.TrimPrefix "." $galleryImageExt -}}
{{- if in $extensions $galleryImageExt -}}
{{ $galleryImageResource := resources.Get (printf "gallery/%s/%s" $folderName $galleryImage.Name) }}
{{ $galleryImagePublicPath := printf "%s/%s/%s" $galleryPublicPath $folderName $galleryImage.Name }}
<a href="{{ $galleryImageResource.RelPermalink | safeURL }}"
class="glightbox"
data-gallery="gallery-{{ $title }}"
data-caption="{{ $title }} - {{ $galleryImage.Name }}"
style="display: none;"></a>
{{- end -}}
{{- end -}}
</div>
{{- end -}}
{{ end }}
{{/* 如果没有找到对应的画廊文件夹 */}}
{{ if not $matchedFolder }}
{{ if $media }}
<div class="gallery" {{ if $.Site.Params.enableUmami}}data-umami-event="GALLERY-{{ $title }}"{{ end }}>
<a href="{{ $image.RelPermalink | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" id="cover" aria-label="{{ $title }}-cover">
<img class="grid-item-img cover-img"
src="{{ $image.RelPermalink }}"
width="{{ $displayWidth }}"
height="{{ $displayHeight }}"
alt=""
{{ if ge $index 10 }}loading="lazy"{{ end }}
onload="this.classList.add('loaded')"
title="查看画廊">
<div class="cover-line"></div>
</a>
{{ if reflect.IsSlice $media }}
{{ range $media }}
<a href="{{ .url | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" style="display: none;"></a>
{{ end }}
{{ else }}
<a href="{{ $media | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" style="display: none;"></a>
{{ end }}
</div>
{{ else }}
{{ if $link0 }}
<a href="{{ $link0 }}" target="_blank" rel="noopener" aria-label="{{ $title }}-img"
{{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ $title }}"{{ end }}>
{{ end }}
<img class="grid-item-img"
src="{{ $image.RelPermalink }}"
width="{{ $displayWidth }}"
height="{{ $displayHeight }}"
alt=""
{{ if ge $index 10 }}loading="lazy"{{ end }}
onload="this.classList.add('loaded')">
{{ if $link0 }}
</a>
{{ end }}
{{ end }}
{{ end }}
{{ else }}
{{ if $link0 }}
<a href="{{ $link0 }}" target="_blank" rel="noopener" aria-label="{{ $title }}-img"
{{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ $title }}"{{ end }}>
{{ end }}
<img class="grid-item-img"
src="{{ $image.RelPermalink }}"
width="{{ $displayWidth }}"
height="{{ $displayHeight }}"
alt=""
{{ if ge $index 10 }}loading="lazy"{{ end }}
onload="this.classList.add('loaded')">
{{ if $link0 }}
</a>
{{ end }}
{{ end }}
{{ break }}
{{ end }}
{{ end }}
{{ if $link0 }}
<a href="{{ $link0 }}" target="_blank" rel="noopener"
{{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ $title }}"{{ end }}>
{{ end }}
<header class="grid-item-header">
<h2 class="grid-item-title">{{ .title }}</h2>
<div class="grid-item-color-mark"
style="background:{{ if eq (substr .hex 0 1) "#" }}{{ .hex }}{{ else }}#{{ .hex }}{{ end }};">
</div>
</header>
{{ if $link0 }}
</a>
{{ end }}
</div>
<div class="grid-item-middle">
<div class="grid-item-tags filter-button-group">
{{ range .tags }}
<button class="filter-btn grid-item-tag" data-filter=".{{ index $.Site.Data.tag_classes . }}">{{ . }}</button>
{{ end }}
</div>
<div class="grid-item-date" datetime="{{ .date }}">{{ .date }}</div>
</div>
{{ if $link0 }}
<a href="{{ $link0 }}" target="_blank" rel="noopener"
{{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ $title }}"{{ end }}>
{{ end }}
<section class="grid-item-description">
<p>{{ .description }}</p>
</section>
{{ if $link0 }}
</a>
{{ end }}
{{ if reflect.IsSlice .links }}
{{ if gt (len .links) 1 }}
<nav class="grid-item-links">
{{ range after 1 .links }}
<a href="{{ .url | safeURL }}" target="_blank" rel="noopener"
{{ if $.Site.Params.enableUmami}}data-umami-event="LINK-{{ $title }}-{{ .name }}"{{ end }}>
{{ .name }}
</a>
{{ end }}
</nav>
{{ end }}
{{ end }}
</div>
</article>
{{ end }}
</div>
<button id="reset-filters" onclick="showConfetti()">✕</button>
<script src="/js/isotope.min.js"></script>
{{ $js := resources.Get "js/script.new.js" }}
{{ $secureJS := $js | resources.Minify | resources.Fingerprint }}
<script src="{{ $secureJS.RelPermalink }}" integrity="{{ $secureJS.Data.Integrity }}"></script>
<script>
window.addEventListener('load', function() {
document.getElementById('myGrid').classList.add('show');
});
</script>
{{ if .Site.Params.greetings }}
<div class="greeting-widget">
<div class="avatar">
<img src="/avatar.webp" alt="Avatar">
</div>
<div class="message">
<span id="random-greeting"></span>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const greetings = {{ .Site.Params.greetings }};
const mobileGreetings = {{ .Site.Params.mobileGreetings | default .Site.Params.greetings }};
const widget = document.querySelector('.greeting-widget');
const greetingEl = document.getElementById('random-greeting');
const isMobile = window.matchMedia('(max-width: 768px)').matches;
const greetingArray = isMobile ? mobileGreetings : greetings;
const randomIndex = Math.floor(Math.random() * greetingArray.length);
greetingEl.textContent = greetingArray[randomIndex];
setTimeout(() => {
widget.classList.add('show');
}, 500);
setTimeout(() => {
widget.classList.remove('show');
}, 3500);
});
</script>
{{ partial "footer.html" . }}
{{ end }}
{{ with .Site.Params.confettiEmojis }}
<script>
document.addEventListener('DOMContentLoaded', function() {
const script = document.createElement('script');
script.src = '/js/js-confetti.js';
script.onload = function() {
const jsConfetti = new JSConfetti();
window.showConfetti = function() {
jsConfetti.addConfetti();
jsConfetti.addConfetti({
emojis: {{ . }},
emojiSize: 60,
confettiNumber: 30
});
}
};
document.head.appendChild(script);
});
</script>
{{ end }}
{{ if .Site.Params.gallery }}
<script>
document.addEventListener('DOMContentLoaded', function() {
const linkElement = document.createElement('link');
linkElement.rel = 'stylesheet';
linkElement.href = '/css/glightbox.min.css';
document.head.appendChild(linkElement);
const script = document.createElement('script');
script.src = '/js/glightbox.min.js';
script.onload = () => {
const lightbox = GLightbox({
loop: true,
});
lightbox.on('open', () => {
setTimeout(() => {
lightbox.nextSlide();
}, 500);
});
};
document.head.appendChild(script);
});
{{ if eq hugo.Environment "production" }}
{{ if $.Site.Params.enableUmami }}
document.querySelectorAll('.gallery').forEach(gallery => {
const eventName = gallery.dataset.umamiEvent;
let canTrack = true;
gallery.querySelectorAll('.glightbox').forEach(link => {
link.addEventListener('click', () => {
if (canTrack) {
window.umami?.track(eventName);
canTrack = false;
setTimeout(() => canTrack = true, 3000);
}
});
});
});
{{ end }}
{{ end }}
</script>
{{ end }}
</body>
</html>
|
000haoji/deep-student
| 20,891 |
src/components/MistakeLibrary.tsx
|
import React, { useState, useEffect, useMemo } from 'react';
import { TauriAPI, MistakeItem } from '../utils/tauriApi';
import { useSubject } from '../contexts/SubjectContext';
interface MistakeLibraryProps {
onSelectMistake: (mistake: MistakeItem) => void;
onBack: () => void;
// 🎯 修复:添加刷新触发器,每次切换到错题库页面时会变化
refreshTrigger?: number;
}
export const MistakeLibrary: React.FC<MistakeLibraryProps> = ({ onSelectMistake, onBack, refreshTrigger }) => {
const [mistakes, setMistakes] = useState<MistakeItem[]>([]);
const [filteredMistakes, setFilteredMistakes] = useState<MistakeItem[]>([]);
const [selectedType, setSelectedType] = useState('全部');
const [searchTerm, setSearchTerm] = useState('');
const [loading, setLoading] = useState(false);
const [availableTypes, setAvailableTypes] = useState<string[]>([]);
// 使用全局科目状态
const { currentSubject } = useSubject();
// 从现有错题数据中提取可用科目
const availableSubjects = useMemo(() => {
const subjects = Array.from(new Set(mistakes.map(mistake => mistake.subject).filter(Boolean)));
return subjects;
}, [mistakes]);
// 新增:分页状态
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(12); // 每页显示12个卡片
const [typeDropdownOpen, setTypeDropdownOpen] = useState(false);
// 🎯 修复:将loadData提取为独立函数,支持手动刷新
const loadData = async () => {
setLoading(true);
try {
// 加载错题数据
console.log('🔍 [MistakeLibrary] 开始加载错题数据...');
const rawMistakes = await TauriAPI.getMistakes();
console.log('🔍 [MistakeLibrary] 从数据库加载的原始错题数据:', {
错题总数: rawMistakes.length,
前3个错题信息: rawMistakes.slice(0, 3).map(m => ({
id: m.id,
questionImagesLength: m.question_images?.length || 0,
questionImages: m.question_images,
hasQuestionImages: !!m.question_images && m.question_images.length > 0
}))
});
// 转换错题数据:为每个错题生成图片URLs
const mistakesWithUrls = await Promise.all(rawMistakes.map(async (mistake) => {
try {
// 转换 question_images (file paths) 为 question_image_urls (URLs)
console.log(`🖼️ [图片处理] 错题 ${mistake.id} 的图片路径:`, {
questionImages: mistake.question_images,
questionImagesLength: mistake.question_images?.length || 0,
questionImagesType: typeof mistake.question_images
});
if (!mistake.question_images || mistake.question_images.length === 0) {
console.log(`⚠️ [图片处理] 错题 ${mistake.id} 没有图片路径`);
return {
...mistake,
question_image_urls: []
};
}
const questionImageUrls = await Promise.all(
mistake.question_images.map(async (imagePath, index) => {
try {
console.log(`🖼️ [图片处理] 正在处理图片 ${index + 1}/${mistake.question_images.length}: "${imagePath}"`);
// 添加超时机制
const timeoutPromise = new Promise<never>((_, reject) => {
setTimeout(() => reject(new Error('图片加载超时')), 10000); // 10秒超时
});
const base64Promise = TauriAPI.getImageAsBase64(imagePath);
const base64Data = await Promise.race([base64Promise, timeoutPromise]);
// 检查返回的数据是否已经是完整的data URL
const dataUrl = base64Data.startsWith('data:') ? base64Data : `data:image/jpeg;base64,${base64Data}`;
console.log(`✅ [图片处理] 图片 ${index + 1} 处理成功`, {
原始数据长度: base64Data.length,
是否已是DataURL: base64Data.startsWith('data:'),
最终URL长度: dataUrl.length,
URL前缀: dataUrl.substring(0, 50)
});
// 验证生成的data URL
if (dataUrl.length < 100) {
console.warn(`⚠️ [图片处理] 图片 ${index + 1} 的data URL似乎太短: ${dataUrl.length} 字符`);
}
return dataUrl;
} catch (error) {
console.error(`❌ [图片处理] 加载图片失败: "${imagePath}"`, {
error,
errorMessage: error instanceof Error ? error.message : String(error),
mistakeId: mistake.id,
imageIndex: index,
isTimeout: error instanceof Error && error.message === '图片加载超时'
});
return ''; // 返回空字符串作为fallback
}
})
);
const validUrls = questionImageUrls.filter(url => url !== '');
console.log(`🖼️ [图片处理] 错题 ${mistake.id} 最终图片URLs:`, {
总数量: questionImageUrls.length,
有效数量: validUrls.length,
失败数量: questionImageUrls.length - validUrls.length,
validUrlsPreview: validUrls.map((url, i) => `${i+1}: ${url.substring(0, 50)}...`),
validUrlsActual: validUrls
});
const filteredUrls = questionImageUrls.filter(url => url !== '');
const result = {
...mistake,
question_image_urls: filteredUrls // 过滤掉失败的图片
};
console.log(`🔧 [数据组装] 错题 ${mistake.id} 最终结果:`, {
有question_image_urls字段: 'question_image_urls' in result,
question_image_urls长度: result.question_image_urls?.length || 0,
question_image_urls值: result.question_image_urls
});
// 调试日志:检查聊天历史数据
console.log(`🔍 错题 ${mistake.id} 数据结构:`, {
id: mistake.id,
chatHistoryLength: mistake.chat_history?.length || 0,
chatHistoryExists: !!mistake.chat_history,
chatHistoryType: typeof mistake.chat_history,
chatHistoryFirst: mistake.chat_history?.[0],
questionImagesCount: mistake.question_images?.length || 0,
questionImageUrlsCount: result.question_image_urls?.length || 0
});
return result;
} catch (error) {
console.warn(`处理错题图片失败: ${mistake.id}`, error);
return {
...mistake,
question_image_urls: [] // 如果所有图片都失败,返回空数组
};
}
}));
const allMistakes = mistakesWithUrls;
setMistakes(allMistakes);
setFilteredMistakes(allMistakes);
// 科目选项现在由全局状态管理
// 动态提取可用的错题类型选项
const types = Array.from(new Set(allMistakes.map(m => m.mistake_type).filter(t => t && t.trim() !== ''))).sort();
setAvailableTypes(types);
console.log('加载错题库数据:', {
总数: allMistakes.length,
科目: Array.from(new Set(allMistakes.map(m => m.subject))).sort(),
类型: types
});
} catch (error) {
console.error('加载错题失败:', error);
alert('加载错题失败: ' + error);
} finally {
setLoading(false);
}
};
// 🎯 修复:页面切换时自动重新加载数据
useEffect(() => {
console.log('🔄 错题库页面加载/刷新,refreshTrigger:', refreshTrigger);
loadData();
}, [refreshTrigger]); // 依赖refreshTrigger,每次切换到错题库页面时都会重新加载
// 应用筛选条件
useEffect(() => {
let filtered = mistakes;
// 使用全局科目状态进行筛选
if (currentSubject && currentSubject !== '全部') {
filtered = filtered.filter(m => m.subject === currentSubject);
}
if (selectedType !== '全部') {
filtered = filtered.filter(m => m.mistake_type === selectedType);
}
if (searchTerm) {
filtered = filtered.filter(m =>
m.user_question.toLowerCase().includes(searchTerm.toLowerCase()) ||
m.ocr_text.toLowerCase().includes(searchTerm.toLowerCase()) ||
m.tags.some(tag => tag.toLowerCase().includes(searchTerm.toLowerCase()))
);
}
setFilteredMistakes(filtered);
setCurrentPage(1); // 每次筛选后重置到第一页
console.log('应用筛选条件:', {
科目: currentSubject,
类型: selectedType,
搜索词: searchTerm,
筛选结果: filtered.length
});
}, [mistakes, currentSubject, selectedType, searchTerm]);
// 处理点击外部关闭下拉框
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (typeDropdownOpen) {
const target = event.target as Node;
const dropdown = document.querySelector('.type-dropdown-container');
if (dropdown && !dropdown.contains(target)) {
setTypeDropdownOpen(false);
}
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [typeDropdownOpen]);
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString('zh-CN', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
};
// 分页逻辑
const paginatedMistakes = useMemo(() => {
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
return filteredMistakes.slice(startIndex, endIndex);
}, [filteredMistakes, currentPage, itemsPerPage]);
const totalPages = Math.ceil(filteredMistakes.length / itemsPerPage);
const handlePageChange = (newPage: number) => {
if (newPage >= 1 && newPage <= totalPages) {
setCurrentPage(newPage);
}
};
return (
<div style={{
width: '100%',
background: '#f8fafc'
}}>
{/* 🎯 修复:添加CSS动画支持 */}
<style>{`
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
`}</style>
{/* 头部区域 - 统一白色样式 */}
<div style={{
background: 'white',
borderBottom: '1px solid #e5e7eb',
padding: '24px 32px',
position: 'relative'
}}>
<div style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
height: '4px',
background: 'linear-gradient(90deg, #667eea, #764ba2)'
}}></div>
<div style={{ position: 'relative', zIndex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
<svg style={{ width: '32px', height: '32px', marginRight: '12px', color: '#667eea' }} fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
<path d="M12 7v14" />
<path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z" />
</svg>
<h1 style={{ fontSize: '28px', fontWeight: '700', margin: 0, color: '#1f2937' }}>错题库</h1>
</div>
<p style={{ fontSize: '16px', color: '#6b7280', margin: 0, lineHeight: '1.5' }}>
管理和回顾您的错题集合,追踪学习进度和薄弱环节
</p>
</div>
</div>
{/* 筛选器 - 与统一回顾分析一致的样式 */}
<div style={{
background: 'white',
margin: '0 24px 24px 24px',
borderRadius: '16px',
padding: '24px',
boxShadow: '0 4px 20px rgba(0, 0, 0, 0.05)',
border: '1px solid #f1f5f9'
}}>
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
gap: '20px',
alignItems: 'end'
}}>
{/* 科目筛选现在由全局状态控制 */}
<div>
<label style={{
display: 'block',
fontSize: '14px',
fontWeight: '600',
color: '#374151',
marginBottom: '8px'
}}>类型筛选</label>
{/* 自定义类型下拉框 - 保持原生样式外观 + 自定义下拉列表 */}
<div className="type-dropdown-container" style={{ position: 'relative' }}>
<div
style={{
width: '100%',
padding: '12px 16px',
border: '2px solid #e2e8f0',
borderRadius: '12px',
fontSize: '14px',
background: 'white',
cursor: 'pointer',
transition: 'all 0.2s ease',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
minHeight: '20px'
}}
onClick={() => setTypeDropdownOpen(!typeDropdownOpen)}
onMouseOver={(e) => {
if (!typeDropdownOpen) {
e.currentTarget.style.borderColor = '#667eea';
}
}}
onMouseOut={(e) => {
if (!typeDropdownOpen) {
e.currentTarget.style.borderColor = '#e2e8f0';
}
}}
>
<span style={{ color: '#374151' }}>
{selectedType === '全部' ? '全部类型' : selectedType}
</span>
<span style={{
transform: typeDropdownOpen ? 'rotate(180deg)' : 'rotate(0deg)',
transition: 'transform 0.2s ease',
color: '#6b7280',
fontSize: '12px'
}}>▼</span>
</div>
{typeDropdownOpen && (
<div style={{
position: 'absolute',
top: '100%',
left: 0,
right: 0,
backgroundColor: '#fff',
borderRadius: '12px',
border: '1px solid #e0e0e0',
marginTop: '8px',
boxShadow: '0 6px 16px rgba(0,0,0,0.12)',
zIndex: 9999,
overflow: 'hidden',
maxHeight: '300px',
overflowY: 'auto'
}}>
<div
style={{
padding: '12px 16px',
cursor: 'pointer',
color: '#333',
fontSize: '14px',
borderBottom: availableTypes.length > 0 ? '1px solid #f0f0f0' : 'none',
backgroundColor: selectedType === '全部' ? '#f0f7ff' : 'transparent',
transition: 'all 0.2s ease',
minHeight: '44px',
display: 'flex',
alignItems: 'center'
}}
onClick={() => {
setSelectedType('全部');
setTypeDropdownOpen(false);
}}
onMouseOver={(e) => {
if (selectedType !== '全部') {
e.currentTarget.style.backgroundColor = '#f7f7f7';
}
}}
onMouseOut={(e) => {
if (selectedType !== '全部') {
e.currentTarget.style.backgroundColor = 'transparent';
}
}}
>
全部类型
</div>
{availableTypes.map((type, index) => (
<div
key={type}
style={{
padding: '12px 16px',
cursor: 'pointer',
color: '#333',
fontSize: '14px',
borderBottom: index < availableTypes.length - 1 ? '1px solid #f0f0f0' : 'none',
backgroundColor: selectedType === type ? '#f0f7ff' : 'transparent',
transition: 'all 0.2s ease',
minHeight: '44px',
display: 'flex',
alignItems: 'center'
}}
onClick={() => {
setSelectedType(type);
setTypeDropdownOpen(false);
}}
onMouseOver={(e) => {
if (selectedType !== type) {
e.currentTarget.style.backgroundColor = '#f7f7f7';
}
}}
onMouseOut={(e) => {
if (selectedType !== type) {
e.currentTarget.style.backgroundColor = 'transparent';
}
}}
>
{type}
</div>
))}
</div>
)}
</div>
</div>
<div>
<label style={{
display: 'block',
fontSize: '14px',
fontWeight: '600',
color: '#374151',
marginBottom: '8px'
}}>搜索</label>
<input
type="text"
placeholder="搜索题目、标签或内容..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
style={{
width: '100%',
padding: '12px 16px',
border: '2px solid #e2e8f0',
borderRadius: '12px',
fontSize: '14px',
background: 'white',
transition: 'all 0.2s ease'
}}
onFocus={(e) => e.target.style.borderColor = '#667eea'}
onBlur={(e) => e.target.style.borderColor = '#e2e8f0'}
/>
</div>
</div>
</div>
<div className="mistake-library" style={{ padding: '0 24px 24px 24px', background: 'transparent' }}>
<div className="library-content">
{loading ? (
<div className="loading">加载中...</div>
) : filteredMistakes.length === 0 ? (
<div className="empty-state">
<p>暂无错题记录</p>
<p>开始分析题目来建立您的错题库吧!</p>
</div>
) : (
<>
<div className="mistakes-grid">
{paginatedMistakes.map((mistake) => (
<div
key={mistake.id}
className="mistake-card"
onClick={() => onSelectMistake(mistake)}
>
<div className="mistake-header">
<span className="subject-badge">{mistake.subject}</span>
<span className="date">{formatDate(mistake.created_at)}</span>
</div>
<div className="mistake-content">
<h4>{mistake.user_question}</h4>
<p className="ocr-preview">
{mistake.ocr_text.length > 100
? mistake.ocr_text.substring(0, 100) + '...'
: mistake.ocr_text
}
</p>
</div>
<div className="mistake-tags">
{mistake.tags.slice(0, 3).map((tag, index) => (
<span key={index} className="tag">{tag}</span>
))}
{mistake.tags.length > 3 && (
<span className="tag-more">+{mistake.tags.length - 3}</span>
)}
</div>
<div className="mistake-footer">
<span className="type">{mistake.mistake_type}</span>
<span className="status">{mistake.status === 'completed' ? '已完成' : '分析中'}</span>
</div>
</div>
))}
</div>
{totalPages > 1 && (
<div className="pagination-controls" style={{ marginTop: '24px', display: 'flex', justifyContent: 'center', alignItems: 'center', gap: '8px' }}>
<button
onClick={() => handlePageChange(currentPage - 1)}
disabled={currentPage === 1}
style={{ padding: '8px 16px', borderRadius: '8px', border: '1px solid #ddd', cursor: 'pointer', background: currentPage === 1 ? '#f5f5f5' : 'white' }}
>
上一页
</button>
<span style={{ fontSize: '14px', color: '#333' }}>
第 {currentPage} 页 / 共 {totalPages} 页
</span>
<button
onClick={() => handlePageChange(currentPage + 1)}
disabled={currentPage === totalPages}
style={{ padding: '8px 16px', borderRadius: '8px', border: '1px solid #ddd', cursor: 'pointer', background: currentPage === totalPages ? '#f5f5f5' : 'white' }}
>
下一页
</button>
</div>
)}
</>
)}
</div>
</div>
</div>
);
};
|
000haoji/deep-student
| 10,158 |
src/components/ReviewAnalysisLibrary.tsx
|
/**
* DEPRECATED: 此组件已废弃 - 2024年6月8日
* 原因: 功能已被统一回顾分析(ReviewAnalysisDashboard)替代
*
* 这个组件使用localStorage存储数据,与新的数据库存储系统不兼容
* 请使用 ReviewAnalysisDashboard 代替此组件
*/
import React, { useState, useEffect } from 'react';
import { ReviewSessionTask } from '../types/index';
import { useNotification } from '../hooks/useNotification';
interface ReviewAnalysisLibraryProps {
onSelectAnalysis: (analysis: ReviewSessionTask) => void;
onBack: () => void;
}
export const ReviewAnalysisLibrary: React.FC<ReviewAnalysisLibraryProps> = ({ onSelectAnalysis, onBack }) => {
const [analyses, setAnalyses] = useState<ReviewSessionTask[]>([]);
const [filteredAnalyses, setFilteredAnalyses] = useState<ReviewSessionTask[]>([]);
const [selectedSubject, setSelectedSubject] = useState('全部');
const [selectedStatus, setSelectedStatus] = useState('全部');
const [searchTerm, setSearchTerm] = useState('');
const [loading, setLoading] = useState(false);
const [availableSubjects, setAvailableSubjects] = useState<string[]>([]);
const { showNotification } = useNotification();
// 加载回顾分析数据
useEffect(() => {
const loadData = async () => {
setLoading(true);
try {
// 从localStorage加载回顾分析数据 - 使用和会话相同的存储键
const savedAnalyses = localStorage.getItem('reviewSessions');
if (savedAnalyses) {
const parsedAnalyses = JSON.parse(savedAnalyses).map((analysis: any) => ({
...analysis,
thinkingContent: new Map(Object.entries(analysis.thinkingContent || {}))
}));
setAnalyses(parsedAnalyses);
setFilteredAnalyses(parsedAnalyses);
// 动态提取可用的科目选项
const subjects = Array.from(new Set(parsedAnalyses.map((a: ReviewSessionTask) => a.subject))).sort();
setAvailableSubjects(subjects);
console.log('加载回顾分析库数据:', {
总数: parsedAnalyses.length,
科目: subjects
});
} else {
setAnalyses([]);
setFilteredAnalyses([]);
setAvailableSubjects([]);
}
} catch (error) {
console.error('加载回顾分析失败:', error);
showNotification('error', '加载回顾分析失败: ' + error);
} finally {
setLoading(false);
}
};
loadData();
}, [showNotification]);
// 筛选逻辑
useEffect(() => {
let filtered = analyses;
if (selectedSubject !== '全部') {
filtered = filtered.filter(analysis => analysis.subject === selectedSubject);
}
if (selectedStatus !== '全部') {
filtered = filtered.filter(analysis => {
if (selectedStatus === '已完成') return analysis.status === 'completed';
if (selectedStatus === '进行中') return analysis.status !== 'completed' && !analysis.status.includes('error');
if (selectedStatus === '错误') return analysis.status.includes('error');
return true;
});
}
if (searchTerm.trim()) {
const term = searchTerm.toLowerCase();
filtered = filtered.filter(analysis =>
analysis.name.toLowerCase().includes(term) ||
analysis.userOverallPrompt?.toLowerCase().includes(term) ||
analysis.id.toLowerCase().includes(term)
);
}
setFilteredAnalyses(filtered);
}, [analyses, selectedSubject, selectedStatus, searchTerm]);
const deleteAnalysis = async (analysisId: string) => {
if (!confirm('确定要删除这个回顾记录吗?')) return;
try {
const updatedAnalyses = analyses.filter(a => a.id !== analysisId);
setAnalyses(updatedAnalyses);
// 保存到localStorage
const analysesToSave = updatedAnalyses.map(analysis => ({
...analysis,
thinkingContent: Object.fromEntries(analysis.thinkingContent)
}));
localStorage.setItem('reviewSessions', JSON.stringify(analysesToSave));
showNotification('success', '回顾记录已删除');
} catch (error) {
console.error('删除回顾分析失败:', error);
showNotification('error', '删除失败: ' + error);
}
};
const getStatusText = (status: string) => {
switch (status) {
case 'completed': return '已完成';
case 'pending': return '等待中';
case 'processing_setup': return '准备中';
case 'streaming_answer': return '分析中';
default:
if (status.includes('error')) return '错误';
return '未知';
}
};
const getStatusColor = (status: string) => {
switch (status) {
case 'completed': return '#28a745';
case 'pending':
case 'processing_setup':
case 'streaming_answer': return '#007bff';
default:
if (status.includes('error')) return '#dc3545';
return '#6c757d';
}
};
return (
<div className="review-analysis-container">
<div className="review-analysis-header">
<button onClick={onBack} className="review-analysis-back-btn">
← 返回
</button>
<h2 className="review-analysis-title">📚 回顾库</h2>
<div className="library-stats">
<span className="stats-text">共 {filteredAnalyses.length} 个回顾</span>
{filteredAnalyses.length !== analyses.length && (
<span className="stats-filter">(从 {analyses.length} 个中筛选)</span>
)}
</div>
</div>
<div className="review-analysis-main">
<div className="review-filters">
<div className="review-form-group">
<label className="review-form-label">科目:</label>
<select
className="review-form-select"
value={selectedSubject}
onChange={(e) => setSelectedSubject(e.target.value)}
>
<option value="全部">全部科目</option>
{availableSubjects.map(subject => (
<option key={subject} value={subject}>{subject}</option>
))}
</select>
</div>
<div className="review-form-group">
<label className="review-form-label">状态:</label>
<select
className="review-form-select"
value={selectedStatus}
onChange={(e) => setSelectedStatus(e.target.value)}
>
<option value="全部">全部状态</option>
<option value="已完成">已完成</option>
<option value="进行中">进行中</option>
<option value="错误">错误</option>
</select>
</div>
<div className="review-form-group search-group">
<label className="review-form-label">搜索:</label>
<input
className="review-form-input search-input"
type="text"
placeholder="搜索回顾名称、目标或ID..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
</div>
{loading ? (
<div className="review-loading">
<div className="review-loading-spinner"></div>
<span className="review-loading-text">加载中...</span>
</div>
) : filteredAnalyses.length === 0 ? (
<div className="review-empty">
<div className="empty-icon">📭</div>
<h3 className="empty-title">暂无回顾记录</h3>
<p className="empty-description">还没有保存的回顾记录</p>
<p className="empty-hint">完成回顾分析后,点击"保存到回顾库"按钮即可保存</p>
</div>
) : (
<div className="analysis-library-grid">
{filteredAnalyses.map((analysis) => (
<div
key={analysis.id}
className="analysis-library-card"
onClick={() => onSelectAnalysis(analysis)}
>
<div className="analysis-card-header">
<div className="analysis-card-info">
<h4 className="analysis-card-title">{analysis.name}</h4>
<span className="analysis-card-id">ID: {analysis.id}</span>
</div>
<div className="analysis-card-actions">
<span
className="analysis-status-badge"
style={{
backgroundColor: getStatusColor(analysis.status),
color: 'white'
}}
>
{getStatusText(analysis.status)}
</span>
<button
className="analysis-delete-btn"
onClick={(e) => {
e.stopPropagation();
deleteAnalysis(analysis.id);
}}
title="删除回顾"
>
🗑️
</button>
</div>
</div>
<div className="analysis-card-content">
<div className="analysis-meta-row">
<span className="meta-item subject-tag">📖 {analysis.subject}</span>
<span className="meta-item mistake-count">📝 {analysis.mistakeIds.length} 个错题</span>
<span className="meta-item chat-count">💬 {analysis.chatHistory.length} 条对话</span>
</div>
<div className="analysis-target-section">
<div className="target-label">回顾目标:</div>
<div className="target-content">{analysis.userOverallPrompt || '统一回顾多个错题'}</div>
</div>
{analysis.chatHistory.length > 0 && (
<div className="analysis-preview-section">
<div className="preview-label">回顾摘要:</div>
<div className="preview-content">{analysis.chatHistory[0]?.content?.substring(0, 100)}...</div>
</div>
)}
<div className="analysis-date-section">
<span className="date-icon">🕒</span>
<span className="date-text">{new Date(analysis.creationDate).toLocaleString('zh-CN')}</span>
</div>
</div>
</div>
))}
</div>
)}
</div>
</div>
);
};
|
000haoji/deep-student
| 9,843 |
src/components/GraphVisualization.tsx
|
import React, { useState, useRef, useEffect } from 'react';
import { GraphConfig, GraphNode, GraphRelationship } from '../types/cogni-graph';
import './GraphVisualization.css';
interface GraphVisualizationProps {
config: GraphConfig;
isInitialized: boolean;
}
const GraphVisualization: React.FC<GraphVisualizationProps> = ({ config, isInitialized }) => {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [selectedNode, setSelectedNode] = useState<any>(null);
const [isInitializing, setIsInitializing] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
const neovisRef = useRef<any>(null);
useEffect(() => {
if (isInitialized && containerRef.current) {
initializeVisualization();
}
return () => {
if (neovisRef.current) {
try {
neovisRef.current.clearNetwork();
} catch (e) {
console.warn('Error clearing network:', e);
}
}
};
}, [isInitialized, config]);
const initializeVisualization = async () => {
if (!containerRef.current || isInitializing) return;
// 检查配置是否完整
if (!config.neo4j.uri || !config.neo4j.username || !config.neo4j.password) {
setError('请先完成 Neo4j 连接配置(URI、用户名、密码都不能为空)');
return;
}
try {
setIsInitializing(true);
setIsLoading(true);
setError(null);
const NeoVis = (await import('neovis.js')).default;
// 清理之前的实例
if (neovisRef.current) {
try {
neovisRef.current.clearNetwork();
} catch (e) {
console.warn('Error clearing previous network:', e);
}
}
const neovisConfig = {
containerId: 'neo4j-viz',
neo4j: {
serverUrl: config.neo4j.uri,
serverUser: config.neo4j.username,
serverPassword: config.neo4j.password,
serverDatabase: config.neo4j.database || 'neo4j'
},
labels: {
ProblemCard: {
label: 'content_problem',
value: 'access_count',
color: '#68CCE5',
size: 'access_count',
caption: ['content_problem'],
title_properties: ['content_problem', 'content_insight', 'status'],
font: {
color: '#2c3e50',
size: 12,
face: 'Arial'
}
},
Tag: {
label: 'name',
value: 'level',
color: '#FFA500',
size: 'level',
caption: ['name'],
title_properties: ['name', 'tag_type', 'description'],
font: {
color: '#2c3e50',
size: 10,
face: 'Arial'
}
}
},
relationships: {
HAS_TAG: {
thickness: '2',
color: '#3498db',
caption: false
},
PARENT_OF: {
thickness: '3',
color: '#e74c3c',
caption: false
},
CHILD_OF: {
thickness: '2',
color: '#f39c12',
caption: false
},
IS_VARIATION_OF: {
thickness: '2',
color: '#9b59b6',
caption: false
},
USES_GENERAL_METHOD: {
thickness: '2',
color: '#27ae60',
caption: false
},
CONTRASTS_WITH: {
thickness: '2',
color: '#e67e22',
caption: false
},
RELATED_TO: {
thickness: '1',
color: '#95a5a6',
caption: false
},
PREREQUISITE_OF: {
thickness: '2',
color: '#34495e',
caption: false
}
},
initialCypher: getInitialCypher(),
consoleDebug: false
};
console.log('Initializing NeoVis with config:', neovisConfig);
const viz = new NeoVis(neovisConfig);
neovisRef.current = viz;
// 检查可用的方法
console.log('NeoVis instance created:', viz);
// 安全的事件注册
try {
if (typeof viz.registerOnEvent === 'function') {
viz.registerOnEvent('clickNode', (event: any) => {
console.log('Node clicked:', event);
setSelectedNode(event);
});
viz.registerOnEvent('clickEdge', (event: any) => {
console.log('Edge clicked:', event);
});
// 尝试多种完成事件
const completionEvents = ['completed', 'complete', 'finished', 'ready', 'renderComplete'];
let eventRegistered = false;
for (const eventName of completionEvents) {
try {
viz.registerOnEvent(eventName, () => {
setIsLoading(false);
setIsInitializing(false);
console.log(`Graph visualization rendered (${eventName})`);
});
eventRegistered = true;
console.log(`Successfully registered ${eventName} event`);
break;
} catch (e) {
console.warn(`${eventName} event not supported`);
}
}
// 如果没有完成事件,使用超时
if (!eventRegistered) {
console.log('No completion events available, using timeout fallback');
setTimeout(() => {
setIsLoading(false);
setIsInitializing(false);
console.log('Graph visualization completed (timeout)');
}, 3000);
}
// 错误事件
viz.registerOnEvent('error', (error: any) => {
console.error('Visualization error:', error);
setError(`可视化错误: ${error.message || error}`);
setIsLoading(false);
setIsInitializing(false);
});
} else {
console.warn('registerOnEvent not available, using timeout');
setTimeout(() => {
setIsLoading(false);
setIsInitializing(false);
}, 3000);
}
} catch (e) {
console.warn('Event registration failed:', e);
setTimeout(() => {
setIsLoading(false);
setIsInitializing(false);
}, 3000);
}
// 渲染图形
viz.render();
} catch (err) {
console.error('Failed to initialize visualization:', err);
setError(`可视化初始化失败: ${err}`);
setIsLoading(false);
} finally {
setIsInitializing(false);
}
};
const getInitialCypher = (): string => {
return `
MATCH (n)
OPTIONAL MATCH (n)-[r]->(m)
RETURN n, r, m
LIMIT 50
`;
};
const refreshVisualization = () => {
if (neovisRef.current) {
try {
setIsLoading(true);
neovisRef.current.reload();
setTimeout(() => setIsLoading(false), 2000);
} catch (err) {
console.error('Failed to refresh visualization:', err);
setError(`刷新失败: ${err}`);
setIsLoading(false);
}
} else {
initializeVisualization();
}
};
const clearVisualization = () => {
if (neovisRef.current) {
try {
neovisRef.current.clearNetwork();
setSelectedNode(null);
} catch (err) {
console.error('Failed to clear visualization:', err);
}
}
};
const customQuery = (cypher: string) => {
if (neovisRef.current && cypher.trim()) {
try {
setIsLoading(true);
neovisRef.current.renderWithCypher(cypher);
setTimeout(() => setIsLoading(false), 2000);
} catch (err) {
console.error('Failed to execute custom query:', err);
setError(`查询执行失败: ${err}`);
setIsLoading(false);
}
}
};
if (!isInitialized) {
return (
<div className="graph-visualization-container">
<div className="not-initialized">
<p>图谱未初始化,请先完成Neo4j连接配置</p>
</div>
</div>
);
}
return (
<div className="graph-visualization-container">
<div className="visualization-header">
<h3>图谱可视化</h3>
<div className="visualization-controls">
<button onClick={refreshVisualization} disabled={isLoading}>
🔄 刷新
</button>
<button onClick={clearVisualization} disabled={isLoading}>
🗑️ 清空
</button>
<button
onClick={() => customQuery('MATCH (n:ProblemCard) RETURN n LIMIT 20')}
disabled={isLoading}
>
📚 显示问题卡片
</button>
<button
onClick={() => customQuery('MATCH (n:Tag) RETURN n LIMIT 20')}
disabled={isLoading}
>
🏷️ 显示标签
</button>
</div>
</div>
{error && (
<div className="error-message">
{error}
<button onClick={() => setError(null)}>✕</button>
</div>
)}
<div className="visualization-content">
<div className="graph-container">
<div
id="neo4j-viz"
ref={containerRef}
className="neo4j-visualization"
/>
{isLoading && (
<div className="loading-overlay">
<div className="loading-spinner">加载图谱中...</div>
</div>
)}
</div>
{selectedNode && (
<div className="node-details">
<h4>节点详情</h4>
<div className="node-info">
<strong>ID:</strong> {selectedNode.id}<br/>
<strong>Labels:</strong> {selectedNode.labels?.join(', ')}<br/>
<strong>Properties:</strong>
<pre>{JSON.stringify(selectedNode.properties, null, 2)}</pre>
</div>
<button onClick={() => setSelectedNode(null)}>关闭</button>
</div>
)}
</div>
</div>
);
};
export default GraphVisualization;
|
0015/StickiNote
| 3,189 |
main/main.cpp
|
#include "nvs_flash.h"
#include "nvs.h"
#include "esp_log.h"
#include "esp_err.h"
#include "esp_check.h"
#include "lvgl.h"
#include "bsp/esp-bsp.h"
#include "bsp/display.h"
#include "LVGL_WidgetManager.hpp"
#include "SplashScreen.hpp"
extern int screen_width;
extern int screen_height;
void createNotebookBackground(lv_obj_t *parent)
{
lv_obj_t *notebook_bg = lv_obj_create(parent);
lv_obj_set_size(notebook_bg, screen_width, screen_height);
lv_obj_align(notebook_bg, LV_ALIGN_CENTER, 0, 0);
lv_obj_clear_flag(notebook_bg, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_style_bg_color(notebook_bg, lv_color_hex(0xFDF3E7), LV_PART_MAIN);
lv_obj_set_style_bg_color(notebook_bg, lv_color_hex(0xFDF3E7), LV_STATE_DEFAULT);
lv_obj_set_style_bg_opa(notebook_bg, LV_OPA_COVER, LV_PART_MAIN);
lv_obj_set_style_bg_opa(notebook_bg, LV_OPA_COVER, LV_STATE_DEFAULT);
for (int y = 40; y < screen_height; y += 40)
{
lv_obj_t *line = lv_obj_create(notebook_bg);
lv_obj_set_size(line, screen_width, 2);
lv_obj_align(line, LV_ALIGN_TOP_MID, 0, y);
lv_obj_set_style_bg_color(line, lv_palette_main(LV_PALETTE_BLUE), LV_PART_MAIN);
lv_obj_set_style_bg_color(line, lv_palette_main(LV_PALETTE_BLUE), LV_STATE_DEFAULT);
lv_obj_set_style_bg_opa(line, LV_OPA_50, LV_PART_MAIN );
lv_obj_set_style_bg_opa(line, LV_OPA_50, LV_STATE_DEFAULT);
}
lv_obj_t *margin_line = lv_obj_create(notebook_bg);
lv_obj_set_size(margin_line, 2, screen_height);
lv_obj_align(margin_line, LV_ALIGN_LEFT_MID, 50, 0);
lv_obj_set_style_bg_color(margin_line, lv_palette_main(LV_PALETTE_RED), LV_PART_MAIN );
lv_obj_set_style_bg_color(margin_line, lv_palette_main(LV_PALETTE_RED), LV_STATE_DEFAULT);
lv_obj_set_style_bg_opa(margin_line, LV_OPA_70, LV_PART_MAIN);
lv_obj_set_style_bg_opa(margin_line, LV_OPA_70, LV_STATE_DEFAULT);
lv_obj_invalidate(notebook_bg);
}
extern "C" void app_main(void)
{
NVSManager::init();
bsp_display_cfg_t cfg = {
.lvgl_port_cfg = ESP_LVGL_PORT_INIT_CONFIG(),
.buffer_size = BSP_LCD_DRAW_BUFF_SIZE,
.double_buffer = BSP_LCD_DRAW_BUFF_DOUBLE,
.flags = {
.buff_dma = true,
.buff_spiram = false,
.sw_rotate = false,
}};
bsp_display_start_with_config(&cfg);
bsp_display_backlight_on();
bsp_display_lock(0);
screen_width = BSP_LCD_H_RES;
screen_height = BSP_LCD_V_RES;
lv_obj_t *screen = lv_obj_create(lv_screen_active());
lv_obj_set_size(screen, screen_width, screen_height);
lv_obj_center(screen);
lv_obj_clear_flag(screen, LV_OBJ_FLAG_SCROLLABLE);
createNotebookBackground(screen);
lv_obj_t *kb = lv_keyboard_create(lv_screen_active());
lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
lv_obj_set_size(kb, screen_width, screen_height / 3);
lv_obj_align(kb, LV_ALIGN_BOTTOM_MID, 0, 0);
static LVGL_WidgetManager widgetManager(screen, kb);
show_splash(screen, [&]()
{
ESP_LOGI("MAIN", "Splash animation finished. Loading Post-its...");
widgetManager.loadPostItsFromNVS();
});
bsp_display_unlock();
}
|
0015/StickiNote
| 2,114 |
main/SplashScreen.cpp
|
#include "SplashScreen.hpp"
#include "esp_log.h"
#define SPLASH_ANIM_TIME 400
#define SPLASH_HOLD_TIME 1500
LV_IMG_DECLARE(notes);
int screen_width = 800; // Default value, will be set in main
int screen_height = 480;
struct SplashData {
lv_obj_t *splash_img;
std::function<void()> on_complete;
};
static void splash_exit_anim_cb(lv_anim_t *a) {
SplashData *data = (SplashData *)lv_anim_get_user_data(a);
lv_obj_del(data->splash_img);
if (data->on_complete) data->on_complete();
delete data;
}
static void splash_hold_timer_cb(lv_timer_t *t) {
SplashData *data = (SplashData *)lv_timer_get_user_data(t);
lv_anim_t slide_exit;
lv_anim_init(&slide_exit);
lv_anim_set_var(&slide_exit, data->splash_img);
lv_anim_set_values(&slide_exit, screen_height / 4, screen_height);
lv_anim_set_time(&slide_exit, SPLASH_ANIM_TIME);
lv_anim_set_exec_cb(&slide_exit, (lv_anim_exec_xcb_t)lv_obj_set_y);
lv_anim_set_deleted_cb(&slide_exit, splash_exit_anim_cb);
lv_anim_set_user_data(&slide_exit, data);
lv_anim_start(&slide_exit);
lv_timer_del(t);
}
static void splash_anim_cb(lv_anim_t *a) {
SplashData *data = (SplashData *)lv_anim_get_user_data(a);
lv_timer_t *hold_timer = lv_timer_create(splash_hold_timer_cb, SPLASH_HOLD_TIME, data);
lv_timer_set_user_data(hold_timer, data);
}
void show_splash(lv_obj_t *screen, std::function<void()> on_complete) {
SplashData *data = new SplashData;
data->splash_img = lv_img_create(screen);
lv_img_set_src(data->splash_img, ¬es);
lv_obj_align(data->splash_img, LV_ALIGN_TOP_MID, 0, -screen_height / 2);
data->on_complete = on_complete;
lv_anim_t slide_down;
lv_anim_init(&slide_down);
lv_anim_set_var(&slide_down, data->splash_img);
lv_anim_set_values(&slide_down, -screen_height / 2, screen_height / 4);
lv_anim_set_time(&slide_down, SPLASH_ANIM_TIME);
lv_anim_set_exec_cb(&slide_down, (lv_anim_exec_xcb_t)lv_obj_set_y);
lv_anim_set_ready_cb(&slide_down, splash_anim_cb);
lv_anim_set_user_data(&slide_down, data);
lv_anim_start(&slide_down);
}
|
000haoji/deep-student
| 8,443 |
src/components/RagQueryView.tsx
|
import React, { useState, useCallback } from 'react';
import { TauriAPI } from '../utils/tauriApi';
import { useNotification } from '../hooks/useNotification';
import type { RetrievedChunk, RagQueryOptions } from '../types';
import './RagQueryView.css';
import { Search, Lightbulb, Sparkles } from 'lucide-react';
interface RagQueryViewProps {
className?: string;
}
export const RagQueryView: React.FC<RagQueryViewProps> = ({
className = ''
}) => {
const [query, setQuery] = useState('');
const [loading, setLoading] = useState(false);
const [retrievedChunks, setRetrievedChunks] = useState<RetrievedChunk[]>([]);
const [llmAnswer, setLlmAnswer] = useState('');
const [queryOptions, setQueryOptions] = useState<RagQueryOptions>({
top_k: 5,
enable_reranking: false,
});
const { showSuccess, showError, showWarning } = useNotification();
// 执行RAG查询
const handleRagQuery = useCallback(async () => {
if (!query.trim()) {
showWarning('请输入查询内容');
return;
}
try {
setLoading(true);
setRetrievedChunks([]);
setLlmAnswer('');
console.log('执行RAG查询:', query, queryOptions);
// 1. 执行RAG检索
const retrievalResult = await TauriAPI.ragQueryKnowledgeBase(query, queryOptions);
setRetrievedChunks(retrievalResult.retrieved_chunks || []);
if (retrievalResult.retrieved_chunks.length === 0) {
showWarning('在知识库中未找到相关内容');
return;
}
showSuccess(`检索到 ${retrievalResult.retrieved_chunks.length} 个相关文档片段`);
// 2. 使用LLM生成回答
console.log('调用LLM生成回答...');
const answer = await TauriAPI.llmGenerateAnswerWithContext(query, JSON.stringify(retrievalResult.retrieved_chunks));
setLlmAnswer(answer);
showSuccess('RAG查询完成');
} catch (error) {
console.error('RAG查询失败:', error);
let errorMessage = '查询失败';
if (typeof error === 'string') {
errorMessage = `查询失败: ${error}`;
} else if (error instanceof Error) {
errorMessage = `查询失败: ${error.message}`;
} else if (error && typeof error === 'object' && 'message' in error) {
errorMessage = `查询失败: ${(error as any).message}`;
}
showError(errorMessage);
} finally {
setLoading(false);
}
}, [query, queryOptions, showSuccess, showError, showWarning]);
// 处理Enter键提交
const handleKeyPress = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleRagQuery();
}
};
// 格式化相似度分数
const formatScore = (score: number) => {
return (score * 100).toFixed(1) + '%';
};
// 截断文本用于显示
const truncateText = (text: string, maxLength: number = 200) => {
if (text.length <= maxLength) return text;
return text.substring(0, maxLength) + '...';
};
return (
<div className={`rag-query-view ${className}`} style={{ width: '100%', height: '100%', overflow: 'auto', background: '#f8fafc' }}>
{/* 统一头部样式 */}
<div style={{
background: 'white',
borderBottom: '1px solid #e5e7eb',
padding: '24px 32px',
position: 'relative'
}}>
<div style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
height: '4px',
background: 'linear-gradient(90deg, #667eea, #764ba2)'
}}></div>
<div style={{ position: 'relative', zIndex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
<svg style={{ width: '32px', height: '32px', marginRight: '12px', color: '#667eea' }} fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
<path d="m21 21-4.34-4.34" />
<circle cx="11" cy="11" r="8" />
</svg>
<h1 style={{ fontSize: '28px', fontWeight: '700', margin: 0, color: '#1f2937' }}>RAG 知识库查询</h1>
</div>
<p style={{ fontSize: '16px', color: '#6b7280', margin: 0, lineHeight: '1.5' }}>
测试知识库检索和增强生成功能,验证AI回答质量
</p>
</div>
</div>
<div style={{ padding: '24px' }}>
{/* 查询配置区域 */}
<div className="query-config-section">
<h3>查询参数配置</h3>
<div className="config-controls">
<div className="config-item">
<label htmlFor="top-k">检索片段数量 (top_k):</label>
<input
id="top-k"
type="number"
min="1"
max="20"
value={queryOptions.top_k}
onChange={(e) => setQueryOptions(prev => ({
...prev,
top_k: parseInt(e.target.value) || 5
}))}
/>
</div>
<div className="config-item">
<label className="checkbox-label">
<input
type="checkbox"
checked={queryOptions.enable_reranking}
onChange={(e) => setQueryOptions(prev => ({
...prev,
enable_reranking: e.target.checked
}))}
/>
启用重排序 (Reranking)
</label>
</div>
</div>
</div>
{/* 查询输入区域 */}
<div className="query-input-section">
<h3>查询输入</h3>
<div className="query-input-container">
<textarea
className="query-input"
placeholder="请输入您的问题..."
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyPress={handleKeyPress}
rows={3}
disabled={loading}
/>
<button
className="query-button"
onClick={handleRagQuery}
disabled={loading || !query.trim()}
>
{loading ? '查询中...' : '执行查询'}
</button>
</div>
<div className="input-hint" style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
<Lightbulb size={16} />
提示:按 Enter 键快速提交查询,Shift+Enter 换行
</div>
</div>
{/* 检索结果区域 */}
{retrievedChunks.length > 0 && (
<div className="retrieval-results-section">
<h3>检索到的知识片段</h3>
<div className="retrieved-chunks">
{retrievedChunks.map((chunk, index) => (
<div key={chunk.chunk.id} className="retrieved-chunk">
<div className="chunk-header">
<span className="chunk-rank">#{index + 1}</span>
<span className="chunk-score">相似度: {formatScore(chunk.score)}</span>
<span className="chunk-source">
来源: {chunk.chunk.metadata.file_name || '未知'}
</span>
</div>
<div className="chunk-content">
<p>{truncateText(chunk.chunk.text)}</p>
{chunk.chunk.text.length > 200 && (
<button
className="expand-button"
onClick={() => {
// 可以添加展开/收起功能
console.log('展开完整内容:', chunk.chunk.text);
}}
>
查看完整内容
</button>
)}
</div>
<div className="chunk-metadata">
<span>块索引: {chunk.chunk.chunk_index}</span>
<span>文档ID: {chunk.chunk.document_id.substring(0, 8)}...</span>
</div>
</div>
))}
</div>
</div>
)}
{/* LLM回答区域 */}
{llmAnswer && (
<div className="llm-answer-section">
<h3>AI 回答</h3>
<div className="llm-answer">
<div className="answer-content">
{llmAnswer.split('\n').map((paragraph, index) => (
<p key={index}>{paragraph}</p>
))}
</div>
<div className="answer-footer">
<span className="answer-source" style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
<Sparkles size={16} />
基于知识库中的 {retrievedChunks.length} 个相关片段生成
</span>
</div>
</div>
</div>
)}
{/* 加载状态 */}
{loading && (
<div className="loading-overlay">
<div className="loading-spinner"></div>
<p>正在查询知识库...</p>
</div>
)}
</div>
</div>
);
};
export default RagQueryView;
|
000haoji/deep-student
| 7,787 |
src/components/SharedPreview.tsx
|
import React, { useRef, useEffect } from 'react';
import { AnkiCardTemplate } from '../types';
export const IframePreview: React.FC<{ htmlContent: string; cssContent: string; }> = ({ htmlContent, cssContent }) => {
const iframeRef = useRef<HTMLIFrameElement>(null);
useEffect(() => {
const iframe = iframeRef.current;
if (!iframe || !iframe.contentWindow) return;
const doc = iframe.contentWindow.document;
doc.open();
doc.write(`
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100%;
box-sizing: border-box;
background-color: transparent;
}
/* 添加填空题高亮样式 */
.cloze-revealed {
background: #FFD700 !important;
color: #2c3e50 !important;
padding: 2px 8px !important;
border-radius: 6px !important;
font-weight: 600 !important;
box-shadow: 0 2px 4px rgba(0,0,0,0.2) !important;
}
${cssContent}
</style>
</head>
<body>
${htmlContent}
</body>
</html>
`);
doc.close();
const updateHeight = () => {
if (iframe && iframe.contentWindow && iframe.contentWindow.document.body) {
const body = iframe.contentWindow.document.body;
const contentHeight = body.scrollHeight;
iframe.style.height = `${contentHeight}px`;
}
};
const timer = setTimeout(updateHeight, 100);
const observer = new ResizeObserver(updateHeight);
observer.observe(doc.body);
return () => {
clearTimeout(timer);
observer.disconnect();
};
}, [htmlContent, cssContent]);
return (
<iframe
ref={iframeRef}
title="Card Preview"
style={{ width: '100%', border: 'none', minHeight: '80px', verticalAlign: 'top' }}
scrolling="no"
/>
);
};
export const renderCardPreview = (template: string, templateData: AnkiCardTemplate, actualCardData?: any) => {
let rendered = template;
rendered = rendered.replace(/\{\{Front\}\}/g, templateData.preview_front);
rendered = rendered.replace(/\{\{Back\}\}/g, templateData.preview_back);
// 检测是否为背面模板
const isBackTemplate = rendered.includes('完整内容') || rendered.includes('{{text:') ||
(templateData.preview_back && rendered.includes(templateData.preview_back));
// 根据模板类型提供合适的示例数据
const getTemplateSpecificData = () => {
const templateName = templateData.name || '';
const templateId = templateData.id || '';
if (templateName.includes('学术') || templateId === 'academic-card') {
return {
'Deck': 'AI学习卡片',
'Notes': '这是一个关于生物学概念的补充说明,帮助更好地理解DNA复制过程。',
'Example': '例如:在细胞分裂过程中,DNA双螺旋结构会解开,每条链作为模板合成新的互补链,从而保证遗传信息的准确传递。',
'Source': '分子生物学教材 - 第五章',
'Tags': '生物学,分子生物学,DNA'
};
} else if (templateName.includes('编程') || templateId === 'code-card') {
return {
'Deck': 'AI学习卡片',
'Notes': '这是一个关于Python编程的补充说明,帮助更好地理解列表操作。',
'Example': '例如:使用append()方法可以向列表末尾添加元素,使用extend()可以添加多个元素。',
'Source': 'Python官方文档',
'Tags': 'Python,编程,数据结构'
};
} else if (templateName.includes('选择题') || templateId === 'choice-card') {
return {
'Deck': 'AI学习卡片',
'Notes': '这是一个关于物理概念的补充说明,帮助更好地理解牛顿定律。',
'Example': '例如:当汽车突然刹车时,车内的人会向前倾,这就是惯性的体现。',
'Source': '大学物理教材 - 第二章',
'Tags': '物理,力学,基础概念'
};
} else if (templateName.includes('填空') || templateId === 'cloze-card') {
return {
'Deck': 'AI学习卡片',
'Notes': '这是一个关于社会工作的补充说明,帮助更好地理解基本要素。',
'Example': '例如:在社区服务中,社会工作者通过专业技能帮助有需要的个人和家庭解决问题。',
'Source': '社会工作基础教材 - 第一章',
'Tags': '社会学,社会工作,基础概念'
};
} else {
return {
'Deck': 'AI学习卡片',
'Notes': '这是一个学习概念的补充说明,帮助更好地理解相关知识点。',
'Example': '例如:通过实践和反复练习,可以更好地掌握和运用所学知识。',
'Source': '学习资料',
'Tags': '学习,知识,基础'
};
}
};
const specificData = getTemplateSpecificData();
const sampleData: Record<string, string> = {
...specificData,
'Code': 'my_list = [1, 2, 3, 4, 5]\nprint(my_list)\n# 输出: [1, 2, 3, 4, 5]',
'Text': '社会工作的要素包括:1. {{c1::社会工作者}}:服务和帮助的提供者;2. {{c2::受助者}}:遇到困难且需要帮助的人。',
'Hint': '记住社会工作的两个基本要素。',
'Question': '下列哪个是牛顿第一定律的内容?',
'OptionA': 'F=ma',
'OptionB': '作用力与反作用力',
'OptionC': '惯性定律',
'OptionD': '万有引力定律',
'optiona': 'F=ma',
'optionb': '作用力与反作用力',
'optionc': '惯性定律',
'optiond': '万有引力定律',
'Correct': 'C',
'correct': 'C',
'Explanation': '牛顿第一定律又称惯性定律,表述物体在没有外力作用时保持静止或匀速直线运动状态。',
'explanation': '牛顿第一定律又称惯性定律,表述物体在没有外力作用时保持静止或匀速直线运动状态。'
};
if (actualCardData) {
Object.keys(sampleData).forEach(key => {
if (actualCardData[key.toLowerCase()] !== undefined) {
sampleData[key] = actualCardData[key.toLowerCase()];
} else if (actualCardData[key] !== undefined) {
sampleData[key] = actualCardData[key];
}
});
}
rendered = rendered.replace(/\{\{cloze:(\w+)\}\}/g, (match, fieldName) => {
if (sampleData[fieldName]) {
if (isBackTemplate) {
// 背面显示完整内容(高亮答案)
return sampleData[fieldName].replace(/\{\{c(\d+)::([^}]+?)\}\}/g,
'<span class="cloze-revealed">$2</span>'
);
} else {
// 正面显示挖空
return sampleData[fieldName].replace(/\{\{c(\d+)::([^}]+?)\}\}/g,
'<span class="cloze">[...]</span>'
);
}
}
return match;
});
rendered = rendered.replace(/\{\{text:(\w+)\}\}/g, (match, fieldName) => {
if (sampleData[fieldName]) {
return sampleData[fieldName].replace(/\{\{c(\d+)::([^}]+?)\}\}/g, '$2');
}
return match;
});
rendered = rendered.replace(/\{\{#(\w+)\}\}([\s\S]*?)\{\{\/\1\}\}/g, (match, fieldName, content) => {
if (sampleData[fieldName]) {
return content.replace(new RegExp(`\\{\\{${fieldName}\\}\\}`, 'g'), sampleData[fieldName]);
}
return '';
});
// 根据模板类型设置标签
const getTemplateTags = () => {
const templateName = templateData.name || '';
const templateId = templateData.id || '';
if (templateName.includes('学术') || templateId === 'academic-card') {
return { array: ['生物学', '分子生物学', 'DNA'], string: '生物学, 分子生物学, DNA' };
} else if (templateName.includes('编程') || templateId === 'code-card') {
return { array: ['Python', '编程', '数据结构'], string: 'Python, 编程, 数据结构' };
} else if (templateName.includes('选择题') || templateId === 'choice-card') {
return { array: ['物理', '力学', '基础'], string: '物理, 力学, 基础' };
} else if (templateName.includes('填空') || templateId === 'cloze-card') {
return { array: ['社会学', '社会工作', '基础'], string: '社会学, 社会工作, 基础' };
} else {
return { array: ['学习', '知识', '基础'], string: '学习, 知识, 基础' };
}
};
const templateTags = getTemplateTags();
rendered = rendered.replace(/\{\{#Tags\}\}([\s\S]*?)\{\{\/Tags\}\}/g, (match, tagTemplate) => {
return templateTags.array.map(tag => tagTemplate.replace(/\{\{\.\}\}/g, tag)).join('');
});
rendered = rendered.replace(/\{\{Tags\}\}/g, templateTags.string);
Object.entries(sampleData).forEach(([key, value]) => {
if (!rendered.includes(`{{cloze:${key}}}`) && !rendered.includes(`{{text:${key}}}`)) {
rendered = rendered.replace(new RegExp(`\\{\\{${key}\\}\\}`, 'g'), value);
}
});
rendered = rendered.replace(/\{\{\.\}\}/g, '');
rendered = rendered.replace(/\{\{[^}]*\}\}/g, '');
return rendered;
};
|
0000cd/wolf-set
| 17,823 |
themes/bluf/layouts/index - 副本2.html
|
<!DOCTYPE html>
<html lang="{{ .Site.LanguageCode }}">
<head>
{{ partial "head.html" . }}
<title>{{ .Site.Title }}</title>
<meta name="description" content="{{ .Site.Params.description }}" />
<meta name="keywords" content="{{ range .Site.Params.keywords }}{{ . }},{{ end }}" />
</head>
<body>
<div class="top-bar">
<div class="top-bar-inner">
<div class="top-bar-title">
<a href="{{ .Site.BaseURL }}">
<img class="top-bar-logo" src="/logo.webp" alt="Logo">
</a>
<h1 class="top-title" style="font-size: 1em;">{{ .Site.Params.pagename }}</h1>
<noscript>{{ .Site.Params.alias }}</noscript>
</div>
<nav class="top-bar-nav">
<div class="menu-container">
<button class="theme-toggle" id="themeToggle" title="切换深浅配色">
深色模式
</button>
</div>
{{ with .Site.Data.navbar.external_links }}
<div class="menu-container external_links">
{{ range . }}
<a href="{{ .url | safeURL }}" target="_blank" class="menu-toggle exlink" rel="noopener"
{{ if $.Site.Params.enableUmami }}data-umami-event="NAV-{{ .name }}" {{ end }}>
{{ .name }}
</a>
{{ end }}
</div>
{{ end }}
{{ range .Site.Data.navbar.categories }}
<div class="menu-container categories">
<div class="menu-toggle" id="menu-toggle-{{ .id }}">{{ .name }}</div>
<div class="nav-button filter-button-group" id="filter-group-{{ .id }}">
{{ range .tags }}
<button class="menu-toggle-btn filter-btn" data-filter=".{{ index $.Site.Data.tag_classes . }}">{{ . }}</button>
{{ end }}
</div>
</div>
{{ end }}
{{ with .Site.Data.navbar.hot_tags }}
<div class="hot-tags-container filter-button-group">
{{ range . }}
<button class="hot-tag filter-btn" data-filter=".{{ index $.Site.Data.tag_classes . }}">{{ . }}</button>
{{ end }}
</div>
{{ end }}
</nav>
</div>
</div>
<div class="grid" id="myGrid">
{{ range $index, $element := .Site.Data.cards }}
{{ $title := .title }}
<article id="{{ .title }}">
<div class="grid-item {{ range .tags }}{{ index $.Site.Data.tag_classes . }} {{ end }}
{{- with .hex -}}
{{ partial "getColorCategory" . }}
{{- end -}}">
{{/* 处理链接变量 */}}
{{ $link0 := false }}
{{ with .links }}
{{ if reflect.IsSlice . }}
{{ $link0 = (index . 0).url | safeURL }}
{{ else }}
{{ $link0 = . | safeURL }}
{{ end }}
{{ end }}
{{ $media := .media | default false }}
<div class="grid-item-head">
{{ $extensions := slice "jpg" "jpeg" "png" "gif" "webp" }}
{{ $galleryPath := "assets/gallery" }}
{{ $galleryPublicPath := "gallery" }}
{{ $folders := readDir $galleryPath }}
{{ range $ext := $extensions }}
{{ $imgPath := printf "img/%s.%s" $title $ext }}
{{ if (resources.Get $imgPath) }}
{{ $image := resources.Get $imgPath }}
{{ $displayWidth := 255 }}
{{ $ratio := div (float $image.Height) $image.Width }}
{{ $displayHeight := math.Round (mul $displayWidth $ratio) }}
{{ if $.Site.Params.gallery }}
{{/* 查找是否存在对应的画廊文件夹 */}}
{{ $matchedFolder := false }}
{{ range $folder := $folders }}
{{- if and $folder.IsDir (eq (lower $folder.Name) (lower $title)) -}}
{{ $matchedFolder = true }}
{{ $folderName := $folder.Name }}
<div class="gallery" {{ if $.Site.Params.enableUmami}}data-umami-event="GALLERY-{{ $title }}" {{ end }}>
<a href="{{ $image.RelPermalink | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" id="cover" aria-label="{{ $title }}-cover">
<img class="grid-item-img cover-img" src="{{ $image.RelPermalink }}" width="{{ $displayWidth }}"
height="{{ $displayHeight }}" alt="" {{ if ge $index 10 }}loading="lazy" {{ end }}
onload="this.classList.add('loaded')" title="查看画廊">
<div class="cover-line" ></div>
</a>
{{ if $media }}
{{ if reflect.IsSlice $media }}
{{ range $media }}
<a href="{{ .url | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" style="display: none;"></a>
{{ end }}
{{ else }}
<a href="{{ $media | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" style="display: none;"></a>
{{ end }}
{{ end }}
{{ $galleryImagesPath := printf "%s/%s" $galleryPath $folderName }}
{{ $galleryImageFiles := readDir $galleryImagesPath }}
{{- range $galleryImage := $galleryImageFiles -}}
{{- $galleryImageExt := path.Ext $galleryImage.Name -}}
{{- $galleryImageExt := strings.TrimPrefix "." $galleryImageExt -}}
{{- if in $extensions $galleryImageExt -}}
{{ $galleryImageResource := resources.Get (printf "gallery/%s/%s" $folderName $galleryImage.Name) }}
{{ $galleryImagePublicPath := printf "%s/%s/%s" $galleryPublicPath $folderName $galleryImage.Name }}
<a href="{{ $galleryImageResource.RelPermalink | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" data-caption="{{ $title }} - {{ $galleryImage.Name }}" style="display: none;"></a>
{{- end -}}
{{- end -}}
</div>
{{- end -}}
{{ end }}
{{/* 如果没有找到对应的画廊文件夹 */}}
{{ if not $matchedFolder }}
{{ if $media }}
<div class="gallery" {{ if $.Site.Params.enableUmami}}data-umami-event="GALLERY-{{ $title }}" {{ end }}>
<a href="{{ $image.RelPermalink | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" id="cover" aria-label="{{ $title }}-cover">
<img class="grid-item-img cover-img" src="{{ $image.RelPermalink }}" width="{{ $displayWidth }}"
height="{{ $displayHeight }}" alt="" {{ if ge $index 10 }}loading="lazy" {{ end }}
onload="this.classList.add('loaded')" title="查看画廊">
<div class="cover-line" ></div>
</a>
{{ if reflect.IsSlice $media }}
{{ range $media }}
<a href="{{ .url | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" style="display: none;"></a>
{{ end }}
{{ else }}
<a href="{{ $media | safeURL }}" class="glightbox" data-gallery="gallery-{{ $title }}" style="display: none;"></a>
{{ end }}
</div>
{{ else }}
{{ if $link0 }}
<a href="{{ $link0 }}" target="_blank" rel="noopener" aria-label="{{ $title }}-img"
{{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ $title }}" {{ end }}>
{{ end }}
<img class="grid-item-img" src="{{ $image.RelPermalink }}" width="{{ $displayWidth }}"
height="{{ $displayHeight }}" alt="" {{ if ge $index 10 }}loading="lazy" {{ end }}
onload="this.classList.add('loaded')">
{{ if $link0 }}
</a>
{{ end }}
{{ end }}
{{ end }}
{{ else }}
{{ if $link0 }}
<a href="{{ $link0 }}" target="_blank" rel="noopener" aria-label="{{ $title }}-img"
{{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ $title }}" {{ end }}>
{{ end }}
<img class="grid-item-img" src="{{ $image.RelPermalink }}" width="{{ $displayWidth }}"
height="{{ $displayHeight }}" alt="" {{ if ge $index 10 }}loading="lazy" {{ end }}
onload="this.classList.add('loaded')">
{{ if $link0 }}
</a>
{{ end }}
{{ end }}
{{ break }}
{{ end }}
{{ end }}
{{ if $link0 }}
<a href="{{ $link0 }}" target="_blank" rel="noopener"
{{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ $title }}" {{ end }}>
{{ end }}
<header class="grid-item-header">
<h2 class="grid-item-title">{{ .title }}</h2>
<div class="grid-item-color-mark"
style="background:{{ if eq (substr .hex 0 1) "#" }}{{ .hex }}{{ else }}#{{ .hex }}{{ end }};">
</div>
</header>
{{ if $link0 }}
</a>
{{ end }}
</div>
<div class="grid-item-middle">
<div class="grid-item-tags filter-button-group">
{{ range .tags }}
<button class="filter-btn grid-item-tag"
data-filter=".{{ index $.Site.Data.tag_classes . }}">{{ . }}</button>
{{ end }}
</div>
<div class="grid-item-date" datetime="{{ .date }}">{{ .date }}</div>
</div>
{{ if $link0 }}
<a href="{{ $link0 }}" target="_blank" rel="noopener"
{{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ $title }}" {{ end }}>
{{ end }}
<section class="grid-item-description">
<p>{{ .description }}</p>
</section>
{{ if $link0 }}
</a>
{{ end }}
{{ if reflect.IsSlice .links }}
{{ if gt (len .links) 1 }}
<nav class="grid-item-links">
{{ range after 1 .links }}
<a href="{{ .url | safeURL }}" target="_blank" rel="noopener"
{{ if $.Site.Params.enableUmami}}data-umami-event="LINK-{{ $title }}-{{ .name }}" {{ end }}>
{{ .name }}
</a>
{{ end }}
</nav>
{{ end }}
{{ end }}
</div>
</article>
{{ end }}
</div>
<button id="reset-filters" onclick="showConfetti()">✕</button>
<script src="/js/isotope.min.js"></script>
{{ $js := resources.Get "js/script.new.js" }}
{{ $secureJS := $js | resources.Minify | resources.Fingerprint }}
<script src="{{ $secureJS.RelPermalink }}" integrity="{{ $secureJS.Data.Integrity }}"></script>
<script>
window.addEventListener('load', function() {
document.getElementById('myGrid').classList.add('show');
});
</script>
{{ if .Site.Params.greetings }}
<div class="greeting-widget">
<div class="avatar">
<img src="/avatar.webp" alt="Avatar">
</div>
<div class="message">
<span id="random-greeting"></span>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const greetings = {{ .Site.Params.greetings }};
const mobileGreetings = {{ .Site.Params.mobileGreetings | default .Site.Params.greetings }};
const widget = document.querySelector('.greeting-widget');
const greetingEl = document.getElementById('random-greeting');
const isMobile = window.matchMedia('(max-width: 768px)').matches;
const greetingArray = isMobile ? mobileGreetings : greetings;
const randomIndex = Math.floor(Math.random() * greetingArray.length);
greetingEl.textContent = greetingArray[randomIndex];
setTimeout(() => {
widget.classList.add('show');
}, 500);
setTimeout(() => {
widget.classList.remove('show');
}, 3500);
});
</script>
{{ partial "footer.html" . }}
{{ end }}
{{ with .Site.Params.confettiEmojis }}
<script>
document.addEventListener('DOMContentLoaded', function() {
// 动态加载 js-confetti 脚本
const script = document.createElement('script');
script.src = '/js/js-confetti.js';
script.onload = function() {
// js-confetti 加载完成后初始化
const jsConfetti = new JSConfetti();
// 定义显示五彩纸屑的函数
window.showConfetti = function() {
jsConfetti.addConfetti();
jsConfetti.addConfetti({
emojis: {{ . }},
emojiSize: 60,
confettiNumber: 30
});
}
};
document.head.appendChild(script);
});
</script>
{{ end }}
{{ if .Site.Params.gallery }}
<script>
document.addEventListener('DOMContentLoaded', function() {
// 动态加载 CSS
const linkElement = document.createElement('link');
linkElement.rel = 'stylesheet';
linkElement.href = '/css/glightbox.min.css';
document.head.appendChild(linkElement);
// 动态加载 JS
const script = document.createElement('script');
script.src = '/js/glightbox.min.js';
script.onload = () => {
// JS加载完成后初始化 GLightbox
const lightbox = GLightbox({
loop: true,
});
lightbox.on('open', () => {
// 延迟500毫秒后自动跳到下一页
setTimeout(() => {
lightbox.nextSlide();
}, 500);
});
};
document.head.appendChild(script);
});
{{ if eq hugo.Environment "production" }}
{{ if $.Site.Params.enableUmami }}
document.querySelectorAll('.gallery').forEach(gallery => {
const eventName = gallery.dataset.umamiEvent;
let canTrack = true;
gallery.querySelectorAll('.glightbox').forEach(link => {
link.addEventListener('click', () => {
if (canTrack) {
window.umami?.track(eventName);
canTrack = false;
setTimeout(() => canTrack = true, 3000);
}
});
});
});
{{ end }}
{{ end }}
</script>
{{ end }}
</body>
</html>
|
0000cd/wolf-set
| 13,047 |
themes/bluf/layouts/index - 副本.html
|
<!DOCTYPE html>
<html lang="{{ .Site.LanguageCode }}">
<head>
{{ partial "head.html" . }}
<title>{{ .Site.Title }}</title>
<meta name="description" content="{{ .Site.Params.description }}" />
<meta name="keywords" content="{{ range .Site.Params.keywords }}{{ . }},{{ end }}" />
</head>
<body>
<div class="top-bar">
<div class="top-bar-inner">
<div class="top-bar-title">
<a href="{{ .Site.BaseURL }}">
<img class="top-bar-logo" src="/logo.webp" alt="Logo">
</a>
<h1 class="top-title" style="font-size: 1em;">{{ .Site.Params.pagename }}</h1>
<noscript>{{ .Site.Params.alias }}</noscript>
</div>
<nav class="top-bar-nav">
<div class="menu-container">
<button class="theme-toggle" id="themeToggle" title="切换深浅配色">
深色模式
</button>
</div>
{{ with .Site.Data.navbar.external_links }}
<div class="menu-container external_links">
{{ range . }}
<a href="{{ .url }}" target="_blank" class="menu-toggle exlink" rel="noopener"
{{ if $.Site.Params.enableUmami }}data-umami-event="NAV-{{ .name }}" {{ end }}>
{{ .name }}
</a>
{{ end }}
</div>
{{ end }}
{{ range .Site.Data.navbar.categories }}
<div class="menu-container categories">
<div class="menu-toggle" id="menu-toggle-{{ .id }}">{{ .name }}</div>
<div class="nav-button filter-button-group" id="filter-group-{{ .id }}">
{{ range .tags }}
<button class="menu-toggle-btn filter-btn" data-filter=".{{ index $.Site.Data.tag_classes . }}">{{ . }}</button>
{{ end }}
</div>
</div>
{{ end }}
{{ with .Site.Data.navbar.hot_tags }}
<div class="hot-tags-container filter-button-group">
{{ range . }}
<button class="hot-tag filter-btn" data-filter=".{{ index $.Site.Data.tag_classes . }}">{{ . }}</button>
{{ end }}
</div>
{{ end }}
</nav>
</div>
</div>
<div class="grid" id="myGrid">
{{ range $index, $element := .Site.Data.cards }}
{{ $title := .title }}
<article id="{{ .title }}">
<div class="grid-item {{ range .tags }}{{ index $.Site.Data.tag_classes . }} {{ end }}
{{- with .hex -}}
{{ partial "getColorCategory" . }}
{{- end -}}">
{{ if reflect.IsSlice .links }}
<a href="{{ (index .links 0).url }}" target="_blank" rel="noopener"
{{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ .title }}" {{ end }}>
{{ else }}
<a href="{{ .links | safeURL }}" target="_blank" rel="noopener"
{{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ .title }}" {{ end }}>
{{ end }}
<div class="grid-item-head">
{{ $extensions := slice "jpg" "jpeg" "png" "gif" "webp" }}
{{ $galleryPath := "assets/gallery" }}
{{ $galleryPublicPath := "gallery" }}
{{ $folders := readDir $galleryPath }}
{{ range $ext := $extensions }}
{{ $imgPath := printf "img/%s.%s" $title $ext }}
{{ if (resources.Get $imgPath) }}
{{ $image := resources.Get $imgPath }}
{{ $displayWidth := 255 }}
{{ $ratio := div (float $image.Height) $image.Width }}
{{ $displayHeight := math.Round (mul $displayWidth $ratio) }}
{{ if $.Site.Params.gallery }}
{{/* 查找是否存在对应的画廊文件夹 */}}
{{ $matchedFolder := false }}
{{ range $folder := $folders }}
{{- if and $folder.IsDir (eq (lower $folder.Name) (lower $title)) -}}
{{ $matchedFolder = true }}
{{ $folderName := $folder.Name }}
<div class="gallery" {{ if $.Site.Params.enableUmami}}data-umami-event="GALLERY-{{ $title }}" {{ end }}>
<a href="{{ $image.RelPermalink }}" id="cover" >
<img class="grid-item-img cover-img" src="{{ $image.RelPermalink }}" width="{{ $displayWidth }}"
height="{{ $displayHeight }}" alt="" {{ if ge $index 10 }}loading="lazy" {{ end }}
onload="this.classList.add('loaded')" title="查看画廊">
<div class="cover-line" ></div>
</a>
{{ $galleryImagesPath := printf "%s/%s" $galleryPath $folderName }}
{{ $galleryImageFiles := readDir $galleryImagesPath }}
{{- range $galleryImage := $galleryImageFiles -}}
{{- $galleryImageExt := path.Ext $galleryImage.Name -}}
{{- $galleryImageExt := strings.TrimPrefix "." $galleryImageExt -}}
{{- if in $extensions $galleryImageExt -}}
{{ $galleryImageResource := resources.Get (printf "gallery/%s/%s" $folderName $galleryImage.Name) }}
{{ $galleryImagePublicPath := printf "%s/%s/%s" $galleryPublicPath $folderName $galleryImage.Name }}
<a href="{{ $galleryImageResource.RelPermalink }}" data-caption="{{ $title }} - {{ $galleryImage.Name }}" style="display: none;"></a>
{{- end -}}
{{- end -}}
</div>
{{- end -}}
{{ end }}
{{/* 如果没有找到对应的画廊文件夹,则只显示单张图片 */}}
{{ if not $matchedFolder }}
<img class="grid-item-img" src="{{ $image.RelPermalink }}" width="{{ $displayWidth }}"
height="{{ $displayHeight }}" alt="" {{ if ge $index 10 }}loading="lazy" {{ end }}
onload="this.classList.add('loaded')">
{{ end }}
{{ else }}
<img class="grid-item-img" src="{{ $image.RelPermalink }}" width="{{ $displayWidth }}"
height="{{ $displayHeight }}" alt="" {{ if ge $index 10 }}loading="lazy" {{ end }}
onload="this.classList.add('loaded')">
{{ end }}
{{ break }}
{{ end }}
{{ end }}
<header class="grid-item-header">
<h2 class="grid-item-title">{{ .title }}</h2>
<div class="grid-item-color-mark"
style="background:{{ if eq (substr .hex 0 1) "#" }}{{ .hex }}{{ else }}#{{ .hex }}{{ end }};">
</div>
</header>
</div>
</a>
<div class="grid-item-middle">
<div class="grid-item-tags filter-button-group">
{{ range .tags }}
<button class="filter-btn grid-item-tag"
data-filter=".{{ index $.Site.Data.tag_classes . }}">{{ . }}</button>
{{ end }}
</div>
<div class="grid-item-date" datetime="{{ .date }}">{{ .date }}</div>
</div>
{{ if reflect.IsSlice .links }}
<a href="{{ (index .links 0).url }}" target="_blank" rel="noopener"
{{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ .title }}" {{ end }}>
{{ else }}
<a href="{{ .links | safeURL }}" target="_blank" rel="noopener"
{{ if $.Site.Params.enableUmami}}data-umami-event="CARD-{{ .title }}" {{ end }}>
{{ end }}
<section class="grid-item-description">
<p>{{ .description }}</p>
</section>
</a>
{{ if reflect.IsSlice .links }}
{{ if gt (len .links) 1 }}
<nav class="grid-item-links">
{{ range after 1 .links }}
<a href="{{ .url }}" target="_blank" rel="noopener"
{{ if $.Site.Params.enableUmami}}data-umami-event="LINK-{{ $title }}-{{ .name }}" {{ end }}>
{{ .name }}
</a>
{{ end }}
</nav>
{{ end }}
{{ end }}
</div>
</article>
{{ end }}
</div>
<button id="reset-filters" onclick="showConfetti()">✕</button>
<script src="/js/isotope.min.js"></script>
{{ $js := resources.Get "js/script.new.js" }}
{{ $secureJS := $js | resources.Minify | resources.Fingerprint }}
<script src="{{ $secureJS.RelPermalink }}" integrity="{{ $secureJS.Data.Integrity }}"></script>
<script>
window.addEventListener('load', function() {
document.getElementById('myGrid').classList.add('show');
});
</script>
{{ if .Site.Params.greetings }}
<div class="greeting-widget">
<div class="avatar">
<img src="avatar.webp" alt="Avatar">
</div>
<div class="message">
<span id="random-greeting"></span>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const greetings = {{ .Site.Params.greetings }};
const mobileGreetings = {{ .Site.Params.mobileGreetings | default .Site.Params.greetings }};
const widget = document.querySelector('.greeting-widget');
const greetingEl = document.getElementById('random-greeting');
const isMobile = window.matchMedia('(max-width: 768px)').matches;
const greetingArray = isMobile ? mobileGreetings : greetings;
const randomIndex = Math.floor(Math.random() * greetingArray.length);
greetingEl.textContent = greetingArray[randomIndex];
setTimeout(() => {
widget.classList.add('show');
}, 500);
setTimeout(() => {
widget.classList.remove('show');
}, 3500);
});
</script>
{{ partial "footer.html" . }}
{{ end }}
{{ with .Site.Params.confettiEmojis }}
<script src="/js/js-confetti.js"></script>
<script>
const jsConfetti = new JSConfetti();
function showConfetti() {
jsConfetti.addConfetti();
jsConfetti.addConfetti({
emojis: {{ . }},
emojiSize: 60,
confettiNumber: 30
});
}
</script>
{{ end }}
{{ if .Site.Params.gallery }}
<script src="/js/baguetteBox.min.js"></script>
<script>
// 动态加载 CSS 文件的函数
function loadCSS(href) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = href;
document.head.appendChild(link);
}
// 加载 CSS
loadCSS('/css/baguetteBox.min.css');
// 等页面加载完成后执行
window.addEventListener('load', function() {
// 初始化 baguetteBox
baguetteBox.run('.gallery', {
afterShow: function() {
// 在相册打开后,切换到下一张图片
setTimeout(function() {
// 延迟 500ms 切换到下一张
baguetteBox.showNext();
}, 500);
}
});
});
</script>
{{ end }}
</body>
</html>
|
000haoji/deep-student
| 74,644 |
src/components/Settings.tsx
|
import React, { useState, useEffect, useCallback } from 'react';
import { SubjectConfig } from './SubjectConfig';
import {
Bot,
FlaskConical,
Target,
Settings as SettingsIcon,
Plus,
TestTube,
Edit,
Trash2,
X,
Check,
AlertTriangle,
Save,
Undo2,
Zap,
CheckCircle,
XCircle,
Book,
Box,
Cpu,
RefreshCcw,
HardDrive,
Atom,
FileText,
ScrollText,
File,
FileWarning,
BookOpen,
BookText,
StickyNote,
Library,
SquareStack,
Image,
Brain,
Palette,
Database,
PartyPopper,
Construction
} from 'lucide-react';
// Tauri 2.x API导入
import { invoke as tauriInvoke } from '@tauri-apps/api/core';
// Tauri类型声明
declare global {
interface Window {
__TAURI_INTERNALS__?: any;
}
}
// 检查是否在Tauri环境中
const isTauri = typeof window !== 'undefined' && window.__TAURI_INTERNALS__;
const invoke = isTauri ? tauriInvoke : null;
// API配置接口
interface ApiConfig {
id: string;
name: string;
apiKey: string;
baseUrl: string;
model: string;
isMultimodal: boolean;
isReasoning: boolean; // 新增:是否为推理模型
enabled: boolean;
modelAdapter: string; // 新增:模型适配器类型
}
// 系统配置接口
interface SystemConfig {
apiConfigs: ApiConfig[];
model1ConfigId: string; // 第一模型(必须是多模态)
model2ConfigId: string; // 第二模型(可以是任意类型)
reviewAnalysisModelConfigId: string; // 回顾分析模型(可以是任意类型)
ankiCardModelConfigId: string; // ANKI制卡模型(可以是任意类型)
embeddingModelConfigId: string; // 嵌入模型(RAG用)
rerankerModelConfigId: string; // 重排序模型(RAG用)
autoSave: boolean;
theme: string;
// RAG设置
ragEnabled: boolean;
ragTopK: number;
// 开发功能设置
batchAnalysisEnabled: boolean;
ankiConnectEnabled: boolean;
geminiAdapterTestEnabled: boolean; // 新增:Gemini适配器测试功能开关
imageOcclusionEnabled: boolean; // 新增:图片遮罩卡功能开关
summary_model_config_id: string; // 新增:总结模型配置ID
}
interface SettingsProps {
onBack: () => void;
}
export const Settings: React.FC<SettingsProps> = ({ onBack }) => {
const [config, setConfig] = useState<SystemConfig>({
apiConfigs: [],
model1ConfigId: '',
model2ConfigId: '',
reviewAnalysisModelConfigId: '',
ankiCardModelConfigId: '',
embeddingModelConfigId: '',
rerankerModelConfigId: '',
autoSave: true,
theme: 'light',
ragEnabled: false,
ragTopK: 5,
batchAnalysisEnabled: false,
ankiConnectEnabled: true,
geminiAdapterTestEnabled: false,
imageOcclusionEnabled: false, // 默认关闭
summary_model_config_id: ''
});
const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(true);
const [testingApi, setTestingApi] = useState<string | null>(null);
const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null);
const [activeTab, setActiveTab] = useState('apis');
const [editingApi, setEditingApi] = useState<ApiConfig | null>(null);
// 处理返回按钮,确保在返回前保存配置
const handleBack = async () => {
if (!loading) {
await handleSave(true); // 静默保存
}
onBack();
};
const showMessage = (type: 'success' | 'error', text: string) => {
setMessage({ type, text });
setTimeout(() => setMessage(null), 3000);
};
const loadConfig = async () => {
setLoading(true);
try {
if (invoke) {
// 使用新的专用API配置管理命令
const [apiConfigs, modelAssignments, autoSave, theme, ragEnabled, ragTopK, batchAnalysisEnabled, ankiConnectEnabled, geminiAdapterTestEnabled, imageOcclusionEnabled] = await Promise.all([
invoke('get_api_configurations').catch(() => []) as Promise<ApiConfig[]>,
invoke('get_model_assignments').catch(() => ({
model1_config_id: null,
model2_config_id: null,
review_analysis_model_config_id: null,
anki_card_model_config_id: null,
embedding_model_config_id: null,
reranker_model_config_id: null,
summary_model_config_id: null // 新增
})) as Promise<{
model1_config_id: string | null,
model2_config_id: string | null,
review_analysis_model_config_id: string | null,
anki_card_model_config_id: string | null,
embedding_model_config_id: string | null,
reranker_model_config_id: string | null,
summary_model_config_id: string | null // 新增
}>,
invoke('get_setting', { key: 'auto_save' }).catch(() => 'true') as Promise<string>,
invoke('get_setting', { key: 'theme' }).catch(() => 'light') as Promise<string>,
invoke('get_setting', { key: 'rag_enabled' }).catch(() => 'false') as Promise<string>,
invoke('get_setting', { key: 'rag_top_k' }).catch(() => '5') as Promise<string>,
invoke('get_setting', { key: 'batch_analysis_enabled' }).catch(() => 'false') as Promise<string>,
invoke('get_setting', { key: 'anki_connect_enabled' }).catch(() => 'true') as Promise<string>,
invoke('get_setting', { key: 'gemini_adapter_test_enabled' }).catch(() => 'false') as Promise<string>,
invoke('get_setting', { key: 'image_occlusion_enabled' }).catch(() => 'false') as Promise<string>,
]);
const newConfig = {
apiConfigs: apiConfigs || [],
model1ConfigId: modelAssignments?.model1_config_id || '',
model2ConfigId: modelAssignments?.model2_config_id || '',
reviewAnalysisModelConfigId: modelAssignments?.review_analysis_model_config_id || '',
ankiCardModelConfigId: modelAssignments?.anki_card_model_config_id || '',
embeddingModelConfigId: modelAssignments?.embedding_model_config_id || '',
rerankerModelConfigId: modelAssignments?.reranker_model_config_id || '',
summary_model_config_id: modelAssignments?.summary_model_config_id || '', // 新增
autoSave: (autoSave || 'true') === 'true',
theme: theme || 'light',
ragEnabled: (ragEnabled || 'false') === 'true',
ragTopK: parseInt(ragTopK || '5', 10),
batchAnalysisEnabled: (batchAnalysisEnabled || 'false') === 'true',
ankiConnectEnabled: (ankiConnectEnabled || 'true') === 'true',
geminiAdapterTestEnabled: (geminiAdapterTestEnabled || 'false') === 'true',
imageOcclusionEnabled: (imageOcclusionEnabled || 'false') === 'true'
};
console.log('加载的配置:', {
apiConfigs: newConfig.apiConfigs.length,
model1ConfigId: newConfig.model1ConfigId,
model2ConfigId: newConfig.model2ConfigId,
reviewAnalysisModelConfigId: newConfig.reviewAnalysisModelConfigId,
modelAssignments
});
setConfig(newConfig);
} else {
// 浏览器环境
const savedConfig = localStorage.getItem('ai-mistake-manager-config');
if (savedConfig) {
setConfig(JSON.parse(savedConfig));
}
}
} catch (error) {
console.error('加载配置失败:', error);
showMessage('error', '加载配置失败: ' + error);
} finally {
setLoading(false);
}
};
const handleSave = useCallback(async (silent = false) => {
setSaving(true);
try {
if (invoke) {
await Promise.all([
invoke('save_api_configurations', { configs: config.apiConfigs }),
invoke('save_model_assignments', {
assignments: {
model1_config_id: config.model1ConfigId || null,
model2_config_id: config.model2ConfigId || null,
review_analysis_model_config_id: config.reviewAnalysisModelConfigId || null,
anki_card_model_config_id: config.ankiCardModelConfigId || null,
embedding_model_config_id: config.embeddingModelConfigId || null,
reranker_model_config_id: config.rerankerModelConfigId || null,
summary_model_config_id: config.summary_model_config_id || null // 新增
}
}),
invoke('save_setting', { key: 'auto_save', value: config.autoSave.toString() }),
invoke('save_setting', { key: 'theme', value: config.theme }),
invoke('save_setting', { key: 'rag_enabled', value: config.ragEnabled.toString() }),
invoke('save_setting', { key: 'rag_top_k', value: config.ragTopK.toString() }),
invoke('save_setting', { key: 'batch_analysis_enabled', value: config.batchAnalysisEnabled.toString() }),
invoke('save_setting', { key: 'anki_connect_enabled', value: config.ankiConnectEnabled.toString() }),
invoke('save_setting', { key: 'gemini_adapter_test_enabled', value: config.geminiAdapterTestEnabled.toString() }),
invoke('save_setting', { key: 'image_occlusion_enabled', value: config.imageOcclusionEnabled.toString() }),
]);
if (!silent) {
showMessage('success', '配置保存成功!');
}
// 触发设置变更事件,通知其他组件
window.dispatchEvent(new CustomEvent('systemSettingsChanged', {
detail: { ankiConnectEnabled: config.ankiConnectEnabled }
}));
} else {
localStorage.setItem('ai-mistake-manager-config', JSON.stringify(config));
if (!silent) {
showMessage('success', '配置保存成功!(浏览器模式)');
}
}
} catch (error) {
console.error('保存配置失败:', error);
if (!silent) {
showMessage('error', '配置保存失败: ' + error);
}
} finally {
setSaving(false);
}
}, [config, invoke]);
// 标签页切换时自动保存配置
const handleTabChange = async (newTab: string) => {
if (!loading) {
// 在切换标签页前先保存当前配置
await handleSave(true);
}
setActiveTab(newTab);
};
useEffect(() => {
loadConfig();
}, []);
// 自动保存配置(当配置发生变化时)
// 注意:模型分配已经在onChange中立即保存,这里主要处理其他配置项
useEffect(() => {
if (!loading && config.autoSave) {
const timeoutId = setTimeout(() => {
// 只保存API配置和通用设置,模型分配已经立即保存了
handleSave(true); // 静默保存
}, 1000); // 1秒后自动保存
return () => clearTimeout(timeoutId);
}
}, [config.apiConfigs, config.autoSave, config.theme, loading, handleSave]);
const testApiConnection = async (apiId: string) => {
const api = config.apiConfigs.find(a => a.id === apiId);
if (!api || !api.apiKey.trim()) {
showMessage('error', '请先输入API密钥');
return;
}
if (!api.model.trim()) {
showMessage('error', '请先设置模型名称');
return;
}
setTestingApi(apiId);
try {
if (invoke) {
// 使用用户指定的模型名称进行测试
const result = await invoke('test_api_connection', {
apiKey: api.apiKey,
apiBase: api.baseUrl,
model: api.model // 传递用户指定的模型名称
});
if (result) {
showMessage('success', `${api.name} (${api.model}) API连接测试成功!`);
} else {
showMessage('error', `${api.name} (${api.model}) API连接测试失败`);
}
} else {
// 浏览器环境模拟
await new Promise(resolve => setTimeout(resolve, 2000));
showMessage('success', `${api.name} API连接测试成功!(模拟)`);
}
} catch (error) {
console.error('连接测试失败:', error);
showMessage('error', `${api.name} 连接测试失败: ` + error);
} finally {
setTestingApi(null);
}
};
const addOrUpdateApi = async (api: ApiConfig) => {
setConfig(prev => {
const existingIndex = prev.apiConfigs.findIndex(a => a.id === api.id);
if (existingIndex >= 0) {
// 更新现有配置
const newConfigs = [...prev.apiConfigs];
newConfigs[existingIndex] = api;
return { ...prev, apiConfigs: newConfigs };
} else {
// 添加新配置
return { ...prev, apiConfigs: [...prev.apiConfigs, api] };
}
});
setEditingApi(null);
// 立即保存
if (!config.autoSave) {
await handleSave(true);
}
};
const deleteApi = async (apiId: string) => {
// 检查是否被使用
if (config.model1ConfigId === apiId ||
config.model2ConfigId === apiId ||
config.reviewAnalysisModelConfigId === apiId ||
config.ankiCardModelConfigId === apiId ||
config.embeddingModelConfigId === apiId ||
config.rerankerModelConfigId === apiId ||
config.summary_model_config_id === apiId // 新增
) {
showMessage('error', '该API配置正在被使用,无法删除');
return;
}
if (confirm('确定要删除这个API配置吗?')) {
setConfig(prev => {
const newConfig = {
...prev,
apiConfigs: prev.apiConfigs.filter(a => a.id !== apiId)
};
return newConfig;
});
// 立即保存删除操作
setTimeout(async () => {
await handleSave(true);
showMessage('success', 'API配置已删除');
}, 100);
}
};
const getMultimodalApis = () => {
return config.apiConfigs.filter(api => api.isMultimodal && api.enabled);
};
const getAllEnabledApis = () => {
return config.apiConfigs.filter(api => api.enabled);
};
// 渲染API类型图标的辅助函数
const renderApiTypeIcons = (api: ApiConfig) => {
return (
<span style={{ display: 'inline-flex', alignItems: 'center', gap: '4px', marginLeft: '8px' }}>
{api.isMultimodal ? <Image size={14} color="#4a90e2" /> : <FileText size={14} color="#6b7280" />}
{api.isReasoning && <Brain size={14} color="#8b5cf6" />}
</span>
);
};
if (loading) {
return (
<div className="settings" style={{ display: 'flex', flexDirection: 'column', height: 'calc(100vh - 80px)' /* 调整以适应可能的外部边距/标题栏 */ }}>
<div className="settings-header">
<button onClick={handleBack} className="back-button">← 返回</button>
<h2>设置</h2>
</div>
<div className="settings-content" style={{ textAlign: 'center', padding: '2rem' }}>
<div>加载配置中...</div>
</div>
</div>
);
}
return (
<div style={{
width: '100%',
height: '100%',
overflow: 'auto',
background: '#f8fafc'
}}>
{/* 头部区域 - 白底统一样式 */}
<div style={{
padding: '1.5rem 2rem',
borderBottom: '1px solid #e2e8f0',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
background: '#ffffff',
boxShadow: '0 1px 3px rgba(0, 0, 0, 0.05)',
minHeight: '72px',
boxSizing: 'border-box'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
<svg style={{ width: '20px', height: '20px', color: '#4a5568' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
<h1 style={{ fontSize: '1.5rem', fontWeight: '600', margin: 0, color: '#2d3748' }}>系统设置</h1>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
{config.autoSave && (
<div style={{
background: 'rgba(40, 167, 69, 0.1)',
border: '1px solid rgba(40, 167, 69, 0.3)',
color: '#22c55e',
padding: '6px 12px',
borderRadius: '6px',
fontSize: '12px',
fontWeight: '500',
display: 'inline-flex',
alignItems: 'center',
gap: '4px'
}}>
<CheckCircle size={14} style={{ marginRight: '4px' }} />
自动保存
</div>
)}
{saving && (
<div style={{
background: 'rgba(59, 130, 246, 0.1)',
border: '1px solid rgba(59, 130, 246, 0.3)',
color: '#3b82f6',
padding: '6px 12px',
borderRadius: '6px',
fontSize: '12px',
fontWeight: '500',
display: 'inline-flex',
alignItems: 'center',
gap: '6px'
}}>
<Save size={14} style={{ marginRight: '4px' }} />
保存中...
</div>
)}
{!isTauri && (
<div style={{
background: 'rgba(156, 163, 175, 0.1)',
border: '1px solid rgba(156, 163, 175, 0.3)',
color: '#6b7280',
padding: '6px 12px',
borderRadius: '6px',
fontSize: '12px',
fontWeight: '500'
}}>
浏览器模式
</div>
)}
</div>
</div>
{message && (
<div className={`message ${message.type}`} style={{
padding: '0.75rem 1.5rem',
margin: '0 1.5rem',
borderRadius: '4px',
backgroundColor: message.type === 'success' ? '#d4edda' : '#f8d7da',
color: message.type === 'success' ? '#155724' : '#721c24',
border: `1px solid ${message.type === 'success' ? '#c3e6cb' : '#f5c6cb'}`
}}>
{message.text}
</div>
)}
<div className="settings-content" style={{ padding: '24px', background: 'transparent' }}>
<div style={{
backgroundColor: 'white',
padding: '1.5rem',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
marginBottom: '1.5rem'
}}>
<div style={{
display: 'flex',
gap: '8px',
marginBottom: '0',
flexShrink: 0,
borderBottom: '1px solid #e5e7eb',
paddingBottom: '0'
}}>
<button
onClick={() => handleTabChange('apis')}
style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
padding: '12px 20px',
border: 'none',
background: activeTab === 'apis' ? '#f0f9ff' : 'transparent',
color: activeTab === 'apis' ? '#0369a1' : '#6b7280',
borderRadius: '8px',
fontWeight: activeTab === 'apis' ? '600' : '500',
fontSize: '14px',
cursor: 'pointer',
transition: 'all 0.2s ease',
position: 'relative',
borderBottom: activeTab === 'apis' ? '3px solid #0369a1' : '3px solid transparent',
marginBottom: '-1px'
}}
onMouseEnter={(e) => {
if (activeTab !== 'apis') {
e.currentTarget.style.background = '#f3f4f6';
e.currentTarget.style.color = '#374151';
}
}}
onMouseLeave={(e) => {
if (activeTab !== 'apis') {
e.currentTarget.style.background = 'transparent';
e.currentTarget.style.color = '#6b7280';
}
}}
>
<Bot style={{ width: '16px', height: '16px', marginRight: '4px' }} />
<span>API配置</span>
</button>
<button
onClick={() => handleTabChange('models')}
style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
padding: '12px 20px',
border: 'none',
background: activeTab === 'models' ? '#f0f9ff' : 'transparent',
color: activeTab === 'models' ? '#0369a1' : '#6b7280',
borderRadius: '8px',
fontWeight: activeTab === 'models' ? '600' : '500',
fontSize: '14px',
cursor: 'pointer',
transition: 'all 0.2s ease',
position: 'relative',
borderBottom: activeTab === 'models' ? '3px solid #0369a1' : '3px solid transparent',
marginBottom: '-1px'
}}
onMouseEnter={(e) => {
if (activeTab !== 'models') {
e.currentTarget.style.background = '#f3f4f6';
e.currentTarget.style.color = '#374151';
}
}}
onMouseLeave={(e) => {
if (activeTab !== 'models') {
e.currentTarget.style.background = 'transparent';
e.currentTarget.style.color = '#6b7280';
}
}}
>
<FlaskConical style={{ width: '16px', height: '16px', marginRight: '4px' }} />
<span>模型分配</span>
</button>
<button
onClick={() => handleTabChange('subjects')}
style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
padding: '12px 20px',
border: 'none',
background: activeTab === 'subjects' ? '#f0f9ff' : 'transparent',
color: activeTab === 'subjects' ? '#0369a1' : '#6b7280',
borderRadius: '8px',
fontWeight: activeTab === 'subjects' ? '600' : '500',
fontSize: '14px',
cursor: 'pointer',
transition: 'all 0.2s ease',
position: 'relative',
borderBottom: activeTab === 'subjects' ? '3px solid #0369a1' : '3px solid transparent',
marginBottom: '-1px'
}}
onMouseEnter={(e) => {
if (activeTab !== 'subjects') {
e.currentTarget.style.background = '#f3f4f6';
e.currentTarget.style.color = '#374151';
}
}}
onMouseLeave={(e) => {
if (activeTab !== 'subjects') {
e.currentTarget.style.background = 'transparent';
e.currentTarget.style.color = '#6b7280';
}
}}
>
<Target style={{ width: '16px', height: '16px', marginRight: '4px' }} />
<span>科目配置</span>
</button>
<button
onClick={() => handleTabChange('general')}
style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
padding: '12px 20px',
border: 'none',
background: activeTab === 'general' ? '#f0f9ff' : 'transparent',
color: activeTab === 'general' ? '#0369a1' : '#6b7280',
borderRadius: '8px',
fontWeight: activeTab === 'general' ? '600' : '500',
fontSize: '14px',
cursor: 'pointer',
transition: 'all 0.2s ease',
position: 'relative',
borderBottom: activeTab === 'general' ? '3px solid #0369a1' : '3px solid transparent',
marginBottom: '-1px'
}}
onMouseEnter={(e) => {
if (activeTab !== 'general') {
e.currentTarget.style.background = '#f3f4f6';
e.currentTarget.style.color = '#374151';
}
}}
onMouseLeave={(e) => {
if (activeTab !== 'general') {
e.currentTarget.style.background = 'transparent';
e.currentTarget.style.color = '#6b7280';
}
}}
>
<SettingsIcon style={{ width: '16px', height: '16px', marginRight: '4px' }} />
<span>通用设置</span>
</button>
</div>
</div>
{/* API配置管理 */}
{activeTab === 'apis' && (
<div style={{
backgroundColor: 'white',
padding: '1.5rem',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
marginBottom: '1.5rem'
}}>
<div className="apis-section">
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
<h3>API配置管理</h3>
<button
className="btn btn-success add-api-button"
onClick={() => setEditingApi({
id: `api_${Date.now()}`,
name: '新API配置',
apiKey: '',
baseUrl: 'https://api.openai.com/v1',
model: '',
isMultimodal: false,
isReasoning: false,
enabled: true,
modelAdapter: 'general'
})}
>
<Plus style={{ width: '16px', height: '16px', marginRight: '4px' }} /> 添加API配置
</button>
</div>
{config.apiConfigs.length === 0 ? (
<div style={{
textAlign: 'center',
padding: '40px',
color: '#666',
border: '2px dashed #ddd',
borderRadius: '8px'
}}>
<Bot style={{ width: '48px', height: '48px', marginBottom: '16px', color: '#ccc' }} />
<div style={{ fontSize: '18px', marginBottom: '8px' }}>还没有API配置</div>
<div style={{ fontSize: '14px' }}>点击上方"添加API配置"按钮开始设置</div>
</div>
) : (
config.apiConfigs.map(api => (
<div key={api.id} className="api-card" style={{
border: '1px solid #ddd',
borderRadius: '8px',
padding: '20px',
marginBottom: '15px',
backgroundColor: api.enabled ? '#fff' : '#f8f9fa'
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
<h4 style={{ margin: '0 0 10px 0' }}>{api.name}</h4>
<div style={{ fontSize: '14px', color: '#666' }}>
<div><strong>模型:</strong> {api.model || '未设置'}</div>
<div><strong>地址:</strong> {api.baseUrl}</div>
<div><strong>类型:</strong> {api.isMultimodal ? <FileText style={{ display: 'inline', width: '16px', height: '16px', verticalAlign: 'middle', marginRight: '4px' }} /> : <Book style={{ display: 'inline', width: '16px', height: '16px', verticalAlign: 'middle', marginRight: '4px' }} />} {api.isMultimodal ? '多模态' : '纯文本'}</div>
<div><strong>推理:</strong> {api.isReasoning ? <Cpu style={{ display: 'inline', width: '16px', height: '16px', verticalAlign: 'middle', marginRight: '4px' }} /> : <RefreshCcw style={{ display: 'inline', width: '16px', height: '16px', verticalAlign: 'middle', marginRight: '4px' }} />} {api.isReasoning ? '推理模型' : '标准模型'}</div>
<div><strong>适配器:</strong> {api.modelAdapter === 'deepseek-r1' ? <Atom style={{ display: 'inline', width: '16px', height: '16px', verticalAlign: 'middle', marginRight: '4px' }} /> : <HardDrive style={{ display: 'inline', width: '16px', height: '16px', verticalAlign: 'middle', marginRight: '4px' }} />} {api.modelAdapter === 'deepseek-r1' ? 'DeepSeek-R1' : '通用模型'}</div>
<div><strong>状态:</strong> {api.enabled ? <CheckCircle style={{ display: 'inline', width: '16px', height: '16px', verticalAlign: 'middle', marginRight: '4px', color: '#28a745' }} /> : <XCircle style={{ display: 'inline', width: '16px', height: '16px', verticalAlign: 'middle', marginRight: '4px', color: '#dc3545' }} />} {api.enabled ? '启用' : '禁用'}</div>
</div>
</div>
<div style={{ display: 'flex', gap: '10px' }}>
<button
className="btn btn-primary"
onClick={() => testApiConnection(api.id)}
disabled={testingApi === api.id || !api.model.trim()}
title={!api.model.trim() ? '请先设置模型名称' : ''}
>
{testingApi === api.id ? '测试中...' : <TestTube style={{ width: '16px', height: '16px', marginRight: '4px' }} />} {testingApi === api.id ? '测试中...' : '测试连接'}
</button>
<button
className="btn btn-secondary"
onClick={() => setEditingApi(api)}
>
<Edit style={{ width: '16px', height: '16px', marginRight: '4px' }} /> 编辑
</button>
<button
className="btn btn-danger"
onClick={() => deleteApi(api.id)}
>
<Trash2 style={{ width: '16px', height: '16px', marginRight: '4px' }} /> 删除
</button>
</div>
</div>
</div>
))
)}
</div>
</div>
)}
{/* 模型分配 */}
{activeTab === 'models' && (
<div style={{
backgroundColor: 'white',
padding: '1.5rem',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
marginBottom: '1.5rem'
}}>
<div className="models-section">
<h3>模型分配</h3>
<p style={{ color: '#666', marginBottom: '20px' }}>
为系统的各项AI功能分配合适的模型。不同的功能(如OCR识别、题目解答、回顾分析、ANKI制卡、知识库嵌入、总结生成等)可能需要不同类型或能力的模型以达到最佳效果。请根据您的API配置和需求进行选择。
</p>
<div style={{ display: 'grid', gap: '20px' }}>
{/* 第一模型配置 */}
<div className="model-config" style={{
border: '1px solid #ddd',
borderRadius: '8px',
padding: '20px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '15px' }}>
<Image size={20} color="#4a90e2" />
<h4 style={{ margin: 0 }}>第一模型(OCR + 分类)</h4>
</div>
<p style={{ color: '#666', fontSize: '14px', marginBottom: '15px' }}>
用于图片识别和题目分类,必须选择多模态模型
</p>
<select
value={config.model1ConfigId}
onChange={async (e) => {
const newValue = e.target.value;
// 立即保存模型选择,使用最新的值
try {
if (invoke) {
await invoke('save_model_assignments', {
assignments: {
model1_config_id: newValue || null,
model2_config_id: config.model2ConfigId || null,
review_analysis_model_config_id: config.reviewAnalysisModelConfigId || null,
anki_card_model_config_id: config.ankiCardModelConfigId || null,
embedding_model_config_id: config.embeddingModelConfigId || null, // 保持其他字段
reranker_model_config_id: config.rerankerModelConfigId || null, // 保持其他字段
summary_model_config_id: config.summary_model_config_id || null // 保持其他字段
}
});
// 保存成功后再更新前端状态
setConfig(prev => ({ ...prev, model1ConfigId: newValue }));
showMessage('success', '第一模型配置已保存');
console.log('第一模型配置保存成功:', newValue);
// 验证保存结果
setTimeout(async () => {
try {
const verification = await invoke('get_model_assignments');
console.log('验证第一模型保存结果:', verification);
} catch (err) {
console.error('验证保存结果失败:', err);
}
}, 500);
}
} catch (error) {
console.error('保存第一模型配置失败:', error);
showMessage('error', '保存第一模型配置失败: ' + error);
// 保存失败时不更新前端状态
}
}}
style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
>
<option value="">请选择多模态模型...</option>
{getMultimodalApis().map(api => (
<option key={api.id} value={api.id}>
{api.name} ({api.model})
</option>
))}
</select>
{getMultimodalApis().length === 0 && (
<div style={{ color: '#dc3545', fontSize: '14px', marginTop: '8px', display: 'flex', alignItems: 'center', gap: '8px' }}>
<AlertTriangle size={16} />
没有可用的多模态API配置,请先添加并启用多模态API
</div>
)}
</div>
{/* 第二模型配置 */}
<div className="model-config" style={{
border: '1px solid #ddd',
borderRadius: '8px',
padding: '20px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '15px' }}>
<Brain size={20} color="#8b5cf6" />
<h4 style={{ margin: 0 }}>第二模型(解答 + 对话)</h4>
</div>
<p style={{ color: '#666', fontSize: '14px', marginBottom: '15px' }}>
用于题目解答和对话交互,可以选择任意类型的模型
</p>
<select
value={config.model2ConfigId}
onChange={async (e) => {
const newValue = e.target.value;
// 立即保存模型选择,使用最新的值
try {
if (invoke) {
await invoke('save_model_assignments', {
assignments: {
model1_config_id: config.model1ConfigId || null,
model2_config_id: newValue || null,
review_analysis_model_config_id: config.reviewAnalysisModelConfigId || null,
anki_card_model_config_id: config.ankiCardModelConfigId || null,
embedding_model_config_id: config.embeddingModelConfigId || null, // 保持其他字段
reranker_model_config_id: config.rerankerModelConfigId || null, // 保持其他字段
summary_model_config_id: config.summary_model_config_id || null // 保持其他字段
}
});
// 保存成功后再更新前端状态
setConfig(prev => ({ ...prev, model2ConfigId: newValue }));
showMessage('success', '第二模型配置已保存');
console.log('第二模型配置保存成功:', newValue);
// 验证保存结果
setTimeout(async () => {
try {
const verification = await invoke('get_model_assignments');
console.log('验证第二模型保存结果:', verification);
} catch (err) {
console.error('验证保存结果失败:', err);
}
}, 500);
}
} catch (error) {
console.error('保存第二模型配置失败:', error);
showMessage('error', '保存第二模型配置失败: ' + error);
// 保存失败时不更新前端状态
}
}}
style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
>
<option value="">请选择模型...</option>
{getAllEnabledApis().map(api => (
<option key={api.id} value={api.id}>
{api.name} ({api.model}) {api.isMultimodal ? '[图像]' : '[文本]'} {api.isReasoning ? '[推理]' : ''}
</option>
))}
</select>
{getAllEnabledApis().length === 0 && (
<div style={{ color: '#dc3545', fontSize: '14px', marginTop: '8px', display: 'flex', alignItems: 'center', gap: '8px' }}>
<AlertTriangle size={16} />
没有可用的API配置,请先添加并启用API
</div>
)}
</div>
{/* 回顾分析模型配置 */}
<div className="model-config" style={{
border: '1px solid #ddd',
borderRadius: '8px',
padding: '20px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '15px' }}>
<Target size={20} color="#ef4444" />
<h4 style={{ margin: 0 }}>第三模型(回顾分析)</h4>
</div>
<p style={{ color: '#666', fontSize: '14px', marginBottom: '15px' }}>
用于回顾分析功能,对多个错题进行统一分析,可以选择任意类型的模型
</p>
<select
value={config.reviewAnalysisModelConfigId}
onChange={async (e) => {
const newValue = e.target.value;
// 立即保存模型选择,使用最新的值
try {
if (invoke) {
await invoke('save_model_assignments', {
assignments: {
model1_config_id: config.model1ConfigId || null,
model2_config_id: config.model2ConfigId || null,
review_analysis_model_config_id: newValue || null,
anki_card_model_config_id: config.ankiCardModelConfigId || null,
embedding_model_config_id: config.embeddingModelConfigId || null, // 保持其他字段
reranker_model_config_id: config.rerankerModelConfigId || null, // 保持其他字段
summary_model_config_id: config.summary_model_config_id || null // 保持其他字段
}
});
// 保存成功后再更新前端状态
setConfig(prev => ({ ...prev, reviewAnalysisModelConfigId: newValue }));
showMessage('success', '回顾分析模型配置已保存');
console.log('回顾分析模型配置保存成功:', newValue);
// 验证保存结果
setTimeout(async () => {
try {
const verification = await invoke('get_model_assignments');
console.log('验证回顾分析模型保存结果:', verification);
} catch (err) {
console.error('验证保存结果失败:', err);
}
}, 500);
}
} catch (error) {
console.error('保存回顾分析模型配置失败:', error);
showMessage('error', '保存回顾分析模型配置失败: ' + error);
// 保存失败时不更新前端状态
}
}}
style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
>
<option value="">请选择模型...</option>
{getAllEnabledApis().map(api => (
<option key={api.id} value={api.id}>
{api.name} ({api.model}) {api.isMultimodal ? '[图像]' : '[文本]'} {api.isReasoning ? '[推理]' : ''}
</option>
))}
</select>
{getAllEnabledApis().length === 0 && (
<div style={{ color: '#dc3545', fontSize: '14px', marginTop: '8px', display: 'flex', alignItems: 'center', gap: '8px' }}>
<AlertTriangle size={16} />
没有可用的API配置,请先添加并启用API
</div>
)}
</div>
{/* ANKI制卡模型配置 */}
<div className="model-config" style={{
border: '1px solid #ddd',
borderRadius: '8px',
padding: '20px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '15px' }}>
<Target size={20} color="#10b981" />
<h4 style={{ margin: 0 }}>ANKI制卡模型(卡片生成)</h4>
</div>
<p style={{ color: '#666', fontSize: '14px', marginBottom: '15px' }}>
用于ANKI卡片生成功能,根据学习内容智能生成问答卡片
</p>
<select
value={config.ankiCardModelConfigId}
onChange={async (e) => {
const newValue = e.target.value;
// 立即保存模型选择,使用最新的值
try {
if (invoke) {
await invoke('save_model_assignments', {
assignments: {
model1_config_id: config.model1ConfigId || null,
model2_config_id: config.model2ConfigId || null,
review_analysis_model_config_id: config.reviewAnalysisModelConfigId || null,
anki_card_model_config_id: newValue || null,
embedding_model_config_id: config.embeddingModelConfigId || null, // 保持其他字段
reranker_model_config_id: config.rerankerModelConfigId || null, // 保持其他字段
summary_model_config_id: config.summary_model_config_id || null // 保持其他字段
}
});
// 保存成功后再更新前端状态
setConfig(prev => ({ ...prev, ankiCardModelConfigId: newValue }));
showMessage('success', 'ANKI制卡模型配置已保存');
console.log('ANKI制卡模型配置保存成功:', newValue);
// 验证保存结果
setTimeout(async () => {
try {
const verification = await invoke('get_model_assignments');
console.log('验证ANKI制卡模型保存结果:', verification);
} catch (err) {
console.error('验证保存结果失败:', err);
}
}, 500);
}
} catch (error) {
console.error('保存ANKI制卡模型配置失败:', error);
showMessage('error', '保存ANKI制卡模型配置失败: ' + error);
// 保存失败时不更新前端状态
}
}}
style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
>
<option value="">请选择模型...</option>
{getAllEnabledApis().map(api => (
<option key={api.id} value={api.id}>
{api.name} ({api.model}) {api.isMultimodal ? '[图像]' : '[文本]'} {api.isReasoning ? '[推理]' : ''}
</option>
))}
</select>
{getAllEnabledApis().length === 0 && (
<div style={{ color: '#dc3545', fontSize: '14px', marginTop: '8px', display: 'flex', alignItems: 'center', gap: '8px' }}>
<AlertTriangle size={16} />
没有可用的API配置,请先添加并启用API
</div>
)}
</div>
{/* RAG嵌入模型配置 */}
<div className="model-config" style={{
border: '1px solid #ddd',
borderRadius: '8px',
padding: '20px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '15px' }}>
<Database size={20} color="#10b981" />
<h4 style={{ margin: 0 }}>嵌入模型(RAG知识库)</h4>
</div>
<p style={{ color: '#666', fontSize: '14px', marginBottom: '15px' }}>
用于将文档转换为向量嵌入,支持RAG知识库检索功能
</p>
<select
value={config.embeddingModelConfigId}
onChange={async (e) => {
const newValue = e.target.value;
try {
if (invoke) {
await invoke('save_model_assignments', {
assignments: {
model1_config_id: config.model1ConfigId || null,
model2_config_id: config.model2ConfigId || null,
review_analysis_model_config_id: config.reviewAnalysisModelConfigId || null,
anki_card_model_config_id: config.ankiCardModelConfigId || null,
embedding_model_config_id: newValue || null,
reranker_model_config_id: config.rerankerModelConfigId || null,
summary_model_config_id: config.summary_model_config_id || null // 保持其他字段
}
});
setConfig(prev => ({ ...prev, embeddingModelConfigId: newValue }));
showMessage('success', '嵌入模型配置已保存');
}
} catch (error) {
console.error('保存嵌入模型配置失败:', error);
showMessage('error', '保存嵌入模型配置失败: ' + error);
}
}}
style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
>
<option value="">请选择嵌入模型...</option>
{getAllEnabledApis().map(api => (
<option key={api.id} value={api.id}>
{api.name} ({api.model}) {api.isMultimodal ? '[图像]' : '[文本]'} {api.isReasoning ? '[推理]' : ''}
</option>
))}
</select>
</div>
{/* RAG重排序模型配置 */}
<div className="model-config" style={{
border: '1px solid #ddd',
borderRadius: '8px',
padding: '20px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '15px' }}>
<RefreshCcw size={20} color="#6366f1" />
<h4 style={{ margin: 0 }}>重排序模型(RAG优化,可选)</h4>
</div>
<p style={{ color: '#666', fontSize: '14px', marginBottom: '15px' }}>
用于对RAG检索结果进行重排序,提高相关性(可选配置)
</p>
<select
value={config.rerankerModelConfigId}
onChange={async (e) => {
const newValue = e.target.value;
try {
if (invoke) {
await invoke('save_model_assignments', {
assignments: {
model1_config_id: config.model1ConfigId || null,
model2_config_id: config.model2ConfigId || null,
review_analysis_model_config_id: config.reviewAnalysisModelConfigId || null,
anki_card_model_config_id: config.ankiCardModelConfigId || null,
embedding_model_config_id: config.embeddingModelConfigId || null,
reranker_model_config_id: newValue || null,
summary_model_config_id: config.summary_model_config_id || null // 保持其他字段
}
});
setConfig(prev => ({ ...prev, rerankerModelConfigId: newValue }));
showMessage('success', '重排序模型配置已保存');
}
} catch (error) {
console.error('保存重排序模型配置失败:', error);
showMessage('error', '保存重排序模型配置失败: ' + error);
}
}}
style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
>
<option value="">不使用重排序(可选)</option>
{getAllEnabledApis().map(api => (
<option key={api.id} value={api.id}>
{api.name} ({api.model}) {api.isMultimodal ? '[图像]' : '[文本]'} {api.isReasoning ? '[推理]' : ''}
</option>
))}
</select>
</div>
{/* 总结生成模型配置 */}
<div className="model-config" style={{
border: '1px solid #ddd',
borderRadius: '8px',
padding: '20px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '15px' }}>
<ScrollText size={20} color="#f59e0b" />
<h4 style={{ margin: 0 }}>总结生成模型(错题总结)</h4>
</div>
<p style={{ color: '#666', fontSize: '14px', marginBottom: '15px' }}>
专门用于生成错题总结,建议使用理解和概括能力强的模型。如果未选择,将使用"第二模型(解答 + 对话)"。
</p>
<select
value={config.summary_model_config_id}
onChange={async (e) => {
const newValue = e.target.value;
try {
if (invoke) {
await invoke('save_model_assignments', {
assignments: {
model1_config_id: config.model1ConfigId || null,
model2_config_id: config.model2ConfigId || null,
review_analysis_model_config_id: config.reviewAnalysisModelConfigId || null,
anki_card_model_config_id: config.ankiCardModelConfigId || null,
embedding_model_config_id: config.embeddingModelConfigId || null,
reranker_model_config_id: config.rerankerModelConfigId || null,
summary_model_config_id: newValue || null
}
});
setConfig(prev => ({ ...prev, summary_model_config_id: newValue }));
showMessage('success', '总结生成模型配置已保存');
}
} catch (error) {
console.error('保存总结生成模型配置失败:', error);
showMessage('error', '保存总结生成模型配置失败: ' + error);
}
}}
style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
>
<option value="">请选择模型(默认使用第二模型)...</option>
{getAllEnabledApis().map(api => (
<option key={api.id} value={api.id}>
{api.name} ({api.model}) {api.isMultimodal ? '[图像]' : '[文本]'} {api.isReasoning ? '[推理]' : ''}
</option>
))}
</select>
</div>
</div>
{/* 配置状态检查 */}
<div style={{ marginTop: '20px', padding: '15px', backgroundColor: '#f8f9fa', borderRadius: '8px' }}>
<h5>配置状态检查</h5>
<div style={{ fontSize: '14px' }}>
<div style={{ color: config.model1ConfigId ? '#28a745' : '#dc3545', display: 'flex', alignItems: 'center', gap: '8px' }}>
{config.model1ConfigId ? <CheckCircle size={16} /> : <XCircle size={16} />}
第一模型: {config.model1ConfigId ? '已配置' : '未配置'}
</div>
<div style={{ color: config.model2ConfigId ? '#28a745' : '#dc3545', display: 'flex', alignItems: 'center', gap: '8px' }}>
{config.model2ConfigId ? <CheckCircle size={16} /> : <XCircle size={16} />}
第二模型: {config.model2ConfigId ? '已配置' : '未配置'}
</div>
<div style={{ color: config.reviewAnalysisModelConfigId ? '#28a745' : '#dc3545', display: 'flex', alignItems: 'center', gap: '8px' }}>
{config.reviewAnalysisModelConfigId ? <CheckCircle size={16} /> : <XCircle size={16} />}
回顾分析模型: {config.reviewAnalysisModelConfigId ? '已配置' : '未配置'}
</div>
<div style={{ color: config.ankiCardModelConfigId ? '#28a745' : '#dc3545', display: 'flex', alignItems: 'center', gap: '8px' }}>
{config.ankiCardModelConfigId ? <CheckCircle size={16} /> : <XCircle size={16} />}
ANKI制卡模型: {config.ankiCardModelConfigId ? '已配置' : '未配置'}
</div>
<div style={{ color: config.embeddingModelConfigId ? '#28a745' : '#dc3545', display: 'flex', alignItems: 'center', gap: '8px' }}>
{config.embeddingModelConfigId ? <CheckCircle size={16} /> : <XCircle size={16} />}
RAG嵌入模型: {config.embeddingModelConfigId ? '已配置' : '未配置'}
</div>
<div style={{ color: config.rerankerModelConfigId ? '#28a745' : '#ffc107', display: 'flex', alignItems: 'center', gap: '8px' }}>
{config.rerankerModelConfigId ? <CheckCircle size={16} /> : <AlertTriangle size={16} />}
RAG重排序模型: {config.rerankerModelConfigId ? '已配置' : '未配置(可选)'}
</div>
<div style={{ color: config.summary_model_config_id ? '#28a745' : '#ffc107', display: 'flex', alignItems: 'center', gap: '8px' }}>
{config.summary_model_config_id ? <CheckCircle size={16} /> : <AlertTriangle size={16} />}
总结生成模型: {config.summary_model_config_id ? '已配置' : '未配置(将使用第二模型)'}
</div>
{config.model1ConfigId && config.model2ConfigId && (
<div style={{ color: '#28a745', marginTop: '8px', display: 'flex', alignItems: 'center', gap: '8px' }}>
<PartyPopper size={16} />
基础功能配置完成,可以开始使用错题分析功能!
</div>
)}
{config.model1ConfigId && config.model2ConfigId && config.reviewAnalysisModelConfigId && (
<div style={{ color: '#28a745', marginTop: '8px', display: 'flex', alignItems: 'center', gap: '8px' }}>
<PartyPopper size={16} />
高级功能配置完成,可以使用错题分析和回顾分析功能!
</div>
)}
{config.model1ConfigId && config.model2ConfigId && config.reviewAnalysisModelConfigId && config.ankiCardModelConfigId && (
<div style={{ color: '#28a745', marginTop: '8px', display: 'flex', alignItems: 'center', gap: '8px' }}>
<PartyPopper size={16} />
所有功能配置完成,可以使用错题分析、回顾分析和ANKI制卡功能!
</div>
)}
</div>
</div>
</div>
</div>
)}
{/* 科目配置 */}
{activeTab === 'subjects' && (
<div style={{
backgroundColor: 'white',
padding: '1.5rem',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
marginBottom: '1.5rem'
}}>
<div className="subjects-section">
<SubjectConfig />
</div>
</div>
)}
{/* 通用设置 */}
{activeTab === 'general' && (
<div style={{
backgroundColor: 'white',
padding: '1.5rem',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
marginBottom: '1.5rem'
}}>
<div className="general-section">
<h3>通用设置</h3>
<div style={{ display: 'grid', gap: '20px' }}>
<div className="setting-item" style={{
border: '1px solid #ddd',
borderRadius: '8px',
padding: '20px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '15px' }}>
<Save size={20} color="#10b981" />
<h4 style={{ margin: 0 }}>自动保存</h4>
</div>
<p style={{ color: '#666', fontSize: '14px', marginBottom: '15px' }}>
启用后,配置更改将自动保存,无需手动点击保存按钮
</p>
<label style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<input
type="checkbox"
checked={config.autoSave}
onChange={(e) => setConfig(prev => ({ ...prev, autoSave: e.target.checked }))}
/>
启用自动保存
</label>
</div>
<div className="setting-item" style={{
border: '1px solid #ddd',
borderRadius: '8px',
padding: '20px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '15px' }}>
<Palette size={20} color="#8b5cf6" />
<h4 style={{ margin: 0 }}>主题设置</h4>
</div>
<p style={{ color: '#666', fontSize: '14px', marginBottom: '15px' }}>
选择应用的外观主题
</p>
<select
value={config.theme}
onChange={(e) => setConfig(prev => ({ ...prev, theme: e.target.value }))}
style={{ width: '200px', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
>
<option value="light">浅色主题</option>
<option value="dark">深色主题</option>
<option value="auto">跟随系统</option>
</select>
</div>
{/* RAG设置 */}
<div className="setting-item" style={{
border: '1px solid #ddd',
borderRadius: '8px',
padding: '20px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '15px' }}>
<Database size={20} color="#3b82f6" />
<h4 style={{ margin: 0 }}>RAG知识库设置</h4>
</div>
<p style={{ color: '#666', fontSize: '14px', marginBottom: '15px' }}>
配置检索增强生成(RAG)功能的全局设置
</p>
<div style={{ marginBottom: '15px' }}>
<label style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<input
type="checkbox"
checked={config.ragEnabled}
onChange={(e) => setConfig(prev => ({ ...prev, ragEnabled: e.target.checked }))}
/>
启用RAG知识库功能
</label>
<p style={{ color: '#666', fontSize: '12px', marginTop: '5px', marginLeft: '20px' }}>
启用后,AI分析将能够利用您上传的知识库文档提供更准确的解答
</p>
</div>
<div style={{ marginBottom: '15px' }}>
<label style={{ display: 'block', marginBottom: '5px', fontSize: '14px', fontWeight: '500' }}>
检索文档数量 (Top-K):
</label>
<input
type="number"
min="1"
max="20"
value={config.ragTopK}
onChange={(e) => setConfig(prev => ({ ...prev, ragTopK: parseInt(e.target.value) || 5 }))}
style={{ width: '100px', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
/>
<p style={{ color: '#666', fontSize: '12px', marginTop: '5px' }}>
每次查询时从知识库检索的相关文档数量,建议设置为3-10
</p>
</div>
{config.ragEnabled && !config.embeddingModelConfigId && (
<div style={{
backgroundColor: '#fff3cd',
border: '1px solid #ffeaa7',
borderRadius: '4px',
padding: '10px',
marginTop: '10px'
}}>
<div style={{ color: '#856404', fontSize: '14px', margin: 0, display: 'flex', alignItems: 'center', gap: '8px' }}>
<AlertTriangle size={16} />
RAG功能已启用,但未配置嵌入模型。请在"模型分配"标签页中配置嵌入模型。
</div>
</div>
)}
</div>
{/* 开发功能设置 */}
<div className="setting-item" style={{
border: '1px solid #ddd',
borderRadius: '8px',
padding: '20px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '15px' }}>
<Construction size={20} color="#f59e0b" />
<h4 style={{ margin: 0 }}>开发功能设置</h4>
</div>
<p style={{ color: '#666', fontSize: '14px', marginBottom: '15px' }}>
控制实验性和开发中的功能
</p>
<div style={{ marginBottom: '15px' }}>
<label style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<input
type="checkbox"
checked={config.batchAnalysisEnabled}
onChange={(e) => setConfig(prev => ({ ...prev, batchAnalysisEnabled: e.target.checked }))}
/>
启用批量分析功能
</label>
<p style={{ color: '#666', fontSize: '12px', marginTop: '5px', marginLeft: '20px' }}>
启用后,将在侧边栏显示"批量分析"选项。此功能仍在开发中,可能存在一些问题。
</p>
</div>
{/* AnkiConnect功能开关 */}
<div style={{ marginBottom: '15px' }}>
<label style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<input
type="checkbox"
checked={config.ankiConnectEnabled}
onChange={(e) => setConfig(prev => ({ ...prev, ankiConnectEnabled: e.target.checked }))}
/>
启用AnkiConnect集成
</label>
<p style={{ color: '#666', fontSize: '12px', marginTop: '5px', marginLeft: '20px' }}>
启用后,ANKI制卡页面将显示AnkiConnect相关功能,可以直接导入卡片到Anki应用。
</p>
</div>
{/* Gemini适配器测试功能开关 */}
<div style={{ marginBottom: '15px' }}>
<label style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<input
type="checkbox"
checked={config.geminiAdapterTestEnabled}
onChange={(e) => setConfig(prev => ({ ...prev, geminiAdapterTestEnabled: e.target.checked }))}
/>
启用Gemini适配器测试模块
</label>
<p style={{ color: '#666', fontSize: '12px', marginTop: '5px', marginLeft: '20px' }}>
启用后,将在侧边栏显示"Gemini适配器测试"选项。此功能用于测试和调试Gemini API适配器。
</p>
</div>
{/* 图片遮罩卡功能开关 */}
<div style={{ marginBottom: '15px' }}>
<label style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<input
type="checkbox"
checked={config.imageOcclusionEnabled}
onChange={(e) => setConfig(prev => ({ ...prev, imageOcclusionEnabled: e.target.checked }))}
/>
启用图片遮罩卡功能
</label>
<p style={{ color: '#666', fontSize: '12px', marginTop: '5px', marginLeft: '20px' }}>
启用后,将在侧边栏显示"图片遮罩卡"选项。此功能用于创建ANKI图片遮罩记忆卡片。
</p>
</div>
{config.batchAnalysisEnabled && (
<div style={{
backgroundColor: '#fff3cd',
border: '1px solid #ffeaa7',
borderRadius: '4px',
padding: '10px',
marginTop: '10px'
}}>
<div style={{ color: '#856404', fontSize: '14px', margin: 0, display: 'flex', alignItems: 'center', gap: '8px' }}>
<AlertTriangle size={16} />
批量分析功能仍在开发中,可能会遇到一些问题。建议优先使用单题分析功能。
</div>
</div>
)}
</div>
{!config.autoSave && (
<div style={{ textAlign: 'center', marginTop: '20px' }}>
<button
className="btn btn-primary save-all-settings-button"
onClick={() => handleSave()}
disabled={saving}
style={{ padding: '12px 24px', fontSize: '16px' }}
>
{saving ? '保存中...' : (
<span style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Save size={16} />
保存所有设置
</span>
)}
</button>
</div>
)}
</div>
</div>
</div>
)}
</div>
{/* API编辑模态框 */}
{editingApi && (
<ApiEditModal
api={editingApi}
onSave={addOrUpdateApi}
onCancel={() => setEditingApi(null)}
/>
)}
</div>
);
};
// API编辑模态框组件
interface ApiEditModalProps {
api: ApiConfig;
onSave: (api: ApiConfig) => void;
onCancel: () => void;
}
const ApiEditModal: React.FC<ApiEditModalProps> = ({ api, onSave, onCancel }) => {
const [formData, setFormData] = useState({
...api,
isReasoning: api.isReasoning || false, // 确保有默认值
modelAdapter: api.modelAdapter || 'general' // 确保有默认值
});
const [modelAdapterOptions, setModelAdapterOptions] = useState<any[]>([]);
// 加载模型适配器选项
React.useEffect(() => {
const loadModelAdapterOptions = async () => {
try {
if (invoke) {
const options = await invoke('get_model_adapter_options') as any[];
setModelAdapterOptions(options);
} else {
// 浏览器环境的默认选项
setModelAdapterOptions([
{ value: 'general', label: '通用模型', description: '适用于大多数标准AI模型' },
{ value: 'deepseek-r1', label: 'DeepSeek-R1', description: '专为DeepSeek-R1推理模型优化' },
{ value: 'google', label: 'Google Gemini', description: 'Google Gemini系列模型,支持多模态和高质量文本生成' },
{ value: 'o1-series', label: 'OpenAI o1系列', description: 'OpenAI o1-preview和o1-mini等推理模型' },
{ value: 'claude-3-5-sonnet', label: 'Claude 3.5 Sonnet', description: 'Anthropic Claude 3.5 Sonnet高性能模型' }
]);
}
} catch (error) {
console.error('加载模型适配器选项失败:', error);
// 使用默认选项
setModelAdapterOptions([
{ value: 'general', label: '通用模型', description: '适用于大多数标准AI模型' },
{ value: 'deepseek-r1', label: 'DeepSeek-R1', description: '专为DeepSeek-R1推理模型优化' },
{ value: 'google', label: 'Google Gemini', description: 'Google Gemini系列模型,支持多模态和高质量文本生成' },
{ value: 'o1-series', label: 'OpenAI o1系列', description: 'OpenAI o1-preview和o1-mini等推理模型' },
{ value: 'claude-3-5-sonnet', label: 'Claude 3.5 Sonnet', description: 'Anthropic Claude 3.5 Sonnet高性能模型' }
]);
}
};
loadModelAdapterOptions();
}, []);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
// 验证必填字段
if (!formData.name.trim()) {
alert('请输入配置名称');
return;
}
if (!formData.baseUrl.trim()) {
alert('请输入API地址');
return;
}
if (!formData.model.trim()) {
alert('请输入模型名称');
return;
}
onSave(formData);
};
return (
<div style={{
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(0,0,0,0.5)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
zIndex: 1000
}}>
<div style={{
backgroundColor: 'white',
borderRadius: '8px',
padding: '24px',
width: '90%',
maxWidth: '500px',
maxHeight: '90vh',
overflow: 'auto'
}}>
<h3 style={{ marginTop: 0 }}>
{api.id.startsWith('api_') ? '添加API配置' : '编辑API配置'}
</h3>
<form onSubmit={handleSubmit}>
<div style={{ marginBottom: '16px' }}>
<label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
配置名称 *
</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
placeholder="例如:OpenAI GPT-4"
required
/>
</div>
<div style={{ marginBottom: '16px' }}>
<label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
API地址 *
</label>
<input
type="url"
value={formData.baseUrl}
onChange={(e) => setFormData(prev => ({ ...prev, baseUrl: e.target.value }))}
style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
placeholder="https://api.openai.com/v1"
required
/>
</div>
<div style={{ marginBottom: '16px' }}>
<label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
模型名称 *
</label>
<input
type="text"
value={formData.model}
onChange={(e) => setFormData(prev => ({ ...prev, model: e.target.value }))}
style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
placeholder="例如:gpt-4-vision-preview"
required
/>
<div style={{ fontSize: '12px', color: '#666', marginTop: '4px' }}>
请输入准确的模型名称,这将用于API调用
</div>
</div>
<div style={{ marginBottom: '16px' }}>
<label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
API密钥
</label>
<input
type="password"
value={formData.apiKey}
onChange={(e) => setFormData(prev => ({ ...prev, apiKey: e.target.value }))}
style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
placeholder="sk-..."
/>
</div>
<div style={{ marginBottom: '16px' }}>
<label style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<input
type="checkbox"
checked={formData.isMultimodal}
onChange={(e) => setFormData(prev => ({ ...prev, isMultimodal: e.target.checked }))}
/>
<span style={{ fontWeight: 'bold' }}>多模态模型</span>
</label>
<div style={{ fontSize: '12px', color: '#666', marginTop: '4px' }}>
勾选此项表示该模型支持图片输入(如GPT-4V、Claude-3等)
</div>
</div>
<div style={{ marginBottom: '16px' }}>
<label style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<input
type="checkbox"
checked={formData.isReasoning}
onChange={(e) => setFormData(prev => ({ ...prev, isReasoning: e.target.checked }))}
/>
<span style={{ fontWeight: 'bold' }}>推理模型</span>
</label>
<div style={{ fontSize: '12px', color: '#666', marginTop: '4px' }}>
勾选此项表示该模型支持推理功能
</div>
</div>
<div style={{ marginBottom: '24px' }}>
<label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
模型适配器 *
</label>
<select
value={formData.modelAdapter}
onChange={(e) => setFormData(prev => ({ ...prev, modelAdapter: e.target.value }))}
style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
required
>
{modelAdapterOptions.map(option => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
{formData.modelAdapter && modelAdapterOptions.find(opt => opt.value === formData.modelAdapter) && (
<div style={{ fontSize: '12px', color: '#666', marginTop: '4px' }}>
{modelAdapterOptions.find(opt => opt.value === formData.modelAdapter)?.description}
</div>
)}
</div>
<div style={{ marginBottom: '24px' }}>
<label style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<input
type="checkbox"
checked={formData.enabled}
onChange={(e) => setFormData(prev => ({ ...prev, enabled: e.target.checked }))}
/>
<span style={{ fontWeight: 'bold' }}>启用此配置</span>
</label>
</div>
<div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
<button
type="button"
className="cancel-button"
onClick={onCancel}
>
取消
</button>
<button
type="submit"
className="save-button"
>
保存
</button>
</div>
</form>
</div>
</div>
);
};
|
0015/StickiNote
| 29,801 |
main/ui_resources/icon_resize.c
|
#ifdef __has_include
#if __has_include("lvgl.h")
#ifndef LV_LVGL_H_INCLUDE_SIMPLE
#define LV_LVGL_H_INCLUDE_SIMPLE
#endif
#endif
#endif
#if defined(LV_LVGL_H_INCLUDE_SIMPLE)
#include "lvgl.h"
#else
#include "lvgl/lvgl.h"
#endif
#ifndef LV_ATTRIBUTE_MEM_ALIGN
#define LV_ATTRIBUTE_MEM_ALIGN
#endif
#ifndef LV_ATTRIBUTE_IMAGE_ICON_RESIZE
#define LV_ATTRIBUTE_IMAGE_ICON_RESIZE
#endif
const LV_ATTRIBUTE_MEM_ALIGN LV_ATTRIBUTE_LARGE_CONST LV_ATTRIBUTE_IMAGE_ICON_RESIZE uint8_t icon_resize_map[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, 0xd8, 0xb5, 0xb8, 0xb5, 0xb8, 0xb5, 0xb8, 0xb5, 0xb8, 0xb5, 0xb8, 0xb5, 0xb7, 0xb5, 0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, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x27, 0x59, 0x7a, 0x8e, 0x9b, 0xa3, 0xa6, 0xa9, 0xaa, 0xaa, 0xaa, 0xaa, 0xa9, 0xa6, 0xa3, 0x9b, 0x8e, 0x7a, 0x5a, 0x28, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x68, 0xda, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xdb, 0x68, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc3, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xdb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xdb, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x03, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc3, 0x03, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x68, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x68, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0xdb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xfb, 0xfc, 0xfc, 0xfc, 0xfc, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xda, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x28, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0x27, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x59, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xfb, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0x59, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x7a, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xfe, 0xff, 0xff, 0xff, 0xfa, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7a, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x8e, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xfe, 0xff, 0xfe, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0x8e, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x9b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xfe, 0xff, 0xfe, 0xfa, 0xfd, 0xff, 0xfa, 0xff, 0xff, 0xff, 0xff, 0xff, 0x9b, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xfe, 0xff, 0xfe, 0xfc, 0xfe, 0xfd, 0xff, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa2, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xfe, 0xff, 0xfe, 0xfc, 0xff, 0xff, 0xfb, 0xfb, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa6, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa9, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xfe, 0xff, 0xfe, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xaa, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xfe, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa9, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xaa, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xfb, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xaa, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xaa, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xfc, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xaa, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xaa, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xfe, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa9, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa9, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xfe, 0xff, 0xff, 0xff, 0xfb, 0xfe, 0xff, 0xfe, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xfe, 0xfc, 0xfe, 0xff, 0xfb, 0xfe, 0xff, 0xfe, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa6, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0xff, 0xff, 0xf9, 0xfb, 0xfe, 0xff, 0xfe, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa2, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x9b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0xff, 0xff, 0xf5, 0xfe, 0xff, 0xfe, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x9b, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x8e, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0xff, 0xff, 0xfe, 0xff, 0xfe, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x8e, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x7a, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0xff, 0xff, 0xff, 0xfe, 0xf7, 0xfb, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x79, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x59, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x59, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x28, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x27, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0xdb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfa, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xda, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x68, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x68, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x03, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc3, 0x03, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xdb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xda, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc3, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x68, 0xda, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xda, 0x68, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x27, 0x59, 0x7a, 0x8e, 0x9b, 0xa2, 0xa6, 0xa8, 0xaa, 0xaa, 0xaa, 0xaa, 0xa8, 0xa6, 0xa2, 0x9b, 0x8e, 0x79, 0x59, 0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
const lv_image_dsc_t icon_resize = {
.header.cf = LV_COLOR_FORMAT_RGB565A8,
.header.magic = LV_IMAGE_HEADER_MAGIC,
.header.w = 40,
.header.h = 40,
.data_size = 1600 * 3,
.data = icon_resize_map,
};
|
000haoji/deep-student
| 1,891 |
src/components/UnifiedTemplateSelector.css
|
/* 统一模板选择器样式 */
.unified-template-selector {
margin-bottom: 24px;
}
.current-template-display {
margin-bottom: 16px;
}
.current-template-card {
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 20px;
transition: all 0.2s ease;
}
.current-template-card:hover {
border-color: #cbd5e0;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}
.template-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 12px;
}
.template-info h6.template-name {
margin: 0 0 4px 0;
font-size: 18px;
font-weight: 600;
color: #1a202c;
}
.template-info .template-description {
margin: 0;
font-size: 14px;
color: #718096;
line-height: 1.4;
}
.template-actions {
display: flex;
gap: 8px;
flex-shrink: 0;
}
.template-quick-info {
display: flex;
gap: 16px;
font-size: 13px;
color: #4a5568;
}
.field-count, .note-type {
display: flex;
align-items: center;
gap: 4px;
}
/* 按钮样式增强 */
.btn.btn-outline {
background: white;
border: 1px solid #d1d5db;
color: #374151;
transition: all 0.2s ease;
}
.btn.btn-outline:hover {
background: #f9fafb;
border-color: #9ca3af;
color: #1f2937;
}
.btn.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
color: white;
font-weight: 500;
transition: all 0.2s ease;
}
.btn.btn-primary:hover {
background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}
.btn.btn-sm {
padding: 8px 16px;
font-size: 14px;
border-radius: 8px;
}
/* 响应式设计 */
@media (max-width: 768px) {
.template-header {
flex-direction: column;
gap: 12px;
align-items: stretch;
}
.template-actions {
justify-content: flex-end;
}
.template-quick-info {
flex-direction: column;
gap: 8px;
}
}
|
0000cd/wolf-set
| 35,445 |
themes/bluf/static/js/isotope.min.js
|
/*!
* Isotope PACKAGED v3.0.6
*
* Licensed GPLv3 for open source use
* or Isotope Commercial License for commercial use
*
* https://isotope.metafizzy.co
* Copyright 2010-2018 Metafizzy
*/
!function(t,e){"function"==typeof define&&define.amd?define("jquery-bridget/jquery-bridget",["jquery"],function(i){return e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("jquery")):t.jQueryBridget=e(t,t.jQuery)}(window,function(t,e){"use strict";function i(i,s,a){function u(t,e,o){var n,s="$()."+i+'("'+e+'")';return t.each(function(t,u){var h=a.data(u,i);if(!h)return void r(i+" not initialized. Cannot call methods, i.e. "+s);var d=h[e];if(!d||"_"==e.charAt(0))return void r(s+" is not a valid method");var l=d.apply(h,o);n=void 0===n?l:n}),void 0!==n?n:t}function h(t,e){t.each(function(t,o){var n=a.data(o,i);n?(n.option(e),n._init()):(n=new s(o,e),a.data(o,i,n))})}a=a||e||t.jQuery,a&&(s.prototype.option||(s.prototype.option=function(t){a.isPlainObject(t)&&(this.options=a.extend(!0,this.options,t))}),a.fn[i]=function(t){if("string"==typeof t){var e=n.call(arguments,1);return u(this,t,e)}return h(this,t),this},o(a))}function o(t){!t||t&&t.bridget||(t.bridget=i)}var n=Array.prototype.slice,s=t.console,r="undefined"==typeof s?function(){}:function(t){s.error(t)};return o(e||t.jQuery),i}),function(t,e){"function"==typeof define&&define.amd?define("ev-emitter/ev-emitter",e):"object"==typeof module&&module.exports?module.exports=e():t.EvEmitter=e()}("undefined"!=typeof window?window:this,function(){function t(){}var e=t.prototype;return e.on=function(t,e){if(t&&e){var i=this._events=this._events||{},o=i[t]=i[t]||[];return o.indexOf(e)==-1&&o.push(e),this}},e.once=function(t,e){if(t&&e){this.on(t,e);var i=this._onceEvents=this._onceEvents||{},o=i[t]=i[t]||{};return o[e]=!0,this}},e.off=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){var o=i.indexOf(e);return o!=-1&&i.splice(o,1),this}},e.emitEvent=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){i=i.slice(0),e=e||[];for(var o=this._onceEvents&&this._onceEvents[t],n=0;n<i.length;n++){var s=i[n],r=o&&o[s];r&&(this.off(t,s),delete o[s]),s.apply(this,e)}return this}},e.allOff=function(){delete this._events,delete this._onceEvents},t}),function(t,e){"function"==typeof define&&define.amd?define("get-size/get-size",e):"object"==typeof module&&module.exports?module.exports=e():t.getSize=e()}(window,function(){"use strict";function t(t){var e=parseFloat(t),i=t.indexOf("%")==-1&&!isNaN(e);return i&&e}function e(){}function i(){for(var t={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0},e=0;e<h;e++){var i=u[e];t[i]=0}return t}function o(t){var e=getComputedStyle(t);return e||a("Style returned "+e+". Are you running this code in a hidden iframe on Firefox? See https://bit.ly/getsizebug1"),e}function n(){if(!d){d=!0;var e=document.createElement("div");e.style.width="200px",e.style.padding="1px 2px 3px 4px",e.style.borderStyle="solid",e.style.borderWidth="1px 2px 3px 4px",e.style.boxSizing="border-box";var i=document.body||document.documentElement;i.appendChild(e);var n=o(e);r=200==Math.round(t(n.width)),s.isBoxSizeOuter=r,i.removeChild(e)}}function s(e){if(n(),"string"==typeof e&&(e=document.querySelector(e)),e&&"object"==typeof e&&e.nodeType){var s=o(e);if("none"==s.display)return i();var a={};a.width=e.offsetWidth,a.height=e.offsetHeight;for(var d=a.isBorderBox="border-box"==s.boxSizing,l=0;l<h;l++){var f=u[l],c=s[f],m=parseFloat(c);a[f]=isNaN(m)?0:m}var p=a.paddingLeft+a.paddingRight,y=a.paddingTop+a.paddingBottom,g=a.marginLeft+a.marginRight,v=a.marginTop+a.marginBottom,_=a.borderLeftWidth+a.borderRightWidth,z=a.borderTopWidth+a.borderBottomWidth,I=d&&r,x=t(s.width);x!==!1&&(a.width=x+(I?0:p+_));var S=t(s.height);return S!==!1&&(a.height=S+(I?0:y+z)),a.innerWidth=a.width-(p+_),a.innerHeight=a.height-(y+z),a.outerWidth=a.width+g,a.outerHeight=a.height+v,a}}var r,a="undefined"==typeof console?e:function(t){console.error(t)},u=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"],h=u.length,d=!1;return s}),function(t,e){"use strict";"function"==typeof define&&define.amd?define("desandro-matches-selector/matches-selector",e):"object"==typeof module&&module.exports?module.exports=e():t.matchesSelector=e()}(window,function(){"use strict";var t=function(){var t=window.Element.prototype;if(t.matches)return"matches";if(t.matchesSelector)return"matchesSelector";for(var e=["webkit","moz","ms","o"],i=0;i<e.length;i++){var o=e[i],n=o+"MatchesSelector";if(t[n])return n}}();return function(e,i){return e[t](i)}}),function(t,e){"function"==typeof define&&define.amd?define("fizzy-ui-utils/utils",["desandro-matches-selector/matches-selector"],function(i){return e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("desandro-matches-selector")):t.fizzyUIUtils=e(t,t.matchesSelector)}(window,function(t,e){var i={};i.extend=function(t,e){for(var i in e)t[i]=e[i];return t},i.modulo=function(t,e){return(t%e+e)%e};var o=Array.prototype.slice;i.makeArray=function(t){if(Array.isArray(t))return t;if(null===t||void 0===t)return[];var e="object"==typeof t&&"number"==typeof t.length;return e?o.call(t):[t]},i.removeFrom=function(t,e){var i=t.indexOf(e);i!=-1&&t.splice(i,1)},i.getParent=function(t,i){for(;t.parentNode&&t!=document.body;)if(t=t.parentNode,e(t,i))return t},i.getQueryElement=function(t){return"string"==typeof t?document.querySelector(t):t},i.handleEvent=function(t){var e="on"+t.type;this[e]&&this[e](t)},i.filterFindElements=function(t,o){t=i.makeArray(t);var n=[];return t.forEach(function(t){if(t instanceof HTMLElement){if(!o)return void n.push(t);e(t,o)&&n.push(t);for(var i=t.querySelectorAll(o),s=0;s<i.length;s++)n.push(i[s])}}),n},i.debounceMethod=function(t,e,i){i=i||100;var o=t.prototype[e],n=e+"Timeout";t.prototype[e]=function(){var t=this[n];clearTimeout(t);var e=arguments,s=this;this[n]=setTimeout(function(){o.apply(s,e),delete s[n]},i)}},i.docReady=function(t){var e=document.readyState;"complete"==e||"interactive"==e?setTimeout(t):document.addEventListener("DOMContentLoaded",t)},i.toDashed=function(t){return t.replace(/(.)([A-Z])/g,function(t,e,i){return e+"-"+i}).toLowerCase()};var n=t.console;return i.htmlInit=function(e,o){i.docReady(function(){var s=i.toDashed(o),r="data-"+s,a=document.querySelectorAll("["+r+"]"),u=document.querySelectorAll(".js-"+s),h=i.makeArray(a).concat(i.makeArray(u)),d=r+"-options",l=t.jQuery;h.forEach(function(t){var i,s=t.getAttribute(r)||t.getAttribute(d);try{i=s&&JSON.parse(s)}catch(a){return void(n&&n.error("Error parsing "+r+" on "+t.className+": "+a))}var u=new e(t,i);l&&l.data(t,o,u)})})},i}),function(t,e){"function"==typeof define&&define.amd?define("outlayer/item",["ev-emitter/ev-emitter","get-size/get-size"],e):"object"==typeof module&&module.exports?module.exports=e(require("ev-emitter"),require("get-size")):(t.Outlayer={},t.Outlayer.Item=e(t.EvEmitter,t.getSize))}(window,function(t,e){"use strict";function i(t){for(var e in t)return!1;return e=null,!0}function o(t,e){t&&(this.element=t,this.layout=e,this.position={x:0,y:0},this._create())}function n(t){return t.replace(/([A-Z])/g,function(t){return"-"+t.toLowerCase()})}var s=document.documentElement.style,r="string"==typeof s.transition?"transition":"WebkitTransition",a="string"==typeof s.transform?"transform":"WebkitTransform",u={WebkitTransition:"webkitTransitionEnd",transition:"transitionend"}[r],h={transform:a,transition:r,transitionDuration:r+"Duration",transitionProperty:r+"Property",transitionDelay:r+"Delay"},d=o.prototype=Object.create(t.prototype);d.constructor=o,d._create=function(){this._transn={ingProperties:{},clean:{},onEnd:{}},this.css({position:"absolute"})},d.handleEvent=function(t){var e="on"+t.type;this[e]&&this[e](t)},d.getSize=function(){this.size=e(this.element)},d.css=function(t){var e=this.element.style;for(var i in t){var o=h[i]||i;e[o]=t[i]}},d.getPosition=function(){var t=getComputedStyle(this.element),e=this.layout._getOption("originLeft"),i=this.layout._getOption("originTop"),o=t[e?"left":"right"],n=t[i?"top":"bottom"],s=parseFloat(o),r=parseFloat(n),a=this.layout.size;o.indexOf("%")!=-1&&(s=s/100*a.width),n.indexOf("%")!=-1&&(r=r/100*a.height),s=isNaN(s)?0:s,r=isNaN(r)?0:r,s-=e?a.paddingLeft:a.paddingRight,r-=i?a.paddingTop:a.paddingBottom,this.position.x=s,this.position.y=r},d.layoutPosition=function(){var t=this.layout.size,e={},i=this.layout._getOption("originLeft"),o=this.layout._getOption("originTop"),n=i?"paddingLeft":"paddingRight",s=i?"left":"right",r=i?"right":"left",a=this.position.x+t[n];e[s]=this.getXValue(a),e[r]="";var u=o?"paddingTop":"paddingBottom",h=o?"top":"bottom",d=o?"bottom":"top",l=this.position.y+t[u];e[h]=this.getYValue(l),e[d]="",this.css(e),this.emitEvent("layout",[this])},d.getXValue=function(t){var e=this.layout._getOption("horizontal");return this.layout.options.percentPosition&&!e?t/this.layout.size.width*100+"%":t+"px"},d.getYValue=function(t){var e=this.layout._getOption("horizontal");return this.layout.options.percentPosition&&e?t/this.layout.size.height*100+"%":t+"px"},d._transitionTo=function(t,e){this.getPosition();var i=this.position.x,o=this.position.y,n=t==this.position.x&&e==this.position.y;if(this.setPosition(t,e),n&&!this.isTransitioning)return void this.layoutPosition();var s=t-i,r=e-o,a={};a.transform=this.getTranslate(s,r),this.transition({to:a,onTransitionEnd:{transform:this.layoutPosition},isCleaning:!0})},d.getTranslate=function(t,e){var i=this.layout._getOption("originLeft"),o=this.layout._getOption("originTop");return t=i?t:-t,e=o?e:-e,"translate3d("+t+"px, "+e+"px, 0)"},d.goTo=function(t,e){this.setPosition(t,e),this.layoutPosition()},d.moveTo=d._transitionTo,d.setPosition=function(t,e){this.position.x=parseFloat(t),this.position.y=parseFloat(e)},d._nonTransition=function(t){this.css(t.to),t.isCleaning&&this._removeStyles(t.to);for(var e in t.onTransitionEnd)t.onTransitionEnd[e].call(this)},d.transition=function(t){if(!parseFloat(this.layout.options.transitionDuration))return void this._nonTransition(t);var e=this._transn;for(var i in t.onTransitionEnd)e.onEnd[i]=t.onTransitionEnd[i];for(i in t.to)e.ingProperties[i]=!0,t.isCleaning&&(e.clean[i]=!0);if(t.from){this.css(t.from);var o=this.element.offsetHeight;o=null}this.enableTransition(t.to),this.css(t.to),this.isTransitioning=!0};var l="opacity,"+n(a);d.enableTransition=function(){if(!this.isTransitioning){var t=this.layout.options.transitionDuration;t="number"==typeof t?t+"ms":t,this.css({transitionProperty:l,transitionDuration:t,transitionDelay:this.staggerDelay||0}),this.element.addEventListener(u,this,!1)}},d.onwebkitTransitionEnd=function(t){this.ontransitionend(t)},d.onotransitionend=function(t){this.ontransitionend(t)};var f={"-webkit-transform":"transform"};d.ontransitionend=function(t){if(t.target===this.element){var e=this._transn,o=f[t.propertyName]||t.propertyName;if(delete e.ingProperties[o],i(e.ingProperties)&&this.disableTransition(),o in e.clean&&(this.element.style[t.propertyName]="",delete e.clean[o]),o in e.onEnd){var n=e.onEnd[o];n.call(this),delete e.onEnd[o]}this.emitEvent("transitionEnd",[this])}},d.disableTransition=function(){this.removeTransitionStyles(),this.element.removeEventListener(u,this,!1),this.isTransitioning=!1},d._removeStyles=function(t){var e={};for(var i in t)e[i]="";this.css(e)};var c={transitionProperty:"",transitionDuration:"",transitionDelay:""};return d.removeTransitionStyles=function(){this.css(c)},d.stagger=function(t){t=isNaN(t)?0:t,this.staggerDelay=t+"ms"},d.removeElem=function(){this.element.parentNode.removeChild(this.element),this.css({display:""}),this.emitEvent("remove",[this])},d.remove=function(){return r&&parseFloat(this.layout.options.transitionDuration)?(this.once("transitionEnd",function(){this.removeElem()}),void this.hide()):void this.removeElem()},d.reveal=function(){delete this.isHidden,this.css({display:""});var t=this.layout.options,e={},i=this.getHideRevealTransitionEndProperty("visibleStyle");e[i]=this.onRevealTransitionEnd,this.transition({from:t.hiddenStyle,to:t.visibleStyle,isCleaning:!0,onTransitionEnd:e})},d.onRevealTransitionEnd=function(){this.isHidden||this.emitEvent("reveal")},d.getHideRevealTransitionEndProperty=function(t){var e=this.layout.options[t];if(e.opacity)return"opacity";for(var i in e)return i},d.hide=function(){this.isHidden=!0,this.css({display:""});var t=this.layout.options,e={},i=this.getHideRevealTransitionEndProperty("hiddenStyle");e[i]=this.onHideTransitionEnd,this.transition({from:t.visibleStyle,to:t.hiddenStyle,isCleaning:!0,onTransitionEnd:e})},d.onHideTransitionEnd=function(){this.isHidden&&(this.css({display:"none"}),this.emitEvent("hide"))},d.destroy=function(){this.css({position:"",left:"",right:"",top:"",bottom:"",transition:"",transform:""})},o}),function(t,e){"use strict";"function"==typeof define&&define.amd?define("outlayer/outlayer",["ev-emitter/ev-emitter","get-size/get-size","fizzy-ui-utils/utils","./item"],function(i,o,n,s){return e(t,i,o,n,s)}):"object"==typeof module&&module.exports?module.exports=e(t,require("ev-emitter"),require("get-size"),require("fizzy-ui-utils"),require("./item")):t.Outlayer=e(t,t.EvEmitter,t.getSize,t.fizzyUIUtils,t.Outlayer.Item)}(window,function(t,e,i,o,n){"use strict";function s(t,e){var i=o.getQueryElement(t);if(!i)return void(u&&u.error("Bad element for "+this.constructor.namespace+": "+(i||t)));this.element=i,h&&(this.$element=h(this.element)),this.options=o.extend({},this.constructor.defaults),this.option(e);var n=++l;this.element.outlayerGUID=n,f[n]=this,this._create();var s=this._getOption("initLayout");s&&this.layout()}function r(t){function e(){t.apply(this,arguments)}return e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e}function a(t){if("number"==typeof t)return t;var e=t.match(/(^\d*\.?\d*)(\w*)/),i=e&&e[1],o=e&&e[2];if(!i.length)return 0;i=parseFloat(i);var n=m[o]||1;return i*n}var u=t.console,h=t.jQuery,d=function(){},l=0,f={};s.namespace="outlayer",s.Item=n,s.defaults={containerStyle:{position:"relative"},initLayout:!0,originLeft:!0,originTop:!0,resize:!0,resizeContainer:!0,transitionDuration:"0.4s",hiddenStyle:{opacity:0,transform:"scale(0.001)"},visibleStyle:{opacity:1,transform:"scale(1)"}};var c=s.prototype;o.extend(c,e.prototype),c.option=function(t){o.extend(this.options,t)},c._getOption=function(t){var e=this.constructor.compatOptions[t];return e&&void 0!==this.options[e]?this.options[e]:this.options[t]},s.compatOptions={initLayout:"isInitLayout",horizontal:"isHorizontal",layoutInstant:"isLayoutInstant",originLeft:"isOriginLeft",originTop:"isOriginTop",resize:"isResizeBound",resizeContainer:"isResizingContainer"},c._create=function(){this.reloadItems(),this.stamps=[],this.stamp(this.options.stamp),o.extend(this.element.style,this.options.containerStyle);var t=this._getOption("resize");t&&this.bindResize()},c.reloadItems=function(){this.items=this._itemize(this.element.children)},c._itemize=function(t){for(var e=this._filterFindItemElements(t),i=this.constructor.Item,o=[],n=0;n<e.length;n++){var s=e[n],r=new i(s,this);o.push(r)}return o},c._filterFindItemElements=function(t){return o.filterFindElements(t,this.options.itemSelector)},c.getItemElements=function(){return this.items.map(function(t){return t.element})},c.layout=function(){this._resetLayout(),this._manageStamps();var t=this._getOption("layoutInstant"),e=void 0!==t?t:!this._isLayoutInited;this.layoutItems(this.items,e),this._isLayoutInited=!0},c._init=c.layout,c._resetLayout=function(){this.getSize()},c.getSize=function(){this.size=i(this.element)},c._getMeasurement=function(t,e){var o,n=this.options[t];n?("string"==typeof n?o=this.element.querySelector(n):n instanceof HTMLElement&&(o=n),this[t]=o?i(o)[e]:n):this[t]=0},c.layoutItems=function(t,e){t=this._getItemsForLayout(t),this._layoutItems(t,e),this._postLayout()},c._getItemsForLayout=function(t){return t.filter(function(t){return!t.isIgnored})},c._layoutItems=function(t,e){if(this._emitCompleteOnItems("layout",t),t&&t.length){var i=[];t.forEach(function(t){var o=this._getItemLayoutPosition(t);o.item=t,o.isInstant=e||t.isLayoutInstant,i.push(o)},this),this._processLayoutQueue(i)}},c._getItemLayoutPosition=function(){return{x:0,y:0}},c._processLayoutQueue=function(t){this.updateStagger(),t.forEach(function(t,e){this._positionItem(t.item,t.x,t.y,t.isInstant,e)},this)},c.updateStagger=function(){var t=this.options.stagger;return null===t||void 0===t?void(this.stagger=0):(this.stagger=a(t),this.stagger)},c._positionItem=function(t,e,i,o,n){o?t.goTo(e,i):(t.stagger(n*this.stagger),t.moveTo(e,i))},c._postLayout=function(){this.resizeContainer()},c.resizeContainer=function(){var t=this._getOption("resizeContainer");if(t){var e=this._getContainerSize();e&&(this._setContainerMeasure(e.width,!0),this._setContainerMeasure(e.height,!1))}},c._getContainerSize=d,c._setContainerMeasure=function(t,e){if(void 0!==t){var i=this.size;i.isBorderBox&&(t+=e?i.paddingLeft+i.paddingRight+i.borderLeftWidth+i.borderRightWidth:i.paddingBottom+i.paddingTop+i.borderTopWidth+i.borderBottomWidth),t=Math.max(t,0),this.element.style[e?"width":"height"]=t+"px"}},c._emitCompleteOnItems=function(t,e){function i(){n.dispatchEvent(t+"Complete",null,[e])}function o(){r++,r==s&&i()}var n=this,s=e.length;if(!e||!s)return void i();var r=0;e.forEach(function(e){e.once(t,o)})},c.dispatchEvent=function(t,e,i){var o=e?[e].concat(i):i;if(this.emitEvent(t,o),h)if(this.$element=this.$element||h(this.element),e){var n=h.Event(e);n.type=t,this.$element.trigger(n,i)}else this.$element.trigger(t,i)},c.ignore=function(t){var e=this.getItem(t);e&&(e.isIgnored=!0)},c.unignore=function(t){var e=this.getItem(t);e&&delete e.isIgnored},c.stamp=function(t){t=this._find(t),t&&(this.stamps=this.stamps.concat(t),t.forEach(this.ignore,this))},c.unstamp=function(t){t=this._find(t),t&&t.forEach(function(t){o.removeFrom(this.stamps,t),this.unignore(t)},this)},c._find=function(t){if(t)return"string"==typeof t&&(t=this.element.querySelectorAll(t)),t=o.makeArray(t)},c._manageStamps=function(){this.stamps&&this.stamps.length&&(this._getBoundingRect(),this.stamps.forEach(this._manageStamp,this))},c._getBoundingRect=function(){var t=this.element.getBoundingClientRect(),e=this.size;this._boundingRect={left:t.left+e.paddingLeft+e.borderLeftWidth,top:t.top+e.paddingTop+e.borderTopWidth,right:t.right-(e.paddingRight+e.borderRightWidth),bottom:t.bottom-(e.paddingBottom+e.borderBottomWidth)}},c._manageStamp=d,c._getElementOffset=function(t){var e=t.getBoundingClientRect(),o=this._boundingRect,n=i(t),s={left:e.left-o.left-n.marginLeft,top:e.top-o.top-n.marginTop,right:o.right-e.right-n.marginRight,bottom:o.bottom-e.bottom-n.marginBottom};return s},c.handleEvent=o.handleEvent,c.bindResize=function(){t.addEventListener("resize",this),this.isResizeBound=!0},c.unbindResize=function(){t.removeEventListener("resize",this),this.isResizeBound=!1},c.onresize=function(){this.resize()},o.debounceMethod(s,"onresize",100),c.resize=function(){this.isResizeBound&&this.needsResizeLayout()&&this.layout()},c.needsResizeLayout=function(){var t=i(this.element),e=this.size&&t;return e&&t.innerWidth!==this.size.innerWidth},c.addItems=function(t){var e=this._itemize(t);return e.length&&(this.items=this.items.concat(e)),e},c.appended=function(t){var e=this.addItems(t);e.length&&(this.layoutItems(e,!0),this.reveal(e))},c.prepended=function(t){var e=this._itemize(t);if(e.length){var i=this.items.slice(0);this.items=e.concat(i),this._resetLayout(),this._manageStamps(),this.layoutItems(e,!0),this.reveal(e),this.layoutItems(i)}},c.reveal=function(t){if(this._emitCompleteOnItems("reveal",t),t&&t.length){var e=this.updateStagger();t.forEach(function(t,i){t.stagger(i*e),t.reveal()})}},c.hide=function(t){if(this._emitCompleteOnItems("hide",t),t&&t.length){var e=this.updateStagger();t.forEach(function(t,i){t.stagger(i*e),t.hide()})}},c.revealItemElements=function(t){var e=this.getItems(t);this.reveal(e)},c.hideItemElements=function(t){var e=this.getItems(t);this.hide(e)},c.getItem=function(t){for(var e=0;e<this.items.length;e++){var i=this.items[e];if(i.element==t)return i}},c.getItems=function(t){t=o.makeArray(t);var e=[];return t.forEach(function(t){var i=this.getItem(t);i&&e.push(i)},this),e},c.remove=function(t){var e=this.getItems(t);this._emitCompleteOnItems("remove",e),e&&e.length&&e.forEach(function(t){t.remove(),o.removeFrom(this.items,t)},this)},c.destroy=function(){var t=this.element.style;t.height="",t.position="",t.width="",this.items.forEach(function(t){t.destroy()}),this.unbindResize();var e=this.element.outlayerGUID;delete f[e],delete this.element.outlayerGUID,h&&h.removeData(this.element,this.constructor.namespace)},s.data=function(t){t=o.getQueryElement(t);var e=t&&t.outlayerGUID;return e&&f[e]},s.create=function(t,e){var i=r(s);return i.defaults=o.extend({},s.defaults),o.extend(i.defaults,e),i.compatOptions=o.extend({},s.compatOptions),i.namespace=t,i.data=s.data,i.Item=r(n),o.htmlInit(i,t),h&&h.bridget&&h.bridget(t,i),i};var m={ms:1,s:1e3};return s.Item=n,s}),function(t,e){"function"==typeof define&&define.amd?define("isotope-layout/js/item",["outlayer/outlayer"],e):"object"==typeof module&&module.exports?module.exports=e(require("outlayer")):(t.Isotope=t.Isotope||{},t.Isotope.Item=e(t.Outlayer))}(window,function(t){"use strict";function e(){t.Item.apply(this,arguments)}var i=e.prototype=Object.create(t.Item.prototype),o=i._create;i._create=function(){this.id=this.layout.itemGUID++,o.call(this),this.sortData={}},i.updateSortData=function(){if(!this.isIgnored){this.sortData.id=this.id,this.sortData["original-order"]=this.id,this.sortData.random=Math.random();var t=this.layout.options.getSortData,e=this.layout._sorters;for(var i in t){var o=e[i];this.sortData[i]=o(this.element,this)}}};var n=i.destroy;return i.destroy=function(){n.apply(this,arguments),this.css({display:""})},e}),function(t,e){"function"==typeof define&&define.amd?define("isotope-layout/js/layout-mode",["get-size/get-size","outlayer/outlayer"],e):"object"==typeof module&&module.exports?module.exports=e(require("get-size"),require("outlayer")):(t.Isotope=t.Isotope||{},t.Isotope.LayoutMode=e(t.getSize,t.Outlayer))}(window,function(t,e){"use strict";function i(t){this.isotope=t,t&&(this.options=t.options[this.namespace],this.element=t.element,this.items=t.filteredItems,this.size=t.size)}var o=i.prototype,n=["_resetLayout","_getItemLayoutPosition","_manageStamp","_getContainerSize","_getElementOffset","needsResizeLayout","_getOption"];return n.forEach(function(t){o[t]=function(){return e.prototype[t].apply(this.isotope,arguments)}}),o.needsVerticalResizeLayout=function(){var e=t(this.isotope.element),i=this.isotope.size&&e;return i&&e.innerHeight!=this.isotope.size.innerHeight},o._getMeasurement=function(){this.isotope._getMeasurement.apply(this,arguments)},o.getColumnWidth=function(){this.getSegmentSize("column","Width")},o.getRowHeight=function(){this.getSegmentSize("row","Height")},o.getSegmentSize=function(t,e){var i=t+e,o="outer"+e;if(this._getMeasurement(i,o),!this[i]){var n=this.getFirstItemSize();this[i]=n&&n[o]||this.isotope.size["inner"+e]}},o.getFirstItemSize=function(){var e=this.isotope.filteredItems[0];return e&&e.element&&t(e.element)},o.layout=function(){this.isotope.layout.apply(this.isotope,arguments)},o.getSize=function(){this.isotope.getSize(),this.size=this.isotope.size},i.modes={},i.create=function(t,e){function n(){i.apply(this,arguments)}return n.prototype=Object.create(o),n.prototype.constructor=n,e&&(n.options=e),n.prototype.namespace=t,i.modes[t]=n,n},i}),function(t,e){"function"==typeof define&&define.amd?define("masonry-layout/masonry",["outlayer/outlayer","get-size/get-size"],e):"object"==typeof module&&module.exports?module.exports=e(require("outlayer"),require("get-size")):t.Masonry=e(t.Outlayer,t.getSize)}(window,function(t,e){var i=t.create("masonry");i.compatOptions.fitWidth="isFitWidth";var o=i.prototype;return o._resetLayout=function(){this.getSize(),this._getMeasurement("columnWidth","outerWidth"),this._getMeasurement("gutter","outerWidth"),this.measureColumns(),this.colYs=[];for(var t=0;t<this.cols;t++)this.colYs.push(0);this.maxY=0,this.horizontalColIndex=0},o.measureColumns=function(){if(this.getContainerWidth(),!this.columnWidth){var t=this.items[0],i=t&&t.element;this.columnWidth=i&&e(i).outerWidth||this.containerWidth}var o=this.columnWidth+=this.gutter,n=this.containerWidth+this.gutter,s=n/o,r=o-n%o,a=r&&r<1?"round":"floor";s=Math[a](s),this.cols=Math.max(s,1)},o.getContainerWidth=function(){var t=this._getOption("fitWidth"),i=t?this.element.parentNode:this.element,o=e(i);this.containerWidth=o&&o.innerWidth},o._getItemLayoutPosition=function(t){t.getSize();var e=t.size.outerWidth%this.columnWidth,i=e&&e<1?"round":"ceil",o=Math[i](t.size.outerWidth/this.columnWidth);o=Math.min(o,this.cols);for(var n=this.options.horizontalOrder?"_getHorizontalColPosition":"_getTopColPosition",s=this[n](o,t),r={x:this.columnWidth*s.col,y:s.y},a=s.y+t.size.outerHeight,u=o+s.col,h=s.col;h<u;h++)this.colYs[h]=a;return r},o._getTopColPosition=function(t){var e=this._getTopColGroup(t),i=Math.min.apply(Math,e);return{col:e.indexOf(i),y:i}},o._getTopColGroup=function(t){if(t<2)return this.colYs;for(var e=[],i=this.cols+1-t,o=0;o<i;o++)e[o]=this._getColGroupY(o,t);return e},o._getColGroupY=function(t,e){if(e<2)return this.colYs[t];var i=this.colYs.slice(t,t+e);return Math.max.apply(Math,i)},o._getHorizontalColPosition=function(t,e){var i=this.horizontalColIndex%this.cols,o=t>1&&i+t>this.cols;i=o?0:i;var n=e.size.outerWidth&&e.size.outerHeight;return this.horizontalColIndex=n?i+t:this.horizontalColIndex,{col:i,y:this._getColGroupY(i,t)}},o._manageStamp=function(t){var i=e(t),o=this._getElementOffset(t),n=this._getOption("originLeft"),s=n?o.left:o.right,r=s+i.outerWidth,a=Math.floor(s/this.columnWidth);a=Math.max(0,a);var u=Math.floor(r/this.columnWidth);u-=r%this.columnWidth?0:1,u=Math.min(this.cols-1,u);for(var h=this._getOption("originTop"),d=(h?o.top:o.bottom)+i.outerHeight,l=a;l<=u;l++)this.colYs[l]=Math.max(d,this.colYs[l])},o._getContainerSize=function(){this.maxY=Math.max.apply(Math,this.colYs);var t={height:this.maxY};return this._getOption("fitWidth")&&(t.width=this._getContainerFitWidth()),t},o._getContainerFitWidth=function(){for(var t=0,e=this.cols;--e&&0===this.colYs[e];)t++;return(this.cols-t)*this.columnWidth-this.gutter},o.needsResizeLayout=function(){var t=this.containerWidth;return this.getContainerWidth(),t!=this.containerWidth},i}),function(t,e){"function"==typeof define&&define.amd?define("isotope-layout/js/layout-modes/masonry",["../layout-mode","masonry-layout/masonry"],e):"object"==typeof module&&module.exports?module.exports=e(require("../layout-mode"),require("masonry-layout")):e(t.Isotope.LayoutMode,t.Masonry)}(window,function(t,e){"use strict";var i=t.create("masonry"),o=i.prototype,n={_getElementOffset:!0,layout:!0,_getMeasurement:!0};for(var s in e.prototype)n[s]||(o[s]=e.prototype[s]);var r=o.measureColumns;o.measureColumns=function(){this.items=this.isotope.filteredItems,r.call(this)};var a=o._getOption;return o._getOption=function(t){return"fitWidth"==t?void 0!==this.options.isFitWidth?this.options.isFitWidth:this.options.fitWidth:a.apply(this.isotope,arguments)},i}),function(t,e){"function"==typeof define&&define.amd?define("isotope-layout/js/layout-modes/fit-rows",["../layout-mode"],e):"object"==typeof exports?module.exports=e(require("../layout-mode")):e(t.Isotope.LayoutMode)}(window,function(t){"use strict";var e=t.create("fitRows"),i=e.prototype;return i._resetLayout=function(){this.x=0,this.y=0,this.maxY=0,this._getMeasurement("gutter","outerWidth")},i._getItemLayoutPosition=function(t){t.getSize();var e=t.size.outerWidth+this.gutter,i=this.isotope.size.innerWidth+this.gutter;0!==this.x&&e+this.x>i&&(this.x=0,this.y=this.maxY);var o={x:this.x,y:this.y};return this.maxY=Math.max(this.maxY,this.y+t.size.outerHeight),this.x+=e,o},i._getContainerSize=function(){return{height:this.maxY}},e}),function(t,e){"function"==typeof define&&define.amd?define("isotope-layout/js/layout-modes/vertical",["../layout-mode"],e):"object"==typeof module&&module.exports?module.exports=e(require("../layout-mode")):e(t.Isotope.LayoutMode)}(window,function(t){"use strict";var e=t.create("vertical",{horizontalAlignment:0}),i=e.prototype;return i._resetLayout=function(){this.y=0},i._getItemLayoutPosition=function(t){t.getSize();var e=(this.isotope.size.innerWidth-t.size.outerWidth)*this.options.horizontalAlignment,i=this.y;return this.y+=t.size.outerHeight,{x:e,y:i}},i._getContainerSize=function(){return{height:this.y}},e}),function(t,e){"function"==typeof define&&define.amd?define(["outlayer/outlayer","get-size/get-size","desandro-matches-selector/matches-selector","fizzy-ui-utils/utils","isotope-layout/js/item","isotope-layout/js/layout-mode","isotope-layout/js/layout-modes/masonry","isotope-layout/js/layout-modes/fit-rows","isotope-layout/js/layout-modes/vertical"],function(i,o,n,s,r,a){return e(t,i,o,n,s,r,a)}):"object"==typeof module&&module.exports?module.exports=e(t,require("outlayer"),require("get-size"),require("desandro-matches-selector"),require("fizzy-ui-utils"),require("isotope-layout/js/item"),require("isotope-layout/js/layout-mode"),require("isotope-layout/js/layout-modes/masonry"),require("isotope-layout/js/layout-modes/fit-rows"),require("isotope-layout/js/layout-modes/vertical")):t.Isotope=e(t,t.Outlayer,t.getSize,t.matchesSelector,t.fizzyUIUtils,t.Isotope.Item,t.Isotope.LayoutMode)}(window,function(t,e,i,o,n,s,r){function a(t,e){return function(i,o){for(var n=0;n<t.length;n++){var s=t[n],r=i.sortData[s],a=o.sortData[s];if(r>a||r<a){var u=void 0!==e[s]?e[s]:e,h=u?1:-1;return(r>a?1:-1)*h}}return 0}}var u=t.jQuery,h=String.prototype.trim?function(t){return t.trim()}:function(t){return t.replace(/^\s+|\s+$/g,"")},d=e.create("isotope",{layoutMode:"masonry",isJQueryFiltering:!0,sortAscending:!0});d.Item=s,d.LayoutMode=r;var l=d.prototype;l._create=function(){this.itemGUID=0,this._sorters={},this._getSorters(),e.prototype._create.call(this),this.modes={},this.filteredItems=this.items,this.sortHistory=["original-order"];for(var t in r.modes)this._initLayoutMode(t)},l.reloadItems=function(){this.itemGUID=0,e.prototype.reloadItems.call(this)},l._itemize=function(){for(var t=e.prototype._itemize.apply(this,arguments),i=0;i<t.length;i++){var o=t[i];o.id=this.itemGUID++}return this._updateItemsSortData(t),t},l._initLayoutMode=function(t){var e=r.modes[t],i=this.options[t]||{};this.options[t]=e.options?n.extend(e.options,i):i,this.modes[t]=new e(this)},l.layout=function(){return!this._isLayoutInited&&this._getOption("initLayout")?void this.arrange():void this._layout()},l._layout=function(){var t=this._getIsInstant();this._resetLayout(),this._manageStamps(),this.layoutItems(this.filteredItems,t),this._isLayoutInited=!0},l.arrange=function(t){this.option(t),this._getIsInstant();var e=this._filter(this.items);this.filteredItems=e.matches,this._bindArrangeComplete(),this._isInstant?this._noTransition(this._hideReveal,[e]):this._hideReveal(e),this._sort(),this._layout()},l._init=l.arrange,l._hideReveal=function(t){this.reveal(t.needReveal),this.hide(t.needHide)},l._getIsInstant=function(){var t=this._getOption("layoutInstant"),e=void 0!==t?t:!this._isLayoutInited;return this._isInstant=e,e},l._bindArrangeComplete=function(){function t(){e&&i&&o&&n.dispatchEvent("arrangeComplete",null,[n.filteredItems])}var e,i,o,n=this;this.once("layoutComplete",function(){e=!0,t()}),this.once("hideComplete",function(){i=!0,t()}),this.once("revealComplete",function(){o=!0,t()})},l._filter=function(t){var e=this.options.filter;e=e||"*";for(var i=[],o=[],n=[],s=this._getFilterTest(e),r=0;r<t.length;r++){var a=t[r];if(!a.isIgnored){var u=s(a);u&&i.push(a),u&&a.isHidden?o.push(a):u||a.isHidden||n.push(a)}}return{matches:i,needReveal:o,needHide:n}},l._getFilterTest=function(t){return u&&this.options.isJQueryFiltering?function(e){return u(e.element).is(t);
}:"function"==typeof t?function(e){return t(e.element)}:function(e){return o(e.element,t)}},l.updateSortData=function(t){var e;t?(t=n.makeArray(t),e=this.getItems(t)):e=this.items,this._getSorters(),this._updateItemsSortData(e)},l._getSorters=function(){var t=this.options.getSortData;for(var e in t){var i=t[e];this._sorters[e]=f(i)}},l._updateItemsSortData=function(t){for(var e=t&&t.length,i=0;e&&i<e;i++){var o=t[i];o.updateSortData()}};var f=function(){function t(t){if("string"!=typeof t)return t;var i=h(t).split(" "),o=i[0],n=o.match(/^\[(.+)\]$/),s=n&&n[1],r=e(s,o),a=d.sortDataParsers[i[1]];return t=a?function(t){return t&&a(r(t))}:function(t){return t&&r(t)}}function e(t,e){return t?function(e){return e.getAttribute(t)}:function(t){var i=t.querySelector(e);return i&&i.textContent}}return t}();d.sortDataParsers={parseInt:function(t){return parseInt(t,10)},parseFloat:function(t){return parseFloat(t)}},l._sort=function(){if(this.options.sortBy){var t=n.makeArray(this.options.sortBy);this._getIsSameSortBy(t)||(this.sortHistory=t.concat(this.sortHistory));var e=a(this.sortHistory,this.options.sortAscending);this.filteredItems.sort(e)}},l._getIsSameSortBy=function(t){for(var e=0;e<t.length;e++)if(t[e]!=this.sortHistory[e])return!1;return!0},l._mode=function(){var t=this.options.layoutMode,e=this.modes[t];if(!e)throw new Error("No layout mode: "+t);return e.options=this.options[t],e},l._resetLayout=function(){e.prototype._resetLayout.call(this),this._mode()._resetLayout()},l._getItemLayoutPosition=function(t){return this._mode()._getItemLayoutPosition(t)},l._manageStamp=function(t){this._mode()._manageStamp(t)},l._getContainerSize=function(){return this._mode()._getContainerSize()},l.needsResizeLayout=function(){return this._mode().needsResizeLayout()},l.appended=function(t){var e=this.addItems(t);if(e.length){var i=this._filterRevealAdded(e);this.filteredItems=this.filteredItems.concat(i)}},l.prepended=function(t){var e=this._itemize(t);if(e.length){this._resetLayout(),this._manageStamps();var i=this._filterRevealAdded(e);this.layoutItems(this.filteredItems),this.filteredItems=i.concat(this.filteredItems),this.items=e.concat(this.items)}},l._filterRevealAdded=function(t){var e=this._filter(t);return this.hide(e.needHide),this.reveal(e.matches),this.layoutItems(e.matches,!0),e.matches},l.insert=function(t){var e=this.addItems(t);if(e.length){var i,o,n=e.length;for(i=0;i<n;i++)o=e[i],this.element.appendChild(o.element);var s=this._filter(e).matches;for(i=0;i<n;i++)e[i].isLayoutInstant=!0;for(this.arrange(),i=0;i<n;i++)delete e[i].isLayoutInstant;this.reveal(s)}};var c=l.remove;return l.remove=function(t){t=n.makeArray(t);var e=this.getItems(t);c.call(this,t);for(var i=e&&e.length,o=0;i&&o<i;o++){var s=e[o];n.removeFrom(this.filteredItems,s)}},l.shuffle=function(){for(var t=0;t<this.items.length;t++){var e=this.items[t];e.sortData.random=Math.random()}this.options.sortBy="random",this._sort(),this._layout()},l._noTransition=function(t,e){var i=this.options.transitionDuration;this.options.transitionDuration=0;var o=t.apply(this,e);return this.options.transitionDuration=i,o},l.getFilteredItemElements=function(){return this.filteredItems.map(function(t){return t.element})},d});
|
0000cd/wolf-set
| 3,472 |
themes/bluf/static/js/Meting.min.js
|
"use strict";function _objectSpread(a){for(var b=1;b<arguments.length;b++){var c=null==arguments[b]?{}:arguments[b],d=Object.keys(c);"function"==typeof Object.getOwnPropertySymbols&&(d=d.concat(Object.getOwnPropertySymbols(c).filter(function(a){return Object.getOwnPropertyDescriptor(c,a).enumerable}))),d.forEach(function(b){_defineProperty(a,b,c[b])})}return a}function _defineProperty(a,b,c){return b in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}class MetingJSElement extends HTMLElement{connectedCallback(){window.APlayer&&window.fetch&&(this._init(),this._parse())}disconnectedCallback(){this.lock||this.aplayer.destroy()}_camelize(a){return a.replace(/^[_.\- ]+/,"").toLowerCase().replace(/[_.\- ]+(\w|$)/g,(a,b)=>b.toUpperCase())}_init(){let a={};for(let b=0;b<this.attributes.length;b+=1)a[this._camelize(this.attributes[b].name)]=this.attributes[b].value;let b=["server","type","id","api","auth","auto","lock","name","title","artist","author","url","cover","pic","lyric","lrc"];this.meta={};for(var c=0;c<b.length;c++){let d=b[c];this.meta[d]=a[d],delete a[d]}this.config=a,this.api=this.meta.api||window.meting_api||"https://api.i-meto.com/meting/api?server=:server&type=:type&id=:id&r=:r",this.meta.auto&&this._parse_link()}_parse_link(){let a=[["music.163.com.*song.*id=(\\d+)","netease","song"],["music.163.com.*album.*id=(\\d+)","netease","album"],["music.163.com.*artist.*id=(\\d+)","netease","artist"],["music.163.com.*playlist.*id=(\\d+)","netease","playlist"],["music.163.com.*discover/toplist.*id=(\\d+)","netease","playlist"],["y.qq.com.*song/(\\w+).html","tencent","song"],["y.qq.com.*album/(\\w+).html","tencent","album"],["y.qq.com.*singer/(\\w+).html","tencent","artist"],["y.qq.com.*playsquare/(\\w+).html","tencent","playlist"],["y.qq.com.*playlist/(\\w+).html","tencent","playlist"],["xiami.com.*song/(\\w+)","xiami","song"],["xiami.com.*album/(\\w+)","xiami","album"],["xiami.com.*artist/(\\w+)","xiami","artist"],["xiami.com.*collect/(\\w+)","xiami","playlist"]];for(var b=0;b<a.length;b++){let c=a[b],d=new RegExp(c[0]),e=d.exec(this.meta.auto);if(null!==e)return this.meta.server=c[1],this.meta.type=c[2],void(this.meta.id=e[1])}}_parse(){if(this.meta.url){let a={name:this.meta.name||this.meta.title||"Audio name",artist:this.meta.artist||this.meta.author||"Audio artist",url:this.meta.url,cover:this.meta.cover||this.meta.pic,lrc:this.meta.lrc||this.meta.lyric||"",type:this.meta.type||"auto"};return a.lrc||(this.meta.lrcType=0),this.innerText&&(a.lrc=this.innerText,this.meta.lrcType=2),void this._loadPlayer([a])}let a=this.api.replace(":server",this.meta.server).replace(":type",this.meta.type).replace(":id",this.meta.id).replace(":auth",this.meta.auth).replace(":r",Math.random());fetch(a).then(a=>a.json()).then(a=>this._loadPlayer(a))}_loadPlayer(a){let b={audio:a,mutex:!0,lrcType:this.meta.lrcType||3,storageName:"metingjs"};if(a.length){let a=_objectSpread({},b,this.config);for(let b in a)("true"===a[b]||"false"===a[b])&&(a[b]="true"===a[b]);let c=document.createElement("div");a.container=c,this.appendChild(c),this.aplayer=new APlayer(a)}}}console.log("\n %c MetingJS v2.0.1 %c https://github.com/metowolf/MetingJS \n","color: #fadfa3; background: #030307; padding:5px 0;","background: #fadfa3; padding:5px 0;"),window.customElements&&!window.customElements.get("meting-js")&&(window.MetingJSElement=MetingJSElement,window.customElements.define("meting-js",MetingJSElement));
|
000haoji/deep-student
| 20,571 |
src/components/EnhancedRagQueryView.tsx
|
import React, { useState, useEffect, useCallback } from 'react';
import { TauriAPI } from '../utils/tauriApi';
import { useNotification } from '../hooks/useNotification';
import { MarkdownRenderer } from './MarkdownRenderer';
import type {
RagQueryResponse,
RetrievedChunk
} from '../types';
import './EnhancedRagQueryView.css';
import {
Search,
FileText,
BookOpen,
Target,
BarChart3,
Settings,
Lightbulb
} from 'lucide-react';
// 定义分库接口类型
interface SubLibrary {
id: string;
name: string;
description?: string;
created_at: string;
updated_at: string;
document_count: number;
chunk_count: number;
}
interface RagQueryOptionsWithLibraries {
top_k: number;
enable_reranking?: boolean;
target_sub_library_ids?: string[];
}
interface EnhancedRagQueryViewProps {
className?: string;
}
export const EnhancedRagQueryView: React.FC<EnhancedRagQueryViewProps> = ({
className = ''
}) => {
// 查询相关状态
const [query, setQuery] = useState('');
const [queryResult, setQueryResult] = useState<RagQueryResponse | null>(null);
const [isQuerying, setIsQuerying] = useState(false);
// 分库相关状态
const [subLibraries, setSubLibraries] = useState<SubLibrary[]>([]);
const [selectedLibraries, setSelectedLibraries] = useState<string[]>([]);
const [showLibrarySelector, setShowLibrarySelector] = useState(false);
// 查询选项
const [topK, setTopK] = useState(5);
const [enableReranking, setEnableReranking] = useState(false);
const [showAdvancedOptions, setShowAdvancedOptions] = useState(false);
const { showSuccess, showError, showWarning } = useNotification();
// 加载分库列表
const loadSubLibraries = useCallback(async () => {
try {
const libraries = await TauriAPI.invoke('get_rag_sub_libraries') as SubLibrary[];
setSubLibraries(libraries);
// 默认选择所有分库
if (selectedLibraries.length === 0) {
setSelectedLibraries(libraries.map((lib: SubLibrary) => lib.id));
}
} catch (error) {
console.error('加载分库列表失败:', error);
showError(`加载分库列表失败: ${error}`);
}
}, [selectedLibraries.length, showError]);
// 执行RAG查询
const performQuery = async () => {
if (!query.trim()) {
showWarning('请输入查询内容');
return;
}
if (selectedLibraries.length === 0) {
showWarning('请至少选择一个分库');
return;
}
setIsQuerying(true);
try {
const options: RagQueryOptionsWithLibraries = {
top_k: topK,
enable_reranking: enableReranking,
target_sub_library_ids: selectedLibraries.length === subLibraries.length
? undefined // 如果选择了所有分库,传undefined表示查询所有
: selectedLibraries
};
const startTime = Date.now();
const result = await TauriAPI.invoke('rag_query_knowledge_base_in_libraries', {
query,
options
}) as RagQueryResponse;
const endTime = Date.now();
setQueryResult(result);
const selectedLibraryNames = selectedLibraries.map(id =>
subLibraries.find(lib => lib.id === id)?.name || id
).join(', ');
showSuccess(
`查询完成!在分库 [${selectedLibraryNames}] 中找到 ${result.retrieved_chunks.length} 个相关结果 (${endTime - startTime}ms)`
);
} catch (error) {
console.error('RAG查询失败:', error);
showError(`RAG查询失败: ${error}`);
} finally {
setIsQuerying(false);
}
};
// 切换分库选择
const toggleLibrarySelection = (libraryId: string) => {
setSelectedLibraries(prev =>
prev.includes(libraryId)
? prev.filter(id => id !== libraryId)
: [...prev, libraryId]
);
};
// 全选/取消全选分库
const toggleAllLibraries = () => {
setSelectedLibraries(
selectedLibraries.length === subLibraries.length
? []
: subLibraries.map(lib => lib.id)
);
};
// 快速选择预设
const selectDefaultLibrary = () => {
setSelectedLibraries(['default']);
};
const selectNonDefaultLibraries = () => {
setSelectedLibraries(subLibraries.filter(lib => lib.id !== 'default').map(lib => lib.id));
};
// 初始化加载
useEffect(() => {
loadSubLibraries();
}, [loadSubLibraries]);
// 处理回车键查询
const handleKeyPress = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
performQuery();
}
};
// 格式化时间显示
const formatTime = (ms: number) => {
return ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${ms}ms`;
};
// 计算相似度颜色
const getScoreColor = (score: number) => {
if (score >= 0.8) return '#22c55e'; // 绿色
if (score >= 0.6) return '#f59e0b'; // 橙色
if (score >= 0.4) return '#ef4444'; // 红色
return '#6b7280'; // 灰色
};
return (
<div style={{
width: '100%',
height: '100%',
overflow: 'auto',
background: '#f8fafc'
}}>
{/* 头部区域 - 统一白色样式 */}
<div style={{
background: 'white',
borderBottom: '1px solid #e5e7eb',
padding: '24px 32px',
position: 'relative'
}}>
<div style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
height: '4px',
background: 'linear-gradient(90deg, #667eea, #764ba2)'
}}></div>
<div style={{ position: 'relative', zIndex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
<svg style={{ width: '32px', height: '32px', marginRight: '12px', color: '#667eea' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<h1 style={{ fontSize: '28px', fontWeight: '700', margin: 0, color: '#1f2937' }}>增强RAG智能查询</h1>
</div>
<p style={{ fontSize: '16px', color: '#6b7280', margin: 0, lineHeight: '1.5' }}>
智能检索知识库内容,获取精准相关信息和文档片段
</p>
<div style={{ marginTop: '24px', display: 'flex', gap: '12px' }}>
<button
onClick={() => setShowLibrarySelector(!showLibrarySelector)}
style={{
background: showLibrarySelector ? '#667eea' : 'white',
border: '1px solid #667eea',
color: showLibrarySelector ? 'white' : '#667eea',
padding: '12px 24px',
borderRadius: '12px',
fontSize: '16px',
fontWeight: '600',
cursor: 'pointer',
display: 'inline-flex',
alignItems: 'center',
gap: '8px',
transition: 'all 0.3s ease'
}}
onMouseOver={(e) => {
e.currentTarget.style.background = '#667eea';
e.currentTarget.style.color = 'white';
e.currentTarget.style.transform = 'translateY(-2px)';
e.currentTarget.style.boxShadow = '0 8px 25px rgba(102, 126, 234, 0.3)';
}}
onMouseOut={(e) => {
e.currentTarget.style.background = showLibrarySelector ? '#667eea' : 'white';
e.currentTarget.style.color = showLibrarySelector ? 'white' : '#667eea';
e.currentTarget.style.transform = 'translateY(0)';
e.currentTarget.style.boxShadow = 'none';
}}
>
<svg style={{ width: '20px', height: '20px' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
分库选择 ({selectedLibraries.length}/{subLibraries.length})
</button>
<button
onClick={() => setShowAdvancedOptions(!showAdvancedOptions)}
style={{
background: showAdvancedOptions ? '#667eea' : 'white',
border: '1px solid #d1d5db',
color: showAdvancedOptions ? 'white' : '#374151',
padding: '12px 24px',
borderRadius: '12px',
fontSize: '16px',
fontWeight: '600',
cursor: 'pointer',
display: 'inline-flex',
alignItems: 'center',
gap: '8px',
transition: 'all 0.3s ease'
}}
onMouseOver={(e) => {
e.currentTarget.style.background = '#f9fafb';
e.currentTarget.style.transform = 'translateY(-2px)';
e.currentTarget.style.boxShadow = '0 8px 25px rgba(0, 0, 0, 0.1)';
}}
onMouseOut={(e) => {
e.currentTarget.style.background = showAdvancedOptions ? '#667eea' : 'white';
e.currentTarget.style.transform = 'translateY(0)';
e.currentTarget.style.boxShadow = 'none';
}}
>
<svg style={{ width: '20px', height: '20px' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
高级选项
</button>
</div>
</div>
</div>
<div className={`enhanced-rag-query-view ${className}`} style={{ padding: '24px', background: 'transparent' }}>
{/* 分库选择器 */}
{showLibrarySelector && (
<div className="library-selector">
<div className="selector-header">
<h3>选择查询分库</h3>
<div className="selector-actions">
<button
onClick={toggleAllLibraries}
className="btn btn-sm btn-secondary"
>
{selectedLibraries.length === subLibraries.length ? '取消全选' : '全选'}
</button>
<button
onClick={selectDefaultLibrary}
className="btn btn-sm btn-secondary"
>
仅默认库
</button>
<button
onClick={selectNonDefaultLibraries}
className="btn btn-sm btn-secondary"
>
仅自定义库
</button>
</div>
</div>
<div className="library-grid">
{subLibraries.map(library => (
<div
key={library.id}
className={`library-card ${selectedLibraries.includes(library.id) ? 'selected' : ''}`}
onClick={() => toggleLibrarySelection(library.id)}
>
<div className="library-checkbox">
<input
type="checkbox"
checked={selectedLibraries.includes(library.id)}
onChange={() => toggleLibrarySelection(library.id)}
/>
</div>
<div className="library-info">
<div className="library-name">{library.name}</div>
<div className="library-stats" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<FileText size={14} />
{library.document_count} |
<BookOpen size={14} />
{library.chunk_count}
</div>
{library.description && (
<div className="library-description">{library.description}</div>
)}
</div>
</div>
))}
</div>
</div>
)}
{/* 高级选项 */}
{showAdvancedOptions && (
<div className="advanced-options">
<div className="options-grid">
<div className="option-group">
<label>返回结果数量 (Top-K)</label>
<input
type="number"
min="1"
max="20"
value={topK}
onChange={(e) => setTopK(parseInt(e.target.value) || 5)}
className="form-input"
/>
<div className="option-hint">建议值: 3-10</div>
</div>
<div className="option-group">
<label className="checkbox-label">
<input
type="checkbox"
checked={enableReranking}
onChange={(e) => setEnableReranking(e.target.checked)}
/>
启用重排序
</label>
<div className="option-hint">使用重排序模型提高结果相关性</div>
</div>
</div>
</div>
)}
{/* 查询输入区域 */}
<div className="query-input-section">
<div className="input-group">
<textarea
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyPress={handleKeyPress}
placeholder="输入您的问题,AI将在选定的知识库分库中搜索相关信息..."
className="query-input"
rows={3}
disabled={isQuerying}
/>
<button
onClick={performQuery}
disabled={isQuerying || !query.trim() || selectedLibraries.length === 0}
className="btn btn-primary query-btn"
style={{ display: 'flex', alignItems: 'center', gap: '6px' }}
>
<Search size={16} />
{isQuerying ? '查询中...' : '智能查询'}
</button>
</div>
{selectedLibraries.length > 0 && (
<div className="selected-libraries-info">
<span className="info-label">查询范围:</span>
<div className="library-tags">
{selectedLibraries.map(id => {
const library = subLibraries.find(lib => lib.id === id);
return library ? (
<span key={id} className="library-tag">
{library.name}
</span>
) : null;
})}
</div>
</div>
)}
</div>
{/* 查询结果 */}
{queryResult && (
<div className="query-results">
<div className="results-header">
<h3 style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<BarChart3 size={20} />
查询结果 ({queryResult.retrieved_chunks.length} 个结果)
</h3>
<div className="results-meta">
<div className="meta-item">
<span className="label">查询时间:</span>
<span className="value">{formatTime(queryResult.query_vector_time_ms)}</span>
</div>
<div className="meta-item">
<span className="label">搜索时间:</span>
<span className="value">{formatTime(queryResult.search_time_ms)}</span>
</div>
{queryResult.reranking_time_ms && (
<div className="meta-item">
<span className="label">重排序时间:</span>
<span className="value">{formatTime(queryResult.reranking_time_ms)}</span>
</div>
)}
<div className="meta-item">
<span className="label">总时间:</span>
<span className="value">{formatTime(queryResult.total_time_ms)}</span>
</div>
</div>
</div>
{queryResult.retrieved_chunks.length === 0 ? (
<div className="no-results">
<div className="no-results-icon">
<Search size={48} />
</div>
<div className="no-results-text">未找到相关内容</div>
<div className="no-results-hint">
尝试使用不同的关键词或选择更多分库
</div>
</div>
) : (
<div className="results-list">
{queryResult.retrieved_chunks.map((chunk: RetrievedChunk, index) => (
<div key={`${chunk.chunk.id}-${index}`} className="result-item">
<div className="result-header">
<div className="result-meta">
<span className="result-index">#{index + 1}</span>
<span className="result-source" style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<FileText size={14} />
{chunk.chunk.metadata.filename || `文档-${chunk.chunk.document_id.slice(0, 8)}`}
</span>
<span className="result-chunk" style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<BookOpen size={14} />
块 {chunk.chunk.chunk_index + 1}
</span>
</div>
<div
className="similarity-score"
style={{ color: getScoreColor(chunk.score), display: 'flex', alignItems: 'center', gap: '4px' }}
>
<Target size={14} />
{(chunk.score * 100).toFixed(1)}%
</div>
</div>
<div className="result-content">
<MarkdownRenderer content={chunk.chunk.text} />
</div>
{chunk.chunk.metadata && Object.keys(chunk.chunk.metadata).length > 0 && (
<div className="result-metadata">
<details>
<summary style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
<BookOpen size={16} />
元数据
</summary>
<div className="metadata-content">
{Object.entries(chunk.chunk.metadata).map(([key, value]) => (
<div key={key} className="metadata-item">
<span className="metadata-key">{key}:</span>
<span className="metadata-value">{value}</span>
</div>
))}
</div>
</details>
</div>
)}
</div>
))}
</div>
)}
</div>
)}
{/* 使用说明 */}
{!queryResult && (
<div className="usage-guide">
<h3 style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Target size={20} />
使用指南
</h3>
<div className="guide-content">
<div className="guide-section">
<h4 style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
<BookOpen size={16} />
分库选择
</h4>
<ul>
<li>选择一个或多个分库进行查询</li>
<li>默认库包含通过普通上传添加的文档</li>
<li>自定义库包含分类管理的专项文档</li>
</ul>
</div>
<div className="guide-section">
<h4 style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
<Search size={16} />
查询技巧
</h4>
<ul>
<li>使用具体的关键词获得更准确的结果</li>
<li>可以提出问题,AI会寻找相关答案</li>
<li>支持中英文混合查询</li>
<li>按 Enter 键快速查询,Shift+Enter 换行</li>
</ul>
</div>
<div className="guide-section">
<h4 style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
<Settings size={16} />
高级设置
</h4>
<ul>
<li><strong>Top-K:</strong> 控制返回结果的数量</li>
<li><strong>重排序:</strong> 使用AI模型重新排序结果以提高相关性</li>
<li><strong>相似度分数:</strong> 绿色(80%+)表示高度相关,橙色(60-80%)表示中等相关</li>
</ul>
</div>
</div>
</div>
)}
</div>
</div>
);
};
export default EnhancedRagQueryView;
|
000haoji/deep-student
| 4,447 |
src/components/StreamingMarkdownRenderer.tsx
|
import React, { useState, useEffect, useMemo } from 'react';
import { MarkdownRenderer } from './MarkdownRenderer';
interface StreamingMarkdownRendererProps {
content: string;
isStreaming: boolean;
chainOfThought?: {
enabled: boolean;
details?: any;
};
}
type ParsedContent = {
thinkingContent: string;
mainContent: string;
}
// 流式内容预处理函数
const preprocessStreamingContent = (content: string, isStreaming: boolean) => {
if (!content) return { content: '', hasPartialMath: false };
let processed = content;
let hasPartialMath = false;
// 检测不完整的数学公式
const incompletePatterns = [
/\$[^$]*$/, // 以$结尾但没有关闭$
/\$\$[^$]*$/, // 以$$结尾但没有关闭$$
/\\begin\{[^}]*\}[^\\]*$/, // 不完整的环境
/\\[a-zA-Z]+\{[^}]*$/, // 不完整的命令
];
if (isStreaming) {
// 更精确地检测不完整的数学公式
hasPartialMath = incompletePatterns.some(pattern => pattern.test(processed));
// 不要隐藏不完整的公式,而是保持原样并添加指示符
// 让用户看到正在输入的数学内容,即使还不完整
if (hasPartialMath) {
// 检查是否是真正的不完整公式(而不是正常的LaTeX语法)
const hasOpenMath = (processed.match(/\$/g) || []).length % 2 !== 0;
const hasOpenDisplayMath = (processed.match(/\$\$/g) || []).length % 2 !== 0;
// 只有当确实存在未闭合的数学公式时才标记为不完整
if (hasOpenMath || hasOpenDisplayMath) {
// 保持内容不变,只是标记状态
hasPartialMath = true;
} else {
hasPartialMath = false;
}
}
}
return { content: processed, hasPartialMath };
};
export const StreamingMarkdownRenderer: React.FC<StreamingMarkdownRendererProps> = ({
content,
isStreaming
}) => {
const [displayContent, setDisplayContent] = useState('');
const [showCursor, setShowCursor] = useState(true);
const [isPartialMath, setIsPartialMath] = useState(false);
useEffect(() => {
// 对流式内容进行智能处理
const processedContent = preprocessStreamingContent(content, isStreaming);
setDisplayContent(processedContent.content);
setIsPartialMath(processedContent.hasPartialMath);
}, [content, isStreaming]);
useEffect(() => {
if (isStreaming) {
const interval = setInterval(() => {
setShowCursor(prev => !prev);
}, 500);
return () => clearInterval(interval);
} else {
setShowCursor(false);
}
}, [isStreaming]);
// 解析思维链内容
const parseChainOfThought = (content: string): ParsedContent | null => {
// 检查是否包含 <thinking> 标签
const thinkingMatch = content.match(/<thinking>([\s\S]*?)<\/thinking>\s*/);
if (thinkingMatch) {
const thinkingContent = thinkingMatch[1].trim();
const mainContent = content.replace(thinkingMatch[0], '').trim();
return {
thinkingContent,
mainContent
};
}
return null;
};
const parsedContent = parseChainOfThought(displayContent);
// 使用 useMemo 优化性能
const renderedContent = useMemo(() => {
if (!displayContent) return null;
return <MarkdownRenderer content={displayContent} />;
}, [displayContent]);
return (
<div className="streaming-markdown">
{parsedContent ? (
<>
{/* 渲染思维链内容 */}
{parsedContent.thinkingContent && (
<div className="chain-of-thought">
<div className="chain-header">
<span className="chain-icon">🧠</span>
<span className="chain-title">AI 思考过程</span>
</div>
<div className="thinking-content">
<MarkdownRenderer content={parsedContent.thinkingContent} />
</div>
</div>
)}
{/* 渲染主要内容 */}
<div className="main-content">
{parsedContent.mainContent ? (
<MarkdownRenderer content={parsedContent.mainContent} />
) : (
renderedContent
)}
{isStreaming && showCursor && (
<span className="streaming-cursor">▋</span>
)}
{isPartialMath && isStreaming && (
<span className="partial-math-indicator" title="正在输入数学公式...">📝</span>
)}
</div>
</>
) : (
<div className="normal-content">
{renderedContent}
{isStreaming && showCursor && (
<span className="streaming-cursor">▋</span>
)}
{isPartialMath && isStreaming && (
<span className="partial-math-indicator" title="正在输入数学公式...">📝</span>
)}
</div>
)}
</div>
);
};
|
0015/StickiNote
| 101,409 |
main/ui_resources/sticky_font_32.c
|
/*******************************************************************************
* Size: 32 px
* Bpp: 4
* Opts: --bpp 4 --size 32 --no-compress --font Sticky Notes.otf --range 32-127 --format lvgl -o sticky_font_32.c
******************************************************************************/
#ifdef __has_include
#if __has_include("lvgl.h")
#ifndef LV_LVGL_H_INCLUDE_SIMPLE
#define LV_LVGL_H_INCLUDE_SIMPLE
#endif
#endif
#endif
#if defined(LV_LVGL_H_INCLUDE_SIMPLE)
#include "lvgl.h"
#else
#include "lvgl/lvgl.h"
#endif
#ifndef STICKY_FONT_32
#define STICKY_FONT_32 1
#endif
#if STICKY_FONT_32
/*-----------------
* BITMAPS
*----------------*/
/*Store the image of the glyphs*/
static LV_ATTRIBUTE_LARGE_CONST const uint8_t glyph_bitmap[] = {
/* U+0020 " " */
/* U+0021 "!" */
0x2, 0x81, 0xc, 0xf8, 0xf, 0xf7, 0xf, 0xf5,
0x1f, 0xf4, 0x1f, 0xf4, 0xf, 0xf4, 0xf, 0xf4,
0xf, 0xf5, 0xf, 0xf5, 0xf, 0xf6, 0xe, 0xf6,
0xe, 0xf7, 0xe, 0xf7, 0xe, 0xf7, 0xe, 0xf7,
0xa, 0xf3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x20,
0x9, 0xf6, 0x6, 0xe3,
/* U+0022 "\"" */
0x8, 0x50, 0x67, 0x5, 0xfe, 0x1f, 0xf2, 0x7f,
0xe2, 0xff, 0x27, 0xfe, 0x3f, 0xf2, 0x7f, 0xe3,
0xff, 0x26, 0xfc, 0x2f, 0xf1, 0x9, 0x40, 0x88,
0x0, 0x0, 0x0, 0x0,
/* U+0023 "#" */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0x0,
0x0, 0x0, 0x3, 0x20, 0x0, 0x5, 0xf9, 0x0,
0x0, 0x0, 0x2f, 0xf1, 0x0, 0xa, 0xfb, 0x0,
0x0, 0x0, 0x7f, 0xf0, 0x0, 0xc, 0xfa, 0x0,
0x0, 0x0, 0xaf, 0xc0, 0x0, 0xe, 0xf8, 0x0,
0x0, 0x0, 0xdf, 0x90, 0x0, 0xf, 0xf8, 0x0,
0x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, 0xb9, 0x89, 0x80, 0x0,
0x0, 0x0, 0x0, 0x8f, 0xff, 0xff, 0xff, 0x40,
0x0, 0x0, 0x0, 0x0, 0x4a, 0xde, 0xff, 0xb0,
0x0,
/* U+007E "~" */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x18, 0xaa, 0x50, 0x0, 0x0, 0x7,
0x40, 0x0, 0x2e, 0xff, 0xff, 0xc2, 0x0, 0xa,
0xff, 0x0, 0x2e, 0xff, 0xcd, 0xff, 0xf8, 0x4a,
0xff, 0x80, 0x8, 0xff, 0x30, 0x8, 0xff, 0xff,
0xff, 0xa0, 0x0, 0x4d, 0x50, 0x0, 0x4, 0xcf,
0xfe, 0x70, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x12, 0x0, 0x0, 0x0
};
/*---------------------
* GLYPH DESCRIPTION
*--------------------*/
static const lv_font_fmt_txt_glyph_dsc_t glyph_dsc[] = {
{.bitmap_index = 0, .adv_w = 0, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0} /* id = 0 reserved */,
{.bitmap_index = 0, .adv_w = 102, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 0, .adv_w = 73, .box_w = 4, .box_h = 22, .ofs_x = 0, .ofs_y = 3},
{.bitmap_index = 44, .adv_w = 109, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = 17},
{.bitmap_index = 72, .adv_w = 259, .box_w = 16, .box_h = 23, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 256, .adv_w = 175, .box_w = 14, .box_h = 22, .ofs_x = -1, .ofs_y = 2},
{.bitmap_index = 410, .adv_w = 235, .box_w = 18, .box_h = 27, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 653, .adv_w = 224, .box_w = 18, .box_h = 30, .ofs_x = -3, .ofs_y = -3},
{.bitmap_index = 923, .adv_w = 57, .box_w = 4, .box_h = 8, .ofs_x = 0, .ofs_y = 17},
{.bitmap_index = 939, .adv_w = 105, .box_w = 11, .box_h = 27, .ofs_x = -3, .ofs_y = 0},
{.bitmap_index = 1088, .adv_w = 103, .box_w = 8, .box_h = 24, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 1184, .adv_w = 190, .box_w = 14, .box_h = 12, .ofs_x = -1, .ofs_y = 12},
{.bitmap_index = 1268, .adv_w = 156, .box_w = 11, .box_h = 11, .ofs_x = -1, .ofs_y = 7},
{.bitmap_index = 1329, .adv_w = 61, .box_w = 4, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1343, .adv_w = 117, .box_w = 7, .box_h = 5, .ofs_x = 0, .ofs_y = 10},
{.bitmap_index = 1361, .adv_w = 47, .box_w = 3, .box_h = 3, .ofs_x = 0, .ofs_y = 3},
{.bitmap_index = 1366, .adv_w = 199, .box_w = 11, .box_h = 25, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 1504, .adv_w = 176, .box_w = 14, .box_h = 24, .ofs_x = -2, .ofs_y = 1},
{.bitmap_index = 1672, .adv_w = 78, .box_w = 4, .box_h = 23, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 1718, .adv_w = 197, .box_w = 18, .box_h = 28, .ofs_x = -3, .ofs_y = 2},
{.bitmap_index = 1970, .adv_w = 172, .box_w = 15, .box_h = 26, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 2165, .adv_w = 179, .box_w = 13, .box_h = 24, .ofs_x = -2, .ofs_y = 2},
{.bitmap_index = 2321, .adv_w = 174, .box_w = 13, .box_h = 26, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2490, .adv_w = 177, .box_w = 18, .box_h = 27, .ofs_x = -5, .ofs_y = -2},
{.bitmap_index = 2733, .adv_w = 161, .box_w = 12, .box_h = 24, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 2877, .adv_w = 170, .box_w = 19, .box_h = 33, .ofs_x = -4, .ofs_y = -2},
{.bitmap_index = 3191, .adv_w = 158, .box_w = 11, .box_h = 28, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 3345, .adv_w = 56, .box_w = 4, .box_h = 12, .ofs_x = 0, .ofs_y = 7},
{.bitmap_index = 3369, .adv_w = 69, .box_w = 5, .box_h = 16, .ofs_x = -1, .ofs_y = 3},
{.bitmap_index = 3409, .adv_w = 147, .box_w = 12, .box_h = 12, .ofs_x = -2, .ofs_y = 7},
{.bitmap_index = 3481, .adv_w = 148, .box_w = 11, .box_h = 11, .ofs_x = -1, .ofs_y = 8},
{.bitmap_index = 3542, .adv_w = 143, .box_w = 12, .box_h = 13, .ofs_x = -1, .ofs_y = 6},
{.bitmap_index = 3620, .adv_w = 123, .box_w = 10, .box_h = 23, .ofs_x = -1, .ofs_y = 3},
{.bitmap_index = 3735, .adv_w = 244, .box_w = 22, .box_h = 16, .ofs_x = -3, .ofs_y = 6},
{.bitmap_index = 3911, .adv_w = 204, .box_w = 15, .box_h = 28, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 4121, .adv_w = 187, .box_w = 14, .box_h = 29, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 4324, .adv_w = 177, .box_w = 12, .box_h = 27, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 4486, .adv_w = 188, .box_w = 13, .box_h = 30, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 4681, .adv_w = 169, .box_w = 12, .box_h = 29, .ofs_x = -1, .ofs_y = -5},
{.bitmap_index = 4855, .adv_w = 160, .box_w = 11, .box_h = 25, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 4993, .adv_w = 199, .box_w = 13, .box_h = 30, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 5188, .adv_w = 239, .box_w = 17, .box_h = 26, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 5409, .adv_w = 75, .box_w = 4, .box_h = 23, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 5455, .adv_w = 188, .box_w = 13, .box_h = 28, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 5637, .adv_w = 181, .box_w = 12, .box_h = 24, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 5781, .adv_w = 188, .box_w = 13, .box_h = 26, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 5950, .adv_w = 247, .box_w = 16, .box_h = 25, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 6150, .adv_w = 226, .box_w = 14, .box_h = 26, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 6332, .adv_w = 194, .box_w = 18, .box_h = 31, .ofs_x = -3, .ofs_y = -6},
{.bitmap_index = 6611, .adv_w = 185, .box_w = 16, .box_h = 30, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 6851, .adv_w = 190, .box_w = 13, .box_h = 26, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 7020, .adv_w = 178, .box_w = 12, .box_h = 26, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 7176, .adv_w = 191, .box_w = 15, .box_h = 28, .ofs_x = 0, .ofs_y = -3},
{.bitmap_index = 7386, .adv_w = 219, .box_w = 16, .box_h = 23, .ofs_x = -1, .ofs_y = 1},
{.bitmap_index = 7570, .adv_w = 204, .box_w = 14, .box_h = 25, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 7745, .adv_w = 189, .box_w = 12, .box_h = 28, .ofs_x = 0, .ofs_y = -4},
{.bitmap_index = 7913, .adv_w = 309, .box_w = 20, .box_h = 31, .ofs_x = 0, .ofs_y = -5},
{.bitmap_index = 8223, .adv_w = 188, .box_w = 13, .box_h = 28, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 8405, .adv_w = 165, .box_w = 12, .box_h = 26, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 8561, .adv_w = 179, .box_w = 18, .box_h = 25, .ofs_x = -2, .ofs_y = -1},
{.bitmap_index = 8786, .adv_w = 136, .box_w = 8, .box_h = 23, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 8878, .adv_w = 199, .box_w = 11, .box_h = 25, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 9016, .adv_w = 136, .box_w = 8, .box_h = 24, .ofs_x = 1, .ofs_y = 1},
{.bitmap_index = 9112, .adv_w = 117, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = 16},
{.bitmap_index = 9144, .adv_w = 223, .box_w = 14, .box_h = 5, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 9179, .adv_w = 178, .box_w = 15, .box_h = 15, .ofs_x = -3, .ofs_y = 1},
{.bitmap_index = 9292, .adv_w = 171, .box_w = 13, .box_h = 25, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 9455, .adv_w = 174, .box_w = 12, .box_h = 15, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 9545, .adv_w = 171, .box_w = 13, .box_h = 26, .ofs_x = -2, .ofs_y = 0},
{.bitmap_index = 9714, .adv_w = 155, .box_w = 12, .box_h = 17, .ofs_x = -1, .ofs_y = 2},
{.bitmap_index = 9816, .adv_w = 182, .box_w = 14, .box_h = 24, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 9984, .adv_w = 184, .box_w = 16, .box_h = 22, .ofs_x = -4, .ofs_y = -5},
{.bitmap_index = 10160, .adv_w = 164, .box_w = 10, .box_h = 23, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 10275, .adv_w = 70, .box_w = 5, .box_h = 18, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 10320, .adv_w = 71, .box_w = 12, .box_h = 25, .ofs_x = -7, .ofs_y = -6},
{.bitmap_index = 10470, .adv_w = 172, .box_w = 11, .box_h = 23, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 10597, .adv_w = 67, .box_w = 4, .box_h = 22, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 10641, .adv_w = 274, .box_w = 18, .box_h = 16, .ofs_x = -1, .ofs_y = 1},
{.bitmap_index = 10785, .adv_w = 190, .box_w = 12, .box_h = 15, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 10875, .adv_w = 139, .box_w = 10, .box_h = 18, .ofs_x = -1, .ofs_y = 1},
{.bitmap_index = 10965, .adv_w = 153, .box_w = 14, .box_h = 23, .ofs_x = 0, .ofs_y = -6},
{.bitmap_index = 11126, .adv_w = 159, .box_w = 11, .box_h = 19, .ofs_x = -1, .ofs_y = -4},
{.bitmap_index = 11231, .adv_w = 158, .box_w = 11, .box_h = 17, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 11325, .adv_w = 123, .box_w = 15, .box_h = 21, .ofs_x = -1, .ofs_y = -2},
{.bitmap_index = 11483, .adv_w = 195, .box_w = 14, .box_h = 21, .ofs_x = -1, .ofs_y = -3},
{.bitmap_index = 11630, .adv_w = 164, .box_w = 12, .box_h = 15, .ofs_x = -1, .ofs_y = 1},
{.bitmap_index = 11720, .adv_w = 146, .box_w = 9, .box_h = 19, .ofs_x = 0, .ofs_y = -3},
{.bitmap_index = 11806, .adv_w = 248, .box_w = 16, .box_h = 16, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 11934, .adv_w = 153, .box_w = 12, .box_h = 17, .ofs_x = -1, .ofs_y = 1},
{.bitmap_index = 12036, .adv_w = 175, .box_w = 13, .box_h = 21, .ofs_x = -1, .ofs_y = -5},
{.bitmap_index = 12173, .adv_w = 153, .box_w = 17, .box_h = 17, .ofs_x = -6, .ofs_y = 1},
{.bitmap_index = 12318, .adv_w = 247, .box_w = 17, .box_h = 7, .ofs_x = -1, .ofs_y = 9}
};
/*---------------------
* CHARACTER MAPPING
*--------------------*/
/*Collect the unicode lists and glyph_id offsets*/
static const lv_font_fmt_txt_cmap_t cmaps[] =
{
{
.range_start = 32, .range_length = 64, .glyph_id_start = 1,
.unicode_list = NULL, .glyph_id_ofs_list = NULL, .list_length = 0, .type = LV_FONT_FMT_TXT_CMAP_FORMAT0_TINY
},
{
.range_start = 97, .range_length = 26, .glyph_id_start = 65,
.unicode_list = NULL, .glyph_id_ofs_list = NULL, .list_length = 0, .type = LV_FONT_FMT_TXT_CMAP_FORMAT0_TINY
},
{
.range_start = 126, .range_length = 1, .glyph_id_start = 91,
.unicode_list = NULL, .glyph_id_ofs_list = NULL, .list_length = 0, .type = LV_FONT_FMT_TXT_CMAP_FORMAT0_TINY
}
};
/*-----------------
* KERNING
*----------------*/
/*Pair left and right glyphs for kerning*/
static const uint8_t kern_pair_glyph_ids[] =
{
17, 20,
17, 22,
17, 24,
17, 26,
18, 19,
18, 20,
18, 24,
18, 26,
19, 17,
19, 18,
19, 20,
19, 21,
19, 23,
19, 24,
19, 25,
20, 22,
20, 24,
21, 17,
21, 18,
21, 19,
21, 20,
21, 24,
22, 19,
22, 20,
22, 24,
22, 26,
23, 19,
23, 20,
23, 21,
23, 22,
23, 24,
23, 26,
24, 17,
24, 20,
24, 22,
24, 23,
24, 25,
25, 20,
25, 22,
25, 24,
26, 17,
26, 20,
26, 22,
26, 23,
26, 24,
26, 25,
34, 3,
34, 8,
34, 10,
34, 11,
34, 16,
34, 53,
34, 56,
34, 58,
34, 61,
34, 62,
35, 9,
35, 14,
35, 16,
35, 34,
35, 41,
35, 57,
35, 61,
35, 62,
35, 70,
35, 77,
35, 78,
35, 83,
35, 84,
35, 86,
35, 88,
35, 90,
36, 9,
36, 14,
36, 16,
36, 41,
36, 61,
36, 62,
36, 70,
36, 83,
36, 84,
36, 90,
37, 10,
37, 13,
37, 15,
37, 16,
37, 43,
37, 53,
37, 57,
37, 58,
37, 59,
37, 61,
37, 62,
37, 64,
38, 9,
38, 11,
38, 14,
38, 16,
38, 27,
38, 36,
38, 40,
38, 41,
38, 48,
38, 50,
38, 54,
38, 61,
38, 62,
38, 65,
38, 67,
38, 68,
38, 69,
38, 70,
38, 71,
38, 79,
38, 81,
38, 84,
38, 85,
38, 86,
38, 87,
38, 89,
39, 9,
39, 13,
39, 14,
39, 15,
39, 16,
39, 27,
39, 28,
39, 34,
39, 36,
39, 40,
39, 41,
39, 48,
39, 50,
39, 52,
39, 59,
39, 62,
39, 64,
39, 65,
39, 67,
39, 68,
39, 69,
39, 70,
39, 71,
39, 73,
39, 74,
39, 77,
39, 78,
39, 79,
39, 80,
39, 81,
39, 82,
39, 83,
39, 84,
39, 85,
39, 86,
39, 87,
39, 88,
39, 89,
39, 90,
40, 10,
40, 13,
40, 16,
40, 57,
40, 59,
40, 61,
40, 62,
40, 83,
40, 88,
41, 3,
41, 8,
41, 10,
41, 13,
41, 15,
41, 16,
41, 27,
41, 28,
41, 32,
41, 43,
41, 52,
41, 53,
41, 57,
41, 58,
41, 59,
41, 61,
41, 62,
41, 64,
41, 65,
41, 67,
41, 68,
41, 71,
41, 81,
42, 10,
42, 16,
42, 61,
42, 62,
43, 10,
43, 13,
43, 16,
43, 53,
43, 57,
43, 58,
43, 59,
43, 61,
43, 62,
44, 9,
44, 11,
44, 14,
44, 27,
44, 36,
44, 38,
44, 40,
44, 41,
44, 48,
44, 50,
44, 54,
44, 55,
44, 56,
44, 61,
44, 67,
44, 68,
44, 69,
44, 70,
44, 71,
44, 79,
44, 84,
44, 85,
44, 86,
44, 87,
44, 89,
45, 3,
45, 8,
45, 9,
45, 11,
45, 14,
45, 27,
45, 36,
45, 40,
45, 41,
45, 48,
45, 50,
45, 53,
45, 54,
45, 55,
45, 56,
45, 58,
45, 61,
45, 67,
45, 68,
45, 69,
45, 70,
45, 71,
45, 79,
45, 84,
45, 85,
45, 86,
45, 87,
45, 89,
46, 10,
46, 16,
46, 53,
46, 58,
46, 61,
46, 62,
47, 10,
47, 16,
47, 57,
47, 61,
47, 62,
48, 3,
48, 8,
48, 10,
48, 13,
48, 16,
48, 53,
48, 57,
48, 58,
48, 61,
48, 62,
49, 10,
49, 13,
49, 15,
49, 16,
49, 32,
49, 57,
49, 59,
49, 61,
49, 62,
49, 64,
49, 65,
49, 68,
49, 71,
49, 81,
50, 3,
50, 8,
50, 10,
50, 16,
50, 53,
50, 58,
50, 61,
50, 62,
51, 9,
51, 14,
51, 16,
51, 34,
51, 41,
51, 61,
51, 62,
51, 65,
51, 67,
51, 68,
51, 69,
51, 70,
51, 71,
51, 77,
51, 78,
51, 79,
51, 80,
51, 81,
51, 82,
51, 83,
51, 84,
51, 85,
51, 86,
51, 87,
51, 89,
51, 90,
52, 3,
52, 8,
52, 9,
52, 11,
52, 14,
52, 16,
52, 36,
52, 40,
52, 41,
52, 53,
52, 54,
52, 55,
52, 56,
52, 58,
52, 61,
52, 62,
52, 70,
52, 84,
52, 86,
53, 9,
53, 13,
53, 14,
53, 15,
53, 16,
53, 27,
53, 28,
53, 34,
53, 36,
53, 40,
53, 41,
53, 48,
53, 50,
53, 52,
53, 59,
53, 62,
53, 64,
53, 65,
53, 67,
53, 68,
53, 69,
53, 70,
53, 71,
53, 73,
53, 74,
53, 77,
53, 78,
53, 79,
53, 80,
53, 81,
53, 82,
53, 83,
53, 84,
53, 85,
53, 86,
53, 87,
53, 88,
53, 89,
53, 90,
54, 10,
54, 16,
54, 61,
54, 62,
55, 9,
55, 13,
55, 15,
55, 16,
55, 34,
55, 59,
55, 61,
55, 62,
55, 64,
55, 65,
55, 67,
55, 68,
55, 69,
55, 70,
55, 71,
55, 77,
55, 78,
55, 79,
55, 80,
55, 81,
55, 82,
55, 83,
55, 85,
55, 86,
55, 87,
55, 88,
55, 89,
55, 90,
56, 9,
56, 13,
56, 15,
56, 16,
56, 34,
56, 52,
56, 59,
56, 61,
56, 62,
56, 64,
56, 65,
56, 67,
56, 68,
56, 69,
56, 70,
56, 71,
56, 77,
56, 78,
56, 79,
56, 80,
56, 81,
56, 82,
56, 83,
56, 85,
56, 86,
56, 87,
56, 88,
56, 89,
56, 90,
57, 2,
57, 9,
57, 11,
57, 14,
57, 16,
57, 27,
57, 36,
57, 38,
57, 40,
57, 41,
57, 47,
57, 48,
57, 50,
57, 54,
57, 61,
57, 62,
57, 65,
57, 67,
57, 68,
57, 69,
57, 70,
57, 71,
57, 77,
57, 78,
57, 79,
57, 81,
57, 84,
57, 85,
57, 86,
57, 87,
57, 89,
58, 9,
58, 13,
58, 14,
58, 15,
58, 16,
58, 34,
58, 36,
58, 40,
58, 41,
58, 50,
58, 59,
58, 61,
58, 62,
58, 64,
58, 65,
58, 67,
58, 68,
58, 69,
58, 70,
58, 71,
58, 77,
58, 78,
58, 79,
58, 80,
58, 81,
58, 82,
58, 83,
58, 84,
58, 85,
58, 86,
58, 87,
58, 88,
58, 89,
58, 90,
59, 9,
59, 13,
59, 14,
59, 15,
59, 16,
59, 28,
59, 34,
59, 36,
59, 40,
59, 41,
59, 48,
59, 50,
59, 61,
59, 62,
59, 64,
59, 65,
59, 67,
59, 68,
59, 69,
59, 70,
59, 71,
59, 73,
59, 74,
59, 77,
59, 78,
59, 79,
59, 80,
59, 81,
59, 82,
59, 83,
59, 84,
59, 85,
59, 86,
59, 87,
59, 88,
59, 89,
59, 90,
65, 10,
65, 11,
65, 16,
65, 61,
65, 62,
65, 75,
65, 76,
66, 3,
66, 8,
66, 10,
66, 11,
66, 16,
66, 61,
66, 62,
66, 83,
66, 84,
66, 88,
66, 90,
67, 2,
67, 9,
67, 10,
67, 11,
67, 14,
67, 16,
67, 61,
67, 62,
67, 70,
67, 83,
67, 84,
67, 90,
68, 16,
68, 61,
68, 62,
69, 9,
69, 16,
69, 27,
69, 61,
69, 62,
69, 67,
69, 68,
69, 71,
69, 79,
69, 89,
70, 13,
70, 15,
70, 16,
70, 27,
70, 28,
70, 62,
70, 64,
70, 65,
70, 71,
70, 81,
71, 10,
71, 11,
71, 16,
71, 61,
71, 62,
71, 74,
71, 75,
71, 84,
71, 90,
72, 2,
72, 3,
72, 8,
72, 10,
72, 11,
72, 16,
72, 32,
72, 61,
72, 62,
72, 83,
73, 3,
73, 8,
73, 10,
73, 11,
73, 16,
73, 61,
73, 62,
73, 75,
73, 76,
74, 3,
74, 8,
74, 10,
74, 11,
74, 16,
74, 61,
74, 62,
74, 75,
74, 76,
75, 3,
75, 8,
75, 9,
75, 11,
75, 14,
75, 16,
75, 27,
75, 61,
75, 62,
75, 68,
75, 69,
75, 70,
75, 84,
75, 86,
75, 87,
75, 89,
76, 16,
76, 61,
76, 62,
77, 10,
77, 11,
77, 16,
77, 61,
77, 62,
77, 75,
77, 83,
78, 10,
78, 11,
78, 14,
78, 16,
78, 61,
78, 62,
78, 70,
78, 75,
78, 84,
79, 10,
79, 11,
79, 16,
79, 61,
79, 62,
79, 83,
79, 88,
80, 10,
80, 11,
80, 13,
80, 16,
80, 61,
80, 62,
80, 83,
80, 84,
80, 88,
80, 90,
81, 10,
81, 16,
81, 61,
81, 62,
82, 10,
82, 13,
82, 15,
82, 16,
82, 27,
82, 28,
82, 32,
82, 61,
82, 62,
82, 64,
82, 65,
82, 67,
82, 68,
82, 69,
82, 71,
82, 79,
82, 81,
83, 3,
83, 8,
83, 10,
83, 11,
83, 14,
83, 16,
83, 61,
83, 62,
83, 70,
83, 84,
83, 90,
84, 2,
84, 3,
84, 8,
84, 9,
84, 10,
84, 11,
84, 14,
84, 16,
84, 32,
84, 61,
84, 62,
84, 70,
84, 83,
84, 90,
85, 9,
85, 10,
85, 11,
85, 16,
85, 61,
85, 62,
85, 74,
85, 75,
85, 84,
85, 86,
86, 10,
86, 13,
86, 15,
86, 16,
86, 61,
86, 62,
86, 64,
87, 10,
87, 13,
87, 15,
87, 16,
87, 61,
87, 62,
87, 64,
88, 10,
88, 16,
88, 27,
88, 61,
88, 62,
88, 65,
88, 67,
88, 68,
88, 69,
88, 71,
88, 79,
88, 81,
89, 10,
89, 16,
89, 61,
89, 62,
89, 75,
89, 76,
90, 2,
90, 9,
90, 10,
90, 16,
90, 27,
90, 28,
90, 32,
90, 60,
90, 61,
90, 62,
90, 65,
90, 67,
90, 68,
90, 69,
90, 71,
90, 73,
90, 75,
90, 76,
90, 77,
90, 79,
90, 81,
90, 85,
90, 87,
90, 89
};
/* Kerning between the respective left and right glyphs
* 4.4 format which needs to scaled with `kern_scale`*/
static const int8_t kern_pair_values[] =
{
-20, -14, -20, -5, -3, -19, -19, -3,
-11, -5, -20, -7, -13, -20, -7, -8,
-19, -3, -5, -6, -19, -19, -17, -14,
-13, -15, -18, -21, -16, -8, -20, -17,
-14, -6, -6, -17, -6, -20, -8, -19,
-4, -20, -9, -7, -20, -4, -16, -16,
-6, -9, -13, -27, -5, -25, -22, -13,
-3, -15, -20, -6, -9, -3, -19, -19,
-17, -4, -3, -8, -12, -5, -6, -12,
-5, -22, -17, -15, -22, -15, -28, -6,
-21, -4, -11, -15, -9, -20, -3, -4,
-14, -3, -10, -20, -20, -9, -16, -4,
-5, -3, -18, -13, -13, -14, -10, -9,
-5, -13, -4, -4, -9, -20, -15, -11,
-11, -9, -3, -13, -7, -11, -10, -13,
-17, -21, -5, -22, -24, -18, -20, -16,
-15, -15, -10, -8, -11, -8, -7, -18,
-22, -28, -27, -30, -25, -12, -28, -23,
-22, -19, -19, -25, -27, -29, -22, -28,
-12, -21, -18, -18, -28, -20, -16, -7,
-5, -20, -10, -3, -20, -19, -9, -5,
-15, -15, -17, -15, -11, -22, -7, -12,
-12, -18, -8, -13, -18, -13, -17, -22,
-21, -12, -13, -4, -10, -14, -17, -3,
-19, -20, -19, -12, -5, -20, -7, -12,
-4, -3, -20, -19, -18, -15, -21, -16,
-15, -3, -16, -20, -10, -8, -10, -9,
-8, -23, -8, -17, -13, -29, -7, -9,
-26, -6, -13, -11, -13, -25, -25, -18,
-25, -25, -23, -14, -16, -17, -7, -5,
-45, -7, -20, -22, -40, -26, -7, -16,
-16, -36, -11, -7, -24, -7, -12, -9,
-16, -7, -18, -3, -6, -20, -17, -4,
-20, -3, -20, -19, -5, -5, -16, -5,
-20, -22, -15, -13, -21, -20, -9, -21,
-21, -22, -6, -13, -24, -21, -20, -20,
-10, -4, -9, -13, -4, -4, -13, -17,
-22, -12, -21, -19, -4, -13, -21, -10,
-7, -14, -20, -12, -16, -24, -20, -26,
-15, -11, -13, -15, -10, -11, -10, -7,
-12, -15, -14, -16, -19, -12, -3, -3,
-8, -12, -17, -10, -4, -3, -14, -13,
-3, -7, -8, -13, -22, -7, -27, -17,
-3, -16, -20, -22, -21, -25, -20, -21,
-33, -17, -16, -8, -6, -8, -6, -4,
-15, -22, -32, -32, -35, -32, -35, -33,
-31, -31, -32, -32, -32, -32, -32, -32,
-34, -34, -32, -32, -32, -33, -32, -33,
-3, -14, -20, -15, -3, -18, -17, -22,
-9, -10, -6, -20, -17, -18, -14, -18,
-12, -5, -17, -7, -9, -13, -15, -20,
-10, -7, -10, -7, -8, -15, -10, -5,
-4, -18, -18, -22, -7, -3, -12, -6,
-20, -18, -17, -13, -18, -11, -4, -16,
-6, -9, -12, -14, -19, -9, -7, -10,
-6, -8, -15, -10, -4, -3, -16, -4,
-18, -5, -10, -15, -4, -16, -20, -3,
-11, -10, -6, -15, -7, -5, -10, -18,
-14, -28, -9, -6, -5, -10, -3, -25,
-9, -15, -12, -15, -6, -17, -11, -16,
-22, -25, -4, -3, -7, -3, -9, -4,
-20, -16, -25, -24, -28, -24, -24, -25,
-15, -21, -24, -24, -25, -22, -10, -11,
-24, -15, -18, -24, -23, -16, -8, -11,
-17, -15, -23, -3, -21, -6, -6, -11,
-3, -4, -4, -21, -16, -27, -27, -29,
-27, -29, -28, -5, -3, -25, -26, -27,
-22, -28, -26, -11, -22, -27, -25, -27,
-18, -27, -25, -4, -7, -11, -22, -11,
-7, -3, -22, -22, -18, -18, -20, -22,
-20, -15, -3, -4, -4, -5, -5, -8,
-16, -11, -16, -22, -17, -17, -13, -15,
-4, -17, -19, -17, -5, -11, -15, -22,
-8, -3, -7, -3, -3, -3, -28, -35,
-20, -6, -9, -12, -32, -8, -6, -15,
-8, -12, -16, -22, -17, -3, -5, -7,
-4, -4, -21, -21, -9, -16, -19, -3,
-22, -16, -6, -8, -8, -6, -5, -13,
-21, -14, -6, -6, -9, -9, -8, -8,
-16, -21, -17, -5, -4, -21, -21, -13,
-20, -17, -9, -16, -23, -6, -6, -6,
-31, -24, -8, -4, -6, -19, -19, -18,
-7, -7, -16, -21, -15, -4, -5, -3,
-15, -4, -12, -22, -11, -4, -6, -11,
-16, -5, -17, -21, -18, -12, -6, -16,
-9, -9, -17, -22, -18, -16, -4, -9,
-5, -14, -17, -22, -18, -19, -22, -20,
-21, -18, -20, -15, -23, -22, -20, -24,
-11, -17, -10, -24, -7, -28, -9, -9,
-10, -16, -15, -18, -21, -19, -13, -18,
-6, -8, -19, -19, -3, -13, -18, -15,
-19, -5, -22, -19, -26, -14, -7, -4,
-3, -10, -11, -22, -10, -3, -4, -5,
-3, -16, -13, -8, -18, -21, -19, -8,
-16, -14, -10, -18, -21, -19, -10, -3,
-9, -15, -22, -10, -5, -7, -11, -7,
-9, -6, -3, -9, -17, -22, -18, -5,
-4, -4, -3, -3, -8, -14, -8, -3,
-4, -22, -10, -11, -9, -9, -8, -13,
-3, -5, -7, -3, -8, -10, -4, -3,
-3
};
/*Collect the kern pair's data in one place*/
static const lv_font_fmt_txt_kern_pair_t kern_pairs =
{
.glyph_ids = kern_pair_glyph_ids,
.values = kern_pair_values,
.pair_cnt = 801,
.glyph_ids_size = 0
};
/*--------------------
* ALL CUSTOM DATA
*--------------------*/
#if LVGL_VERSION_MAJOR == 8
/*Store all the custom data of the font*/
static lv_font_fmt_txt_glyph_cache_t cache;
#endif
#if LVGL_VERSION_MAJOR >= 8
static const lv_font_fmt_txt_dsc_t font_dsc = {
#else
static lv_font_fmt_txt_dsc_t font_dsc = {
#endif
.glyph_bitmap = glyph_bitmap,
.glyph_dsc = glyph_dsc,
.cmaps = cmaps,
.kern_dsc = &kern_pairs,
.kern_scale = 16,
.cmap_num = 3,
.bpp = 4,
.kern_classes = 0,
.bitmap_format = 0,
#if LVGL_VERSION_MAJOR == 8
.cache = &cache
#endif
};
extern const lv_font_t lv_font_montserrat_24;
/*-----------------
* PUBLIC FONT
*----------------*/
/*Initialize a public general font descriptor*/
#if LVGL_VERSION_MAJOR >= 8
const lv_font_t sticky_font_32 = {
#else
lv_font_t sticky_font_32 = {
#endif
.get_glyph_dsc = lv_font_get_glyph_dsc_fmt_txt, /*Function pointer to get glyph's data*/
.get_glyph_bitmap = lv_font_get_bitmap_fmt_txt, /*Function pointer to get glyph's bitmap*/
.line_height = 37, /*The maximum line height required by the font*/
.base_line = 6, /*Baseline measured from the bottom of the line*/
#if !(LVGL_VERSION_MAJOR == 6 && LVGL_VERSION_MINOR == 0)
.subpx = LV_FONT_SUBPX_NONE,
#endif
#if LV_VERSION_CHECK(7, 4, 0) || LVGL_VERSION_MAJOR >= 8
.underline_position = 0,
.underline_thickness = 0,
#endif
.dsc = &font_dsc, /*The custom font data. Will be accessed by `get_glyph_bitmap/dsc` */
#if LV_VERSION_CHECK(8, 2, 0) || LVGL_VERSION_MAJOR >= 9
.fallback = &lv_font_montserrat_24,
#endif
.user_data = NULL,
};
#endif /*#if STICKY_FONT_32*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.