Girish Jeswani commited on
Commit
63da3a1
·
1 Parent(s): c3523ce

add canvas backend

Browse files
multi_llm_chatbot_backend/app/api/routes/phd_canvas.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, HTTPException, Depends, status, BackgroundTasks
2
+ from typing import Dict, Optional
3
+ from datetime import datetime
4
+ import logging
5
+
6
+ from app.models.user import User
7
+ from app.models.phd_canvas import PhdCanvas, CanvasResponse, UpdateCanvasRequest
8
+ from app.core.auth import get_current_active_user
9
+
10
+ from pydantic import BaseModel
11
+
12
+ logger = logging.getLogger(__name__)
13
+ router = APIRouter()
14
+
15
+ # Request/Response models
16
+ class CanvasStatsResponse(BaseModel):
17
+ total_insights: int
18
+ total_sections: int
19
+ last_updated: Optional[str] = None
20
+ last_chat_processed: Optional[str] = None
21
+ created_at: Optional[str] = None
22
+ auto_update: bool = True
23
+ sections_breakdown: Dict = {}
24
+
25
+ class PrintCanvasResponse(BaseModel):
26
+ user_id: str
27
+ generated_at: str
28
+ total_insights: int
29
+ last_updated: Optional[str] = None
30
+ sections: list
31
+ metadata: Dict
32
+
33
+ def get_canvas_manager():
34
+ """Lazy import to avoid circular dependency"""
35
+ from app.core.canvas_manager import get_canvas_manager
36
+ return get_canvas_manager()
37
+
38
+ @router.get("/phd-canvas", response_model=CanvasResponse)
39
+ async def get_phd_canvas(
40
+ current_user: User = Depends(get_current_active_user)
41
+ ):
42
+ """Get the user's PhD Canvas, creating it if it doesn't exist"""
43
+ try:
44
+ canvas_manager = get_canvas_manager()
45
+ canvas = await canvas_manager.get_or_create_canvas(str(current_user.id))
46
+
47
+ # Convert to response model
48
+ return CanvasResponse(
49
+ id=str(canvas.id),
50
+ user_id=str(canvas.user_id),
51
+ sections=canvas.sections,
52
+ created_at=canvas.created_at,
53
+ last_updated=canvas.last_updated,
54
+ last_chat_processed=canvas.last_chat_processed,
55
+ total_insights=canvas.total_insights,
56
+ auto_update=canvas.auto_update,
57
+ print_optimized=canvas.print_optimized
58
+ )
59
+
60
+ except Exception as e:
61
+ logger.error(f"Error getting PhD canvas for user {current_user.id}: {e}")
62
+ raise HTTPException(
63
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
64
+ detail="Failed to retrieve PhD canvas"
65
+ )
66
+
67
+ @router.post("/phd-canvas/update", response_model=CanvasResponse)
68
+ async def update_phd_canvas(
69
+ request: UpdateCanvasRequest,
70
+ background_tasks: BackgroundTasks,
71
+ current_user: User = Depends(get_current_active_user)
72
+ ):
73
+ """Update the PhD Canvas with latest insights from chat sessions"""
74
+ try:
75
+ canvas_manager = get_canvas_manager()
76
+
77
+ # For large updates, run in background
78
+ if request.force_full_update:
79
+ logger.info(f"Queuing background canvas update for user {current_user.id}")
80
+ background_tasks.add_task(
81
+ _background_canvas_update,
82
+ str(current_user.id),
83
+ request
84
+ )
85
+
86
+ # Return current canvas immediately
87
+ canvas = await canvas_manager.get_or_create_canvas(str(current_user.id))
88
+ else:
89
+ # For incremental updates, process immediately
90
+ logger.info(f"Processing incremental canvas update for user {current_user.id}")
91
+ canvas = await canvas_manager.update_canvas(str(current_user.id), request)
92
+
93
+ return CanvasResponse(
94
+ id=str(canvas.id),
95
+ user_id=str(canvas.user_id),
96
+ sections=canvas.sections,
97
+ created_at=canvas.created_at,
98
+ last_updated=canvas.last_updated,
99
+ last_chat_processed=canvas.last_chat_processed,
100
+ total_insights=canvas.total_insights,
101
+ auto_update=canvas.auto_update,
102
+ print_optimized=canvas.print_optimized
103
+ )
104
+
105
+ except Exception as e:
106
+ logger.error(f"Error updating PhD canvas for user {current_user.id}: {e}")
107
+ raise HTTPException(
108
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
109
+ detail="Failed to update PhD canvas"
110
+ )
111
+
112
+ @router.get("/phd-canvas/stats", response_model=CanvasStatsResponse)
113
+ async def get_canvas_stats(
114
+ current_user: User = Depends(get_current_active_user)
115
+ ):
116
+ """Get statistics about the user's PhD Canvas"""
117
+ try:
118
+ canvas_manager = get_canvas_manager()
119
+ stats = await canvas_manager.get_canvas_stats(str(current_user.id))
120
+
121
+ return CanvasStatsResponse(
122
+ total_insights=stats.get("total_insights", 0),
123
+ total_sections=stats.get("total_sections", 0),
124
+ last_updated=stats.get("last_updated").isoformat() if stats.get("last_updated") else None,
125
+ last_chat_processed=stats.get("last_chat_processed").isoformat() if stats.get("last_chat_processed") else None,
126
+ created_at=stats.get("created_at").isoformat() if stats.get("created_at") else None,
127
+ auto_update=stats.get("auto_update", True),
128
+ sections_breakdown=stats.get("sections_breakdown", {})
129
+ )
130
+
131
+ except Exception as e:
132
+ logger.error(f"Error getting canvas stats for user {current_user.id}: {e}")
133
+ raise HTTPException(
134
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
135
+ detail="Failed to retrieve canvas statistics"
136
+ )
137
+
138
+ @router.get("/phd-canvas/print", response_model=PrintCanvasResponse)
139
+ async def get_print_canvas(
140
+ current_user: User = Depends(get_current_active_user)
141
+ ):
142
+ """Get PhD Canvas formatted for printing"""
143
+ try:
144
+ canvas_manager = get_canvas_manager()
145
+ print_data = await canvas_manager.export_canvas_for_printing(str(current_user.id))
146
+
147
+ return PrintCanvasResponse(
148
+ user_id=print_data["user_id"],
149
+ generated_at=print_data["generated_at"].isoformat(),
150
+ total_insights=print_data["total_insights"],
151
+ last_updated=print_data["last_updated"].isoformat() if print_data["last_updated"] else None,
152
+ sections=print_data["sections"],
153
+ metadata=print_data["metadata"]
154
+ )
155
+
156
+ except Exception as e:
157
+ logger.error(f"Error exporting print canvas for user {current_user.id}: {e}")
158
+ raise HTTPException(
159
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
160
+ detail="Failed to export canvas for printing"
161
+ )
162
+
163
+ @router.post("/phd-canvas/auto-update")
164
+ async def trigger_auto_update(
165
+ background_tasks: BackgroundTasks,
166
+ current_user: User = Depends(get_current_active_user)
167
+ ):
168
+ """Trigger automatic canvas update (typically called when user opens canvas page)"""
169
+ try:
170
+ canvas_manager = get_canvas_manager()
171
+
172
+ # Get current canvas to check if auto-update is needed
173
+ canvas = await canvas_manager.get_or_create_canvas(str(current_user.id))
174
+
175
+ if not canvas.auto_update:
176
+ return {"message": "Auto-update is disabled for this canvas"}
177
+
178
+ # Check if we need to update (has been more than 1 hour since last update)
179
+ from datetime import timedelta
180
+ needs_update = (
181
+ canvas.last_updated is None or
182
+ (datetime.utcnow() - canvas.last_updated) > timedelta(hours=1)
183
+ )
184
+
185
+ if needs_update:
186
+ logger.info(f"Auto-updating canvas for user {current_user.id}")
187
+
188
+ # Queue incremental update in background
189
+ background_tasks.add_task(
190
+ _background_canvas_update,
191
+ str(current_user.id),
192
+ UpdateCanvasRequest(force_full_update=False)
193
+ )
194
+
195
+ return {"message": "Canvas update queued", "status": "updating"}
196
+ else:
197
+ return {"message": "Canvas is up to date", "status": "current"}
198
+
199
+ except Exception as e:
200
+ logger.error(f"Error triggering auto-update for user {current_user.id}: {e}")
201
+ raise HTTPException(
202
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
203
+ detail="Failed to trigger canvas auto-update"
204
+ )
205
+
206
+ @router.delete("/phd-canvas")
207
+ async def delete_canvas(
208
+ current_user: User = Depends(get_current_active_user)
209
+ ):
210
+ """Delete the user's PhD Canvas"""
211
+ try:
212
+ canvas_manager = get_canvas_manager()
213
+ deleted = await canvas_manager.delete_canvas(str(current_user.id))
214
+
215
+ if deleted:
216
+ return {"message": "PhD Canvas deleted successfully"}
217
+ else:
218
+ return {"message": "No canvas found to delete"}
219
+
220
+ except Exception as e:
221
+ logger.error(f"Error deleting canvas for user {current_user.id}: {e}")
222
+ raise HTTPException(
223
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
224
+ detail="Failed to delete PhD canvas"
225
+ )
226
+
227
+ @router.get("/phd-canvas/refresh")
228
+ async def refresh_canvas_data(
229
+ background_tasks: BackgroundTasks,
230
+ current_user: User = Depends(get_current_active_user)
231
+ ):
232
+ """Force refresh canvas with full update from all chats"""
233
+ try:
234
+ logger.info(f"Force refreshing canvas for user {current_user.id}")
235
+
236
+ # Queue full update in background
237
+ background_tasks.add_task(
238
+ _background_canvas_update,
239
+ str(current_user.id),
240
+ UpdateCanvasRequest(force_full_update=True)
241
+ )
242
+
243
+ return {
244
+ "message": "Full canvas refresh initiated",
245
+ "status": "processing",
246
+ "estimated_completion": "2-3 minutes"
247
+ }
248
+
249
+ except Exception as e:
250
+ logger.error(f"Error refreshing canvas for user {current_user.id}: {e}")
251
+ raise HTTPException(
252
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
253
+ detail="Failed to refresh PhD canvas"
254
+ )
255
+
256
+ # Background task functions
257
+ async def _background_canvas_update(user_id: str, request: UpdateCanvasRequest):
258
+ """Background task to update canvas without blocking the API response"""
259
+ try:
260
+ logger.info(f"Starting background canvas update for user {user_id}")
261
+ canvas_manager = get_canvas_manager()
262
+
263
+ updated_canvas = await canvas_manager.update_canvas(user_id, request)
264
+
265
+ logger.info(f"Background canvas update completed for user {user_id}. Total insights: {updated_canvas.total_insights}")
266
+
267
+ except Exception as e:
268
+ logger.error(f"Error in background canvas update for user {user_id}: {e}")
269
+ import traceback
270
+ logger.error(f"Full traceback: {traceback.format_exc()}")
271
+
272
+ # Health check endpoint
273
+ @router.get("/phd-canvas/health")
274
+ async def canvas_health_check():
275
+ """Health check for canvas service"""
276
+ try:
277
+ canvas_manager = get_canvas_manager()
278
+ return {
279
+ "status": "healthy",
280
+ "service": "phd-canvas",
281
+ "timestamp": datetime.utcnow().isoformat()
282
+ }
283
+ except Exception as e:
284
+ logger.error(f"Canvas health check failed: {e}")
285
+ raise HTTPException(
286
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
287
+ detail="Canvas service is not healthy"
288
+ )
multi_llm_chatbot_backend/app/core/canvas_analysis.py ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import json
3
+ import logging
4
+ from typing import Dict, List, Tuple, Set
5
+ from datetime import datetime
6
+ from collections import defaultdict
7
+
8
+ from app.models.phd_canvas import CanvasInsight, CanvasSection
9
+ from app.llm.improved_gemini_client import ImprovedGeminiClient
10
+ from app.llm.improved_ollama_client import ImprovedOllamaClient
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ class CanvasAnalysisService:
15
+ """Service for extracting and categorizing insights from chat messages"""
16
+
17
+ def __init__(self, llm_client=None):
18
+ self.llm_client = llm_client
19
+
20
+ # Predefined section mappings for semantic analysis
21
+ self.section_keywords = {
22
+ "research_progress": [
23
+ "progress", "milestone", "completed", "finished", "accomplished",
24
+ "achieved", "timeline", "deadline", "chapter", "draft", "version"
25
+ ],
26
+ "methodology": [
27
+ "method", "methodology", "approach", "design", "data collection",
28
+ "survey", "interview", "experiment", "analysis", "statistical",
29
+ "qualitative", "quantitative", "mixed methods"
30
+ ],
31
+ "theoretical_framework": [
32
+ "theory", "theoretical", "framework", "concept", "model",
33
+ "literature", "author", "philosophy", "paradigm", "assumption"
34
+ ],
35
+ "challenges_obstacles": [
36
+ "challenge", "problem", "difficulty", "obstacle", "stuck",
37
+ "confused", "frustrated", "struggle", "barrier", "issue"
38
+ ],
39
+ "next_steps": [
40
+ "next", "plan", "should", "will", "going to", "need to",
41
+ "action", "step", "priority", "focus", "goal", "objective"
42
+ ],
43
+ "writing_communication": [
44
+ "write", "writing", "paper", "thesis", "dissertation", "publication",
45
+ "communication", "presentation", "defense", "draft", "revision"
46
+ ],
47
+ "career_development": [
48
+ "career", "job", "position", "networking", "conference",
49
+ "skills", "CV", "resume", "application", "fellowship", "grant"
50
+ ],
51
+ "literature_review": [
52
+ "literature", "sources", "papers", "articles", "bibliography",
53
+ "citation", "author", "study", "research", "gap", "review"
54
+ ],
55
+ "data_analysis": [
56
+ "data", "analysis", "results", "findings", "statistics",
57
+ "coding", "software", "tool", "visualization", "pattern"
58
+ ],
59
+ "motivation_mindset": [
60
+ "motivation", "confidence", "stress", "anxiety", "balance",
61
+ "mental health", "mindset", "support", "overwhelmed", "burnout"
62
+ ]
63
+ }
64
+
65
+ async def extract_insights_from_messages(self, messages: List[Dict], chat_session_id: str) -> List[CanvasInsight]:
66
+ """Extract actionable insights from chat messages using semantic analysis"""
67
+ try:
68
+ insights = []
69
+
70
+ for message in messages:
71
+ if message.get("type") == "assistant" and "responses" in message:
72
+ # Handle multi-persona responses
73
+ for response in message.get("responses", []):
74
+ persona_insights = await self._extract_insights_from_persona_response(
75
+ response, message.get("id"), chat_session_id
76
+ )
77
+ insights.extend(persona_insights)
78
+ elif message.get("role") == "assistant" and message.get("content"):
79
+ # Handle single response format
80
+ persona_insights = await self._extract_insights_from_content(
81
+ message.get("content", ""), "assistant",
82
+ message.get("id"), chat_session_id
83
+ )
84
+ insights.extend(persona_insights)
85
+
86
+ # Remove duplicates and low-confidence insights
87
+ unique_insights = self._deduplicate_insights(insights)
88
+ high_confidence_insights = [i for i in unique_insights if i.confidence_score >= 0.6]
89
+
90
+ logger.info(f"Extracted {len(high_confidence_insights)} insights from {len(messages)} messages")
91
+ return high_confidence_insights
92
+
93
+ except Exception as e:
94
+ logger.error(f"Error extracting insights from messages: {e}")
95
+ return []
96
+
97
+ async def _extract_insights_from_persona_response(self, response: Dict, message_id: str, chat_session_id: str) -> List[CanvasInsight]:
98
+ """Extract insights from a single persona response"""
99
+ persona_id = response.get("persona_id", "unknown")
100
+ content = response.get("content", "")
101
+
102
+ return await self._extract_insights_from_content(content, persona_id, message_id, chat_session_id)
103
+
104
+ async def _extract_insights_from_content(self, content: str, persona_id: str, message_id: str, chat_session_id: str) -> List[CanvasInsight]:
105
+ """Extract actionable insights from content using LLM analysis"""
106
+ if not content or len(content.strip()) < 50:
107
+ return []
108
+
109
+ try:
110
+ # Use LLM to extract key insights
111
+ extraction_prompt = f"""
112
+ Extract actionable insights from this PhD advisor response that would be valuable for a student's progress summary:
113
+
114
+ PERSONA: {persona_id}
115
+ CONTENT: {content}
116
+
117
+ Return a JSON list of insights. Each insight should be:
118
+ - Actionable and specific to PhD progress
119
+ - 1-2 sentences long
120
+ - Valuable for advisor meetings
121
+ - Not generic advice
122
+
123
+ Format: [{{"insight": "specific actionable insight here", "keywords": ["keyword1", "keyword2"]}}]
124
+
125
+ Return ONLY the JSON array, no other text.
126
+ """
127
+
128
+ if self.llm_client:
129
+ llm_response = await self.llm_client.generate(
130
+ system_prompt="You are an expert at extracting actionable PhD guidance from advisor responses.",
131
+ context=[{"role": "user", "content": extraction_prompt}],
132
+ temperature=0.3,
133
+ max_tokens=500
134
+ )
135
+
136
+ try:
137
+ insights_data = json.loads(llm_response.strip())
138
+ insights = []
139
+
140
+ for item in insights_data:
141
+ if isinstance(item, dict) and "insight" in item:
142
+ insight = CanvasInsight(
143
+ content=item["insight"],
144
+ source_persona=persona_id,
145
+ source_message_id=message_id,
146
+ source_chat_session=chat_session_id,
147
+ confidence_score=0.8, # High confidence from LLM extraction
148
+ keywords=item.get("keywords", [])
149
+ )
150
+ insights.append(insight)
151
+
152
+ return insights
153
+
154
+ except json.JSONDecodeError:
155
+ logger.warning(f"Failed to parse LLM insights response for {persona_id}")
156
+ # Fallback to rule-based extraction
157
+ return self._extract_insights_rule_based(content, persona_id, message_id, chat_session_id)
158
+
159
+ # Fallback if no LLM available
160
+ return self._extract_insights_rule_based(content, persona_id, message_id, chat_session_id)
161
+
162
+ except Exception as e:
163
+ logger.error(f"Error extracting insights from {persona_id} content: {e}")
164
+ return []
165
+
166
+ def _extract_insights_rule_based(self, content: str, persona_id: str, message_id: str, chat_session_id: str) -> List[CanvasInsight]:
167
+ """Fallback rule-based insight extraction"""
168
+ insights = []
169
+
170
+ # Extract actionable sentences
171
+ sentences = re.split(r'[.!?]+', content)
172
+ actionable_patterns = [
173
+ r"(?:you should|consider|try|focus on|prioritize|next step|recommended?|suggest)",
174
+ r"(?:action item|goal|objective|plan|strategy)",
175
+ r"(?:deadline|timeline|schedule|by \w+)",
176
+ r"(?:complete|finish|work on|tackle|address)"
177
+ ]
178
+
179
+ for sentence in sentences:
180
+ sentence = sentence.strip()
181
+ if len(sentence) < 20: # Skip very short sentences
182
+ continue
183
+
184
+ # Check if sentence contains actionable language
185
+ is_actionable = any(re.search(pattern, sentence, re.IGNORECASE) for pattern in actionable_patterns)
186
+
187
+ if is_actionable:
188
+ # Extract keywords
189
+ keywords = self._extract_keywords_from_sentence(sentence)
190
+
191
+ insight = CanvasInsight(
192
+ content=sentence,
193
+ source_persona=persona_id,
194
+ source_message_id=message_id,
195
+ source_chat_session=chat_session_id,
196
+ confidence_score=0.6, # Lower confidence for rule-based
197
+ keywords=keywords
198
+ )
199
+ insights.append(insight)
200
+
201
+ return insights[:3] # Limit to 3 insights per message to avoid noise
202
+
203
+ def _extract_keywords_from_sentence(self, sentence: str) -> List[str]:
204
+ """Extract relevant keywords from a sentence"""
205
+ # Simple keyword extraction
206
+ words = re.findall(r'\b\w{4,}\b', sentence.lower()) # Words with 4+ chars
207
+
208
+ # Filter out common words
209
+ stop_words = {
210
+ "should", "could", "would", "your", "research", "work", "study",
211
+ "consider", "think", "important", "also", "really", "maybe",
212
+ "probably", "definitely", "certainly", "particular", "specific"
213
+ }
214
+
215
+ keywords = [word for word in words if word not in stop_words]
216
+ return keywords[:5] # Limit to 5 keywords
217
+
218
+ def categorize_insights(self, insights: List[CanvasInsight]) -> Dict[str, List[CanvasInsight]]:
219
+ """Categorize insights into canvas sections using semantic analysis"""
220
+ categorized = defaultdict(list)
221
+
222
+ for insight in insights:
223
+ section = self._determine_section(insight)
224
+ categorized[section].append(insight)
225
+
226
+ return dict(categorized)
227
+
228
+ def _determine_section(self, insight: CanvasInsight) -> str:
229
+ """Determine which canvas section an insight belongs to"""
230
+ content_lower = insight.content.lower()
231
+ keywords_lower = [kw.lower() for kw in insight.keywords]
232
+ all_text = content_lower + " " + " ".join(keywords_lower)
233
+
234
+ # Score each section based on keyword matches
235
+ section_scores = {}
236
+
237
+ for section_key, section_keywords in self.section_keywords.items():
238
+ score = 0
239
+ for keyword in section_keywords:
240
+ if keyword in all_text:
241
+ score += 1
242
+
243
+ # Bonus for persona-specific insights
244
+ persona_bonuses = {
245
+ "methodologist": {"methodology": 2, "data_analysis": 1},
246
+ "theorist": {"theoretical_framework": 2, "literature_review": 1},
247
+ "pragmatist": {"next_steps": 2, "research_progress": 1},
248
+ "socratic": {"theoretical_framework": 1, "challenges_obstacles": 1},
249
+ "motivator": {"motivation_mindset": 2, "career_development": 1},
250
+ "critic": {"challenges_obstacles": 1, "writing_communication": 1},
251
+ "empathetic": {"motivation_mindset": 2},
252
+ "visionary": {"career_development": 1, "research_progress": 1}
253
+ }
254
+
255
+ if insight.source_persona in persona_bonuses:
256
+ score += persona_bonuses[insight.source_persona].get(section_key, 0)
257
+
258
+ section_scores[section_key] = score
259
+
260
+ # Return section with highest score, default to general category
261
+ best_section = max(section_scores, key=section_scores.get) if section_scores else "research_progress"
262
+
263
+ # If no keywords matched, categorize by persona type
264
+ if section_scores[best_section] == 0:
265
+ persona_defaults = {
266
+ "methodologist": "methodology",
267
+ "theorist": "theoretical_framework",
268
+ "pragmatist": "next_steps",
269
+ "socratic": "theoretical_framework",
270
+ "motivator": "motivation_mindset",
271
+ "critic": "challenges_obstacles",
272
+ "empathetic": "motivation_mindset",
273
+ "visionary": "career_development",
274
+ "storyteller": "writing_communication",
275
+ "minimalist": "next_steps"
276
+ }
277
+ best_section = persona_defaults.get(insight.source_persona, "research_progress")
278
+
279
+ return best_section
280
+
281
+ def _deduplicate_insights(self, insights: List[CanvasInsight]) -> List[CanvasInsight]:
282
+ """Remove duplicate insights based on semantic similarity"""
283
+ if not insights:
284
+ return []
285
+
286
+ unique_insights = []
287
+ seen_contents = set()
288
+
289
+ for insight in insights:
290
+ # Simple deduplication based on content similarity
291
+ content_normalized = re.sub(r'\s+', ' ', insight.content.lower().strip())
292
+
293
+ # Check for substantial overlap with existing insights
294
+ is_duplicate = False
295
+ for seen_content in seen_contents:
296
+ if self._calculate_similarity(content_normalized, seen_content) > 0.8:
297
+ is_duplicate = True
298
+ break
299
+
300
+ if not is_duplicate:
301
+ unique_insights.append(insight)
302
+ seen_contents.add(content_normalized)
303
+
304
+ return unique_insights
305
+
306
+ def _calculate_similarity(self, text1: str, text2: str) -> float:
307
+ """Calculate simple similarity between two texts"""
308
+ words1 = set(text1.split())
309
+ words2 = set(text2.split())
310
+
311
+ if not words1 or not words2:
312
+ return 0.0
313
+
314
+ intersection = words1.intersection(words2)
315
+ union = words1.union(words2)
316
+
317
+ return len(intersection) / len(union) if union else 0.0
318
+
319
+ def prioritize_insights(self, insights: List[CanvasInsight]) -> List[CanvasInsight]:
320
+ """Prioritize insights based on relevance and actionability"""
321
+
322
+ def calculate_priority_score(insight: CanvasInsight) -> float:
323
+ score = insight.confidence_score
324
+
325
+ # Boost score for actionable language
326
+ actionable_terms = ["should", "need to", "must", "plan", "goal", "deadline", "complete"]
327
+ content_lower = insight.content.lower()
328
+ for term in actionable_terms:
329
+ if term in content_lower:
330
+ score += 0.1
331
+
332
+ # Boost score for specific vs generic advice
333
+ specific_terms = ["chapter", "data", "analysis", "method", "theory", "timeline"]
334
+ for term in specific_terms:
335
+ if term in content_lower:
336
+ score += 0.05
337
+
338
+ # Boost score for certain personas
339
+ persona_boosts = {
340
+ "pragmatist": 0.1, # Action-oriented insights are valuable
341
+ "methodologist": 0.08, # Methodological insights are important
342
+ "critic": 0.06 # Critical feedback is valuable
343
+ }
344
+ score += persona_boosts.get(insight.source_persona, 0)
345
+
346
+ return min(score, 1.0) # Cap at 1.0
347
+
348
+ # Calculate scores and sort
349
+ for insight in insights:
350
+ insight.confidence_score = calculate_priority_score(insight)
351
+
352
+ return sorted(insights, key=lambda x: x.confidence_score, reverse=True)
353
+
354
+ async def generate_section_summary(self, section: CanvasSection) -> str:
355
+ """Generate a summary for a canvas section using LLM"""
356
+ if not section.insights or not self.llm_client:
357
+ return f"Key insights for {section.title}"
358
+
359
+ try:
360
+ insights_text = "\n".join([f"- {insight.content}" for insight in section.insights])
361
+
362
+ prompt = f"""
363
+ Create a 1-2 sentence summary of these PhD insights for the section "{section.title}":
364
+
365
+ {insights_text}
366
+
367
+ The summary should be concise, professional, and suitable for sharing with an advisor.
368
+ Return only the summary text, no other content.
369
+ """
370
+
371
+ summary = await self.llm_client.generate(
372
+ system_prompt="You create concise summaries of academic insights.",
373
+ context=[{"role": "user", "content": prompt}],
374
+ temperature=0.2,
375
+ max_tokens=100
376
+ )
377
+
378
+ return summary.strip()
379
+
380
+ except Exception as e:
381
+ logger.error(f"Error generating section summary: {e}")
382
+ return f"Key insights and guidance for {section.title}"
multi_llm_chatbot_backend/app/core/canvas_database.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from motor.motor_asyncio import AsyncIOMotorDatabase
3
+
4
+ logger = logging.getLogger(__name__)
5
+
6
+ async def setup_canvas_collections(db: AsyncIOMotorDatabase):
7
+ """Setup MongoDB collections and indexes for PhD Canvas"""
8
+ try:
9
+ # Create indexes for phd_canvases collection
10
+ canvas_indexes = [
11
+ # User lookup index
12
+ ("user_id", 1),
13
+ # Query optimization indexes
14
+ [("user_id", 1), ("last_updated", -1)],
15
+ [("user_id", 1), ("created_at", -1)],
16
+ ("last_updated", -1), # For cleanup operations
17
+ ]
18
+
19
+ collection = db.phd_canvases
20
+
21
+ # Create indexes
22
+ for index in canvas_indexes:
23
+ if isinstance(index, list):
24
+ # Compound index
25
+ await collection.create_index(index)
26
+ logger.info(f"Created compound index: {index}")
27
+ else:
28
+ # Simple index
29
+ await collection.create_index(index)
30
+ logger.info(f"Created index: {index}")
31
+
32
+ # Ensure TTL index for old canvases (optional cleanup after 2 years)
33
+ await collection.create_index(
34
+ "created_at",
35
+ expireAfterSeconds=63072000 # 2 years in seconds
36
+ )
37
+ logger.info("Created TTL index for canvas cleanup")
38
+
39
+ logger.info("PhD Canvas database setup completed successfully")
40
+
41
+ except Exception as e:
42
+ logger.error(f"Error setting up canvas collections: {e}")
43
+ raise
44
+
45
+ async def cleanup_old_canvas_data(db: AsyncIOMotorDatabase):
46
+ """Cleanup old or orphaned canvas data (maintenance function)"""
47
+ try:
48
+ # Find canvases with no corresponding users (orphaned data)
49
+ pipeline = [
50
+ {
51
+ "$lookup": {
52
+ "from": "users",
53
+ "localField": "user_id",
54
+ "foreignField": "_id",
55
+ "as": "user_data"
56
+ }
57
+ },
58
+ {
59
+ "$match": {
60
+ "user_data": {"$size": 0} # No matching user found
61
+ }
62
+ }
63
+ ]
64
+
65
+ orphaned_canvases = await db.phd_canvases.aggregate(pipeline).to_list(length=100)
66
+
67
+ if orphaned_canvases:
68
+ orphaned_ids = [canvas["_id"] for canvas in orphaned_canvases]
69
+ result = await db.phd_canvases.delete_many({"_id": {"$in": orphaned_ids}})
70
+ logger.info(f"Cleaned up {result.deleted_count} orphaned canvas records")
71
+ else:
72
+ logger.info("No orphaned canvas records found")
73
+
74
+ except Exception as e:
75
+ logger.error(f"Error during canvas cleanup: {e}")
76
+
multi_llm_chatbot_backend/app/core/canvas_manager.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Dict, List, Optional
3
+ from datetime import datetime, timedelta
4
+ from bson import ObjectId
5
+
6
+ from app.models.phd_canvas import PhdCanvas, CanvasInsight, UpdateCanvasRequest
7
+ from app.core.canvas_analysis import CanvasAnalysisService
8
+ # Remove this import: from app.core.database import get_database
9
+ from app.core.bootstrap import llm
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ class CanvasManager:
14
+ """Manages PhD Canvas creation, updates, and incremental processing"""
15
+
16
+ def __init__(self):
17
+ self.analysis_service = CanvasAnalysisService(llm_client=llm)
18
+ self._db = None
19
+
20
+ def get_database(self):
21
+ """Lazy database connection to avoid circular imports"""
22
+ if not self._db:
23
+ # Import here to avoid circular import
24
+ from app.core.database import get_database
25
+ self._db = get_database()
26
+ return self._db
27
+
28
+ async def get_or_create_canvas(self, user_id: str) -> PhdCanvas:
29
+ """Get existing canvas or create new one for user"""
30
+ try:
31
+ db = self.get_database()
32
+ user_object_id = ObjectId(user_id)
33
+
34
+ # Try to find existing canvas
35
+ canvas_doc = await db.phd_canvases.find_one({"user_id": user_object_id})
36
+
37
+ if canvas_doc:
38
+ # Convert to PhdCanvas model
39
+ canvas = PhdCanvas(**canvas_doc)
40
+ logger.info(f"Found existing canvas for user {user_id} with {canvas.total_insights} insights")
41
+ return canvas
42
+ else:
43
+ # Create new canvas
44
+ canvas = PhdCanvas(user_id=user_object_id)
45
+
46
+ # Insert into database
47
+ result = await db.phd_canvases.insert_one(canvas.dict(by_alias=True))
48
+ canvas.id = result.inserted_id
49
+
50
+ logger.info(f"Created new canvas for user {user_id}")
51
+ return canvas
52
+
53
+ except Exception as e:
54
+ logger.error(f"Error getting/creating canvas for user {user_id}: {e}")
55
+ # Return empty canvas as fallback
56
+ return PhdCanvas(user_id=ObjectId(user_id))
57
+
58
+ async def update_canvas(self, user_id: str, request: UpdateCanvasRequest) -> PhdCanvas:
59
+ """Update canvas with latest insights from chat sessions"""
60
+ try:
61
+ db = self.get_database()
62
+ canvas = await self.get_or_create_canvas(user_id)
63
+
64
+ logger.info(f"Updating canvas for user {user_id}, force_full={request.force_full_update}")
65
+
66
+ # Determine which chats to process
67
+ if request.force_full_update:
68
+ # Process all chats
69
+ chat_sessions = await self._get_all_user_chat_sessions(user_id)
70
+ logger.info(f"Force full update: processing {len(chat_sessions)} total chat sessions")
71
+ else:
72
+ # Process only chats created/updated after last canvas update
73
+ chat_sessions = await self._get_new_chat_sessions(user_id, canvas.last_chat_processed)
74
+ logger.info(f"Incremental update: processing {len(chat_sessions)} new chat sessions since {canvas.last_chat_processed}")
75
+
76
+ if not chat_sessions:
77
+ logger.info("No new chat sessions to process")
78
+ return canvas
79
+
80
+ # Filter chat sessions if specific ones requested
81
+ if request.include_chat_sessions:
82
+ chat_sessions = [
83
+ chat for chat in chat_sessions
84
+ if str(chat["_id"]) in request.include_chat_sessions
85
+ ]
86
+ logger.info(f"Filtered to {len(chat_sessions)} specifically requested chat sessions")
87
+
88
+ # Process each chat session for insights
89
+ all_new_insights = []
90
+ processed_chat_ids = []
91
+
92
+ for chat_session in chat_sessions:
93
+ try:
94
+ chat_id = str(chat_session["_id"])
95
+ messages = chat_session.get("messages", [])
96
+
97
+ if not messages:
98
+ continue
99
+
100
+ logger.info(f"Processing chat {chat_id} with {len(messages)} messages")
101
+
102
+ # Extract insights from this chat session
103
+ session_insights = await self.analysis_service.extract_insights_from_messages(
104
+ messages, chat_id
105
+ )
106
+
107
+ if session_insights:
108
+ all_new_insights.extend(session_insights)
109
+ processed_chat_ids.append(chat_id)
110
+ logger.info(f"Extracted {len(session_insights)} insights from chat {chat_id}")
111
+
112
+ except Exception as e:
113
+ logger.error(f"Error processing chat session {chat_session.get('_id')}: {e}")
114
+ continue
115
+
116
+ if all_new_insights:
117
+ # Categorize insights by section
118
+ categorized_insights = self.analysis_service.categorize_insights(all_new_insights)
119
+
120
+ # Update canvas sections
121
+ sections_updated = 0
122
+ for section_key, insights in categorized_insights.items():
123
+ if request.exclude_sections and section_key in request.exclude_sections:
124
+ continue
125
+
126
+ # Prioritize insights before adding
127
+ prioritized_insights = self.analysis_service.prioritize_insights(insights)
128
+
129
+ # Limit insights per section to avoid overwhelming canvas
130
+ max_insights_per_section = 10
131
+ limited_insights = prioritized_insights[:max_insights_per_section]
132
+
133
+ if limited_insights:
134
+ canvas.update_section(section_key, limited_insights)
135
+ sections_updated += 1
136
+ logger.info(f"Updated section '{section_key}' with {len(limited_insights)} insights")
137
+
138
+ # Update canvas metadata
139
+ canvas.last_chat_processed = datetime.utcnow()
140
+ canvas.last_updated = datetime.utcnow()
141
+
142
+ # Save updated canvas to database
143
+ await self._save_canvas(canvas)
144
+
145
+ logger.info(f"Canvas update completed: {len(all_new_insights)} new insights, {sections_updated} sections updated")
146
+ else:
147
+ logger.info("No insights extracted from chat sessions")
148
+
149
+ return canvas
150
+
151
+ except Exception as e:
152
+ logger.error(f"Error updating canvas for user {user_id}: {e}")
153
+ import traceback
154
+ logger.error(f"Full traceback: {traceback.format_exc()}")
155
+ raise
156
+
157
+ async def _get_all_user_chat_sessions(self, user_id: str) -> List[Dict]:
158
+ """Get all chat sessions for a user"""
159
+ try:
160
+ db = self.get_database()
161
+ user_object_id = ObjectId(user_id)
162
+
163
+ cursor = db.chat_sessions.find({
164
+ "user_id": user_object_id,
165
+ "is_active": {"$ne": False}, # Include active sessions
166
+ "deleted_at": {"$exists": False} # Exclude deleted sessions
167
+ }).sort("created_at", -1) # Most recent first
168
+
169
+ chat_sessions = await cursor.to_list(length=100) # Limit to last 100 chats
170
+ return chat_sessions
171
+
172
+ except Exception as e:
173
+ logger.error(f"Error getting all chat sessions for user {user_id}: {e}")
174
+ return []
175
+
176
+ async def _get_new_chat_sessions(self, user_id: str, since: Optional[datetime]) -> List[Dict]:
177
+ """Get chat sessions created or updated after a specific time"""
178
+ try:
179
+ db = self.get_database()
180
+ user_object_id = ObjectId(user_id)
181
+
182
+ # Build query filter
183
+ query_filter = {
184
+ "user_id": user_object_id,
185
+ "is_active": {"$ne": False},
186
+ "deleted_at": {"$exists": False}
187
+ }
188
+
189
+ if since:
190
+ # Get chats created or updated after the since timestamp
191
+ query_filter["$or"] = [
192
+ {"created_at": {"$gt": since}},
193
+ {"updated_at": {"$gt": since}}
194
+ ]
195
+ else:
196
+ # If no since time, get chats from last 7 days as default
197
+ one_week_ago = datetime.utcnow() - timedelta(days=7)
198
+ query_filter["created_at"] = {"$gte": one_week_ago}
199
+
200
+ cursor = db.chat_sessions.find(query_filter).sort("created_at", -1)
201
+ chat_sessions = await cursor.to_list(length=50) # Limit for incremental updates
202
+
203
+ return chat_sessions
204
+
205
+ except Exception as e:
206
+ logger.error(f"Error getting new chat sessions for user {user_id}: {e}")
207
+ return []
208
+
209
+ async def _save_canvas(self, canvas: PhdCanvas):
210
+ """Save canvas to database"""
211
+ try:
212
+ db = self.get_database()
213
+
214
+ # Update existing canvas
215
+ await db.phd_canvases.replace_one(
216
+ {"_id": canvas.id},
217
+ canvas.dict(by_alias=True),
218
+ upsert=True
219
+ )
220
+
221
+ logger.info(f"Saved canvas {canvas.id} to database")
222
+
223
+ except Exception as e:
224
+ logger.error(f"Error saving canvas to database: {e}")
225
+ raise
226
+
227
+ async def delete_canvas(self, user_id: str) -> bool:
228
+ """Delete canvas for a user"""
229
+ try:
230
+ db = self.get_database()
231
+ user_object_id = ObjectId(user_id)
232
+
233
+ result = await db.phd_canvases.delete_one({"user_id": user_object_id})
234
+
235
+ if result.deleted_count > 0:
236
+ logger.info(f"Deleted canvas for user {user_id}")
237
+ return True
238
+ else:
239
+ logger.info(f"No canvas found to delete for user {user_id}")
240
+ return False
241
+
242
+ except Exception as e:
243
+ logger.error(f"Error deleting canvas for user {user_id}: {e}")
244
+ return False
245
+
246
+ async def get_canvas_stats(self, user_id: str) -> Dict:
247
+ """Get statistics about user's canvas"""
248
+ try:
249
+ canvas = await self.get_or_create_canvas(user_id)
250
+
251
+ stats = {
252
+ "total_insights": canvas.total_insights,
253
+ "total_sections": len(canvas.sections),
254
+ "last_updated": canvas.last_updated,
255
+ "last_chat_processed": canvas.last_chat_processed,
256
+ "created_at": canvas.created_at,
257
+ "auto_update": canvas.auto_update,
258
+ "sections_breakdown": {}
259
+ }
260
+
261
+ # Add breakdown by section
262
+ for section_key, section in canvas.sections.items():
263
+ stats["sections_breakdown"][section_key] = {
264
+ "title": section.title,
265
+ "insight_count": len(section.insights),
266
+ "last_updated": section.updated_at,
267
+ "priority": section.priority
268
+ }
269
+
270
+ return stats
271
+
272
+ except Exception as e:
273
+ logger.error(f"Error getting canvas stats for user {user_id}: {e}")
274
+ return {
275
+ "total_insights": 0,
276
+ "total_sections": 0,
277
+ "error": str(e)
278
+ }
279
+
280
+ async def export_canvas_for_printing(self, user_id: str) -> Dict:
281
+ """Export canvas in a print-optimized format"""
282
+ try:
283
+ canvas = await self.get_or_create_canvas(user_id)
284
+
285
+ # Sort sections by priority and insight count
286
+ sorted_sections = []
287
+ for section_key, section in canvas.sections.items():
288
+ if section.insights: # Only include sections with insights
289
+ # Sort insights by confidence score
290
+ sorted_insights = sorted(
291
+ section.insights,
292
+ key=lambda x: x.confidence_score,
293
+ reverse=True
294
+ )
295
+
296
+ sorted_sections.append({
297
+ "key": section_key,
298
+ "title": section.title,
299
+ "description": section.description,
300
+ "insights": [
301
+ {
302
+ "content": insight.content,
303
+ "source": insight.source_persona.title(),
304
+ "confidence": round(insight.confidence_score, 2)
305
+ }
306
+ for insight in sorted_insights[:8] # Limit for printing
307
+ ],
308
+ "insight_count": len(section.insights),
309
+ "priority": section.priority
310
+ })
311
+
312
+ # Sort sections by priority, then by insight count
313
+ sorted_sections.sort(key=lambda x: (x["priority"], -x["insight_count"]))
314
+
315
+ return {
316
+ "user_id": user_id,
317
+ "generated_at": datetime.utcnow(),
318
+ "total_insights": canvas.total_insights,
319
+ "last_updated": canvas.last_updated,
320
+ "sections": sorted_sections,
321
+ "metadata": {
322
+ "canvas_id": str(canvas.id),
323
+ "created_at": canvas.created_at,
324
+ "version": "1.0"
325
+ }
326
+ }
327
+
328
+ except Exception as e:
329
+ logger.error(f"Error exporting canvas for printing: {e}")
330
+ raise
331
+
332
+ # Global canvas manager instance
333
+ canvas_manager = CanvasManager()
334
+
335
+ def get_canvas_manager() -> CanvasManager:
336
+ """Get the global canvas manager instance"""
337
+ return canvas_manager
multi_llm_chatbot_backend/app/models/phd_canvas.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, Field
2
+ from typing import Dict, List, Optional, Any
3
+ from datetime import datetime
4
+ from bson import ObjectId
5
+ from app.models.user import PyObjectId
6
+
7
+ class CanvasInsight(BaseModel):
8
+ """Individual insight extracted from chat messages"""
9
+ content: str
10
+ source_persona: str
11
+ source_message_id: Optional[str] = None
12
+ source_chat_session: Optional[str] = None
13
+ confidence_score: float = Field(ge=0.0, le=1.0, default=0.8)
14
+ extracted_at: datetime = Field(default_factory=datetime.utcnow)
15
+ keywords: List[str] = Field(default_factory=list)
16
+
17
+ class CanvasSection(BaseModel):
18
+ """A themed section of the PhD Canvas with related insights"""
19
+ title: str
20
+ description: str
21
+ insights: List[CanvasInsight] = Field(default_factory=list)
22
+ priority: int = Field(default=1, ge=1, le=5) # 1=highest priority
23
+ updated_at: datetime = Field(default_factory=datetime.utcnow)
24
+
25
+ class PhdCanvas(BaseModel):
26
+ """Main PhD Canvas model storing all user insights organized by sections"""
27
+ id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
28
+ user_id: PyObjectId
29
+
30
+ # Canvas sections organized by theme
31
+ sections: Dict[str, CanvasSection] = Field(default_factory=dict)
32
+
33
+ # Metadata
34
+ created_at: datetime = Field(default_factory=datetime.utcnow)
35
+ last_updated: datetime = Field(default_factory=datetime.utcnow)
36
+ last_chat_processed: Optional[datetime] = None
37
+ total_insights: int = Field(default=0)
38
+
39
+ # Settings
40
+ auto_update: bool = Field(default=True)
41
+ print_optimized: bool = Field(default=True)
42
+
43
+ class Config:
44
+ allow_population_by_field_name = True
45
+ arbitrary_types_allowed = True
46
+ json_encoders = {ObjectId: str}
47
+
48
+ def update_section(self, section_key: str, insights: List[CanvasInsight]):
49
+ """Update a specific canvas section with new insights"""
50
+ if section_key not in self.sections:
51
+ self.sections[section_key] = CanvasSection(
52
+ title=self._get_section_title(section_key),
53
+ description=self._get_section_description(section_key)
54
+ )
55
+
56
+ # Add new insights and remove duplicates
57
+ existing_contents = {insight.content for insight in self.sections[section_key].insights}
58
+ new_insights = [insight for insight in insights if insight.content not in existing_contents]
59
+
60
+ self.sections[section_key].insights.extend(new_insights)
61
+ self.sections[section_key].updated_at = datetime.utcnow()
62
+ self.last_updated = datetime.utcnow()
63
+
64
+ # Update total insights count
65
+ self.total_insights = sum(len(section.insights) for section in self.sections.values())
66
+
67
+ def _get_section_title(self, section_key: str) -> str:
68
+ """Get human-readable title for section"""
69
+ titles = {
70
+ "research_progress": "Research Progress & Milestones",
71
+ "methodology": "Research Methods & Approach",
72
+ "theoretical_framework": "Theoretical Foundations",
73
+ "challenges_obstacles": "Challenges & Solutions",
74
+ "next_steps": "Action Items & Next Steps",
75
+ "writing_communication": "Writing & Communication",
76
+ "career_development": "Academic Career Planning",
77
+ "literature_review": "Literature & Sources",
78
+ "data_analysis": "Data & Analysis",
79
+ "motivation_mindset": "Motivation & Mindset"
80
+ }
81
+ return titles.get(section_key, section_key.replace("_", " ").title())
82
+
83
+ def _get_section_description(self, section_key: str) -> str:
84
+ """Get description for each section"""
85
+ descriptions = {
86
+ "research_progress": "Key milestones, accomplishments, and timeline updates",
87
+ "methodology": "Research design decisions and methodological insights",
88
+ "theoretical_framework": "Theoretical perspectives and conceptual foundations",
89
+ "challenges_obstacles": "Challenges faced and strategies for overcoming them",
90
+ "next_steps": "Immediate action items and upcoming priorities",
91
+ "writing_communication": "Writing strategies and communication insights",
92
+ "career_development": "Professional development and career planning",
93
+ "literature_review": "Literature gaps, sources, and review strategies",
94
+ "data_analysis": "Data collection and analysis approaches",
95
+ "motivation_mindset": "Motivational insights and mental health considerations"
96
+ }
97
+ return descriptions.get(section_key, "General insights and guidance")
98
+
99
+ class CanvasResponse(BaseModel):
100
+ """Response model for canvas API endpoints"""
101
+ id: str
102
+ user_id: str
103
+ sections: Dict[str, CanvasSection]
104
+ created_at: datetime
105
+ last_updated: datetime
106
+ last_chat_processed: Optional[datetime]
107
+ total_insights: int
108
+ auto_update: bool
109
+ print_optimized: bool
110
+
111
+ class UpdateCanvasRequest(BaseModel):
112
+ """Request model for updating canvas"""
113
+ force_full_update: bool = Field(default=False)
114
+ include_chat_sessions: Optional[List[str]] = None # Specific sessions to include
115
+ exclude_sections: Optional[List[str]] = None # Sections to skip updating