Spaces:
Sleeping
Sleeping
Upload 5 files
Browse files376 unmodified lines3773783793803813823834 unmodified lines3883893903913923933943953963973983994004014024034044054064074084094104114124134144154164176 unmodified lines42442542642742842943043143243311 unmodified lines44544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948021 unmodified lines50250350450550650750850951051151251351451551651751851952052152217 unmodified lines54054154254354454554654754854955055155255355455592 unmodified lines648649650651652653654655656657658659660661662663664665666667668669376 unmodified lines'groq': groq_client is not None,'gemini': genai_client is not None},'storage': 'file_based','auth': 'disabled'})4 unmodified lines"""Return simple system health info using file-based storage (no external deps)."""try:import shutildata_root = DATA_ROOTschema = {}total_rows = 0db_size = 0if os.path.exists(data_root):for folder in os.listdir(data_root):folder_path = os.path.join(data_root, folder)if os.path.isdir(folder_path):files = [f for f in os.listdir(folder_path) if f.endswith('.json')]row_count = len(files)total_rows += row_count# approximate sizesize = 0for fn in files:p = os.path.join(folder_path, fn)try:size += os.path.getsize(p)except Exception:passdb_size += sizeschema[folder] = {'row_count': row_count, 'size_bytes': size}# disk usage for current filesystemtry:du = shutil.disk_usage('.')disk = {6 unmodified linesdisk = {}health = {'memory': None,'disk': disk,'database': {'data_root': data_root,'total_rows': total_rows,'estimated_size_bytes': db_size,'tables': schema11 unmodified linesdef admin_database_schema():"""Return a simple schema overview derived from hf_data folders."""try:data_root = DATA_ROOTschema = {}if os.path.exists(data_root):for folder in os.listdir(data_root):folder_path = os.path.join(data_root, folder)if os.path.isdir(folder_path):files = [f for f in os.listdir(folder_path) if f.endswith('.json')]# try to infer columns from first filecols = []if files:sample_path = os.path.join(folder_path, files[0])try:with open(sample_path, 'r', encoding='utf-8') as fh:data = json.load(fh)if isinstance(data, list) and data:sample = data[0]elif isinstance(data, dict):sample = dataelse:sample = {}cols = [{'name': k, 'type': type(v).__name__} for k, v in (sample or {}).items()]except Exception:cols = []schema[folder] = {'row_count': len(files),'columns': cols}else:schema = {}return jsonify({'success': True, 'schema': schema})except Exception as e:21 unmodified linesflashcards = len(load_user_data(uid, 'flashcards'))conversations = len(load_user_data(uid, 'conversations'))analytics = len(load_user_data(uid, 'analytics'))# estimate created_at by file mtime if availablecreated_at = Nonetry:path_candidates = [os.path.join(DATA_ROOT, 'flashcards', f"{uid}.json"),os.path.join(DATA_ROOT, 'conversations', f"{uid}.json"),os.path.join(DATA_ROOT, 'analytics', f"{uid}.json")]mtimes = []for p in path_candidates:if os.path.exists(p):mtimes.append(os.path.getmtime(p))if mtimes:created_at = datetime.fromtimestamp(min(mtimes)).isoformat()except Exception:created_at = None17 unmodified lines"""Get detailed info for a user or delete their data (file-based)."""try:if request.method == 'DELETE':# remove files across hf_dataremoved = []for folder in ['flashcards', 'conversations', 'analytics']:p = os.path.join(DATA_ROOT, folder, f"{user_id}.json")try:if os.path.exists(p):os.remove(p)removed.append(p)except Exception as ex:print(f"Failed deleting {p}: {ex}")return jsonify({'success': True, 'deleted': removed})# GET -> return analytics, flashcards, conversations92 unmodified lines"""Package the entire DATA_ROOT into a zip and send for download."""try:import zipfileimport tempfileif not os.path.exists(DATA_ROOT):return jsonify({'success': False, 'error': 'No data directory found'}), 404tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.zip')tmp.close()with zipfile.ZipFile(tmp.name, 'w', compression=zipfile.ZIP_DEFLATED) as zf:for root, dirs, files in os.walk(DATA_ROOT):for f in files:full = os.path.join(root, f)arcname = os.path.relpath(full, DATA_ROOT)zf.write(full, arcname)return send_file(tmp.name, mimetype='application/zip', as_attachment=True, download_name='hf_data_export.zip')except Exception as e:print(f"export all error: {e}")return jsonify({'success': False, 'error': str(e)}), 500376 unmodified lines3773783793803813823833844 unmodified lines3893903913923933943953963973983994004014024034044054064074084094104114124134146 unmodified lines42142242342442542642742842943011 unmodified lines44244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347421 unmodified lines49649749849950050150250350450550650717 unmodified lines52552652752852953053153253353453553653753853954054154254354454554692 unmodified lines639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668376 unmodified lines'groq': groq_client is not None,'gemini': genai_client is not None},'storage': 'in_memory','demo_mode': True,'auth': 'disabled'})4 unmodified lines"""Return simple system health info using file-based storage (no external deps)."""try:import shutil# compute simple stats from IN_MEMORYschema = {}total_rows = 0db_size = 0for table, table_data in IN_MEMORY.items():if isinstance(table_data, dict):row_count = sum(1 for _ in table_data.keys())# approximate size by serializing entriessize = 0for k, v in table_data.items():try:size += len(json.dumps(v, ensure_ascii=False).encode('utf-8'))except Exception:passschema[table] = {'row_count': row_count, 'size_bytes': size}total_rows += row_countdb_size += size# disk usage for current filesystem (informational)try:du = shutil.disk_usage('.')disk = {6 unmodified linesdisk = {}health = {'memory': True,'disk': disk,'database': {'storage': 'in_memory','total_rows': total_rows,'estimated_size_bytes': db_size,'tables': schema11 unmodified linesdef admin_database_schema():"""Return a simple schema overview derived from hf_data folders."""try:# derive schema from IN_MEMORYschema = {}for table, table_data in IN_MEMORY.items():cols = []row_count = 0if isinstance(table_data, dict):row_count = sum(1 for _ in table_data.keys())# infer columns/types from first valuetry:first_val = Nonefor v in table_data.values():first_val = vbreaksample = Noneif isinstance(first_val, list) and first_val:sample = first_val[0]elif isinstance(first_val, dict):sample = first_valif isinstance(sample, dict):cols = [{'name': k, 'type': type(v).__name__} for k, v in sample.items()]except Exception:cols = []schema[table] = {'row_count': row_count,'columns': cols}return jsonify({'success': True, 'schema': schema})except Exception as e:21 unmodified linesflashcards = len(load_user_data(uid, 'flashcards'))conversations = len(load_user_data(uid, 'conversations'))analytics = len(load_user_data(uid, 'analytics'))# created_at from user record if availablecreated_at = Nonetry:urec = IN_MEMORY.get('users', {}).get(uid)if urec and isinstance(urec, dict):created_at = urec.get('created_at')except Exception:created_at = None17 unmodified lines"""Get detailed info for a user or delete their data (file-based)."""try:if request.method == 'DELETE':# remove in-memory records across tablesremoved = []for folder in ['flashcards', 'conversations', 'analytics', 'study_plans']:try:tbl = IN_MEMORY.get(folder, {})if user_id in tbl:del tbl[user_id]removed.append(f"{folder}/{user_id}")except Exception as ex:print(f"Failed deleting in-memory {folder}/{user_id}: {ex}")# remove user recordtry:if user_id in IN_MEMORY.get('users', {}):del IN_MEMORY['users'][user_id]except Exception:passreturn jsonify({'success': True, 'deleted': removed})# GET -> return analytics, flashcards, conversations92 unmodified lines"""Package the entire DATA_ROOT into a zip and send for download."""try:import zipfilemem_zip = io.BytesIO()with zipfile.ZipFile(mem_zip, 'w', compression=zipfile.ZIP_DEFLATED) as zf:# dump each table as filesfor table, table_data in IN_MEMORY.items():if isinstance(table_data, dict):for uid, val in table_data.items():try:payload = json.dumps(val, ensure_ascii=False, indent=2)except Exception:payload = str(val)arcname = os.path.join(table, f"{uid}.json")zf.writestr(arcname, payload)else:# serialize whole objecttry:payload = json.dumps(table_data, ensure_ascii=False, indent=2)except Exception:payload = str(table_data)arcname = f"{table}.json"zf.writestr(arcname, payload)mem_zip.seek(0)return send_file(mem_zip, mimetype='application/zip', as_attachment=True, download_name='hf_data_export.zip')except Exception as e:print(f"export all error: {e}")return jsonify({'success': False, 'error': str(e)}), 500
flask_app_hf.py+84-85