Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /ParisNeo_lollms /backend /routers /admin /content_management.py
| # backend/routers/admin/content_management.py | |
| import json | |
| import shutil | |
| import uuid | |
| import asyncio | |
| import re | |
| from typing import List, Dict, Optional | |
| from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, status | |
| from fastapi.responses import JSONResponse | |
| from sqlalchemy.orm import Session, joinedload | |
| from pydantic import BaseModel | |
| from backend.db import get_db | |
| from backend.db.models.prompt import SavedPrompt as DBSavedPrompt | |
| from backend.db.models.fun_fact import FunFact as DBFunFact, FunFactCategory as DBFunFactCategory | |
| from backend.db.models.datastore import DataStore as DBDataStore | |
| from backend.models import ( | |
| UserAuthDetails, TaskInfo, PromptCreate, PromptPublic, PromptUpdate, | |
| FunFactCategoryCreate, FunFactCategoryPublic, FunFactCategoryUpdate, | |
| FunFactCreate, FunFactPublic, FunFactUpdate, | |
| FunFactsImportRequest, FunFactExport, FunFactCategoryExport, FunFactCategoryImport | |
| ) | |
| from backend.session import get_current_admin_user, get_user_temp_uploads_path, get_user_lollms_client, get_safe_store_instance | |
| from backend.migration_utils import run_openwebui_migration | |
| from backend.zoo_cache import force_build_full_cache | |
| from backend.task_manager import task_manager, Task | |
| from backend.settings import settings | |
| from ascii_colors import trace_exception | |
| # --- Tool Imports --- | |
| try: | |
| from duckduckgo_search import DDGS | |
| except ImportError: | |
| DDGS = None | |
| try: | |
| from scrapemaster import ScrapeMaster | |
| except ImportError: | |
| ScrapeMaster = None | |
| try: | |
| import wikipedia | |
| except ImportError: | |
| wikipedia = None | |
| content_management_router = APIRouter() | |
| class GenerateFunFactsRequest(BaseModel): | |
| source_type: str = "topic" # topic, text, url, search, datastore, wikipedia | |
| content: str # The topic, raw text, url, search query, or prompt for datastore | |
| category: Optional[str] = None | |
| n_facts: int = 5 | |
| datastore_id: Optional[str] = None | |
| def _refresh_zoo_cache_task(task: Task): | |
| task.log("Starting Zoo cache refresh.") | |
| task.set_progress(10) | |
| force_build_full_cache() | |
| task.set_progress(100) | |
| task.log("Zoo cache refresh completed.") | |
| return {"message": "Zoo cache refreshed successfully."} | |
| def _generate_fun_facts_task(task: Task, request_data: dict, username: str): | |
| task.log("Starting fun facts generation task...") | |
| source_type = request_data.get('source_type', 'topic') | |
| content_input = (request_data.get('content') or '').strip() | |
| category_name = request_data.get('category') | |
| n_facts = int(request_data.get('n_facts', 5)) | |
| datastore_id = request_data.get('datastore_id') | |
| task.log(f"DEBUG: Input Content: '{content_input}'") | |
| task.log(f"DEBUG: Initial Source Type: {source_type}") | |
| lc = get_user_lollms_client(username) | |
| context_text = "" | |
| # 1. Gather Context / Auto-Correction | |
| if source_type == 'topic' or source_type == 'url': | |
| if 'wikipedia.org/wiki/' in content_input: | |
| task.log("Wikipedia URL detected. Switching to Wikipedia mode.", "INFO") | |
| source_type = 'wikipedia' | |
| elif source_type == 'topic' and re.search(r'^(https?://|www\.)', content_input, re.IGNORECASE): | |
| task.log("URL pattern detected. Switching mode to URL scraping...", "INFO") | |
| source_type = 'url' | |
| if content_input.lower().startswith('www.'): | |
| content_input = 'https://' + content_input | |
| task.set_progress(10) | |
| try: | |
| if source_type == 'topic': | |
| context_text = "" # Will use internal knowledge | |
| task.log(f"Generating based on internal knowledge for topic: {content_input}") | |
| elif source_type == 'text': | |
| context_text = content_input | |
| task.log("Context gathered from provided text.") | |
| elif source_type == 'wikipedia': | |
| if not wikipedia: | |
| raise ImportError("Wikipedia library not installed.") | |
| task.log(f"Fetching Wikipedia content for: {content_input}") | |
| try: | |
| lang = "en" | |
| title = content_input | |
| url_match = re.search(r'https?://(\w+)\.wikipedia\.org/wiki/(.+)', content_input) | |
| if url_match: | |
| lang = url_match.group(1) | |
| title = url_match.group(2).replace('_', ' ') | |
| try: | |
| from urllib.parse import unquote | |
| title = unquote(title) | |
| except: pass | |
| wikipedia.set_lang(lang) | |
| page = wikipedia.page(title, auto_suggest=False) | |
| context_text = page.content | |
| task.log(f"Retrieved Wikipedia page: '{page.title}'. Length: {len(context_text)} chars.") | |
| if not category_name: | |
| category_name = page.title | |
| except Exception as e: | |
| task.log(f"Wikipedia fetch failed: {e}", "ERROR") | |
| raise e | |
| elif source_type == 'url': | |
| if not ScrapeMaster: | |
| raise ImportError("ScrapeMaster library is not installed.") | |
| task.log(f"Scraping URL: {content_input}") | |
| try: | |
| scraper = ScrapeMaster(content_input, headless=True) | |
| try: | |
| context_text = scraper.scrape_markdown() | |
| except AttributeError: | |
| res = scraper.scrape_all(max_depth=0, convert_to_markdown=True) | |
| context_text = res.get('markdown', '') | |
| if not context_text or len(context_text.strip()) < 50: | |
| context_text = f"URL Topic: {content_input}" | |
| except Exception as e: | |
| task.log(f"Scraping failed: {e}. Treating as topic.", "WARNING") | |
| context_text = f"Topic: {content_input}" | |
| elif source_type == 'search': | |
| if not DDGS: | |
| raise ImportError("DuckDuckGo Search library not installed.") | |
| task.log(f"Searching for: {content_input}") | |
| try: | |
| with DDGS() as ddgs: | |
| results = [r for r in ddgs.text(content_input, max_results=3)] | |
| context_text = "\n".join([f"- {r['title']}: {r['body']}" for r in results]) | |
| except Exception as e: | |
| task.log(f"Search failed: {e}", "ERROR") | |
| context_text = f"Topic: {content_input}" | |
| elif source_type == 'datastore': | |
| if not datastore_id: | |
| raise ValueError("Datastore ID required for datastore source.") | |
| with task.db_session_factory() as db: | |
| ss = get_safe_store_instance(username, datastore_id, db) | |
| results = ss.query(content_input, top_k=5) | |
| context_text = "\n---\n".join([r['chunk_text'] for r in results]) | |
| except Exception as e: | |
| task.log(f"Error gathering context: {e}", "ERROR") | |
| raise e | |
| task.set_progress(30) | |
| # 2. Process via Long Context if context is large, otherwise standard | |
| style_guide = f"Each fact must be a complete, standalone sentence that explicitly mentions the subject. Do not use pronouns (He/She/It) to start sentences. Provide exactly {n_facts} facts." | |
| schema_json = { | |
| "type": "object", | |
| "properties": { | |
| "category": {"type": "string"}, | |
| "fun_facts": {"type": "array", "items": {"type": "string"}} | |
| }, | |
| "required": ["category", "fun_facts"] | |
| } | |
| # Instructions at the end for maximum impact | |
| final_prompt = f"""Identify exactly {n_facts} interesting and verifiable fun facts based on the content. | |
| REQUIREMENTS: | |
| 1. Output format: JSON. | |
| 2. {style_guide} | |
| 3. Category: {category_name or 'Auto'} | |
| JSON SCHEMA: | |
| {json.dumps(schema_json, indent=2)} | |
| JSON RESPONSE: | |
| """ | |
| task.log("Running AI generation...") | |
| try: | |
| # Use long_context_processing to handle the heavy lifting | |
| # This will chunk the Wikipedia page and synthesize the facts | |
| if len(context_text) > 2000: | |
| task.log(f"Large context ({len(context_text)} chars). Utilizing long_context_processing...") | |
| raw_response = lc.long_context_processing( | |
| text_to_process=context_text, | |
| contextual_prompt=final_prompt, | |
| context_fill_percentage=0.7, | |
| overlap_tokens=200, | |
| max_generation_tokens=2048 | |
| ) | |
| else: | |
| task.log("Short context. Utilizing standard structured generation...") | |
| # If short, use the dedicated structured method which handles the JSON block extraction automatically | |
| data = lc.generate_structured_content( | |
| f"Topic Content: {context_text or content_input}\n\n{final_prompt}", | |
| schema=schema_json, | |
| temperature=0.7 | |
| ) | |
| raw_response = json.dumps(data) | |
| task.set_progress(80) | |
| # 3. Robust JSON Parsing | |
| # Long context processing returns a string, so we must extract the JSON block | |
| json_match = re.search(r'(\{[\s\S]*\})', raw_response) | |
| if json_match: | |
| data = json.loads(json_match.group(1)) | |
| else: | |
| # Fallback to direct parse if no markdown blocks | |
| data = json.loads(raw_response) | |
| facts_list = data.get("fun_facts", []) | |
| suggested_category = data.get("category", category_name or "General") | |
| if not facts_list or len(facts_list) == 0: | |
| raise ValueError("AI returned an empty facts list.") | |
| # 4. Save to Database | |
| with task.db_session_factory() as db: | |
| final_cat_name = category_name or suggested_category | |
| db_category = db.query(DBFunFactCategory).filter(DBFunFactCategory.name == final_cat_name).first() | |
| if not db_category: | |
| db_category = DBFunFactCategory(name=final_cat_name, is_active=True) | |
| db.add(db_category) | |
| db.flush() | |
| facts_to_add = [DBFunFact(content=f.strip(), category_id=db_category.id) for f in facts_list if f.strip()] | |
| if facts_to_add: | |
| db.add_all(facts_to_add) | |
| db.commit() | |
| task.set_progress(100) | |
| task.log(f"Successfully saved {len(facts_to_add)} facts to '{final_cat_name}'.") | |
| return {"facts_added": len(facts_to_add), "category": final_cat_name} | |
| except Exception as e: | |
| task.log(f"Generation or parsing failed: {e}", "ERROR") | |
| trace_exception(e) | |
| raise e | |
| async def refresh_zoo_cache_endpoint(current_user: UserAuthDetails = Depends(get_current_admin_user)): | |
| return task_manager.submit_task( | |
| name="Refreshing Zoo Cache", | |
| target=_refresh_zoo_cache_task, | |
| description="Scanning all Zoo repositories and rebuilding the cache.", | |
| owner_username=current_user.username | |
| ) | |
| async def import_openwebui_data( | |
| file: UploadFile = File(...), | |
| current_admin: UserAuthDetails = Depends(get_current_admin_user) | |
| ): | |
| if not file or file.filename != "webui.db": | |
| raise HTTPException(status_code=400, detail="Invalid file. Please upload 'webui.db'.") | |
| temp_import_dir = get_user_temp_uploads_path(current_admin.username) / f"owui_import_{uuid.uuid4()}" | |
| temp_import_dir.mkdir(parents=True, exist_ok=True) | |
| try: | |
| with open(temp_import_dir / file.filename, "wb") as buffer: | |
| shutil.copyfileobj(file.file, buffer) | |
| finally: | |
| file.file.close() | |
| task_manager.submit_task( | |
| name="Import OpenWebUI Data", | |
| target=run_openwebui_migration, | |
| args=(str(temp_import_dir),), | |
| description=f"Migrating data from {file.filename}", | |
| owner_username=current_admin.username | |
| ) | |
| return {"message": "Migration started. Check Task Manager for progress."} | |
| async def get_fun_fact_categories(db: Session = Depends(get_db)): | |
| return db.query(DBFunFactCategory).order_by(DBFunFactCategory.name).all() | |
| async def create_fun_fact_category(category_data: FunFactCategoryCreate, db: Session = Depends(get_db)): | |
| if db.query(DBFunFactCategory).filter(DBFunFactCategory.name == category_data.name).first(): | |
| raise HTTPException(status_code=409, detail="A category with this name already exists.") | |
| new_category = DBFunFactCategory(**category_data.model_dump()) | |
| db.add(new_category) | |
| db.commit() | |
| db.refresh(new_category) | |
| return new_category | |
| async def update_fun_fact_category(category_id: int, update_data: FunFactCategoryUpdate, db: Session = Depends(get_db)): | |
| category = db.query(DBFunFactCategory).filter(DBFunFactCategory.id == category_id).first() | |
| if not category: | |
| raise HTTPException(status_code=404, detail="Category not found.") | |
| update_dict = update_data.model_dump(exclude_unset=True) | |
| if 'name' in update_dict and update_dict['name'] != category.name: | |
| if db.query(DBFunFactCategory).filter(DBFunFactCategory.name == update_dict['name']).first(): | |
| raise HTTPException(status_code=409, detail="A category with this name already exists.") | |
| for key, value in update_dict.items(): | |
| setattr(category, key, value) | |
| db.commit() | |
| db.refresh(category) | |
| return category | |
| async def delete_fun_fact_category(category_id: int, db: Session = Depends(get_db)): | |
| category = db.query(DBFunFactCategory).filter(DBFunFactCategory.id == category_id).first() | |
| if not category: | |
| raise HTTPException(status_code=404, detail="Category not found.") | |
| db.query(DBFunFact).filter(DBFunFact.category_id == category_id).delete() | |
| db.delete(category) | |
| db.commit() | |
| async def get_all_fun_facts(db: Session = Depends(get_db)): | |
| return db.query(DBFunFact).options(joinedload(DBFunFact.category)).order_by(DBFunFact.id.desc()).all() | |
| async def create_fun_fact(fact_data: FunFactCreate, db: Session = Depends(get_db)): | |
| if not db.query(DBFunFactCategory).filter(DBFunFactCategory.id == fact_data.category_id).first(): | |
| raise HTTPException(status_code=404, detail="Category not found.") | |
| new_fact = DBFunFact(**fact_data.model_dump()) | |
| db.add(new_fact) | |
| db.commit() | |
| db.refresh(new_fact) | |
| return new_fact | |
| async def update_fun_fact(fact_id: int, update_data: FunFactUpdate, db: Session = Depends(get_db)): | |
| fact = db.query(DBFunFact).filter(DBFunFact.id == fact_id).first() | |
| if not fact: | |
| raise HTTPException(status_code=404, detail="Fun fact not found.") | |
| update_dict = update_data.model_dump(exclude_unset=True) | |
| if 'category_id' in update_dict: | |
| if not db.query(DBFunFactCategory).filter(DBFunFactCategory.id == update_dict['category_id']).first(): | |
| raise HTTPException(status_code=404, detail="New category not found.") | |
| for key, value in update_dict.items(): | |
| setattr(fact, key, value) | |
| db.commit() | |
| db.refresh(fact) | |
| return fact | |
| async def delete_fun_fact(fact_id: int, db: Session = Depends(get_db)): | |
| fact = db.query(DBFunFact).filter(DBFunFact.id == fact_id).first() | |
| if not fact: | |
| raise HTTPException(status_code=404, detail="Fun fact not found.") | |
| db.delete(fact) | |
| db.commit() | |
| async def generate_fun_facts_from_prompt( | |
| request: GenerateFunFactsRequest, | |
| current_admin_user: UserAuthDetails = Depends(get_current_admin_user) | |
| ): | |
| request_data = request.model_dump() | |
| return task_manager.submit_task( | |
| name=f"Generate Fun Facts ({request.source_type})", | |
| target=_generate_fun_facts_task, | |
| args=(request_data, current_admin_user.username), | |
| owner_username=current_admin_user.username | |
| ) | |
| async def import_fun_facts(import_data: FunFactsImportRequest, db: Session = Depends(get_db)): | |
| existing_categories = {cat.name: cat.id for cat in db.query(DBFunFactCategory).all()} | |
| created_categories = 0 | |
| created_facts = 0 | |
| for item in import_data.fun_facts: | |
| category_id = existing_categories.get(item.category) | |
| if not category_id: | |
| new_cat = DBFunFactCategory(name=item.category, is_active=True) | |
| db.add(new_cat) | |
| db.flush() | |
| category_id = new_cat.id | |
| existing_categories[item.category] = category_id | |
| created_categories += 1 | |
| db.add(DBFunFact(content=item.content, category_id=category_id)) | |
| created_facts += 1 | |
| db.commit() | |
| return {"categories_created": created_categories, "facts_created": created_facts} | |
| async def export_fun_facts(db: Session = Depends(get_db)): | |
| all_facts = db.query(DBFunFact).options(joinedload(DBFunFact.category)).all() | |
| return [FunFactExport(category=fact.category.name, content=fact.content) for fact in all_facts] | |
| async def export_fun_fact_category(category_id: int, db: Session = Depends(get_db)): | |
| category = db.query(DBFunFactCategory).filter(DBFunFactCategory.id == category_id).first() | |
| if not category: | |
| raise HTTPException(status_code=404, detail="Category not found.") | |
| facts = [fact.content for fact in db.query(DBFunFact.content).filter(DBFunFact.category_id == category_id).all()] | |
| export_data = FunFactCategoryExport(name=category.name, is_active=category.is_active, color=category.color, facts=facts) | |
| headers = {'Content-Disposition': f'attachment; filename="fun_facts_{category.name}.json"'} | |
| return JSONResponse(content=export_data.model_dump(), headers=headers) | |
| async def import_fun_fact_category(file: UploadFile = File(...), db: Session = Depends(get_db)): | |
| try: | |
| data = json.loads(await file.read()) | |
| import_data = FunFactCategoryImport(**data) | |
| except Exception as e: | |
| raise HTTPException(status_code=400, detail=f"Invalid JSON file or format: {e}") | |
| finally: | |
| await file.close() | |
| category = db.query(DBFunFactCategory).filter(DBFunFactCategory.name == import_data.name).first() | |
| categories_created = 0 | |
| if not category: | |
| category = DBFunFactCategory(name=import_data.name, is_active=import_data.is_active, color=import_data.color) | |
| db.add(category) | |
| db.flush() | |
| categories_created = 1 | |
| facts_created = sum(1 for _ in import_data.facts) | |
| for fact_content in import_data.facts: | |
| db.add(DBFunFact(content=fact_content, category_id=category.id)) | |
| db.commit() | |
| return {"categories_created": categories_created, "facts_created": facts_created} | |
Xet Storage Details
- Size:
- 19.9 kB
- Xet hash:
- 5cc16e263ea3b6399fe546ba2b5da17b55e1e5589c0ae46348912e37c2e045f0
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.