- 
                Notifications
    You must be signed in to change notification settings 
- Fork 4
Add avatar path support for personas #10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            7 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      0b8dc05
              
                Add support for persona avatars via file path
              
              
                Zsailer 0460b68
              
                Fix Content-Type header for avatar handler
              
              
                Zsailer 03abc2d
              
                Fix Python 3.9 compatibility for type hints
              
              
                Zsailer e250e3f
              
                Add logging to avatar handler for debugging
              
              
                Zsailer df09c6c
              
                Remove debug logging from avatar handler
              
              
                Zsailer fac6f66
              
                Add avatar path support for personas
              
              
                Zsailer bea930c
              
                Remove unused health endpoint check from frontend
              
              
                Zsailer File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -1,14 +1,99 @@ | ||
| import json | ||
| import mimetypes | ||
| import os | ||
| from typing import Dict, Optional | ||
| from urllib.parse import unquote | ||
|  | ||
| from jupyter_server.base.handlers import APIHandler | ||
| from jupyter_server.base.handlers import JupyterHandler | ||
| import tornado | ||
|  | ||
| class RouteHandler(APIHandler): | ||
| # The following decorator should be present on all verb methods (head, get, post, | ||
| # patch, put, delete, options) to ensure only authorized user can request the | ||
| # Jupyter server | ||
|  | ||
| # Maximum avatar file size (5MB) | ||
| MAX_AVATAR_SIZE = 5 * 1024 * 1024 | ||
|  | ||
| # Module-level cache: {persona_id: avatar_path} | ||
| # This is populated when personas are initialized/refreshed | ||
| _avatar_cache: Dict[str, str] = {} | ||
|  | ||
|  | ||
| def build_avatar_cache(persona_managers: dict) -> None: | ||
| """ | ||
| Build the avatar cache from all persona managers. | ||
|  | ||
| This should be called when personas are initialized or refreshed. | ||
| """ | ||
| global _avatar_cache | ||
| _avatar_cache = {} | ||
|  | ||
| for room_id, persona_manager in persona_managers.items(): | ||
| for persona in persona_manager.personas.values(): | ||
| try: | ||
| avatar_path = persona.defaults.avatar_path | ||
| if avatar_path and os.path.exists(avatar_path): | ||
| _avatar_cache[persona.id] = avatar_path | ||
| except Exception: | ||
| # Skip personas with invalid avatar paths | ||
| continue | ||
|  | ||
|  | ||
| def clear_avatar_cache() -> None: | ||
| """Clear the avatar cache. Called during persona refresh.""" | ||
| global _avatar_cache | ||
| _avatar_cache = {} | ||
|  | ||
|  | ||
| class AvatarHandler(JupyterHandler): | ||
| """ | ||
| Handler for serving persona avatar files. | ||
|  | ||
| Looks up avatar files by persona ID and serves the image file | ||
| with appropriate content-type headers. | ||
| """ | ||
|  | ||
| @tornado.web.authenticated | ||
| def get(self): | ||
| self.finish(json.dumps({ | ||
| "data": "This is /jupyter-ai-persona-manager/get-example endpoint!" | ||
| })) | ||
| async def get(self, persona_id: str): | ||
| """Serve an avatar file by persona ID.""" | ||
| # URL-decode the persona ID | ||
| persona_id = unquote(persona_id) | ||
|  | ||
| # Get the avatar file path | ||
| avatar_path = self._find_avatar_file(persona_id) | ||
|  | ||
| if avatar_path is None: | ||
| raise tornado.web.HTTPError(404, f"Avatar not found for persona") | ||
|  | ||
| # Check file size | ||
| try: | ||
| file_size = os.path.getsize(avatar_path) | ||
| if file_size > MAX_AVATAR_SIZE: | ||
| self.log.error(f"Avatar file too large: {file_size} bytes (max: {MAX_AVATAR_SIZE})") | ||
| raise tornado.web.HTTPError(413, "Avatar file too large") | ||
| except OSError as e: | ||
| self.log.error(f"Error checking avatar file size: {e}") | ||
| raise tornado.web.HTTPError(500, "Error accessing avatar file") | ||
|  | ||
| # Serve the file | ||
| try: | ||
| # Set content type based on file extension | ||
| content_type, _ = mimetypes.guess_type(avatar_path) | ||
| if content_type: | ||
| self.set_header("Content-Type", content_type) | ||
|  | ||
| # Read and serve the file | ||
| with open(avatar_path, 'rb') as f: | ||
| content = f.read() | ||
| self.write(content) | ||
|  | ||
| await self.finish() | ||
| except Exception as e: | ||
| self.log.error(f"Error serving avatar file: {e}") | ||
| raise tornado.web.HTTPError(500, f"Error serving avatar file: {str(e)}") | ||
|  | ||
| def _find_avatar_file(self, persona_id: str) -> Optional[str]: | ||
| """ | ||
| Find the avatar file path by persona ID using the module-level cache. | ||
|  | ||
| The cache is built when personas are initialized or refreshed, | ||
| so this is an O(1) lookup instead of iterating all personas. | ||
| """ | ||
| return _avatar_cache.get(persona_id) | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.