Buckets:
AnonymousSpottedToad/human_verified_bucket / codebase /python /ParisNeo_lollms /backend /routers /skills.py
| import re | |
| import yaml | |
| import xml.etree.ElementTree as ET | |
| from typing import List, Optional | |
| import datetime | |
| from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File, Response | |
| from sqlalchemy.orm import Session | |
| from sqlalchemy.exc import IntegrityError | |
| from pydantic import BaseModel | |
| from backend.db import get_db | |
| from backend.db.models.skill import Skill as DBSkill | |
| from backend.db.models.user import User as DBUser | |
| from backend.models.user import UserAuthDetails | |
| from backend.session import get_current_active_user | |
| from backend.models.personality import PersonalitySendRequest | |
| skills_router = APIRouter( | |
| prefix="/api/skills", | |
| tags=["Skills"], | |
| dependencies=[Depends(get_current_active_user)] | |
| ) | |
| from sqlalchemy import or_ | |
| class SkillBase(BaseModel): | |
| name: str | |
| content: str | |
| description: Optional[str] = None | |
| category: Optional[str] = None | |
| language: Optional[str] = "markdown" | |
| author: Optional[str] = None | |
| version: Optional[str] = "1.0.0" | |
| class SkillCreate(SkillBase): | |
| is_system: bool = False | |
| class SkillUpdate(BaseModel): | |
| name: Optional[str] = None | |
| content: Optional[str] = None | |
| description: Optional[str] = None | |
| category: Optional[str] = None | |
| language: Optional[str] = None | |
| author: Optional[str] = None | |
| version: Optional[str] = None | |
| is_system: Optional[bool] = None | |
| class SkillPublic(SkillBase): | |
| id: str | |
| is_system: bool = False | |
| owner_user_id: Optional[int] = None | |
| created_at: Optional[datetime.datetime] = None | |
| updated_at: Optional[datetime.datetime] = None | |
| class Config: | |
| from_attributes = True | |
| def _to_skill_public(s: DBSkill) -> SkillPublic: | |
| return SkillPublic( | |
| id=s.id, | |
| name=s.name, | |
| description=s.description, | |
| category=s.category or "Development", | |
| language=s.language or "markdown", | |
| content=s.content, | |
| author=s.author or ("System" if s.owner_user_id is None else "Personal"), | |
| version=s.version or "1.0.0", | |
| is_system=(s.owner_user_id is None), | |
| owner_user_id=s.owner_user_id, | |
| created_at=s.created_at, | |
| updated_at=s.updated_at | |
| ) | |
| def get_skills(current_user: UserAuthDetails = Depends(get_current_active_user), db: Session = Depends(get_db)): | |
| # Return both User Skills (owned by current_user) and System Skills (owner_user_id is None) | |
| skills = db.query(DBSkill).filter( | |
| or_(DBSkill.owner_user_id == current_user.id, DBSkill.owner_user_id.is_(None)) | |
| ).order_by(DBSkill.name).all() | |
| return [_to_skill_public(s) for s in skills] | |
| def create_skill(skill: SkillCreate, current_user: UserAuthDetails = Depends(get_current_active_user), db: Session = Depends(get_db)): | |
| # Support creating System Skills if admin requests it | |
| is_admin = getattr(current_user, "is_admin", False) | |
| target_owner_id = None if (is_admin and skill.is_system) else current_user.id | |
| target_author = skill.author or ("System" if target_owner_id is None else current_user.username) | |
| existing_skill = db.query(DBSkill).filter( | |
| DBSkill.owner_user_id == target_owner_id, | |
| DBSkill.name == skill.name | |
| ).first() | |
| if existing_skill: | |
| existing_skill.content = skill.content | |
| if skill.description: existing_skill.description = skill.description | |
| if skill.category: existing_skill.category = skill.category | |
| if skill.language: existing_skill.language = skill.language | |
| existing_skill.author = target_author | |
| existing_skill.version = skill.version or existing_skill.version | |
| existing_skill.updated_at = datetime.datetime.now() | |
| db.commit() | |
| db.refresh(existing_skill) | |
| return _to_skill_public(existing_skill) | |
| data = skill.model_dump() | |
| data.pop("is_system", None) | |
| new_skill = DBSkill(**data, owner_user_id=target_owner_id, author=target_author) | |
| db.add(new_skill) | |
| try: | |
| db.commit() | |
| db.refresh(new_skill) | |
| return _to_skill_public(new_skill) | |
| except IntegrityError: | |
| db.rollback() | |
| raise HTTPException(status_code=400, detail="Error creating skill.") | |
| def update_skill(skill_id: str, skill_update: SkillUpdate, current_user: UserAuthDetails = Depends(get_current_active_user), db: Session = Depends(get_db)): | |
| skill = db.query(DBSkill).filter(DBSkill.id == skill_id).first() | |
| if not skill: | |
| raise HTTPException(status_code=404, detail="Skill not found") | |
| is_admin = getattr(current_user, "is_admin", False) | |
| is_system = (skill.owner_user_id is None) | |
| # Permissions: System skills can only be edited by admins; User skills by their owner or admins | |
| if is_system and not is_admin: | |
| raise HTTPException(status_code=403, detail="Only administrators can edit System Skills.") | |
| if not is_system and skill.owner_user_id != current_user.id and not is_admin: | |
| raise HTTPException(status_code=403, detail="You do not have permission to edit this skill.") | |
| update_data = skill_update.model_dump(exclude_unset=True) | |
| if "is_system" in update_data: | |
| if is_admin: | |
| skill.owner_user_id = None if update_data.pop("is_system") else current_user.id | |
| else: | |
| update_data.pop("is_system", None) | |
| for key, value in update_data.items(): | |
| if hasattr(skill, key): | |
| setattr(skill, key, value) | |
| try: | |
| db.commit() | |
| db.refresh(skill) | |
| return _to_skill_public(skill) | |
| except IntegrityError: | |
| db.rollback() | |
| raise HTTPException(status_code=400, detail="Error updating skill.") | |
| def delete_skill(skill_id: str, current_user: UserAuthDetails = Depends(get_current_active_user), db: Session = Depends(get_db)): | |
| skill = db.query(DBSkill).filter(DBSkill.id == skill_id).first() | |
| if not skill: | |
| raise HTTPException(status_code=404, detail="Skill not found") | |
| is_admin = getattr(current_user, "is_admin", False) | |
| is_system = (skill.owner_user_id is None) | |
| is_authorized = is_admin or (not is_system and skill.owner_user_id == current_user.id) | |
| if not is_authorized: | |
| detail_msg = "Only administrators can delete System Skills." if is_system else "You do not have permission to delete this skill." | |
| raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=detail_msg) | |
| db.delete(skill) | |
| db.commit() | |
| class ExportFormat(BaseModel): | |
| format: str | |
| def export_skill(skill_id: str, payload: ExportFormat, current_user: UserAuthDetails = Depends(get_current_active_user), db: Session = Depends(get_db)): | |
| skill = db.query(DBSkill).filter(DBSkill.id == skill_id, DBSkill.owner_user_id == current_user.id).first() | |
| if not skill: | |
| raise HTTPException(status_code=404, detail="Skill not found") | |
| if payload.format == 'xml': | |
| root = ET.Element("skill", id=skill.id) | |
| ET.SubElement(root, "name").text = skill.name | |
| if skill.description: | |
| ET.SubElement(root, "description").text = skill.description | |
| if skill.category: | |
| ET.SubElement(root, "category").text = skill.category | |
| if skill.language: | |
| ET.SubElement(root, "language").text = skill.language | |
| ET.SubElement(root, "timestamp").text = str(int(skill.updated_at.timestamp() * 1000)) if skill.updated_at else "0" | |
| content_el = ET.SubElement(root, "content") | |
| content_el.text = f"<![CDATA[\n{skill.content}\n]]>" | |
| xml_str = ET.tostring(root, encoding="utf-8").decode("utf-8") | |
| xml_str = xml_str.replace("<![CDATA[", "<![CDATA[").replace("]]>", "]]>") | |
| safe_name = re.sub(r'[^\w\-_\. ]', '_', skill.name) | |
| return Response(content=xml_str, media_type="application/xml", headers={"Content-Disposition": f'attachment; filename="skill_{safe_name}.xml"'}) | |
| elif payload.format == 'claude': | |
| frontmatter = { | |
| "name": skill.name, | |
| "version": "1.0.0", | |
| } | |
| if skill.description: | |
| frontmatter["description"] = skill.description | |
| if skill.category: | |
| frontmatter["category"] = skill.category | |
| yaml_str = yaml.dump(frontmatter, sort_keys=False) | |
| claude_str = f"---\n{yaml_str}---\n\n{skill.content}" | |
| safe_name = re.sub(r'[^\w\-_\. ]', '_', skill.name) | |
| return Response(content=claude_str, media_type="text/markdown", headers={"Content-Disposition": f'attachment; filename="skill_{safe_name}.md"'}) | |
| else: | |
| raise HTTPException(status_code=400, detail="Unsupported format") | |
| async def share_skill( | |
| skill_id: str, | |
| payload: PersonalitySendRequest, | |
| current_user: UserAuthDetails = Depends(get_current_active_user), | |
| db: Session = Depends(get_db) | |
| ): | |
| skill = db.query(DBSkill).filter(DBSkill.id == skill_id, DBSkill.owner_user_id == current_user.id).first() | |
| if not skill: | |
| raise HTTPException(status_code=404, detail="Skill not found") | |
| target_user = db.query(DBUser).filter(DBUser.username == payload.target_username).first() | |
| if not target_user: | |
| raise HTTPException(status_code=404, detail="Target user not found") | |
| # Check for duplicates | |
| if db.query(DBSkill).filter(DBSkill.owner_user_id == target_user.id, DBSkill.name == skill.name).first(): | |
| raise HTTPException(status_code=409, detail=f"User already has a skill named '{skill.name}'") | |
| # Tag the sender's copy | |
| share_log = f"\n[Shared with {target_user.username} on {datetime.datetime.now().strftime('%Y-%m-%d')}]" | |
| if not skill.description: | |
| skill.description = share_log | |
| elif share_log not in skill.description: | |
| skill.description += f" {share_log}" | |
| # Create the receiver's copy with the "Shared" tag | |
| new_skill = DBSkill( | |
| name=skill.name, | |
| description=skill.description, | |
| category=skill.category, | |
| language=skill.language, | |
| content=skill.content, | |
| author=f"Shared by {current_user.username}", # This acts as the UI tag | |
| owner_user_id=target_user.id | |
| ) | |
| db.add(new_skill) | |
| try: | |
| db.commit() | |
| from backend.ws_manager import manager | |
| manager.send_personal_message_sync({ | |
| "type": "skill_shared", | |
| "data": { | |
| "message": f"🎁 {current_user.username} shared AI skill: {skill.name}", | |
| "sender_username": current_user.username, | |
| "sender_icon": current_user.icon, | |
| "skill_id": new_skill.id, | |
| "title": skill.name, | |
| "type": "success", | |
| "duration": 6000 | |
| } | |
| }, target_user.id) | |
| manager.send_personal_message_sync({"type": "skill_saved", "data": {"title": skill.name}}, target_user.id) | |
| return {"message": f"Skill shared with {payload.target_username}"} | |
| except Exception as e: | |
| db.rollback() | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def import_skill(file: UploadFile = File(...), current_user: UserAuthDetails = Depends(get_current_active_user), db: Session = Depends(get_db)): | |
| content_bytes = await file.read() | |
| text_content = content_bytes.decode('utf-8', errors='replace') | |
| name = "Imported Skill" | |
| description = "" | |
| category = "Imported" | |
| language = "markdown" | |
| skill_content = "" | |
| try: | |
| # Detect XML (Custom format) | |
| if "<!DOCTYPE" in text_content.upper() or "<!ENTITY" in text_content.upper(): | |
| raise ValueError("XML DTD and custom entity declarations are forbidden.") | |
| if "<skill" in text_content: | |
| cdata_match = re.search(r'<!\[CDATA\[(.*?)\]\]>', text_content, re.DOTALL) | |
| cdata_content = cdata_match.group(1) if cdata_match else "" | |
| clean_xml = re.sub(r'<!\[CDATA\[.*?\]\]>', '', text_content, flags=re.DOTALL) | |
| root = ET.fromstring(clean_xml) | |
| name_el = root.find("name") | |
| if name_el is not None and name_el.text: name = name_el.text | |
| desc_el = root.find("description") | |
| if desc_el is not None and desc_el.text: description = desc_el.text | |
| cat_el = root.find("category") | |
| if cat_el is not None and cat_el.text: category = cat_el.text | |
| lang_el = root.find("language") | |
| if lang_el is not None and lang_el.text: language = lang_el.text | |
| cont_el = root.find("content") | |
| if cdata_content: | |
| skill_content = cdata_content.strip() | |
| elif cont_el is not None and cont_el.text: | |
| skill_content = cont_el.text.strip() | |
| elif text_content.strip().startswith("---"): | |
| # Normalize newlines to prevent multiline regex anchor issues | |
| text_content = text_content.replace('\r\n', '\n') | |
| parts = re.split(r'^---[ \t]*$', text_content, maxsplit=2, flags=re.MULTILINE) | |
| if len(parts) >= 3: | |
| frontmatter_text = parts[1] | |
| skill_content = parts[2].strip() | |
| frontmatter = yaml.safe_load(frontmatter_text) | |
| if isinstance(frontmatter, dict): | |
| name = frontmatter.get("name", name) | |
| description = frontmatter.get("description", description) | |
| category = frontmatter.get("category", category) | |
| else: | |
| # Fallback if split fails but starts with '---' | |
| skill_content = text_content.strip() | |
| else: | |
| raise ValueError("Unknown file format. Please upload a valid XML or Claude-style markdown skill file.") | |
| new_skill = DBSkill( | |
| name=name, | |
| content=skill_content, | |
| description=description, | |
| category=category, | |
| language=language, | |
| owner_user_id=current_user.id | |
| ) | |
| db.add(new_skill) | |
| db.commit() | |
| db.refresh(new_skill) | |
| return new_skill | |
| except Exception as e: | |
| raise HTTPException(status_code=400, detail=f"Failed to import skill: {str(e)}") |
Xet Storage Details
- Size:
- 14.6 kB
- Xet hash:
- 2f474d20eece62ec3ac8ecf7618bf1ef438c981faf631b269b3edfdc4d2a3d7f
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.