From bf8a388a2c07f8cac875699f5988f3a385be17df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C2=A8rudramani1=C2=A8?= Date: Sun, 20 Jul 2025 12:38:45 +0530 Subject: [PATCH 1/3] Updated DockArea.py and requirements.txt with necessary changes added Backend and also changes Usermanual.py --- Backend/esim_help.csv | 85 +++++ Backend/helpbot.py | 389 +++++++++++++++++++++ Backend/vector.py | 115 ++++++ requirements.txt | 8 + resources/esim_faq.csv | 25 ++ src/browser/UserManual.py | 716 +++++++++++++++++++++++++++++++++++++- src/browser/main.py | 9 + src/frontEnd/DockArea.py | 29 +- 8 files changed, 1346 insertions(+), 30 deletions(-) create mode 100644 Backend/esim_help.csv create mode 100644 Backend/helpbot.py create mode 100644 Backend/vector.py create mode 100644 resources/esim_faq.csv create mode 100644 src/browser/main.py diff --git a/Backend/esim_help.csv b/Backend/esim_help.csv new file mode 100644 index 000000000..a37840b33 --- /dev/null +++ b/Backend/esim_help.csv @@ -0,0 +1,85 @@ +category,subcategory,command,syntax,description,example,parameters,notes,use_case,related_commands +Overview,About eSIM,N/A,N/A,"eSIM is a virtual electronics simulator developed by FOSSEE (IIT Bombay) for learning circuit design and simulation. It uses Ngspice for backend simulation and runs in a browser.","Simulate a common emitter amplifier using Ngspice and visualize output graph.","Circuit file, type of analysis (AC, DC, Transient)","Requires modern browser, designed for academic purposes.","Education, training, virtual labs in electronics and communication engineering.",".tran, .ac, run, plot, .print, .measure" +Installation Issues,Dependencies Missing,install_dependencies,sudo apt-get install dependencies,KiCad or Ngspice dependencies not installed properly,sudo apt-get install kicad ngspice,Package names for Ubuntu,Check system requirements before installation,Fresh installation on Ubuntu,verify_installation +Installation Issues,Permission Errors,fix_permissions,sudo chmod +x install_script,Installation fails due to insufficient permissions,sudo chmod +x eSim-2.3.run,Executable file path,Run as administrator on Windows,Installation script won't execute,installation_troubleshooting +Installation Issues,Path Issues,set_path,export PATH=$PATH:/opt/eSim,eSim commands not found in terminal,export PATH=$PATH:/opt/eSim-2.3/bin,Correct eSim installation directory,Add to .bashrc for permanent fix,Command not found errors,environment_setup +Installation Issues,Version Conflicts,version_check,esim --version,Conflicting versions of dependencies installed,Check KiCad version compatibility,Version numbers,Uninstall old versions first,Multiple eSim versions installed,uninstall_old +Installation Issues,Browser Compatibility,check_browser,Open supported browser,eSIM not loading properly in browser,Use Chrome Firefox or Safari latest versions,Modern browser required,Disable ad blockers for eSIM,Web interface not working,browser_setup +Installation Issues,Python Dependencies,install_python_deps,pip install PyQt5 matplotlib numpy,Python or PyQt5 dependencies missing,pip install PyQt5 matplotlib numpy scipy,Python package requirements,Use pip3 for Python3 installations,GUI not loading or plotting issues,python_setup +Simulation Errors,Netlist Generation Failed,check_netlist,Tools → Generate Netlist,Schematic cannot be converted to SPICE netlist,Missing ground connection in circuit,Proper component labeling required,All components must have SPICE models,Netlist conversion errors,add_spice_models +Simulation Errors,Convergence Problems,convergence_fix,.options gmin=1e-12,Simulation fails to converge,".options gmin=1e-12 abstol=1e-12",Tolerance parameters,Adjust simulation options,Large circuits or nonlinear elements,simulation_options +Simulation Errors,Model Not Found,add_model,Model Editor → Import,Component SPICE model missing from library,Import transistor.lib to model library,Model file path,Check model syntax,Custom components not simulating,model_library +Simulation Errors,Syntax Errors,fix_syntax,Edit netlist manually,SPICE syntax errors in netlist,Fix ".model" statement format,Proper SPICE syntax,Use Model Editor for validation,Simulation won't start,netlist_debug +Simulation Errors,Timeout Errors,adjust_timeout,Set simulation timeout,Simulation runs too long and times out,Increase timeout limit in settings,Time limit in seconds,Reduce circuit complexity if needed,Long running simulations,simulation_settings +Simulation Errors,Memory Overflow,reduce_complexity,Simplify circuit design,Simulation exceeds available memory,Break large circuit into smaller blocks,Available system memory,Close other browser tabs,Very large circuits,memory_management +Simulation Errors,Division by Zero,check_parameters,Verify component values,Mathematical error in simulation,Ensure no zero-value resistors or capacitors,Component parameter validation,Use realistic component values,Parameter validation errors,component_check +Schematic Issues,Component Not Found,add_component_library,Library → Add,Required component missing from library,Add custom component library,Library file path,Install additional KiCad libraries,Missing components in palette,library_manager +Schematic Issues,ERC Violations,run_erc,Tools → ERC,Electrical Rule Check failures,Unconnected pins or power issues,Design rule settings,Fix all ERC errors before simulation,Schematic validation fails,design_rules +Schematic Issues,Pin Connection Errors,fix_connections,Manual wire placement,Components not properly connected,Add junction dots at wire intersections,Proper wire routing,Check for floating nodes,Connectivity issues,wire_connections +Schematic Issues,Label Issues,fix_labels,Edit component properties,Component reference designators missing,Set R1 R2 for resistors V1 for voltage source,Unique component names,Sequential numbering required,Duplicate component names,component_properties +Schematic Issues,Wire Crossing Problems,fix_wire_crossing,Use junction dots,Ambiguous wire connections at crossings,Add junction dots where wires should connect,Visual connection indicators,Avoid T-junctions without dots,Connection ambiguity,wire_management +Schematic Issues,Component Rotation,rotate_component,Right-click → Rotate,Component orientation incorrect,Rotate component to proper orientation,90-degree increments,Use R key for quick rotation,Schematic readability,component_placement +Schematic Issues,Grid Alignment,snap_to_grid,View → Grid Settings,Components not aligned properly,Enable snap-to-grid functionality,Grid spacing settings,Use consistent grid for neat schematics,Schematic organization,design_aesthetics +Schematic Issues,Bus Connections,create_bus,Place → Bus,Multiple signal lines need organization,Create bus for address or data lines,Bus notation standards,Label bus segments clearly,Multi-bit signal management,signal_organization +PCB Design Issues,Footprint Missing,assign_footprint,Tools → Assign Footprints,Component footprint not assigned,Map schematic symbol to PCB footprint,Footprint library selection,Check component associations,PCB layout cannot be generated,footprint_library +PCB Design Issues,DRC Violations,run_drc,Tools → DRC,Design Rule Check failures in PCB,Trace width or spacing violations,Design rule file settings,Adjust PCB layout or rules,PCB manufacturing errors,pcb_rules +PCB Design Issues,Routing Problems,manual_route,Route → Interactive Router,Auto-routing fails or incomplete,Manually route critical nets,Layer and via settings,Use multiple PCB layers,Complex PCB layouts,via_placement +PCB Design Issues,Layer Stack Issues,configure_layers,Setup → Layer Stack,Incorrect PCB layer configuration,Set up 2-layer or 4-layer stackup,Layer count and thickness,Consult manufacturer specs,Multi-layer PCB design,stackup_planning +PCB Design Issues,Via Problems,fix_vias,Place → Via,Vias not connecting layers properly,Check via drill size and pad size,Via specifications,Verify layer connections,Inter-layer connections,layer_connectivity +Performance Issues,Simulation Slow,optimize_simulation,Reduce timestep or complexity,Simulation takes too long to complete,Reduce circuit complexity or timestep,Simulation parameters,Use appropriate analysis types,Large circuit simulation,simulation_tuning +Performance Issues,Memory Issues,increase_memory,System settings,Out of memory during simulation,Close other applications increase swap,System memory allocation,Monitor system resources,Complex mixed-signal circuits,system_resources +Performance Issues,GUI Freezing,restart_gui,Ctrl+Alt+T → killall eSim,eSim interface becomes unresponsive,Restart eSim application,Process management,Save work frequently,Large schematics or long simulations,force_quit +Performance Issues,Browser Lag,optimize_browser,Clear browser cache,Web interface running slowly,Clear cache and restart browser,Browser optimization,Disable unnecessary extensions,Poor web performance,browser_maintenance +Performance Issues,Plot Generation Slow,reduce_plot_points,Limit data points,Graph plotting takes too long,Reduce number of plot points in analysis,Plot resolution settings,Balance detail vs performance,Large dataset visualization,plot_optimization +Model Issues,Custom Model Errors,validate_model,Model Editor → Check Syntax,User-created SPICE models have errors,Check .model statement syntax,SPICE model parameters,Refer to SPICE manual,Custom component simulation,spice_syntax +Model Issues,Library Path Wrong,fix_library_path,Configure → Library Paths,Model libraries not found,Set correct path to model files,Directory paths,Use absolute paths,Model import failures,path_configuration +Model Issues,Model Parameters Invalid,check_model_params,Edit model parameters,Component model has invalid parameters,Verify all model parameters are realistic,Parameter ranges and units,Check manufacturer datasheets,Simulation accuracy issues,parameter_validation +Model Issues,Temperature Dependence,set_temperature,.temp 27,Temperature effects not modeled,Add temperature analysis commands,Temperature in Celsius,Consider temperature coefficients,Environmental simulation,thermal_analysis +Analysis Issues,AC Analysis Problems,setup_ac_analysis,.ac dec 10 1 1meg,AC analysis not working correctly,Set up proper AC analysis parameters,Frequency range and points,Use logarithmic or linear sweep,Frequency response analysis,frequency_analysis +Analysis Issues,Transient Analysis Errors,fix_transient,.tran 0.1ms 10ms,Transient simulation fails,Check time step and stop time,Time parameters,Ensure stable initial conditions,Time domain analysis,time_analysis +Analysis Issues,DC Sweep Issues,configure_dc_sweep,.dc V1 0 5 0.1,DC sweep not producing results,Set up DC source sweep parameters,Voltage or current range,Check sweep variable exists,Parameter variation analysis,parametric_analysis +Analysis Issues,Operating Point Problems,check_operating_point,.op,DC operating point calculation fails,Verify all DC sources and connections,Circuit biasing,Check for floating nodes,Initial condition problems,bias_analysis +Analysis Issues,Noise Analysis Setup,setup_noise_analysis,.noise v(out) V1 dec 10 1 1meg,Noise analysis configuration issues,Configure noise analysis parameters,Input and output nodes,Specify noise source,Circuit noise characterization,noise_modeling +File Issues,Project Won't Open,repair_project,File → Recent Projects,eSim project file corrupted,Restore from backup or recreate,Project file integrity,Regular project backups,Lost work recovery,backup_restore +File Issues,Save Errors,fix_save_permissions,Change file permissions,Cannot save project files,Check folder write permissions,File system permissions,Save to user directory,Permission denied errors,file_permissions +File Issues,Import Errors,fix_import,File → Import,Cannot import external files,Check file format and encoding,Supported file formats,Convert files if necessary,External file integration,format_conversion +File Issues,Export Problems,troubleshoot_export,File → Export,File export functionality not working,Verify export format and destination,Export options and formats,Check write permissions,Data sharing and backup,file_output +Mixed Signal Issues,NGHDL Setup,configure_nghdl,NGHDL → Configuration,Mixed-signal simulation setup problems,Configure Verilog/VHDL compiler paths,Compiler installation paths,Install GHDL and Verilator,Digital simulation not working,digital_setup +Mixed Signal Issues,Interface Errors,debug_interface,Check log files,Analog-digital interface problems,Verify interface component connections,Interface component parameters,Check simulation log for errors,Mixed-signal coupling issues,simulation_log +Mixed Signal Issues,Digital Logic Problems,check_digital_logic,Verify logic levels,Digital components not behaving correctly,Check logic threshold and timing,Logic family specifications,Ensure proper power supply,Digital circuit design,logic_verification +Mixed Signal Issues,Clock Signal Issues,fix_clock_signals,Check clock sources,Clock signals not propagating,Verify clock source and distribution,Clock frequency and duty cycle,Avoid clock skew problems,Sequential circuit timing,timing_analysis +Export Issues,Gerber Generation,fix_gerber,File → Plot,PCB Gerber files not generated correctly,Check layer setup and plot settings,Layer selection and format,Verify plot output directory,Manufacturing file problems,plot_settings +Export Issues,Netlist Export,export_debug,File → Export → Netlist,Netlist export fails or incomplete,Check component models and connections,Export format selection,Validate netlist before export,External tool integration,netlist_validation +Export Issues,BOM Generation,generate_bom,Tools → Generate BOM,Bill of Materials not generating,Check component properties and values,Component attributes,Ensure all parts have part numbers,Manufacturing documentation,parts_list +Export Issues,3D Model Export,export_3d,File → Export → 3D,3D model export not working,Verify 3D models assigned to footprints,3D model libraries,Check export format settings,Mechanical design integration,cad_integration +System Issues,Display Problems,fix_display,System display settings,GUI elements not displaying correctly,Adjust system scaling or resolution,Display configuration,Check graphics drivers,High DPI displays,graphics_setup +System Issues,Font Issues,configure_fonts,System font settings,Text not readable in interface,Install required fonts or change settings,Font configuration,Restart after font changes,Text rendering problems,system_fonts +System Issues,Audio Problems,fix_audio,System audio settings,No sound from simulation alerts,Check system audio configuration,Audio device settings,Enable system sounds,User feedback and alerts,audio_configuration +System Issues,Keyboard Shortcuts,configure_shortcuts,Edit → Preferences,Keyboard shortcuts not working,Check shortcut key assignments,Key binding configuration,Avoid conflicts with system shortcuts,Workflow efficiency,hotkey_setup +Integration Issues,KiCad Version,kicad_compatibility,Check KiCad version,KiCad integration not working,Ensure compatible KiCad version,Version compatibility matrix,Update or downgrade KiCad,Schematic editor issues,version_management +Integration Issues,Ngspice Path,ngspice_setup,Configure Ngspice path,Ngspice simulation engine not found,Set correct Ngspice installation path,Executable file location,Verify Ngspice installation,Simulation engine errors,tool_configuration +Integration Issues,Python Dependencies,install_python_deps,pip install required_packages,Python scripts not executing,Install required Python packages,Package requirements,Use virtual environment,Script automation features,python_setup +Integration Issues,MATLAB Interface,setup_matlab,Configure MATLAB path,MATLAB integration not working,Set MATLAB installation directory,MATLAB toolbox requirements,Check license availability,Advanced analysis features,matlab_configuration +Update Issues,Version Update Failed,manual_update,Download latest version,eSim update process fails,Uninstall old version then reinstall,Clean installation process,Backup projects before update,Update mechanism broken,clean_install +Update Issues,Configuration Lost,restore_config,Copy configuration files,Settings lost after update,Restore configuration from backup,Configuration file locations,Export settings before update,Personalized settings missing,config_backup +Update Issues,Plugin Compatibility,check_plugins,Verify plugin versions,Plugins not working after update,Check plugin compatibility with new version,Plugin version requirements,Update or disable incompatible plugins,Extended functionality issues,plugin_management +Network Issues,Download Failures,check_network,Network connectivity test,Cannot download models or updates,Check internet connection and firewall,Network configuration,Use alternative download methods,Resource download problems,proxy_settings +Network Issues,Proxy Configuration,setup_proxy,Configure proxy settings,Behind corporate firewall,Set proxy in system and eSim settings,Proxy server details,Contact IT for proxy information,Corporate network restrictions,network_configuration +Network Issues,SSL Certificate Errors,fix_ssl,Update certificates,SSL certificate validation failures,Update system certificates or bypass SSL,Certificate management,Consult IT administrator,Secure connection problems,security_configuration +Documentation Issues,Help Not Available,access_help,Online documentation,Built-in help system not working,Visit eSim FOSSEE website for documentation,Internet connection required,Bookmark important documentation,Learning eSim usage,online_resources +Documentation Issues,Tutorial Problems,alternative_tutorials,Spoken Tutorial website,Video tutorials not playing,Use alternative browsers or players,Media player requirements,Download tutorials for offline use,Learning specific features,video_playback +Documentation Issues,Missing Examples,find_examples,Example projects directory,Cannot find example circuits,Look in installation examples folder,Example file locations,Download examples from website,Learning circuit design,sample_projects +Educational Issues,Learning Curve,structured_learning,Follow tutorial sequence,New users finding eSIM difficult,Start with basic circuits and tutorials,Progressive difficulty levels,Practice with simple examples first,Academic learning support,tutorial_progression +Educational Issues,Assignment Help,academic_support,Contact instructor,Students need help with assignments,Provide guidance on circuit analysis,Academic context understanding,Encourage independent learning,Classroom integration,instructor_resources +Educational Issues,Lab Setup,configure_lab,Multi-user environment,Setting up eSIM for laboratory use,Configure shared resources and accounts,Network and user management,Plan for concurrent users,Educational institution deployment,lab_management +Feature Requests,New Components,request_component,Community forum,Need component not in library,Submit component request to developers,Component specifications,Consider creating custom model,Expanding component library,community_contribution +Feature Requests,Analysis Types,request_analysis,Feature request form,Need analysis type not available,Request new analysis capability,Analysis requirements,Use existing tools as workaround,Advanced simulation needs,development_roadmap +Bug Reports,Crash Reports,report_crash,GitHub Issues → Bug Report,eSim crashes unexpectedly,Document steps to reproduce crash,Crash dump information,Include system information,Getting help from developers,log_analysis +Bug Reports,Feature Requests,request_feature,GitHub Issues → Feature Request,Need functionality not available,Describe desired feature clearly,Use case explanation,Check existing feature requests,Suggesting improvements,community_feedback +Bug Reports,Simulation Inaccuracy,report_accuracy,Compare with known results,Simulation results seem incorrect,Verify with hand calculations or other tools,Expected vs actual results,Check model accuracy and parameters,Result validation concerns,verification_methods +Troubleshooting,Log Analysis,check_logs,View → Log Files,Need to diagnose simulation problems,Examine log files for error messages,Log file locations and formats,Look for warning and error messages,Debugging simulation issues,error_diagnosis +Troubleshooting,Component Testing,isolate_component,Test individual components,Circuit not working as expected,Test components individually,Component isolation techniques,Use simple test circuits,Systematic debugging approach,debug_strategy +Troubleshooting,Backup Recovery,restore_backup,File → Restore,Lost work due to system crash,Restore from automatic or manual backups,Backup file locations,Enable automatic backup feature,Data recovery and protection,data_safety +Advanced Features,Parametric Analysis,setup_parametric,.step param R 1k 10k 1k,Need to vary component values,Set up parameter sweep analysis,Parameter ranges and steps,Use .step command for sweeps,Design optimization studies,optimization_analysis +Advanced Features,Monte Carlo Analysis,monte_carlo_setup,.mc 100,Analyze circuit with component tolerances,Set up Monte Carlo statistical analysis,Number of iterations,Define component variations,Statistical design analysis,statistical_modeling +Advanced Features,Worst Case Analysis,worst_case_setup,.wcase,Find worst case circuit performance,Configure worst case analysis parameters,Component tolerance limits,Identify critical components,Robustness analysis,reliability_analysis \ No newline at end of file diff --git a/Backend/helpbot.py b/Backend/helpbot.py new file mode 100644 index 000000000..d091d486f --- /dev/null +++ b/Backend/helpbot.py @@ -0,0 +1,389 @@ +from flask import Flask, request, jsonify, session +from langchain_ollama.llms import OllamaLLM +from langchain_core.prompts import ChatPromptTemplate +from vector import retriever +import uuid +import threading +import time +from datetime import datetime, timedelta +from collections import defaultdict +import secrets + +app = Flask(__name__) +app.secret_key = secrets.token_hex(16) # Generate a secure secret key + +# === Configuration === +SESSION_TIMEOUT = 30 * 60 # 30 minutes in seconds +MAX_HISTORY_PER_USER = 50 # Maximum chat history per user + +# === Thread-safe data structures === +class UserManager: + def __init__(self): + self.lock = threading.RLock() + self.users = {} # user_id -> user_data + self.last_activity = {} # user_id -> timestamp + + def get_or_create_user(self, user_id=None): + with self.lock: + if not user_id: + user_id = str(uuid.uuid4()) + + if user_id not in self.users: + self.users[user_id] = { + 'id': user_id, + 'chat_history': [], + 'created_at': datetime.now(), + 'message_count': 0 + } + print(f"[UserManager] Created new user: {user_id}") + + self.last_activity[user_id] = time.time() + return user_id, self.users[user_id] + + def update_user_activity(self, user_id): + with self.lock: + if user_id in self.users: + self.last_activity[user_id] = time.time() + + def add_to_history(self, user_id, question, response): + with self.lock: + if user_id in self.users: + user_data = self.users[user_id] + user_data['chat_history'].append({ + 'timestamp': datetime.now().isoformat(), + 'question': question, + 'response': response + }) + user_data['message_count'] += 1 + + # Keep only the last MAX_HISTORY_PER_USER messages + if len(user_data['chat_history']) > MAX_HISTORY_PER_USER: + user_data['chat_history'] = user_data['chat_history'][-MAX_HISTORY_PER_USER:] + + def get_user_stats(self, user_id): + with self.lock: + if user_id in self.users: + user_data = self.users[user_id] + return { + 'user_id': user_id, + 'message_count': user_data['message_count'], + 'created_at': user_data['created_at'].isoformat(), + 'last_activity': datetime.fromtimestamp(self.last_activity[user_id]).isoformat(), + 'history_length': len(user_data['chat_history']) + } + return None + + def cleanup_inactive_users(self): + """Remove users who have been inactive for more than SESSION_TIMEOUT""" + current_time = time.time() + with self.lock: + inactive_users = [ + user_id for user_id, last_active in self.last_activity.items() + if current_time - last_active > SESSION_TIMEOUT + ] + + for user_id in inactive_users: + del self.users[user_id] + del self.last_activity[user_id] + print(f"[UserManager] Cleaned up inactive user: {user_id}") + + return len(inactive_users) + + def get_active_users_count(self): + with self.lock: + return len(self.users) + +# === Initialize components === +user_manager = UserManager() + +# Initialize LLM with error handling +try: + model = OllamaLLM(model="qwen2.5-coder:3b") + print("[Server] LLM initialized successfully") +except Exception as e: + print(f"[Server] Error initializing LLM: {e}") + model = None + +# Updated prompt template for better context handling +template = """ +You are a professional electronic engineer and expert assistant specializing in EDA tools including eSim, KiCad, and NgSPICE simulation. + +Use the following knowledge base information to provide accurate and helpful answers: +{context} + +Previous conversation context (if any): +{history} + +Current question: {question} + +Instructions: +- Provide practical, actionable advice +- Include specific commands, syntax, or examples when relevant +- Keep responses concise but comprehensive (maximum 200 words) +- If the question is about debugging, provide step-by-step troubleshooting steps +- Reference specific parameters or options when applicable +- If you're not certain about something, say so clearly + +Answer: +""" + +prompt = ChatPromptTemplate.from_template(template) + +# === Cleanup thread === +def cleanup_thread(): + """Background thread to cleanup inactive users""" + while True: + try: + time.sleep(300) # Run every 5 minutes + cleaned_count = user_manager.cleanup_inactive_users() + if cleaned_count > 0: + print(f"[Cleanup] Removed {cleaned_count} inactive users") + except Exception as e: + print(f"[Cleanup] Error during cleanup: {e}") + +# Start cleanup thread +cleanup_worker = threading.Thread(target=cleanup_thread, daemon=True) +cleanup_worker.start() + +# === API Routes === + +@app.route("/chat", methods=["POST"]) +def chat(): + try: + # Get or create user session + user_id = request.json.get("user_id") or session.get('user_id') + user_id, user_data = user_manager.get_or_create_user(user_id) + session['user_id'] = user_id + + question = request.json.get("prompt", "").strip() + if not question: + return jsonify({"error": "No question provided"}), 400 + + print(f"[API] User {user_id[:8]}... asked: {question}") + + # Check if LLM is available + if model is None: + return jsonify({"error": "LLM not available"}), 503 + + # 1. Retrieve relevant documents + context = "" + try: + docs = retriever.invoke(question) + if isinstance(docs, list) and docs: + # Format context with more structure + context_parts = [] + for i, doc in enumerate(docs[:5], 1): # Limit to top 5 results + if hasattr(doc, 'page_content') and hasattr(doc, 'metadata'): + content = doc.page_content + metadata = doc.metadata + + # Add command information if available + cmd_info = f"[{i}] " + if metadata.get('command'): + cmd_info += f"Command: {metadata['command']} | " + if metadata.get('category'): + cmd_info += f"Category: {metadata['category']} | " + + cmd_info += content + context_parts.append(cmd_info) + + context = "\n\n".join(context_parts) + elif hasattr(docs, "page_content"): + context = docs.page_content + else: + context = str(docs) if docs else "" + + except Exception as e: + print(f"[API] Retriever error for user {user_id[:8]}...: {e}") + context = "" + + # 2. Get recent chat history for context + history = "" + if user_data['chat_history']: + recent_history = user_data['chat_history'][-3:] # Last 3 exchanges + history_parts = [] + for h in recent_history: + history_parts.append(f"Previous Q: {h['question']}") + history_parts.append(f"Previous A: {h['response'][:100]}...") # Truncate long responses + history = "\n".join(history_parts) + + # 3. Run LLM + try: + chain = prompt | model + output = chain.invoke({ + "context": context, + "history": history, + "question": question + }) + response = str(output).strip() + + # Store in user's chat history + user_manager.add_to_history(user_id, question, response) + + return jsonify({ + "response": response, + "user_id": user_id, + "message_count": user_data['message_count'] + 1, + "context_found": bool(context.strip()) + }) + + except Exception as e: + print(f"[API] LLM error for user {user_id[:8]}...: {e}") + return jsonify({"error": f"LLM processing error: {str(e)}"}), 500 + + except Exception as e: + print(f"[API] Unexpected error: {e}") + return jsonify({"error": f"Unexpected error: {str(e)}"}), 500 + +@app.route("/search", methods=["POST"]) +def search_knowledge(): + """Search the knowledge base directly""" + try: + query = request.json.get("query", "").strip() + if not query: + return jsonify({"error": "No search query provided"}), 400 + + # Retrieve relevant documents + docs = retriever.invoke(query) + results = [] + + if isinstance(docs, list): + for doc in docs[:10]: # Return top 10 results + if hasattr(doc, 'page_content') and hasattr(doc, 'metadata'): + results.append({ + "content": doc.page_content, + "metadata": doc.metadata, + "command": doc.metadata.get('command', ''), + "category": doc.metadata.get('category', ''), + "description": doc.metadata.get('description', '') + }) + + return jsonify({ + "query": query, + "results": results, + "count": len(results) + }) + + except Exception as e: + return jsonify({"error": str(e)}), 500 + +@app.route("/new_session", methods=["POST"]) +def new_session(): + """Create a new user session""" + try: + user_id, user_data = user_manager.get_or_create_user() + session['user_id'] = user_id + + return jsonify({ + "user_id": user_id, + "message": "New session created", + "created_at": user_data['created_at'].isoformat() + }) + except Exception as e: + return jsonify({"error": str(e)}), 500 + +@app.route("/history", methods=["GET"]) +def get_history(): + """Get chat history for current user""" + try: + user_id = request.args.get("user_id") or session.get('user_id') + if not user_id: + return jsonify({"error": "No user session found"}), 400 + + user_id, user_data = user_manager.get_or_create_user(user_id) + user_manager.update_user_activity(user_id) + + limit = int(request.args.get("limit", 10)) + history = user_data['chat_history'][-limit:] if limit > 0 else user_data['chat_history'] + + return jsonify({ + "history": history, + "total_messages": user_data['message_count'], + "user_id": user_id + }) + except Exception as e: + return jsonify({"error": str(e)}), 500 + +@app.route("/clear_history", methods=["POST"]) +def clear_history(): + """Clear chat history for current user""" + try: + user_id = request.json.get("user_id") or session.get('user_id') + if not user_id: + return jsonify({"error": "No user session found"}), 400 + + user_id, user_data = user_manager.get_or_create_user(user_id) + user_data['chat_history'] = [] + user_manager.update_user_activity(user_id) + + return jsonify({"message": "History cleared", "user_id": user_id}) + except Exception as e: + return jsonify({"error": str(e)}), 500 + +@app.route("/stats", methods=["GET"]) +def get_stats(): + """Get user statistics""" + try: + user_id = request.args.get("user_id") or session.get('user_id') + if user_id: + user_stats = user_manager.get_user_stats(user_id) + if user_stats: + user_manager.update_user_activity(user_id) + return jsonify(user_stats) + + return jsonify({"error": "User not found"}), 404 + except Exception as e: + return jsonify({"error": str(e)}), 500 + +@app.route("/server_stats", methods=["GET"]) +def get_server_stats(): + """Get server statistics (admin endpoint)""" + try: + return jsonify({ + "active_users": user_manager.get_active_users_count(), + "server_uptime": "Running", + "llm_status": "Available" if model else "Unavailable", + "vector_db_status": "Available" + }) + except Exception as e: + return jsonify({"error": str(e)}), 500 + +@app.route("/health", methods=["GET"]) +def health_check(): + """Health check endpoint""" + return jsonify({ + "status": "healthy", + "timestamp": datetime.now().isoformat(), + "active_users": user_manager.get_active_users_count(), + "components": { + "llm": "Available" if model else "Unavailable", + "vector_db": "Available", + "user_manager": "Available" + } + }) + +# === Error handlers === +@app.errorhandler(404) +def not_found(error): + return jsonify({"error": "Endpoint not found"}), 404 + +@app.errorhandler(500) +def internal_error(error): + return jsonify({"error": "Internal server error"}), 500 + +if __name__ == "__main__": + print("\n" + "="*50) + print("[Server] Starting NgSPICE ChatBot Server...") + print("="*50) + print(f"[Server] Session timeout: {SESSION_TIMEOUT // 60} minutes") + print(f"[Server] Max history per user: {MAX_HISTORY_PER_USER}") + print(f"[Server] LLM Model: {'qwen2.5-coder:3b' if model else 'Not Available'}") + print("="*50) + + # Run with threading support for multiple users + app.run( + host="0.0.0.0", + port=5000, + debug=False, # Set to False for production + threaded=True # Enable threading for concurrent requests + ) \ No newline at end of file diff --git a/Backend/vector.py b/Backend/vector.py new file mode 100644 index 000000000..c1cfe2d4d --- /dev/null +++ b/Backend/vector.py @@ -0,0 +1,115 @@ +from langchain_ollama import OllamaEmbeddings +from langchain_chroma import Chroma +from langchain_core.documents import Document +import os +import pandas as pd + +# Load the CSV data +df = pd.read_csv("esim_help.csv") + +# Initialize embeddings +embeddings = OllamaEmbeddings(model="mxbai-embed-large") + +# Database location +db_location = "./chroma_langchain_db" +add_documents = not os.path.exists(db_location) + +if add_documents: + print("[Vector] Creating new vector database...") + documents = [] + ids = [] + + for i, row in df.iterrows(): + # Handle NaN values by converting to empty strings + command = str(row['command']) if pd.notna(row['command']) else "" + category = str(row['category']) if pd.notna(row['category']) else "" + subcategory = str(row['subcategory']) if pd.notna(row['subcategory']) else "" + syntax = str(row['syntax']) if pd.notna(row['syntax']) else "" + description = str(row['description']) if pd.notna(row['description']) else "" + example = str(row['example']) if pd.notna(row['example']) else "" + parameters = str(row['parameters']) if pd.notna(row['parameters']) else "" + notes = str(row['notes']) if pd.notna(row['notes']) else "" + use_case = str(row['use_case']) if pd.notna(row['use_case']) else "" + related_commands = str(row['related_commands']) if pd.notna(row['related_commands']) else "" + + # Create focused content for better semantic search + page_content_parts = [] + + if command: + page_content_parts.append(f"Command: {command}") + if category: + page_content_parts.append(f"Category: {category}") + if subcategory: + page_content_parts.append(f"Subcategory: {subcategory}") + if description: + page_content_parts.append(f"Description: {description}") + if syntax: + page_content_parts.append(f"Syntax: {syntax}") + if example: + page_content_parts.append(f"Example: {example}") + if use_case: + page_content_parts.append(f"Use case: {use_case}") + if parameters: + page_content_parts.append(f"Parameters: {parameters}") + if notes: + page_content_parts.append(f"Notes: {notes}") + if related_commands: + page_content_parts.append(f"Related commands: {related_commands}") + + page_content = ". ".join(page_content_parts) + + # Comprehensive metadata + metadata = { + "command": command, + "category": category, + "subcategory": subcategory, + "syntax": syntax, + "description": description, + "example": example, + "parameters": parameters, + "notes": notes, + "use_case": use_case, + "related_commands": related_commands, + "row_index": i + } + + document = Document(page_content=page_content, metadata=metadata) + doc_id = f"{command}_{i}" if command else f"doc_{i}" + + ids.append(doc_id) + documents.append(document) + + print(f"[Vector] Created {len(documents)} documents") + +# Initialize vector store +vector_store = Chroma( + collection_name="ngspice_commands_db", + embedding_function=embeddings, + persist_directory=db_location, +) + +if add_documents: + print("[Vector] Adding documents to vector store...") + # Add documents in batches to avoid memory issues + batch_size = 100 + for i in range(0, len(documents), batch_size): + batch_docs = documents[i:i + batch_size] + batch_ids = ids[i:i + batch_size] + vector_store.add_documents(batch_docs, ids=batch_ids) + print(f"[Vector] Added batch {i//batch_size + 1}/{(len(documents) + batch_size - 1)//batch_size}") + + print("[Vector] Persisting vector store...") + vector_store.persist() + print("[Vector] Vector database created successfully!") +else: + print("[Vector] Loading existing vector database...") + +# Create retriever with optimized search parameters +retriever = vector_store.as_retriever( + search_type="similarity", + search_kwargs={ + "k": 5 # Return top 5 most relevant documents + } +) + +print("[Vector] Vector database and retriever initialized successfully!") \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 5ff1f9526..4ccf82a27 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,3 +3,11 @@ flake8==3.7.7 mccabe==0.6.1 pycodestyle==2.5.0 pyflakes==2.1.1 +Flask==3.1.1 +langchain-ollama==0.3.3 +langchain-core==0.3.65 +langchain-chroma==0.2.4 +pandas==2.3.0 +requests==2.32.4 +uuid==1.30 +secrets==1.0.0 diff --git a/resources/esim_faq.csv b/resources/esim_faq.csv new file mode 100644 index 000000000..dea6e7afe --- /dev/null +++ b/resources/esim_faq.csv @@ -0,0 +1,25 @@ +question,answer +"eSim installed successfully, but it's not launching. What should I do?","If eSim is not launching, try running it through the terminal to check for any error messages. Common causes include missing dependencies (like Python, ngspice, or KiCad), incorrect installation paths, or incompatible OS versions. Reinstalling eSim using the official instructions or installing missing dependencies can usually resolve the issue." +"How do I run my first simulation in eSim after installation?","After launching eSim, start a new project. Use KiCad's Eeschema to draw your circuit schematic. Save it, then use eSim's 'Convert KiCad to Ngspice' tool to generate the netlist. Finally, run the simulation using the Ngspice interface provided within eSim. Check outputs in the waveform viewer or log terminal." +"I see an error saying 'Ngspice not found'. How can I fix this?","This error means eSim cannot detect the Ngspice installation. Ensure Ngspice is correctly installed on your system and its path is included in your system environment variables. On Linux, try installing Ngspice via the package manager (e.g., `sudo apt install ngspice`). Restart eSim after making changes." +"How can I check if eSim was installed properly?","You can verify eSim's installation by opening a demo project from the tutorial or documentation and running a basic simulation. Check if all components are visible, netlist generation works, and waveform outputs are displayed without error. This ensures your setup, libraries, and tools like Ngspice and KiCad are working correctly." +"Why are component libraries not showing up in KiCad after installing eSim?","Component libraries may not load due to incorrect library paths. Open KiCad and navigate to Preferences > Manage Symbol Libraries. Ensure that the FOSSEE component libraries are listed and correctly linked to their directory. You can re-run the configuration script provided during eSim setup to auto-link libraries." +"Simulation is not running even after creating the netlist. What could be the issue?","Common reasons include missing power or ground connections, open circuits, unrecognized components, or syntax errors in the schematic. Double-check all component connections and labels. After conversion, open the generated netlist to inspect for any errors or warnings before simulation." +"Where are the eSim project files saved on my system?","By default, eSim saves project files in your home directory under a folder named 'eSim' or 'Projects'. However, during project creation, you can select a custom location. Each project folder contains schematic files, netlists, simulation data, and configuration files necessary for your work." +"How do I update eSim to the latest version?","Visit the official eSim website and download the latest version for your operating system. On Linux systems, you can remove the old version and install the new one using updated shell scripts or `.deb` packages. Make sure to backup your existing project files before updating to prevent data loss." +"I'm getting 'permission denied' errors while running eSim. What should I do?","This usually occurs when eSim is installed in a directory requiring elevated permissions, or when user privileges are insufficient. Avoid running eSim as root. Ensure the install directory and all project files have appropriate read/write permissions for your user account using commands like `chmod` or `chown` on Linux." +"Can I import old KiCad projects into eSim after installation?","Yes. You can import existing KiCad schematics into eSim by creating a new eSim project and selecting the KiCad `.sch` file. Then use the 'Convert KiCad to Ngspice' feature to generate a netlist and simulate your circuit. Ensure your schematic uses supported components and proper wiring conventions." +"How do I configure eSim after installation?","After installation, you may need to configure library paths, simulation settings, and environment variables. Open eSim, go to the preferences/settings menu, and specify paths for KiCad, Ngspice, and user libraries if needed. On Linux, you can also run post-install configuration scripts to automate this setup." +"Is there a sample project I can use to test eSim after installation?","Yes, the eSim website and documentation provide multiple sample projects. These include basic analog and digital circuits that you can open, simulate, and analyze. Running these helps validate that your installation, component libraries, and simulation engine are functioning correctly." +"eSim GUI is slow or unresponsive. How can I fix this?","Performance issues may stem from high system load, insufficient RAM, or GPU driver problems. Close other heavy applications, update your graphics drivers, and ensure your system meets the minimum requirements. On Linux, running eSim on a lightweight desktop environment like XFCE or LXDE can also improve responsiveness." +"How do I uninstall eSim if I face repeated issues?","On Linux, if installed via a `.deb` package, you can uninstall using `sudo apt remove esim`. If installed manually, delete the eSim directory and associated configuration files. For Windows and macOS, use the standard uninstall methods or run the provided uninstaller if available. Always back up projects before uninstalling." +"Can I use eSim offline after installation?","Yes, once installed, eSim works fully offline. All core features like schematic design, simulation, netlist generation, and waveform viewing are available without an internet connection. However, for documentation or community support, you may need internet access occasionally." +"How do I add custom component models to eSim?","To add custom components, place your SPICE model files (.lib or .mod) in the eSim library directory, typically located in the installation folder under 'library/deviceModelLibrary'. Then update the component library in KiCad by editing the symbol libraries and associating your custom symbols with the SPICE models. Restart eSim to recognize new components." +"Why is my simulation taking too long to complete?","Long simulation times can result from small time steps, large simulation duration, or complex circuits with many nodes. Try increasing the time step in simulation parameters, reducing the total simulation time, or simplifying your circuit. For transient analysis, consider using appropriate initial conditions to speed up convergence." +"How do I export simulation results from eSim?","Simulation results can be exported from the waveform viewer by right-clicking on the plot and selecting export options. You can save waveforms as CSV files, images (PNG/SVG), or copy data to clipboard. For batch processing, results are also saved automatically in the project directory as text files." +"What should I do if components are missing from the eSim library?","If required components are missing, you can download additional SPICE models from component manufacturers or online databases. Place these models in the appropriate library folders and create corresponding symbols in KiCad. Alternatively, you can use equivalent components or create subcircuit models using basic elements." +"How do I perform AC analysis in eSim?","For AC analysis, ensure your circuit has an AC voltage source. In the simulation setup, select 'AC Analysis' and specify the frequency range (start, stop) and type (decade, linear, or octave). Set the number of points per decade/octave. After running simulation, view frequency response plots in the waveform viewer to analyze gain, phase, and other AC characteristics." +"Can I simulate digital circuits in eSim?","Yes, eSim supports mixed-signal simulation through Ngspice. You can use digital components from the library or create digital subcircuits. For pure digital simulation, consider using behavioral models or Verilog-A models. Mixed analog-digital circuits require proper interfacing between analog and digital domains using appropriate bridge elements." +"How do I troubleshoot convergence errors in simulation?","Convergence errors often occur due to unrealistic initial conditions, stiff circuits, or inappropriate component values. Try setting initial conditions for capacitors and inductors, use smaller time steps, adjust simulation tolerances in Ngspice options, or add small resistances to floating nodes. Check for feedback loops without proper compensation." +"What file formats does eSim support for import/export?","eSim primarily works with KiCad schematic files (.sch), Ngspice netlists (.cir), and SPICE model files (.lib, .mod). It can export simulation results as CSV, text files, and images. For PCB design, it integrates with KiCad's PCB editor supporting standard formats like Gerber files for manufacturing." +"How do I set up parametric analysis in eSim?","Parametric analysis in eSim allows you to vary the value of a component (like a resistor or voltage source) over a defined range to observe its impact on circuit behavior. To set it up, first create your circuit, then define the parameter using the 'Parameters' option and configure the analysis settings in the simulation control panel." \ No newline at end of file diff --git a/src/browser/UserManual.py b/src/browser/UserManual.py index 4ac78825e..b63778126 100644 --- a/src/browser/UserManual.py +++ b/src/browser/UserManual.py @@ -1,28 +1,710 @@ -from PyQt5 import QtWidgets +import sys +import csv import subprocess import os +import markdown +from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, + QHBoxLayout, QScrollArea, QFrame, QLabel, QPushButton, + QLineEdit, QTextEdit, QSplitter, QMessageBox, QSizePolicy, + QTabWidget, QStyle, QToolButton, QTextBrowser) +from PyQt5.QtCore import Qt, QPropertyAnimation, QEasingCurve, pyqtSignal, QSize, QThread, QUrl +from PyQt5.QtGui import QFont, QPalette, QColor, QIcon +from browser.main import get_bot_response +class ExpandableQAWidget(QFrame): + + + def __init__(self, question, answer, parent=None): + super().__init__(parent) + self.question = question + self.answer = answer + self.is_expanded = False + + self.setFrameStyle(QFrame.NoFrame) + self.setLineWidth(0) + self.setStyleSheet(""" + ExpandableQAWidget { + background-color: transparent; + border: none; + margin: 0px; + padding: 0px; + } + """) + self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum) + self.setup_ui() + self.setup_animation() + + def setup_ui(self): + self.layout = QVBoxLayout(self) + self.layout.setContentsMargins(0, 0, 0, 12) # More bottom margin for spacing + self.layout.setSpacing(0) + + # Main container for visuals, to handle border and background + self.container = QFrame() + self.container.setObjectName("container") + self.container.setFrameStyle(QFrame.Box | QFrame.Plain) + self.container.setLineWidth(1) + self.container.setStyleSheet(""" + #container { + background-color: #f9f9f9; + border: 1.5px solid #d0d0d0; + border-radius: 10px; + margin: 0px; + padding: 0px; + } + """) -class UserManual(QtWidgets.QWidget): - """ - This class opens User-Manual page in new tab of web browser - when help button is clicked. - """ + container_layout = QVBoxLayout(self.container) + container_layout.setContentsMargins(8, 18, 16, 18) # Add left/right margin for arrow + container_layout.setSpacing(8) + + # Question section (always visible) + self.question_widget = QWidget() + question_layout = QHBoxLayout(self.question_widget) + question_layout.setContentsMargins(0, 0, 12, 0) # Add more right margin for arrow + question_layout.setSpacing(12) + + # Question label + self.question_label = QLabel(self.question) + self.question_label.setWordWrap(True) + self.question_label.setFont(QFont("Segoe UI", 11, QFont.Bold)) + self.question_label.setStyleSheet("color: #2c3e50; background-color: transparent; border: none; padding: 8px 0px 8px 0px;") + self.question_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) + self.question_label.setMinimumWidth(0) + self.question_label.setMaximumWidth(10000) + + # Expand/collapse indicator (modern arrow) + self.indicator = QLabel() + self.indicator.setFont(QFont("Arial", 18, QFont.Bold)) + self.indicator.setText("▶") + self.indicator.setStyleSheet("color: #4a90e2; background-color: transparent; border: none; margin-right: 4px;") + self.indicator.setFixedWidth(28) + self.indicator.setFixedHeight(28) + self.indicator.setAlignment(Qt.AlignCenter) + + question_layout.addWidget(self.question_label, 1) + question_layout.addWidget(self.indicator, 0, Qt.AlignVCenter) + + container_layout.addWidget(self.question_widget) + + # Answer section (initially hidden and animated) + self.answer_widget = QWidget() + self.answer_widget.setVisible(False) + self.answer_widget.setStyleSheet("background-color: transparent; border: none;") + + answer_layout = QVBoxLayout(self.answer_widget) + answer_layout.setContentsMargins(0, 10, 0, 0) + answer_layout.setSpacing(8) + + # Separator line + separator = QFrame() + separator.setFrameShape(QFrame.HLine) + separator.setStyleSheet("background-color: #e0e0e0;") + separator.setFixedHeight(1) + answer_layout.addWidget(separator) + + # Answer label + self.answer_label = QLabel(self.answer) + self.answer_label.setWordWrap(True) + self.answer_label.setFont(QFont("Segoe UI", 10)) + self.answer_label.setStyleSheet("color: #34495e; padding: 6px 0px 6px 0px; line-height: 1.6; background-color: transparent; border: none;") + self.answer_label.setOpenExternalLinks(True) + self.answer_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) + self.answer_label.setMinimumWidth(0) + self.answer_label.setMaximumWidth(10000) + answer_layout.addWidget(self.answer_label) + + container_layout.addWidget(self.answer_widget) + self.layout.addWidget(self.container) + + def setup_animation(self): + self.answer_widget.setMaximumHeight(0) + self.animation = QPropertyAnimation(self.answer_widget, b"maximumHeight") + self.animation.setDuration(250) + self.animation.setEasingCurve(QEasingCurve.InOutCubic) - def __init__(self): - QtWidgets.QWidget.__init__(self) + def enterEvent(self, event): + self.container.setStyleSheet(self.container.styleSheet() + "\n#container { border-color: #357abd; }") + super().enterEvent(event) + def leaveEvent(self, event): + self.container.setStyleSheet(""" + #container { + background-color: #f9f9f9; + border: 1.5px solid #d0d0d0; + border-radius: 10px; + margin: 0px; + padding: 0px; + } + """) + super().leaveEvent(event) - self.vlayout = QtWidgets.QVBoxLayout() + def mousePressEvent(self, event): + if event.button() == Qt.LeftButton: + self.toggle_expansion() + super().mousePressEvent(event) + + def toggle_expansion(self): + self.is_expanded = not self.is_expanded + start_height = self.answer_widget.maximumHeight() + if self.is_expanded: + self.indicator.setText("▼") + self.container.setStyleSheet(self.container.styleSheet() + "\n#container { background-color: #f3f7fa; border-color: #4a90e2; }") + self.answer_widget.setVisible(True) + end_height = self.answer_widget.sizeHint().height() + else: + self.indicator.setText("▶") + self.container.setStyleSheet(""" + #container { + background-color: #f9f9f9; + border: 1.5px solid #d0d0d0; + border-radius: 10px; + margin: 0px; + padding: 0px; + } + """) + end_height = 0 + self.animation.setStartValue(start_height) + self.animation.setEndValue(end_height) + self.animation.start() - manual = 'library/browser/User-Manual/eSim_Manual_2.4.pdf' +class BotWorker(QThread): + finished = pyqtSignal(str) + def __init__(self, prompt, parent=None): + super().__init__(parent) + self.prompt = prompt + def run(self): + try: + response = get_bot_response(self.prompt) + except Exception as e: + response = "I apologize, but I encountered an error while processing your request. Please try again." + self.finished.emit(response) + +class ChatBotWidget(QWidget): + """Simple chatbot interface widget with eSIM app theme, now with async/markdown/timestamp features and backend integration""" + def __init__(self, parent=None): + super().__init__(parent) + self.setup_ui() + self.show_welcome_message() + self.typing_label = None + self.worker = None + self.thread = None + self.typing_message = None + + def setup_ui(self): + self.setStyleSheet("background-color: #f8f9fa;") + layout = QVBoxLayout(self) + layout.setContentsMargins(10, 10, 10, 10) + layout.setSpacing(10) + # Chat header + header = QLabel("💬 Support Chat") + header.setFont(QFont("Segoe UI", 10, QFont.Bold)) + header.setStyleSheet(""" + color: #2c3e50; + padding: 8px; + background-color: #ecf0f1; + border: 1px solid #bdc3c7; + border-radius: 4px; + border-bottom-left-radius: 0px; + border-bottom-right-radius: 0px; + """) + layout.addWidget(header) + # Chat display area + self.chat_display = QTextEdit() + self.chat_display.setReadOnly(True) + self.chat_display.setFont(QFont("Segoe UI", 9)) + self.chat_display.setStyleSheet(""" + QTextEdit { + border: 1px solid #bdc3c7; + border-top: none; + border-radius: 0px; + padding: 8px; + background-color: #ffffff; + } + """) + layout.addWidget(self.chat_display) + # Input area + input_layout = QHBoxLayout() + input_layout.setSpacing(5) + self.message_input = QLineEdit() + self.message_input.setPlaceholderText("Type your message here...") + self.message_input.setFont(QFont("Segoe UI", 9)) + self.message_input.setStyleSheet(""" + QLineEdit { + border: 1px solid #bdc3c7; + border-radius: 4px; + padding: 8px; + } + QLineEdit:focus { + border-color: #4a90e2; + } + """) + self.message_input.returnPressed.connect(self.send_message) + self.send_button = QPushButton("Send") + self.send_button.setFont(QFont("Segoe UI", 9, QFont.Bold)) + self.send_button.setStyleSheet(""" + QPushButton { + background-color: #4a90e2; + color: white; + border: none; + border-radius: 4px; + padding: 8px 16px; + } + QPushButton:hover { + background-color: #357abd; + } + QPushButton:pressed { + background-color: #2968a3; + } + """) + self.send_button.clicked.connect(self.send_message) + input_layout.addWidget(self.message_input) + input_layout.addWidget(self.send_button) + layout.addLayout(input_layout) + layout.setStretchFactor(self.chat_display, 1) + + def show_welcome_message(self): + welcome_text = ("👋 Welcome to the eSIM Assistant!

" + "I'm here to help you with all your eSIM-related questions and tasks. " + "Whether you're activating, troubleshooting, or just curious—I've got you covered!") + self.append_bot_message(welcome_text, is_welcome=True) + + def send_message(self): + text = self.message_input.text().strip() + if not text: + return + self.send_button.setEnabled(False) + self.message_input.setEnabled(False) + self.append_user_message(text) + self.message_input.clear() + self.show_typing_indicator() + # Start worker thread for bot response + self.worker = BotWorker(text) + self.worker.finished.connect(self.on_bot_response) + self.worker.start() - if os.name == 'nt': - os.startfile(os.path.realpath(manual)) + def show_typing_indicator(self): + # Remove any existing typing indicator before adding a new one + self.remove_typing_indicator() + if self.typing_message is None: + # Use a unique HTML id for the typing indicator + self.typing_message = QLabel('eSIM Support is typing...') + self.typing_message.setStyleSheet("color: #4a90e2; font-style: italic; font-size: 15px; padding: 8px 0px 8px 0px;") + self.chat_display.append("") + self.chat_display.insertHtml(self.typing_message.text()) + self.chat_display.append("") + self.scroll_to_bottom() + + def remove_typing_indicator(self): + # Remove the typing message from the chat area using the unique HTML id + if self.typing_message is not None: + html = self.chat_display.toHtml() + html = html.replace('eSIM Support is typing...', "") + html = html.replace('eSIM Support is typing...', "") + self.chat_display.setHtml(html) + self.typing_message = None + + def on_bot_response(self, response): + self.remove_typing_indicator() + if response.strip().lower().startswith('error:'): + # Show error in red + html = f'Error: {response[6:].strip()}' + self.append_bot_message(html) + else: + html = markdown.markdown(response) + self.append_bot_message(html) + self.send_button.setEnabled(True) + self.message_input.setEnabled(True) + self.message_input.setFocus() + + def append_user_message(self, text): + timestamp = self.get_timestamp() + html = f'
You: {text}
{timestamp}
' + self.chat_display.append(html) + self.scroll_to_bottom() + + def append_bot_message(self, text, is_welcome=False): + timestamp = self.get_timestamp() + if not is_welcome: + html = f'
eSIM Support: {text}
{timestamp}
' else: - manual_path = '../../' + manual - subprocess.Popen( - ['xdg-open', os.path.realpath(manual_path)], shell=False - ) + html = f'
{text}
' + self.chat_display.append(html) + self.scroll_to_bottom() + + def scroll_to_bottom(self): + scrollbar = self.chat_display.verticalScrollBar() + scrollbar.setValue(scrollbar.maximum()) + + def get_timestamp(self): + from datetime import datetime + return datetime.now().strftime("%H:%M") + +class PDFManualWidget(QWidget): + """Widget to display the eSim.html manual only""" + + def __init__(self, parent=None): + super().__init__(parent) + self.setup_ui() + + def setup_ui(self): + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(0) + + # Add maximize button + maximize_btn = QPushButton("Open in New Window") + maximize_btn.setFixedWidth(160) + maximize_btn.clicked.connect(self.open_in_new_window) + layout.addWidget(maximize_btn, alignment=Qt.AlignRight) + # Manual Viewer ONLY + self.manual_viewer = QTextBrowser() + manual_path = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../../library/browser/User-Manual/eSim.html') + ) + if os.path.exists(manual_path): + self.manual_viewer.setSource(QUrl.fromLocalFile(manual_path)) + else: + self.manual_viewer.setHtml("

eSim.html file not found.

") + self.manual_viewer.setOpenExternalLinks(True) + layout.addWidget(self.manual_viewer, stretch=1) + + def open_in_new_window(self): + self.new_window = QMainWindow(self) + self.new_window.setWindowTitle("eSim User Manual") + viewer = QTextBrowser() + manual_path = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../../library/browser/User-Manual/eSim.html') + ) + if os.path.exists(manual_path): + viewer.setSource(QUrl.fromLocalFile(manual_path)) + else: + viewer.setHtml("

eSim.html file not found.

") + viewer.setOpenExternalLinks(True) + self.new_window.setCentralWidget(viewer) + self.new_window.resize(900, 700) + self.new_window.show() + +class FosseHelpWidget(QWidget): + """Main Help widget with FAQ section (FAQ search bar small and in header row, no icon)""" + + def __init__(self, parent=None): + super().__init__(parent) + self.qa_data = [] + self.setup_ui() + self.load_faq_from_csv() + + def setup_ui(self): + # Set widget background to match eSIM app theme + self.setStyleSheet(""" + FosseHelpWidget { + background-color: #f8f9fa; + } + """) + # Main layout + main_layout = QVBoxLayout(self) + main_layout.setContentsMargins(0, 0, 0, 0) + main_layout.setSpacing(0) + # FAQ Section + faq_widget = self.create_faq_section() + main_layout.addWidget(faq_widget) + main_layout.addStretch() + def create_faq_section(self): + """Create the FAQ section with scrollable Q&A widgets (search bar in header, small, no icon)""" + faq_widget = QWidget() + faq_layout = QVBoxLayout(faq_widget) + faq_layout.setContentsMargins(0, 0, 0, 0) + faq_layout.setSpacing(0) + # FAQ Header Row (label + small search bar at end) + header_row = QHBoxLayout() + header_row.setContentsMargins(24, 24, 24, 0) + header_row.setSpacing(8) + faq_header = QLabel("\ud83d\udccb Frequently Asked Questions") + faq_header.setFont(QFont("Segoe UI", 16, QFont.Bold)) + faq_header.setStyleSheet("color: #2c3e50;") + header_row.addWidget(faq_header) + header_row.addStretch() + # Small search bar + self.search_bar = QLineEdit() + self.search_bar.setPlaceholderText("Search FAQs...") + self.search_bar.setFont(QFont("Segoe UI", 9)) + self.search_bar.setFixedWidth(160) + self.search_bar.setFixedHeight(26) + self.search_bar.setStyleSheet(""" + QLineEdit { + border: 1.2px solid #e6e6e6; + border-radius: 13px; + padding: 2px 10px; + background-color: #ffffff; + font-size: 13px; + } + QLineEdit:focus { + border-color: #4a90e2; + background-color: #f8faff; + } + """) + self.search_bar.textChanged.connect(self.filter_faqs) + header_row.addWidget(self.search_bar, 0, Qt.AlignVCenter) + faq_layout.addLayout(header_row) + # Divider + divider = QFrame() + divider.setFrameShape(QFrame.HLine) + divider.setStyleSheet("background-color: #e6e6e6;") + divider.setFixedHeight(2) + faq_layout.addWidget(divider) + # Scroll area for Q&A widgets + self.scroll_area = QScrollArea() + self.scroll_area.setWidgetResizable(True) + self.scroll_area.setStyleSheet(""" + QScrollArea { + border: none; + background-color: transparent; + } + QScrollBar:vertical { + border: none; + background: #e0e0e0; + width: 10px; + margin: 0px 0px 0px 0px; + border-radius: 5px; + } + QScrollBar::handle:vertical { + background: #bdc3c7; + min-height: 25px; + border-radius: 5px; + } + QScrollBar::handle:vertical:hover { + background: #95a5a6; + } + QScrollBar::handle:vertical:pressed { + background: none; + } + """) + # Container widget for Q&A items + self.qa_container = QWidget() + self.qa_container.setStyleSheet("background-color: transparent;") + self.qa_layout = QVBoxLayout(self.qa_container) + self.qa_layout.setSpacing(0) + self.qa_layout.setContentsMargins(24, 0, 24, 24) + self.qa_layout.addStretch() # Add stretch to push items to top + self.scroll_area.setWidget(self.qa_container) + faq_layout.addWidget(self.scroll_area) + return faq_widget + + def load_faq_from_csv(self): + """Automatically load FAQ data from CSV file""" + csv_filename = "resources/esim_faq_new.csv" + + try: + with open(csv_filename, 'r', encoding='utf-8', newline='') as csvfile: + # Use csv.Sniffer to detect delimiter + sample = csvfile.read(1024) + csvfile.seek(0) + + sniffer = csv.Sniffer() + try: + delimiter = sniffer.sniff(sample).delimiter + except: + delimiter = ',' # Default to comma + + reader = csv.reader(csvfile, delimiter=delimiter) + + # Skip header row if it exists + first_row = next(reader, None) + if first_row and (first_row[0].lower() in ['question', 'q'] or 'question' in first_row[0].lower()): + pass # Skip header + else: + # First row is data, add it back + if first_row and len(first_row) >= 2: + self.qa_data.append((first_row[0], first_row[1])) + + # Read the rest of the data + for row in reader: + if len(row) >= 2 and row[0].strip() and row[1].strip(): + self.qa_data.append((row[0].strip(), row[1].strip())) + + if self.qa_data: + self.populate_qa_widgets() + else: + self.load_default_esim_faq() + + except FileNotFoundError: + print(f"CSV file '{csv_filename}' not found. Loading default eSIM FAQ data.") + self.load_default_esim_faq() + except Exception as e: + print(f"Error loading CSV file: {str(e)}. Loading default eSIM FAQ data.") + self.load_default_esim_faq() + + def load_default_esim_faq(self): + """Load default eSIM FAQ data""" + esim_faq_data = [ + ("How do I activate my eSIM?", "Open the eSIM app → 'My Plans' → 'Activate New Plan' → Scan QR code from your purchase email → Follow setup instructions. Your eSIM will be active within minutes."), + + ("Which devices work with eSIM?", "Compatible devices: iPhone XS/XR and newer, iPad Pro (3rd gen+), iPad Air (3rd gen+), iPad mini (5th gen+), Google Pixel 3+, Samsung Galaxy S20+, and most recent Android devices with eSIM support."), + + ("How many countries does eSIM cover?", "eSIM provides coverage in 200+ countries worldwide including Europe, Asia, Americas, Africa, and Oceania. Check specific coverage in the app's 'Browse Plans' section."), + + ("What data plans are available?", "Flexible plans available: Daily (100MB-1GB), Weekly (1GB-10GB), Monthly (3GB-50GB), Regional multi-country plans. Starting from $3 with no hidden fees."), + + ("How do I check my data usage?", "Open eSIM app → Main dashboard shows current usage under 'Usage Overview' → 'My Plans' section displays remaining data, plan expiry, and usage history."), + + ("Can I use eSIM with my regular SIM?", "Yes! eSIM works alongside your physical SIM card. Use dual SIM functionality - keep your home SIM for calls/texts and eSIM for data while traveling."), + + ("My eSIM won't connect. What should I do?", "Troubleshooting: 1) Check device compatibility 2) Verify coverage area 3) Restart device 4) Toggle airplane mode 5) Enable eSIM in Settings → Cellular 6) Contact 24/7 support if issues persist."), + + ("How do I add more data to my plan?", "In eSIM app: 'My Plans' → Select active plan → 'Top Up' or 'Extend Plan' → Choose additional data/time → Complete payment. Updates immediately without new QR code."), + + ("What is the refund policy?", "30-day money-back guarantee for unused plans. Full refund available if you haven't activated your plan or used less than 10MB of data. Contact support for refund requests."), + + ("How do I contact support?", "Multiple support channels: 1) In-app chat (24/7) 2) Email: support@esim.com 3) App help center 4) Website live chat. Multilingual support with 2-4 hour response time."), + ] + + self.qa_data = esim_faq_data + self.populate_qa_widgets() + + def populate_qa_widgets(self): + """Create and add Q&A widgets to the scroll area""" + # Clear existing widgets except the stretch + while self.qa_layout.count() > 1: + child = self.qa_layout.takeAt(0) + if child.widget(): + child.widget().deleteLater() + + # Add new Q&A widgets + for question, answer in self.qa_data: + qa_widget = ExpandableQAWidget(question, answer) + self.qa_layout.insertWidget(self.qa_layout.count() - 1, qa_widget) # Insert before stretch + + def filter_faqs(self): + """Filter the displayed FAQs based on the search bar text. Show 'No FAQs found.' if nothing matches.""" + search_text = self.search_bar.text().lower().strip() + found = False + # The last item is a spacer/stretch, so we iterate up to count - 1 + for i in range(self.qa_layout.count() - 1): + item = self.qa_layout.itemAt(i) + qa_widget = item.widget() + if isinstance(qa_widget, ExpandableQAWidget): + question = qa_widget.question.lower() + answer = qa_widget.answer.lower() + if search_text in question or search_text in answer: + qa_widget.setVisible(True) + found = True + else: + qa_widget.setVisible(False) + # Remove any previous 'not found' label + if hasattr(self, '_not_found_label') and self._not_found_label: + self.qa_layout.removeWidget(self._not_found_label) + self._not_found_label.deleteLater() + self._not_found_label = None + # If nothing found, show a message + if not found: + self._not_found_label = QLabel("No FAQs found.") + self._not_found_label.setStyleSheet("color: #888; font-size: 13px; padding: 24px 0px;") + self._not_found_label.setAlignment(Qt.AlignCenter) + self.qa_layout.insertWidget(self.qa_layout.count() - 1, self._not_found_label) + else: + self._not_found_label = None + +class UserManual(QWidget): + """ + Enhanced User Manual class that combines the original PDF opening functionality + with the comprehensive help GUI system + """ + + def __init__(self): + super().__init__() + self.setup_ui() + + # Maintain compatibility with original class behavior + # Auto-open PDF if needed (comment out if not desired) + # self.open_pdf_manual() + + def setup_ui(self): + """Setup the main UI with tabs for different help sections""" + self.vlayout = QVBoxLayout() + self.vlayout.setContentsMargins(0, 0, 0, 0) + + # Create tab widget + self.tab_widget = QTabWidget() + self.tab_widget.setIconSize(QSize(20, 20)) + self.tab_widget.setStyleSheet(""" + QTabWidget::pane { + border-top: 1px solid #bdc3c7; + background-color: #f8f9fa; + } + """) + + # Tab 1: FAQ + help_widget = FosseHelpWidget() + faq_icon = self.style().standardIcon(QStyle.SP_MessageBoxQuestion) + self.tab_widget.addTab(help_widget, faq_icon, "FAQ") + + # Tab 2: PDF Manual + pdf_widget = PDFManualWidget() + pdf_icon = self.style().standardIcon(QStyle.SP_FileIcon) + self.tab_widget.addTab(pdf_widget, pdf_icon, "User Manual (PDF)") + + # Tab 3: Support Chat + chat_widget = ChatBotWidget() + chat_icon = self.style().standardIcon(QStyle.SP_MessageBoxInformation) + self.tab_widget.addTab(chat_widget, chat_icon, "Support Chat") + + self.vlayout.addWidget(self.tab_widget) self.setLayout(self.vlayout) - self.show() + + def open_pdf_manual(self): + """Original PDF opening functionality""" + manual = 'library/browser/User-Manual/eSim_Manual_2.4.pdf' + + try: + if os.name == 'nt': + os.startfile(os.path.realpath(manual)) + else: + manual_path = '../../' + manual + subprocess.Popen( + ['xdg-open', os.path.realpath(manual_path)], shell=False + ) + except Exception as e: + print(f"Error opening PDF manual: {str(e)}") + +class HelpSectionGUI(QMainWindow): + """Standalone Help section GUI for testing""" + + def __init__(self): + super().__init__() + self.setup_ui() + + def setup_ui(self): + self.setWindowTitle("eSIM Help Center") + self.setGeometry(100, 100, 700, 600) + + # Set application style to match eSIM app + self.setStyleSheet(""" + QMainWindow { + background-color: #f8f9fa; + } + """) + + # Use the enhanced UserManual widget as central widget + user_manual = UserManual() + self.setCentralWidget(user_manual) + +def main(): + app = QApplication(sys.argv) + + # Set application style + app.setStyle('Fusion') + + # Create and show the standalone window for testing + window = HelpSectionGUI() + window.show() + + sys.exit(app.exec_()) + +# Integration instructions: +# 1. Replace your existing UserManual class with this enhanced version +# 2. It maintains the same interface: UserManual() creates the widget +# 3. The widget now includes both FAQ/Chat and PDF manual functionality +# 4. You can still call open_pdf_manual() method directly if needed + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/src/browser/main.py b/src/browser/main.py new file mode 100644 index 000000000..2efe51bad --- /dev/null +++ b/src/browser/main.py @@ -0,0 +1,9 @@ +import requests + +# Note: The URL "http://192.168.243.207:5000/chat" will be updated based on the hosting server's provided link. +def get_bot_response(prompt: str) -> str: + try: + res = requests.post("http://192.168.243.207:5000/chat", json={"prompt": prompt}) + return res.json().get("response", "No response") + except Exception as e: + return f"Error: {str(e)}" diff --git a/src/frontEnd/DockArea.py b/src/frontEnd/DockArea.py index 7f7116465..2283144a0 100755 --- a/src/frontEnd/DockArea.py +++ b/src/frontEnd/DockArea.py @@ -495,32 +495,35 @@ def makerchip(self): count = count + 1 def usermanual(self): - """This function creates a widget for user manual.""" - global count + dock_name = 'Help Section' + + # If the dock already exists, bring it to the front + if dock_name in dock and dock[dock_name].isVisible(): + dock[dock_name].setFocus() + dock[dock_name].raise_() + return + self.usermanualWidget = QtWidgets.QWidget() self.usermanualLayout = QtWidgets.QVBoxLayout() self.usermanualLayout.addWidget(UserManual()) self.usermanualWidget.setLayout(self.usermanualLayout) - dock['User Manual-' + - str(count)] = QtWidgets.QDockWidget('User Manual-' + str(count)) - dock['User Manual-' + str(count)].setWidget(self.usermanualWidget) + dock[dock_name] = QtWidgets.QDockWidget(dock_name) + dock[dock_name].setWidget(self.usermanualWidget) self.addDockWidget(QtCore.Qt.TopDockWidgetArea, - dock['User Manual-' + str(count)]) + dock[dock_name]) self.tabifyDockWidget(dock['Welcome'], - dock['User Manual-' + str(count)]) + dock[dock_name]) # CSS - dock['User Manual-' + str(count)].setStyleSheet(" \ + dock[dock_name].setStyleSheet(" \ .QWidget { border-radius: 15px; border: 1px solid gray;\ padding: 5px; width: 200px; height: 150px; } \ ") - dock['User Manual-' + str(count)].setVisible(True) - dock['User Manual-' + str(count)].setFocus() - dock['User Manual-' + str(count)].raise_() - - count = count + 1 + dock[dock_name].setVisible(True) + dock[dock_name].setFocus() + dock[dock_name].raise_() def modelicaEditor(self, projDir): """This function sets up the UI for ngspice to modelica conversion.""" From 644943396f1b222751a864c65a9d9a92fe3f3d30 Mon Sep 17 00:00:00 2001 From: Rudra mani upadhyay <145674918+Rudramani1@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:26:07 +0530 Subject: [PATCH 2/3] Update UserManual.py --- src/browser/UserManual.py | 24 ++---------------------- 1 file changed, 2 insertions(+), 22 deletions(-) diff --git a/src/browser/UserManual.py b/src/browser/UserManual.py index b63778126..1381900f0 100644 --- a/src/browser/UserManual.py +++ b/src/browser/UserManual.py @@ -536,27 +536,7 @@ def load_faq_from_csv(self): def load_default_esim_faq(self): """Load default eSIM FAQ data""" - esim_faq_data = [ - ("How do I activate my eSIM?", "Open the eSIM app → 'My Plans' → 'Activate New Plan' → Scan QR code from your purchase email → Follow setup instructions. Your eSIM will be active within minutes."), - - ("Which devices work with eSIM?", "Compatible devices: iPhone XS/XR and newer, iPad Pro (3rd gen+), iPad Air (3rd gen+), iPad mini (5th gen+), Google Pixel 3+, Samsung Galaxy S20+, and most recent Android devices with eSIM support."), - - ("How many countries does eSIM cover?", "eSIM provides coverage in 200+ countries worldwide including Europe, Asia, Americas, Africa, and Oceania. Check specific coverage in the app's 'Browse Plans' section."), - - ("What data plans are available?", "Flexible plans available: Daily (100MB-1GB), Weekly (1GB-10GB), Monthly (3GB-50GB), Regional multi-country plans. Starting from $3 with no hidden fees."), - - ("How do I check my data usage?", "Open eSIM app → Main dashboard shows current usage under 'Usage Overview' → 'My Plans' section displays remaining data, plan expiry, and usage history."), - - ("Can I use eSIM with my regular SIM?", "Yes! eSIM works alongside your physical SIM card. Use dual SIM functionality - keep your home SIM for calls/texts and eSIM for data while traveling."), - - ("My eSIM won't connect. What should I do?", "Troubleshooting: 1) Check device compatibility 2) Verify coverage area 3) Restart device 4) Toggle airplane mode 5) Enable eSIM in Settings → Cellular 6) Contact 24/7 support if issues persist."), - - ("How do I add more data to my plan?", "In eSIM app: 'My Plans' → Select active plan → 'Top Up' or 'Extend Plan' → Choose additional data/time → Complete payment. Updates immediately without new QR code."), - - ("What is the refund policy?", "30-day money-back guarantee for unused plans. Full refund available if you haven't activated your plan or used less than 10MB of data. Contact support for refund requests."), - - ("How do I contact support?", "Multiple support channels: 1) In-app chat (24/7) 2) Email: support@esim.com 3) App help center 4) Website live chat. Multilingual support with 2-4 hour response time."), - ] + esim_faq_data = [] self.qa_data = esim_faq_data self.populate_qa_widgets() @@ -707,4 +687,4 @@ def main(): # 4. You can still call open_pdf_manual() method directly if needed if __name__ == '__main__': - main() \ No newline at end of file + main() From 9b66622971562a6033a7fad9c2c34fdeef9b3c78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C2=A8rudramani1=C2=A8?= Date: Mon, 21 Jul 2025 13:39:06 +0530 Subject: [PATCH 3/3] Updated DockArea.py and requirements.txt and added Helpsection --- Backend/esim_help.csv | 85 ----- Backend/helpbot.py | 389 --------------------- resources/esim_help.csv | 322 +++++++++++++++++ src/{browser => Helpsection}/UserManual.py | 4 +- src/Helpsection/local_bot.py | 65 ++++ {Backend => src/Helpsection}/vector.py | 2 +- src/browser/main.py | 9 - src/frontEnd/DockArea.py | 2 +- 8 files changed, 391 insertions(+), 487 deletions(-) delete mode 100644 Backend/esim_help.csv delete mode 100644 Backend/helpbot.py create mode 100644 resources/esim_help.csv rename src/{browser => Helpsection}/UserManual.py (99%) create mode 100644 src/Helpsection/local_bot.py rename {Backend => src/Helpsection}/vector.py (98%) delete mode 100644 src/browser/main.py diff --git a/Backend/esim_help.csv b/Backend/esim_help.csv deleted file mode 100644 index a37840b33..000000000 --- a/Backend/esim_help.csv +++ /dev/null @@ -1,85 +0,0 @@ -category,subcategory,command,syntax,description,example,parameters,notes,use_case,related_commands -Overview,About eSIM,N/A,N/A,"eSIM is a virtual electronics simulator developed by FOSSEE (IIT Bombay) for learning circuit design and simulation. It uses Ngspice for backend simulation and runs in a browser.","Simulate a common emitter amplifier using Ngspice and visualize output graph.","Circuit file, type of analysis (AC, DC, Transient)","Requires modern browser, designed for academic purposes.","Education, training, virtual labs in electronics and communication engineering.",".tran, .ac, run, plot, .print, .measure" -Installation Issues,Dependencies Missing,install_dependencies,sudo apt-get install dependencies,KiCad or Ngspice dependencies not installed properly,sudo apt-get install kicad ngspice,Package names for Ubuntu,Check system requirements before installation,Fresh installation on Ubuntu,verify_installation -Installation Issues,Permission Errors,fix_permissions,sudo chmod +x install_script,Installation fails due to insufficient permissions,sudo chmod +x eSim-2.3.run,Executable file path,Run as administrator on Windows,Installation script won't execute,installation_troubleshooting -Installation Issues,Path Issues,set_path,export PATH=$PATH:/opt/eSim,eSim commands not found in terminal,export PATH=$PATH:/opt/eSim-2.3/bin,Correct eSim installation directory,Add to .bashrc for permanent fix,Command not found errors,environment_setup -Installation Issues,Version Conflicts,version_check,esim --version,Conflicting versions of dependencies installed,Check KiCad version compatibility,Version numbers,Uninstall old versions first,Multiple eSim versions installed,uninstall_old -Installation Issues,Browser Compatibility,check_browser,Open supported browser,eSIM not loading properly in browser,Use Chrome Firefox or Safari latest versions,Modern browser required,Disable ad blockers for eSIM,Web interface not working,browser_setup -Installation Issues,Python Dependencies,install_python_deps,pip install PyQt5 matplotlib numpy,Python or PyQt5 dependencies missing,pip install PyQt5 matplotlib numpy scipy,Python package requirements,Use pip3 for Python3 installations,GUI not loading or plotting issues,python_setup -Simulation Errors,Netlist Generation Failed,check_netlist,Tools → Generate Netlist,Schematic cannot be converted to SPICE netlist,Missing ground connection in circuit,Proper component labeling required,All components must have SPICE models,Netlist conversion errors,add_spice_models -Simulation Errors,Convergence Problems,convergence_fix,.options gmin=1e-12,Simulation fails to converge,".options gmin=1e-12 abstol=1e-12",Tolerance parameters,Adjust simulation options,Large circuits or nonlinear elements,simulation_options -Simulation Errors,Model Not Found,add_model,Model Editor → Import,Component SPICE model missing from library,Import transistor.lib to model library,Model file path,Check model syntax,Custom components not simulating,model_library -Simulation Errors,Syntax Errors,fix_syntax,Edit netlist manually,SPICE syntax errors in netlist,Fix ".model" statement format,Proper SPICE syntax,Use Model Editor for validation,Simulation won't start,netlist_debug -Simulation Errors,Timeout Errors,adjust_timeout,Set simulation timeout,Simulation runs too long and times out,Increase timeout limit in settings,Time limit in seconds,Reduce circuit complexity if needed,Long running simulations,simulation_settings -Simulation Errors,Memory Overflow,reduce_complexity,Simplify circuit design,Simulation exceeds available memory,Break large circuit into smaller blocks,Available system memory,Close other browser tabs,Very large circuits,memory_management -Simulation Errors,Division by Zero,check_parameters,Verify component values,Mathematical error in simulation,Ensure no zero-value resistors or capacitors,Component parameter validation,Use realistic component values,Parameter validation errors,component_check -Schematic Issues,Component Not Found,add_component_library,Library → Add,Required component missing from library,Add custom component library,Library file path,Install additional KiCad libraries,Missing components in palette,library_manager -Schematic Issues,ERC Violations,run_erc,Tools → ERC,Electrical Rule Check failures,Unconnected pins or power issues,Design rule settings,Fix all ERC errors before simulation,Schematic validation fails,design_rules -Schematic Issues,Pin Connection Errors,fix_connections,Manual wire placement,Components not properly connected,Add junction dots at wire intersections,Proper wire routing,Check for floating nodes,Connectivity issues,wire_connections -Schematic Issues,Label Issues,fix_labels,Edit component properties,Component reference designators missing,Set R1 R2 for resistors V1 for voltage source,Unique component names,Sequential numbering required,Duplicate component names,component_properties -Schematic Issues,Wire Crossing Problems,fix_wire_crossing,Use junction dots,Ambiguous wire connections at crossings,Add junction dots where wires should connect,Visual connection indicators,Avoid T-junctions without dots,Connection ambiguity,wire_management -Schematic Issues,Component Rotation,rotate_component,Right-click → Rotate,Component orientation incorrect,Rotate component to proper orientation,90-degree increments,Use R key for quick rotation,Schematic readability,component_placement -Schematic Issues,Grid Alignment,snap_to_grid,View → Grid Settings,Components not aligned properly,Enable snap-to-grid functionality,Grid spacing settings,Use consistent grid for neat schematics,Schematic organization,design_aesthetics -Schematic Issues,Bus Connections,create_bus,Place → Bus,Multiple signal lines need organization,Create bus for address or data lines,Bus notation standards,Label bus segments clearly,Multi-bit signal management,signal_organization -PCB Design Issues,Footprint Missing,assign_footprint,Tools → Assign Footprints,Component footprint not assigned,Map schematic symbol to PCB footprint,Footprint library selection,Check component associations,PCB layout cannot be generated,footprint_library -PCB Design Issues,DRC Violations,run_drc,Tools → DRC,Design Rule Check failures in PCB,Trace width or spacing violations,Design rule file settings,Adjust PCB layout or rules,PCB manufacturing errors,pcb_rules -PCB Design Issues,Routing Problems,manual_route,Route → Interactive Router,Auto-routing fails or incomplete,Manually route critical nets,Layer and via settings,Use multiple PCB layers,Complex PCB layouts,via_placement -PCB Design Issues,Layer Stack Issues,configure_layers,Setup → Layer Stack,Incorrect PCB layer configuration,Set up 2-layer or 4-layer stackup,Layer count and thickness,Consult manufacturer specs,Multi-layer PCB design,stackup_planning -PCB Design Issues,Via Problems,fix_vias,Place → Via,Vias not connecting layers properly,Check via drill size and pad size,Via specifications,Verify layer connections,Inter-layer connections,layer_connectivity -Performance Issues,Simulation Slow,optimize_simulation,Reduce timestep or complexity,Simulation takes too long to complete,Reduce circuit complexity or timestep,Simulation parameters,Use appropriate analysis types,Large circuit simulation,simulation_tuning -Performance Issues,Memory Issues,increase_memory,System settings,Out of memory during simulation,Close other applications increase swap,System memory allocation,Monitor system resources,Complex mixed-signal circuits,system_resources -Performance Issues,GUI Freezing,restart_gui,Ctrl+Alt+T → killall eSim,eSim interface becomes unresponsive,Restart eSim application,Process management,Save work frequently,Large schematics or long simulations,force_quit -Performance Issues,Browser Lag,optimize_browser,Clear browser cache,Web interface running slowly,Clear cache and restart browser,Browser optimization,Disable unnecessary extensions,Poor web performance,browser_maintenance -Performance Issues,Plot Generation Slow,reduce_plot_points,Limit data points,Graph plotting takes too long,Reduce number of plot points in analysis,Plot resolution settings,Balance detail vs performance,Large dataset visualization,plot_optimization -Model Issues,Custom Model Errors,validate_model,Model Editor → Check Syntax,User-created SPICE models have errors,Check .model statement syntax,SPICE model parameters,Refer to SPICE manual,Custom component simulation,spice_syntax -Model Issues,Library Path Wrong,fix_library_path,Configure → Library Paths,Model libraries not found,Set correct path to model files,Directory paths,Use absolute paths,Model import failures,path_configuration -Model Issues,Model Parameters Invalid,check_model_params,Edit model parameters,Component model has invalid parameters,Verify all model parameters are realistic,Parameter ranges and units,Check manufacturer datasheets,Simulation accuracy issues,parameter_validation -Model Issues,Temperature Dependence,set_temperature,.temp 27,Temperature effects not modeled,Add temperature analysis commands,Temperature in Celsius,Consider temperature coefficients,Environmental simulation,thermal_analysis -Analysis Issues,AC Analysis Problems,setup_ac_analysis,.ac dec 10 1 1meg,AC analysis not working correctly,Set up proper AC analysis parameters,Frequency range and points,Use logarithmic or linear sweep,Frequency response analysis,frequency_analysis -Analysis Issues,Transient Analysis Errors,fix_transient,.tran 0.1ms 10ms,Transient simulation fails,Check time step and stop time,Time parameters,Ensure stable initial conditions,Time domain analysis,time_analysis -Analysis Issues,DC Sweep Issues,configure_dc_sweep,.dc V1 0 5 0.1,DC sweep not producing results,Set up DC source sweep parameters,Voltage or current range,Check sweep variable exists,Parameter variation analysis,parametric_analysis -Analysis Issues,Operating Point Problems,check_operating_point,.op,DC operating point calculation fails,Verify all DC sources and connections,Circuit biasing,Check for floating nodes,Initial condition problems,bias_analysis -Analysis Issues,Noise Analysis Setup,setup_noise_analysis,.noise v(out) V1 dec 10 1 1meg,Noise analysis configuration issues,Configure noise analysis parameters,Input and output nodes,Specify noise source,Circuit noise characterization,noise_modeling -File Issues,Project Won't Open,repair_project,File → Recent Projects,eSim project file corrupted,Restore from backup or recreate,Project file integrity,Regular project backups,Lost work recovery,backup_restore -File Issues,Save Errors,fix_save_permissions,Change file permissions,Cannot save project files,Check folder write permissions,File system permissions,Save to user directory,Permission denied errors,file_permissions -File Issues,Import Errors,fix_import,File → Import,Cannot import external files,Check file format and encoding,Supported file formats,Convert files if necessary,External file integration,format_conversion -File Issues,Export Problems,troubleshoot_export,File → Export,File export functionality not working,Verify export format and destination,Export options and formats,Check write permissions,Data sharing and backup,file_output -Mixed Signal Issues,NGHDL Setup,configure_nghdl,NGHDL → Configuration,Mixed-signal simulation setup problems,Configure Verilog/VHDL compiler paths,Compiler installation paths,Install GHDL and Verilator,Digital simulation not working,digital_setup -Mixed Signal Issues,Interface Errors,debug_interface,Check log files,Analog-digital interface problems,Verify interface component connections,Interface component parameters,Check simulation log for errors,Mixed-signal coupling issues,simulation_log -Mixed Signal Issues,Digital Logic Problems,check_digital_logic,Verify logic levels,Digital components not behaving correctly,Check logic threshold and timing,Logic family specifications,Ensure proper power supply,Digital circuit design,logic_verification -Mixed Signal Issues,Clock Signal Issues,fix_clock_signals,Check clock sources,Clock signals not propagating,Verify clock source and distribution,Clock frequency and duty cycle,Avoid clock skew problems,Sequential circuit timing,timing_analysis -Export Issues,Gerber Generation,fix_gerber,File → Plot,PCB Gerber files not generated correctly,Check layer setup and plot settings,Layer selection and format,Verify plot output directory,Manufacturing file problems,plot_settings -Export Issues,Netlist Export,export_debug,File → Export → Netlist,Netlist export fails or incomplete,Check component models and connections,Export format selection,Validate netlist before export,External tool integration,netlist_validation -Export Issues,BOM Generation,generate_bom,Tools → Generate BOM,Bill of Materials not generating,Check component properties and values,Component attributes,Ensure all parts have part numbers,Manufacturing documentation,parts_list -Export Issues,3D Model Export,export_3d,File → Export → 3D,3D model export not working,Verify 3D models assigned to footprints,3D model libraries,Check export format settings,Mechanical design integration,cad_integration -System Issues,Display Problems,fix_display,System display settings,GUI elements not displaying correctly,Adjust system scaling or resolution,Display configuration,Check graphics drivers,High DPI displays,graphics_setup -System Issues,Font Issues,configure_fonts,System font settings,Text not readable in interface,Install required fonts or change settings,Font configuration,Restart after font changes,Text rendering problems,system_fonts -System Issues,Audio Problems,fix_audio,System audio settings,No sound from simulation alerts,Check system audio configuration,Audio device settings,Enable system sounds,User feedback and alerts,audio_configuration -System Issues,Keyboard Shortcuts,configure_shortcuts,Edit → Preferences,Keyboard shortcuts not working,Check shortcut key assignments,Key binding configuration,Avoid conflicts with system shortcuts,Workflow efficiency,hotkey_setup -Integration Issues,KiCad Version,kicad_compatibility,Check KiCad version,KiCad integration not working,Ensure compatible KiCad version,Version compatibility matrix,Update or downgrade KiCad,Schematic editor issues,version_management -Integration Issues,Ngspice Path,ngspice_setup,Configure Ngspice path,Ngspice simulation engine not found,Set correct Ngspice installation path,Executable file location,Verify Ngspice installation,Simulation engine errors,tool_configuration -Integration Issues,Python Dependencies,install_python_deps,pip install required_packages,Python scripts not executing,Install required Python packages,Package requirements,Use virtual environment,Script automation features,python_setup -Integration Issues,MATLAB Interface,setup_matlab,Configure MATLAB path,MATLAB integration not working,Set MATLAB installation directory,MATLAB toolbox requirements,Check license availability,Advanced analysis features,matlab_configuration -Update Issues,Version Update Failed,manual_update,Download latest version,eSim update process fails,Uninstall old version then reinstall,Clean installation process,Backup projects before update,Update mechanism broken,clean_install -Update Issues,Configuration Lost,restore_config,Copy configuration files,Settings lost after update,Restore configuration from backup,Configuration file locations,Export settings before update,Personalized settings missing,config_backup -Update Issues,Plugin Compatibility,check_plugins,Verify plugin versions,Plugins not working after update,Check plugin compatibility with new version,Plugin version requirements,Update or disable incompatible plugins,Extended functionality issues,plugin_management -Network Issues,Download Failures,check_network,Network connectivity test,Cannot download models or updates,Check internet connection and firewall,Network configuration,Use alternative download methods,Resource download problems,proxy_settings -Network Issues,Proxy Configuration,setup_proxy,Configure proxy settings,Behind corporate firewall,Set proxy in system and eSim settings,Proxy server details,Contact IT for proxy information,Corporate network restrictions,network_configuration -Network Issues,SSL Certificate Errors,fix_ssl,Update certificates,SSL certificate validation failures,Update system certificates or bypass SSL,Certificate management,Consult IT administrator,Secure connection problems,security_configuration -Documentation Issues,Help Not Available,access_help,Online documentation,Built-in help system not working,Visit eSim FOSSEE website for documentation,Internet connection required,Bookmark important documentation,Learning eSim usage,online_resources -Documentation Issues,Tutorial Problems,alternative_tutorials,Spoken Tutorial website,Video tutorials not playing,Use alternative browsers or players,Media player requirements,Download tutorials for offline use,Learning specific features,video_playback -Documentation Issues,Missing Examples,find_examples,Example projects directory,Cannot find example circuits,Look in installation examples folder,Example file locations,Download examples from website,Learning circuit design,sample_projects -Educational Issues,Learning Curve,structured_learning,Follow tutorial sequence,New users finding eSIM difficult,Start with basic circuits and tutorials,Progressive difficulty levels,Practice with simple examples first,Academic learning support,tutorial_progression -Educational Issues,Assignment Help,academic_support,Contact instructor,Students need help with assignments,Provide guidance on circuit analysis,Academic context understanding,Encourage independent learning,Classroom integration,instructor_resources -Educational Issues,Lab Setup,configure_lab,Multi-user environment,Setting up eSIM for laboratory use,Configure shared resources and accounts,Network and user management,Plan for concurrent users,Educational institution deployment,lab_management -Feature Requests,New Components,request_component,Community forum,Need component not in library,Submit component request to developers,Component specifications,Consider creating custom model,Expanding component library,community_contribution -Feature Requests,Analysis Types,request_analysis,Feature request form,Need analysis type not available,Request new analysis capability,Analysis requirements,Use existing tools as workaround,Advanced simulation needs,development_roadmap -Bug Reports,Crash Reports,report_crash,GitHub Issues → Bug Report,eSim crashes unexpectedly,Document steps to reproduce crash,Crash dump information,Include system information,Getting help from developers,log_analysis -Bug Reports,Feature Requests,request_feature,GitHub Issues → Feature Request,Need functionality not available,Describe desired feature clearly,Use case explanation,Check existing feature requests,Suggesting improvements,community_feedback -Bug Reports,Simulation Inaccuracy,report_accuracy,Compare with known results,Simulation results seem incorrect,Verify with hand calculations or other tools,Expected vs actual results,Check model accuracy and parameters,Result validation concerns,verification_methods -Troubleshooting,Log Analysis,check_logs,View → Log Files,Need to diagnose simulation problems,Examine log files for error messages,Log file locations and formats,Look for warning and error messages,Debugging simulation issues,error_diagnosis -Troubleshooting,Component Testing,isolate_component,Test individual components,Circuit not working as expected,Test components individually,Component isolation techniques,Use simple test circuits,Systematic debugging approach,debug_strategy -Troubleshooting,Backup Recovery,restore_backup,File → Restore,Lost work due to system crash,Restore from automatic or manual backups,Backup file locations,Enable automatic backup feature,Data recovery and protection,data_safety -Advanced Features,Parametric Analysis,setup_parametric,.step param R 1k 10k 1k,Need to vary component values,Set up parameter sweep analysis,Parameter ranges and steps,Use .step command for sweeps,Design optimization studies,optimization_analysis -Advanced Features,Monte Carlo Analysis,monte_carlo_setup,.mc 100,Analyze circuit with component tolerances,Set up Monte Carlo statistical analysis,Number of iterations,Define component variations,Statistical design analysis,statistical_modeling -Advanced Features,Worst Case Analysis,worst_case_setup,.wcase,Find worst case circuit performance,Configure worst case analysis parameters,Component tolerance limits,Identify critical components,Robustness analysis,reliability_analysis \ No newline at end of file diff --git a/Backend/helpbot.py b/Backend/helpbot.py deleted file mode 100644 index d091d486f..000000000 --- a/Backend/helpbot.py +++ /dev/null @@ -1,389 +0,0 @@ -from flask import Flask, request, jsonify, session -from langchain_ollama.llms import OllamaLLM -from langchain_core.prompts import ChatPromptTemplate -from vector import retriever -import uuid -import threading -import time -from datetime import datetime, timedelta -from collections import defaultdict -import secrets - -app = Flask(__name__) -app.secret_key = secrets.token_hex(16) # Generate a secure secret key - -# === Configuration === -SESSION_TIMEOUT = 30 * 60 # 30 minutes in seconds -MAX_HISTORY_PER_USER = 50 # Maximum chat history per user - -# === Thread-safe data structures === -class UserManager: - def __init__(self): - self.lock = threading.RLock() - self.users = {} # user_id -> user_data - self.last_activity = {} # user_id -> timestamp - - def get_or_create_user(self, user_id=None): - with self.lock: - if not user_id: - user_id = str(uuid.uuid4()) - - if user_id not in self.users: - self.users[user_id] = { - 'id': user_id, - 'chat_history': [], - 'created_at': datetime.now(), - 'message_count': 0 - } - print(f"[UserManager] Created new user: {user_id}") - - self.last_activity[user_id] = time.time() - return user_id, self.users[user_id] - - def update_user_activity(self, user_id): - with self.lock: - if user_id in self.users: - self.last_activity[user_id] = time.time() - - def add_to_history(self, user_id, question, response): - with self.lock: - if user_id in self.users: - user_data = self.users[user_id] - user_data['chat_history'].append({ - 'timestamp': datetime.now().isoformat(), - 'question': question, - 'response': response - }) - user_data['message_count'] += 1 - - # Keep only the last MAX_HISTORY_PER_USER messages - if len(user_data['chat_history']) > MAX_HISTORY_PER_USER: - user_data['chat_history'] = user_data['chat_history'][-MAX_HISTORY_PER_USER:] - - def get_user_stats(self, user_id): - with self.lock: - if user_id in self.users: - user_data = self.users[user_id] - return { - 'user_id': user_id, - 'message_count': user_data['message_count'], - 'created_at': user_data['created_at'].isoformat(), - 'last_activity': datetime.fromtimestamp(self.last_activity[user_id]).isoformat(), - 'history_length': len(user_data['chat_history']) - } - return None - - def cleanup_inactive_users(self): - """Remove users who have been inactive for more than SESSION_TIMEOUT""" - current_time = time.time() - with self.lock: - inactive_users = [ - user_id for user_id, last_active in self.last_activity.items() - if current_time - last_active > SESSION_TIMEOUT - ] - - for user_id in inactive_users: - del self.users[user_id] - del self.last_activity[user_id] - print(f"[UserManager] Cleaned up inactive user: {user_id}") - - return len(inactive_users) - - def get_active_users_count(self): - with self.lock: - return len(self.users) - -# === Initialize components === -user_manager = UserManager() - -# Initialize LLM with error handling -try: - model = OllamaLLM(model="qwen2.5-coder:3b") - print("[Server] LLM initialized successfully") -except Exception as e: - print(f"[Server] Error initializing LLM: {e}") - model = None - -# Updated prompt template for better context handling -template = """ -You are a professional electronic engineer and expert assistant specializing in EDA tools including eSim, KiCad, and NgSPICE simulation. - -Use the following knowledge base information to provide accurate and helpful answers: -{context} - -Previous conversation context (if any): -{history} - -Current question: {question} - -Instructions: -- Provide practical, actionable advice -- Include specific commands, syntax, or examples when relevant -- Keep responses concise but comprehensive (maximum 200 words) -- If the question is about debugging, provide step-by-step troubleshooting steps -- Reference specific parameters or options when applicable -- If you're not certain about something, say so clearly - -Answer: -""" - -prompt = ChatPromptTemplate.from_template(template) - -# === Cleanup thread === -def cleanup_thread(): - """Background thread to cleanup inactive users""" - while True: - try: - time.sleep(300) # Run every 5 minutes - cleaned_count = user_manager.cleanup_inactive_users() - if cleaned_count > 0: - print(f"[Cleanup] Removed {cleaned_count} inactive users") - except Exception as e: - print(f"[Cleanup] Error during cleanup: {e}") - -# Start cleanup thread -cleanup_worker = threading.Thread(target=cleanup_thread, daemon=True) -cleanup_worker.start() - -# === API Routes === - -@app.route("/chat", methods=["POST"]) -def chat(): - try: - # Get or create user session - user_id = request.json.get("user_id") or session.get('user_id') - user_id, user_data = user_manager.get_or_create_user(user_id) - session['user_id'] = user_id - - question = request.json.get("prompt", "").strip() - if not question: - return jsonify({"error": "No question provided"}), 400 - - print(f"[API] User {user_id[:8]}... asked: {question}") - - # Check if LLM is available - if model is None: - return jsonify({"error": "LLM not available"}), 503 - - # 1. Retrieve relevant documents - context = "" - try: - docs = retriever.invoke(question) - if isinstance(docs, list) and docs: - # Format context with more structure - context_parts = [] - for i, doc in enumerate(docs[:5], 1): # Limit to top 5 results - if hasattr(doc, 'page_content') and hasattr(doc, 'metadata'): - content = doc.page_content - metadata = doc.metadata - - # Add command information if available - cmd_info = f"[{i}] " - if metadata.get('command'): - cmd_info += f"Command: {metadata['command']} | " - if metadata.get('category'): - cmd_info += f"Category: {metadata['category']} | " - - cmd_info += content - context_parts.append(cmd_info) - - context = "\n\n".join(context_parts) - elif hasattr(docs, "page_content"): - context = docs.page_content - else: - context = str(docs) if docs else "" - - except Exception as e: - print(f"[API] Retriever error for user {user_id[:8]}...: {e}") - context = "" - - # 2. Get recent chat history for context - history = "" - if user_data['chat_history']: - recent_history = user_data['chat_history'][-3:] # Last 3 exchanges - history_parts = [] - for h in recent_history: - history_parts.append(f"Previous Q: {h['question']}") - history_parts.append(f"Previous A: {h['response'][:100]}...") # Truncate long responses - history = "\n".join(history_parts) - - # 3. Run LLM - try: - chain = prompt | model - output = chain.invoke({ - "context": context, - "history": history, - "question": question - }) - response = str(output).strip() - - # Store in user's chat history - user_manager.add_to_history(user_id, question, response) - - return jsonify({ - "response": response, - "user_id": user_id, - "message_count": user_data['message_count'] + 1, - "context_found": bool(context.strip()) - }) - - except Exception as e: - print(f"[API] LLM error for user {user_id[:8]}...: {e}") - return jsonify({"error": f"LLM processing error: {str(e)}"}), 500 - - except Exception as e: - print(f"[API] Unexpected error: {e}") - return jsonify({"error": f"Unexpected error: {str(e)}"}), 500 - -@app.route("/search", methods=["POST"]) -def search_knowledge(): - """Search the knowledge base directly""" - try: - query = request.json.get("query", "").strip() - if not query: - return jsonify({"error": "No search query provided"}), 400 - - # Retrieve relevant documents - docs = retriever.invoke(query) - results = [] - - if isinstance(docs, list): - for doc in docs[:10]: # Return top 10 results - if hasattr(doc, 'page_content') and hasattr(doc, 'metadata'): - results.append({ - "content": doc.page_content, - "metadata": doc.metadata, - "command": doc.metadata.get('command', ''), - "category": doc.metadata.get('category', ''), - "description": doc.metadata.get('description', '') - }) - - return jsonify({ - "query": query, - "results": results, - "count": len(results) - }) - - except Exception as e: - return jsonify({"error": str(e)}), 500 - -@app.route("/new_session", methods=["POST"]) -def new_session(): - """Create a new user session""" - try: - user_id, user_data = user_manager.get_or_create_user() - session['user_id'] = user_id - - return jsonify({ - "user_id": user_id, - "message": "New session created", - "created_at": user_data['created_at'].isoformat() - }) - except Exception as e: - return jsonify({"error": str(e)}), 500 - -@app.route("/history", methods=["GET"]) -def get_history(): - """Get chat history for current user""" - try: - user_id = request.args.get("user_id") or session.get('user_id') - if not user_id: - return jsonify({"error": "No user session found"}), 400 - - user_id, user_data = user_manager.get_or_create_user(user_id) - user_manager.update_user_activity(user_id) - - limit = int(request.args.get("limit", 10)) - history = user_data['chat_history'][-limit:] if limit > 0 else user_data['chat_history'] - - return jsonify({ - "history": history, - "total_messages": user_data['message_count'], - "user_id": user_id - }) - except Exception as e: - return jsonify({"error": str(e)}), 500 - -@app.route("/clear_history", methods=["POST"]) -def clear_history(): - """Clear chat history for current user""" - try: - user_id = request.json.get("user_id") or session.get('user_id') - if not user_id: - return jsonify({"error": "No user session found"}), 400 - - user_id, user_data = user_manager.get_or_create_user(user_id) - user_data['chat_history'] = [] - user_manager.update_user_activity(user_id) - - return jsonify({"message": "History cleared", "user_id": user_id}) - except Exception as e: - return jsonify({"error": str(e)}), 500 - -@app.route("/stats", methods=["GET"]) -def get_stats(): - """Get user statistics""" - try: - user_id = request.args.get("user_id") or session.get('user_id') - if user_id: - user_stats = user_manager.get_user_stats(user_id) - if user_stats: - user_manager.update_user_activity(user_id) - return jsonify(user_stats) - - return jsonify({"error": "User not found"}), 404 - except Exception as e: - return jsonify({"error": str(e)}), 500 - -@app.route("/server_stats", methods=["GET"]) -def get_server_stats(): - """Get server statistics (admin endpoint)""" - try: - return jsonify({ - "active_users": user_manager.get_active_users_count(), - "server_uptime": "Running", - "llm_status": "Available" if model else "Unavailable", - "vector_db_status": "Available" - }) - except Exception as e: - return jsonify({"error": str(e)}), 500 - -@app.route("/health", methods=["GET"]) -def health_check(): - """Health check endpoint""" - return jsonify({ - "status": "healthy", - "timestamp": datetime.now().isoformat(), - "active_users": user_manager.get_active_users_count(), - "components": { - "llm": "Available" if model else "Unavailable", - "vector_db": "Available", - "user_manager": "Available" - } - }) - -# === Error handlers === -@app.errorhandler(404) -def not_found(error): - return jsonify({"error": "Endpoint not found"}), 404 - -@app.errorhandler(500) -def internal_error(error): - return jsonify({"error": "Internal server error"}), 500 - -if __name__ == "__main__": - print("\n" + "="*50) - print("[Server] Starting NgSPICE ChatBot Server...") - print("="*50) - print(f"[Server] Session timeout: {SESSION_TIMEOUT // 60} minutes") - print(f"[Server] Max history per user: {MAX_HISTORY_PER_USER}") - print(f"[Server] LLM Model: {'qwen2.5-coder:3b' if model else 'Not Available'}") - print("="*50) - - # Run with threading support for multiple users - app.run( - host="0.0.0.0", - port=5000, - debug=False, # Set to False for production - threaded=True # Enable threading for concurrent requests - ) \ No newline at end of file diff --git a/resources/esim_help.csv b/resources/esim_help.csv new file mode 100644 index 000000000..869dbadce --- /dev/null +++ b/resources/esim_help.csv @@ -0,0 +1,322 @@ +category,subcategory,command,syntax,description,example,parameters,notes,use_case,related_commands +Overview,About eSIM,N/A,N/A,"eSIM is a virtual electronics simulator developed by FOSSEE (IIT Bombay) for learning circuit design and simulation. It uses Ngspice for backend simulation and runs in a browser.","Simulate a common emitter amplifier using Ngspice and visualize output graph.","Circuit file, type of analysis (AC, DC, Transient)","Requires modern browser, designed for academic purposes.","Education, training, virtual labs in electronics and communication engineering.",".tran, .ac, run, plot, .print, .measure" +Installation Issues,Dependencies Missing,install_dependencies,sudo apt-get install dependencies,KiCad or Ngspice dependencies not installed properly,sudo apt-get install kicad ngspice,Package names for Ubuntu,Check system requirements before installation,Fresh installation on Ubuntu,verify_installation +Installation Issues,Permission Errors,fix_permissions,sudo chmod +x install_script,Installation fails due to insufficient permissions,sudo chmod +x eSim-2.3.run,Executable file path,Run as administrator on Windows,Installation script won't execute,installation_troubleshooting +Installation Issues,Path Issues,set_path,export PATH=$PATH:/opt/eSim,eSim commands not found in terminal,export PATH=$PATH:/opt/eSim-2.3/bin,Correct eSim installation directory,Add to .bashrc for permanent fix,Command not found errors,environment_setup +Installation Issues,Version Conflicts,version_check,esim --version,Conflicting versions of dependencies installed,Check KiCad version compatibility,Version numbers,Uninstall old versions first,Multiple eSim versions installed,uninstall_old +Installation Issues,Browser Compatibility,check_browser,Open supported browser,eSIM not loading properly in browser,Use Chrome Firefox or Safari latest versions,Modern browser required,Disable ad blockers for eSIM,Web interface not working,browser_setup +Installation Issues,Python Dependencies,install_python_deps,pip install PyQt5 matplotlib numpy,Python or PyQt5 dependencies missing,pip install PyQt5 matplotlib numpy scipy,Python package requirements,Use pip3 for Python3 installations,GUI not loading or plotting issues,python_setup +Simulation Errors,Netlist Generation Failed,check_netlist,Tools → Generate Netlist,Schematic cannot be converted to SPICE netlist,Missing ground connection in circuit,Proper component labeling required,All components must have SPICE models,Netlist conversion errors,add_spice_models +Simulation Errors,Convergence Problems,convergence_fix,.options gmin=1e-12,Simulation fails to converge,".options gmin=1e-12 abstol=1e-12",Tolerance parameters,Adjust simulation options,Large circuits or nonlinear elements,simulation_options +Simulation Errors,Model Not Found,add_model,Model Editor → Import,Component SPICE model missing from library,Import transistor.lib to model library,Model file path,Check model syntax,Custom components not simulating,model_library +Simulation Errors,Syntax Errors,fix_syntax,Edit netlist manually,SPICE syntax errors in netlist,Fix ".model" statement format,Proper SPICE syntax,Use Model Editor for validation,Simulation won't start,netlist_debug +Simulation Errors,Timeout Errors,adjust_timeout,Set simulation timeout,Simulation runs too long and times out,Increase timeout limit in settings,Time limit in seconds,Reduce circuit complexity if needed,Long running simulations,simulation_settings +Simulation Errors,Memory Overflow,reduce_complexity,Simplify circuit design,Simulation exceeds available memory,Break large circuit into smaller blocks,Available system memory,Close other browser tabs,Very large circuits,memory_management +Simulation Errors,Division by Zero,check_parameters,Verify component values,Mathematical error in simulation,Ensure no zero-value resistors or capacitors,Component parameter validation,Use realistic component values,Parameter validation errors,component_check +Schematic Issues,Component Not Found,add_component_library,Library → Add,Required component missing from library,Add custom component library,Library file path,Install additional KiCad libraries,Missing components in palette,library_manager +Schematic Issues,ERC Violations,run_erc,Tools → ERC,Electrical Rule Check failures,Unconnected pins or power issues,Design rule settings,Fix all ERC errors before simulation,Schematic validation fails,design_rules +Schematic Issues,Pin Connection Errors,fix_connections,Manual wire placement,Components not properly connected,Add junction dots at wire intersections,Proper wire routing,Check for floating nodes,Connectivity issues,wire_connections +Schematic Issues,Label Issues,fix_labels,Edit component properties,Component reference designators missing,Set R1 R2 for resistors V1 for voltage source,Unique component names,Sequential numbering required,Duplicate component names,component_properties +Schematic Issues,Wire Crossing Problems,fix_wire_crossing,Use junction dots,Ambiguous wire connections at crossings,Add junction dots where wires should connect,Visual connection indicators,Avoid T-junctions without dots,Connection ambiguity,wire_management +Schematic Issues,Component Rotation,rotate_component,Right-click → Rotate,Component orientation incorrect,Rotate component to proper orientation,90-degree increments,Use R key for quick rotation,Schematic readability,component_placement +Schematic Issues,Grid Alignment,snap_to_grid,View → Grid Settings,Components not aligned properly,Enable snap-to-grid functionality,Grid spacing settings,Use consistent grid for neat schematics,Schematic organization,design_aesthetics +Schematic Issues,Bus Connections,create_bus,Place → Bus,Multiple signal lines need organization,Create bus for address or data lines,Bus notation standards,Label bus segments clearly,Multi-bit signal management,signal_organization +PCB Design Issues,Footprint Missing,assign_footprint,Tools → Assign Footprints,Component footprint not assigned,Map schematic symbol to PCB footprint,Footprint library selection,Check component associations,PCB layout cannot be generated,footprint_library +PCB Design Issues,DRC Violations,run_drc,Tools → DRC,Design Rule Check failures in PCB,Trace width or spacing violations,Design rule file settings,Adjust PCB layout or rules,PCB manufacturing errors,pcb_rules +PCB Design Issues,Routing Problems,manual_route,Route → Interactive Router,Auto-routing fails or incomplete,Manually route critical nets,Layer and via settings,Use multiple PCB layers,Complex PCB layouts,via_placement +PCB Design Issues,Layer Stack Issues,configure_layers,Setup → Layer Stack,Incorrect PCB layer configuration,Set up 2-layer or 4-layer stackup,Layer count and thickness,Consult manufacturer specs,Multi-layer PCB design,stackup_planning +PCB Design Issues,Via Problems,fix_vias,Place → Via,Vias not connecting layers properly,Check via drill size and pad size,Via specifications,Verify layer connections,Inter-layer connections,layer_connectivity +Performance Issues,Simulation Slow,optimize_simulation,Reduce timestep or complexity,Simulation takes too long to complete,Reduce circuit complexity or timestep,Simulation parameters,Use appropriate analysis types,Large circuit simulation,simulation_tuning +Performance Issues,Memory Issues,increase_memory,System settings,Out of memory during simulation,Close other applications increase swap,System memory allocation,Monitor system resources,Complex mixed-signal circuits,system_resources +Performance Issues,GUI Freezing,restart_gui,Ctrl+Alt+T → killall eSim,eSim interface becomes unresponsive,Restart eSim application,Process management,Save work frequently,Large schematics or long simulations,force_quit +Performance Issues,Browser Lag,optimize_browser,Clear browser cache,Web interface running slowly,Clear cache and restart browser,Browser optimization,Disable unnecessary extensions,Poor web performance,browser_maintenance +Performance Issues,Plot Generation Slow,reduce_plot_points,Limit data points,Graph plotting takes too long,Reduce number of plot points in analysis,Plot resolution settings,Balance detail vs performance,Large dataset visualization,plot_optimization +Model Issues,Custom Model Errors,validate_model,Model Editor → Check Syntax,User-created SPICE models have errors,Check .model statement syntax,SPICE model parameters,Refer to SPICE manual,Custom component simulation,spice_syntax +Model Issues,Library Path Wrong,fix_library_path,Configure → Library Paths,Model libraries not found,Set correct path to model files,Directory paths,Use absolute paths,Model import failures,path_configuration +Model Issues,Model Parameters Invalid,check_model_params,Edit model parameters,Component model has invalid parameters,Verify all model parameters are realistic,Parameter ranges and units,Check manufacturer datasheets,Simulation accuracy issues,parameter_validation +Model Issues,Temperature Dependence,set_temperature,.temp 27,Temperature effects not modeled,Add temperature analysis commands,Temperature in Celsius,Consider temperature coefficients,Environmental simulation,thermal_analysis +Analysis Issues,AC Analysis Problems,setup_ac_analysis,.ac dec 10 1 1meg,AC analysis not working correctly,Set up proper AC analysis parameters,Frequency range and points,Use logarithmic or linear sweep,Frequency response analysis,frequency_analysis +Analysis Issues,Transient Analysis Errors,fix_transient,.tran 0.1ms 10ms,Transient simulation fails,Check time step and stop time,Time parameters,Ensure stable initial conditions,Time domain analysis,time_analysis +Analysis Issues,DC Sweep Issues,configure_dc_sweep,.dc V1 0 5 0.1,DC sweep not producing results,Set up DC source sweep parameters,Voltage or current range,Check sweep variable exists,Parameter variation analysis,parametric_analysis +Analysis Issues,Operating Point Problems,check_operating_point,.op,DC operating point calculation fails,Verify all DC sources and connections,Circuit biasing,Check for floating nodes,Initial condition problems,bias_analysis +Analysis Issues,Noise Analysis Setup,setup_noise_analysis,.noise v(out) V1 dec 10 1 1meg,Noise analysis configuration issues,Configure noise analysis parameters,Input and output nodes,Specify noise source,Circuit noise characterization,noise_modeling +File Issues,Project Won't Open,repair_project,File → Recent Projects,eSim project file corrupted,Restore from backup or recreate,Project file integrity,Regular project backups,Lost work recovery,backup_restore +File Issues,Save Errors,fix_save_permissions,Change file permissions,Cannot save project files,Check folder write permissions,File system permissions,Save to user directory,Permission denied errors,file_permissions +File Issues,Import Errors,fix_import,File → Import,Cannot import external files,Check file format and encoding,Supported file formats,Convert files if necessary,External file integration,format_conversion +File Issues,Export Problems,troubleshoot_export,File → Export,File export functionality not working,Verify export format and destination,Export options and formats,Check write permissions,Data sharing and backup,file_output +Mixed Signal Issues,NGHDL Setup,configure_nghdl,NGHDL → Configuration,Mixed-signal simulation setup problems,Configure Verilog/VHDL compiler paths,Compiler installation paths,Install GHDL and Verilator,Digital simulation not working,digital_setup +Mixed Signal Issues,Interface Errors,debug_interface,Check log files,Analog-digital interface problems,Verify interface component connections,Interface component parameters,Check simulation log for errors,Mixed-signal coupling issues,simulation_log +Mixed Signal Issues,Digital Logic Problems,check_digital_logic,Verify logic levels,Digital components not behaving correctly,Check logic threshold and timing,Logic family specifications,Ensure proper power supply,Digital circuit design,logic_verification +Mixed Signal Issues,Clock Signal Issues,fix_clock_signals,Check clock sources,Clock signals not propagating,Verify clock source and distribution,Clock frequency and duty cycle,Avoid clock skew problems,Sequential circuit timing,timing_analysis +Export Issues,Gerber Generation,fix_gerber,File → Plot,PCB Gerber files not generated correctly,Check layer setup and plot settings,Layer selection and format,Verify plot output directory,Manufacturing file problems,plot_settings +Export Issues,Netlist Export,export_debug,File → Export → Netlist,Netlist export fails or incomplete,Check component models and connections,Export format selection,Validate netlist before export,External tool integration,netlist_validation +Export Issues,BOM Generation,generate_bom,Tools → Generate BOM,Bill of Materials not generating,Check component properties and values,Component attributes,Ensure all parts have part numbers,Manufacturing documentation,parts_list +Export Issues,3D Model Export,export_3d,File → Export → 3D,3D model export not working,Verify 3D models assigned to footprints,3D model libraries,Check export format settings,Mechanical design integration,cad_integration +System Issues,Display Problems,fix_display,System display settings,GUI elements not displaying correctly,Adjust system scaling or resolution,Display configuration,Check graphics drivers,High DPI displays,graphics_setup +System Issues,Font Issues,configure_fonts,System font settings,Text not readable in interface,Install required fonts or change settings,Font configuration,Restart after font changes,Text rendering problems,system_fonts +System Issues,Audio Problems,fix_audio,System audio settings,No sound from simulation alerts,Check system audio configuration,Audio device settings,Enable system sounds,User feedback and alerts,audio_configuration +System Issues,Keyboard Shortcuts,configure_shortcuts,Edit → Preferences,Keyboard shortcuts not working,Check shortcut key assignments,Key binding configuration,Avoid conflicts with system shortcuts,Workflow efficiency,hotkey_setup +Integration Issues,KiCad Version,kicad_compatibility,Check KiCad version,KiCad integration not working,Ensure compatible KiCad version,Version compatibility matrix,Update or downgrade KiCad,Schematic editor issues,version_management +Integration Issues,Ngspice Path,ngspice_setup,Configure Ngspice path,Ngspice simulation engine not found,Set correct Ngspice installation path,Executable file location,Verify Ngspice installation,Simulation engine errors,tool_configuration +Integration Issues,Python Dependencies,install_python_deps,pip install required_packages,Python scripts not executing,Install required Python packages,Package requirements,Use virtual environment,Script automation features,python_setup +Integration Issues,MATLAB Interface,setup_matlab,Configure MATLAB path,MATLAB integration not working,Set MATLAB installation directory,MATLAB toolbox requirements,Check license availability,Advanced analysis features,matlab_configuration +Update Issues,Version Update Failed,manual_update,Download latest version,eSim update process fails,Uninstall old version then reinstall,Clean installation process,Backup projects before update,Update mechanism broken,clean_install +Update Issues,Configuration Lost,restore_config,Copy configuration files,Settings lost after update,Restore configuration from backup,Configuration file locations,Export settings before update,Personalized settings missing,config_backup +Update Issues,Plugin Compatibility,check_plugins,Verify plugin versions,Plugins not working after update,Check plugin compatibility with new version,Plugin version requirements,Update or disable incompatible plugins,Extended functionality issues,plugin_management +Network Issues,Download Failures,check_network,Network connectivity test,Cannot download models or updates,Check internet connection and firewall,Network configuration,Use alternative download methods,Resource download problems,proxy_settings +Network Issues,Proxy Configuration,setup_proxy,Configure proxy settings,Behind corporate firewall,Set proxy in system and eSim settings,Proxy server details,Contact IT for proxy information,Corporate network restrictions,network_configuration +Network Issues,SSL Certificate Errors,fix_ssl,Update certificates,SSL certificate validation failures,Update system certificates or bypass SSL,Certificate management,Consult IT administrator,Secure connection problems,security_configuration +Documentation Issues,Help Not Available,access_help,Online documentation,Built-in help system not working,Visit eSim FOSSEE website for documentation,Internet connection required,Bookmark important documentation,Learning eSim usage,online_resources +Documentation Issues,Tutorial Problems,alternative_tutorials,Spoken Tutorial website,Video tutorials not playing,Use alternative browsers or players,Media player requirements,Download tutorials for offline use,Learning specific features,video_playback +Documentation Issues,Missing Examples,find_examples,Example projects directory,Cannot find example circuits,Look in installation examples folder,Example file locations,Download examples from website,Learning circuit design,sample_projects +Educational Issues,Learning Curve,structured_learning,Follow tutorial sequence,New users finding eSIM difficult,Start with basic circuits and tutorials,Progressive difficulty levels,Practice with simple examples first,Academic learning support,tutorial_progression +Educational Issues,Assignment Help,academic_support,Contact instructor,Students need help with assignments,Provide guidance on circuit analysis,Academic context understanding,Encourage independent learning,Classroom integration,instructor_resources +Educational Issues,Lab Setup,configure_lab,Multi-user environment,Setting up eSIM for laboratory use,Configure shared resources and accounts,Network and user management,Plan for concurrent users,Educational institution deployment,lab_management +Feature Requests,New Components,request_component,Community forum,Need component not in library,Submit component request to developers,Component specifications,Consider creating custom model,Expanding component library,community_contribution +Feature Requests,Analysis Types,request_analysis,Feature request form,Need analysis type not available,Request new analysis capability,Analysis requirements,Use existing tools as workaround,Advanced simulation needs,development_roadmap +Bug Reports,Crash Reports,report_crash,GitHub Issues → Bug Report,eSim crashes unexpectedly,Document steps to reproduce crash,Crash dump information,Include system information,Getting help from developers,log_analysis +Bug Reports,Feature Requests,request_feature,GitHub Issues → Feature Request,Need functionality not available,Describe desired feature clearly,Use case explanation,Check existing feature requests,Suggesting improvements,community_feedback +Bug Reports,Simulation Inaccuracy,report_accuracy,Compare with known results,Simulation results seem incorrect,Verify with hand calculations or other tools,Expected vs actual results,Check model accuracy and parameters,Result validation concerns,verification_methods +Troubleshooting,Log Analysis,check_logs,View → Log Files,Need to diagnose simulation problems,Examine log files for error messages,Log file locations and formats,Look for warning and error messages,Debugging simulation issues,error_diagnosis +Troubleshooting,Component Testing,isolate_component,Test individual components,Circuit not working as expected,Test components individually,Component isolation techniques,Use simple test circuits,Systematic debugging approach,debug_strategy +Troubleshooting,Backup Recovery,restore_backup,File → Restore,Lost work due to system crash,Restore from automatic or manual backups,Backup file locations,Enable automatic backup feature,Data recovery and protection,data_safety +Advanced Features,Parametric Analysis,setup_parametric,.step param R 1k 10k 1k,Need to vary component values,Set up parameter sweep analysis,Parameter ranges and steps,Use .step command for sweeps,Design optimization studies,optimization_analysis +Advanced Features,Monte Carlo Analysis,monte_carlo_setup,.mc 100,Analyze circuit with component tolerances,Set up Monte Carlo statistical analysis,Number of iterations,Define component variations,Statistical design analysis,statistical_modeling +Advanced Features,Worst Case Analysis,worst_case_setup,.wcase,Find worst case circuit performance,Configure worst case analysis parameters,Component tolerance limits,Identify critical components,Robustness analysis,reliability_analysis +basic_commands,simulation,run,run,"Executes the currently loaded netlist simulation","run","none","Must have a netlist loaded first","Running basic simulations","load, plot" +basic_commands,file_operations,source,source ,"Loads and executes a netlist file","source amplifier.cir","filename: path to netlist file","File must exist and be readable","Loading circuit files","include, load" +basic_commands,plotting,plot,plot ,"Displays graphical plots of simulation results","plot v(out) i(r1)","vector_list: space-separated list of vectors","Requires simulation to be run first","Viewing simulation results","print, write" +basic_commands,data_output,print,print ,"Prints numerical values of vectors to console","print v(1) v(2) i(vin)","vector_list: vectors to display","Shows current values or all values","Getting numerical data","plot, show" +basic_commands,information,show,show,"Displays information about current circuit","show all","all, nodes, devices, models","Useful for debugging circuits","Circuit inspection","print, listing" +basic_commands,help,help,help [command],"Shows help information","help plot","command: specific command (optional)","Shows available commands if no argument","Getting command information","?" +basic_commands,simulation,quit,quit,"Exits the NGSPICE simulator","quit","none","Saves current state before exiting","Ending simulation session","exit, stop" +basic_commands,simulation,exit,exit,"Alternative command to quit simulator","exit","none","Same as quit command","Ending simulation session","quit, stop" +basic_commands,simulation,version,version,"Displays NGSPICE version information","version","none","Shows build date and version number","Checking simulator version","help" +basic_commands,simulation,rusage,rusage,"Shows resource usage statistics","rusage","none","Displays CPU time and memory usage","Performance monitoring","status, time" +basic_commands,simulation,history,history,"Shows command history","history","none","Lists previously executed commands","Command recall","alias" +basic_commands,simulation,alias,alias ,"Creates command aliases","alias h help","name: alias name, command: command to alias","Shortens frequently used commands","Command shortcuts","history, unalias" +basic_commands,simulation,unalias,unalias ,"Removes command alias","unalias h","name: alias to remove","Removes previously defined alias","Alias management","alias" +basic_commands,simulation,time,time,"Shows current simulation time","time","none","Displays elapsed time in transient analysis","Time tracking","rusage, status" +analysis_types,dc_analysis,dc,dc ,"Performs DC sweep analysis","dc vin 0 5 0.1","source: voltage/current source, start/stop: sweep range, step: increment","Creates DC operating point sweep","DC characteristic curves","op, tf" +analysis_types,ac_analysis,ac,ac ,"Performs AC small-signal analysis","ac dec 100 1 1meg","type: dec/oct/lin, points: number per decade/octave, start/stop: frequency range","Frequency domain analysis","Frequency response analysis","noise, disto" +analysis_types,transient,tran,tran [start] [max],"Performs transient time-domain analysis","tran 1ns 100ns","step: time step, stop: end time, start: start time (optional), max: max time step (optional)","Time domain simulation","Time-based circuit behavior","ic, uic" +analysis_types,operating_point,op,op,"Calculates DC operating point","op","none","Finds quiescent operating point","Initial circuit conditions","dc, tf" +analysis_types,transfer_function,tf,tf ,"Calculates small-signal transfer function","tf v(out) vin","output: output variable, input: input source","Linear circuit analysis","Gain and impedance calculation","ac, op" +analysis_types,noise_analysis,noise,noise ,"Performs noise analysis","noise v(out) vin dec 10 1 1k","output: output node, input: input source, type: dec/oct/lin","Noise characteristic analysis","Circuit noise performance","ac" +analysis_types,distortion_analysis,disto,disto ,"Performs distortion analysis","disto 1k 0.1","freq: fundamental frequency, amplitude: input amplitude","Harmonic distortion analysis","Amplifier linearity testing","ac, noise" +analysis_types,pole_zero,pz,pz ,"Performs pole-zero analysis","pz vin vout vol pz","input: input node, output: output node, type: vol/cur/pz","Stability analysis","Control system design","tf, ac" +analysis_types,small_signal,sens,sens ,"Performs small-signal sensitivity analysis","sens v(out)","output: output variable","Component sensitivity","Design optimization","dc, ac" +circuit_elements,resistor,resistor,R ,"Defines a resistor element","R1 1 0 1k","name: unique identifier, node1/node2: connection nodes, value: resistance","Basic passive element","Voltage division, current limiting","capacitor, inductor" +circuit_elements,capacitor,capacitor,C [IC],"Defines a capacitor element","C1 1 2 10u IC=0","name: identifier, nodes: connections, value: capacitance, IC: initial condition","Reactive element for AC analysis","Filtering, timing circuits","resistor, inductor" +circuit_elements,inductor,inductor,L [IC],"Defines an inductor element","L1 2 3 1m IC=0","name: identifier, nodes: connections, value: inductance, IC: initial current","Reactive element, magnetic coupling","Energy storage, filtering","resistor, capacitor" +circuit_elements,voltage_source,voltage_source,V ,"Defines a voltage source","VCC 1 0 DC 5","name: identifier, node+: positive terminal, node-: negative terminal, value: voltage specification","Independent voltage source","Power supply, signal generation","current_source, controlled_sources" +circuit_elements,current_source,current_source,I ,"Defines a current source","I1 0 1 DC 1m","name: identifier, node+: current flows into, node-: current flows out, value: current specification","Independent current source","Biasing, signal injection","voltage_source, controlled_sources" +circuit_elements,diode,diode,D ,"Defines a diode element","D1 1 2 1N4148","name: identifier, anode: positive terminal, cathode: negative terminal, model: diode model name","Nonlinear semiconductor device","Rectification, protection","bjt, mosfet" +circuit_elements,bjt,bjt,Q ,"Defines a bipolar junction transistor","Q1 3 2 1 2N2222","name: identifier, collector/base/emitter: terminal nodes, model: BJT model name","Three-terminal amplifying device","Amplification, switching","mosfet, diode" +circuit_elements,mosfet,mosfet,M ,"Defines a MOSFET transistor","M1 2 1 0 0 NMOS","name: identifier, drain/gate/source/bulk: terminal nodes, model: MOSFET model name","Voltage-controlled switching device","Digital circuits, power control","bjt, jfet" +circuit_elements,opamp,opamp,X ,"Defines an operational amplifier subcircuit","X1 2 1 3 LM741","name: identifier, in+: non-inverting input, in-: inverting input, out: output, model: opamp model","High-gain differential amplifier","Signal amplification, filtering","subcircuit, controlled_sources" +circuit_elements,jfet,jfet,J ,"Defines a JFET transistor","J1 2 1 0 2N3819","name: identifier, drain/gate/source: terminal nodes, model: JFET model name","Voltage-controlled current source","High-impedance amplification","mosfet, bjt" +circuit_elements,mutual_inductor,mutual,K ,"Defines mutual inductance between inductors","K1 L1 L2 0.9","name: identifier, inductor1/inductor2: coupled inductors, coupling: coupling coefficient","Magnetic coupling","Transformers, coupled circuits","inductor, transformer" +circuit_elements,transmission_line,tline,T ,"Defines a transmission line","T1 1 0 2 0 TLINE","name: identifier, n1-n4: port nodes, model: transmission line model","Distributed parameter element","High-frequency circuits, PCB traces","lossy_tline, coupled_tline" +circuit_elements,switch,switch,S ,"Defines a voltage-controlled switch","S1 1 2 3 0 SMOD","name: identifier, node1/node2: switched nodes, control+/control-: control voltage nodes, model: switch model","Voltage-controlled switching","Switching circuits, multiplexers","current_switch, relay" +circuit_elements,current_switch,current_switch,W ,"Defines a current-controlled switch","W1 1 2 VCTL","name: identifier, node1/node2: switched nodes, control: controlling voltage source","Current-controlled switching","Current-sensing switches","switch, cccs" +circuit_elements,transformer,transformer,K ,"Defines a transformer using mutual inductance","K1 LPRI LSEC 0.95","name: identifier, L1/L2: primary/secondary inductors, coupling: coupling coefficient","Electrical isolation and transformation","Power supplies, isolation","mutual_inductor, inductor" +controlled_sources,vcvs,vcvs,E ,"Voltage-controlled voltage source","E1 3 0 1 2 100","name: identifier, out+/out-: output nodes, in+/in-: control nodes, gain: voltage gain","Linear voltage amplification","Operational amplifier modeling","vccs, ccvs" +controlled_sources,vccs,vccs,G ,"Voltage-controlled current source","G1 3 0 1 2 0.001","name: identifier, out+/out-: output nodes, in+/in-: control nodes, gain: transconductance","Voltage-to-current conversion","Transconductance amplifiers","vcvs, cccs" +controlled_sources,ccvs,ccvs,H ,"Current-controlled voltage source","H1 3 0 VIN 1000","name: identifier, out+/out-: output nodes, control: controlling voltage source, gain: transimpedance","Current-to-voltage conversion","Transimpedance amplifiers","cccs, vcvs" +controlled_sources,cccs,cccs,F ,"Current-controlled current source","F1 3 0 VIN 50","name: identifier, out+/out-: output nodes, control: controlling voltage source, gain: current gain","Current amplification","Current mirrors, amplifiers","ccvs, vccs" +controlled_sources,poly_vcvs,poly_vcvs,E POLY() ,"Polynomial voltage-controlled voltage source","E1 3 0 POLY(1) 1 2 0 100 0.1","name: identifier, out+/out-: output nodes, dim: polynomial dimension, control_pairs: control node pairs, coeffs: polynomial coefficients","Nonlinear voltage relationships","Behavioral modeling, nonlinear circuits","poly_vccs, behavioral" +controlled_sources,poly_vccs,poly_vccs,G POLY() ,"Polynomial voltage-controlled current source","G1 3 0 POLY(2) 1 2 4 5 0 0.01 0.001","name: identifier, out+/out-: output nodes, dim: polynomial dimension, control_pairs: control node pairs, coeffs: polynomial coefficients","Nonlinear transconductance","Behavioral modeling, nonlinear circuits","poly_vcvs, behavioral" +controlled_sources,behavioral,behavioral,B ,"Behavioral source with arbitrary expression","B1 3 0 V=V(1)*V(2)","name: identifier, out+/out-: output nodes, expression: mathematical expression","Arbitrary mathematical relationships","Complex behavioral modeling","poly_vcvs, table" +controlled_sources,table,table,B TABLE = ,"Table-based behavioral source","B1 3 0 TABLE {V(1)} = (0,0) (1,2) (2,5)","name: identifier, out+/out-: output nodes, input: input expression, table_data: input-output pairs","Lookup table functionality","Nonlinear characteristic modeling","behavioral, poly_vcvs" +sources,dc_source,dc,DC ,"Specifies a DC source value","DC 12V","value: constant voltage or current","Time-invariant source","Power supplies, biasing","ac, pulse" +sources,ac_source,ac,AC [phase],"Specifies an AC source for small-signal analysis","AC 1V 0","magnitude: AC amplitude, phase: phase angle in degrees","Small-signal AC analysis","Frequency response testing","dc, sin" +sources,sine_source,sin,SIN( [delay] [damping]),"Defines a sinusoidal time-varying source","SIN(0 5V 1kHz)","offset: DC offset, amplitude: peak amplitude, frequency: frequency, delay: time delay, damping: damping factor","Sinusoidal waveform generation","AC signal testing, oscillator analysis","pulse, exp" +sources,pulse_source,pulse,PULSE( ),"Defines a pulse waveform source","PULSE(0 5V 0 1ns 1ns 50ns 100ns)","v1/v2: low/high values, td: delay, tr/tf: rise/fall times, pw: pulse width, per: period","Digital signal generation","Clock signals, switching analysis","sin, exp" +sources,exponential_source,exp,EXP( ),"Defines an exponential waveform source","EXP(0 5V 0 1us 50us 2us)","v1/v2: initial/final values, td1: rise delay, tau1: rise time constant, td2: fall delay, tau2: fall time constant","Exponential transient analysis","RC/RL circuit step response","pulse, sin" +sources,piecewise_linear,pwl,PWL( ...),"Defines a piecewise linear source","PWL(0 0V 1us 5V 2us 5V 3us 0V)","t1,v1,t2,v2: time-voltage pairs","Arbitrary waveform generation","Custom signal shapes","pulse, sin" +sources,single_freq_fm,sffm,SFFM( ),"Single-frequency FM source","SFFM(0 1V 1MHz 5 1kHz)","offset: DC offset, amplitude: carrier amplitude, carrier_freq: carrier frequency, mod_index: modulation index, signal_freq: modulating frequency","Frequency modulation","Communication system modeling","am, sin" +sources,amplitude_modulation,am,AM( ),"Amplitude modulated source","AM(0 1V 1MHz 1kHz 0.5)","offset: DC offset, amplitude: carrier amplitude, carrier_freq: carrier frequency, mod_freq: modulation frequency, mod_depth: modulation depth","Amplitude modulation","Communication circuits","sffm, sin" +sources,random_noise,trnoise,TRNOISE( ),"Transient noise source","TRNOISE(0.1V 1ns 1)","amplitude: noise amplitude, time_step: time step, type: noise type (1=uniform, 2=gaussian)","Noise injection","Noise analysis, jitter simulation","sin, pulse" +sources,file_source,file_source,FILE=,"Source from external file","FILE=input_data.txt","filename: data file path","External stimulus","Complex waveform generation","pwl, behavioral" +models,diode_model,diode_model,.MODEL D (),"Defines a diode model",".MODEL 1N4148 D (IS=5.84n RS=0.592 N=1.906 TT=4n CJO=0.95p VJ=0.55 M=0.278 FC=0.5 ISR=0.09n NR=2.71 BV=100 IBV=0.1u)","name: model name, parameters: diode model parameters","Diode device modeling","Rectifier circuits, voltage regulation","bjt_model, mosfet_model" +models,bjt_model,bjt_model,.MODEL NPN/PNP (),"Defines a BJT model",".MODEL 2N2222 NPN (IS=1.14f XTI=3 EG=1.11 VAF=74.03 BF=255.9 NE=1.307 ISE=14.34f IKF=0.2847 XTB=1.5 BR=6.092 NC=2 ICS=0 IKR=0 RC=1 CJC=7.306p MJC=0.3416 VJC=0.75 FC=0.5 CJE=22.01p MJE=0.377 VJE=0.75 TR=46.91n TF=411.1p XTF=0.7371 VTF=1.7 ITF=0.6 RB=10)","name: model name, type: NPN or PNP, parameters: BJT model parameters","BJT device modeling","Amplifier design, switching circuits","diode_model, mosfet_model" +models,mosfet_model,mosfet_model,.MODEL NMOS/PMOS (),"Defines a MOSFET model",".MODEL NMOS NMOS (LEVEL=1 VTO=0.7 KP=120u GAMMA=0.37 PHI=0.65 LAMBDA=0.02 RD=0 RS=0 CBD=0 CBS=0 IS=0 PB=0.87 CGSO=0.1n CGDO=0.1n CGBO=1n)","name: model name, type: NMOS or PMOS, parameters: MOSFET model parameters","MOSFET device modeling","Digital circuits, power electronics","bjt_model, diode_model" +models,resistor_model,resistor_model,.MODEL R (),"Defines a resistor model",".MODEL RMOD R (TC1=0.001 TC2=0.0001 RSH=100)","name: model name, parameters: temperature coefficients, sheet resistance","Temperature-dependent resistor modeling","Precision circuits, temperature sensing","capacitor_model, inductor_model" +models,capacitor_model,capacitor_model,.MODEL C (),"Defines a capacitor model",".MODEL CMOD C (CJ=1e-12 CJSW=5e-11 DEFW=1e-6 NARROW=0)","name: model name, parameters: junction capacitance, sidewall capacitance, default width, narrowing","Capacitor device modeling","Precision timing circuits","resistor_model, inductor_model" +models,inductor_model,inductor_model,.MODEL L (),"Defines an inductor model",".MODEL LMOD L (TC1=0.001 TC2=0.0001 IL1=0 IL2=0)","name: model name, parameters: temperature coefficients, current coefficients","Inductor device modeling","RF circuits, power inductors","resistor_model, capacitor_model" +models,switch_model,switch_model,.MODEL SW (),"Defines a switch model",".MODEL SMOD SW (VT=1 VH=0.1 RON=1 ROFF=1MEG)","name: model name, parameters: threshold voltage, hysteresis, on/off resistance","Switch device modeling","Digital circuits, power switches","current_switch_model, relay_model" +models,current_switch_model,current_switch_model,.MODEL CSW (),"Defines a current-controlled switch model",".MODEL CSMOD CSW (IT=1mA IH=0.1mA RON=1 ROFF=1MEG)","name: model name, parameters: threshold current, hysteresis, on/off resistance","Current switch modeling","Current-sensing circuits","switch_model, cccs" +models,transmission_line_model,tline_model,.MODEL TRA (),"Defines a transmission line model",".MODEL TLINE TRA (Z0=50 TD=5ns)","name: model name, parameters: characteristic impedance, time delay","Transmission line modeling","High-frequency circuits, PCB design","lossy_tline_model, coupled_tline_model" +models,lossy_tline_model,lossy_tline_model,.MODEL LTRA (),"Defines a lossy transmission line model",".MODEL LOSSYTLINE LTRA (R=1 L=1nH C=1pF G=0 LEN=1)","name: model name, parameters: resistance, inductance, capacitance, conductance per unit length","Lossy transmission line modeling","Realistic PCB trace modeling","tline_model, coupled_tline_model" +models,jfet_model,jfet_model,.MODEL NJF/PJF (),"Defines a JFET model",".MODEL 2N3819 NJF (VTO=-3 BETA=1.304m RD=1 RS=1 LAMBDA=2.25m IS=33.57f CGS=1.2p CGD=1.2p PB=1 FC=0.5)","name: model name, type: NJF or PJF, parameters: JFET model parameters","JFET device modeling","High-impedance amplifiers, analog switches","mosfet_model, bjt_model" +models,behavioral_model,behavioral_model,.MODEL BSIM3 (),"Defines a BSIM3 MOSFET model",".MODEL NMOS BSIM3 (TYPE=1 MOBMOD=1 CAPMOD=2 NOIMOD=1)","name: model name, parameters: BSIM3 parameters","Advanced MOSFET modeling","Sub-micron CMOS design","mosfet_model, psp_model" +control_structures,if_statement,if,.IF ,"Conditional execution in control blocks",".IF (TEMP > 27) .PARAM VDD=3.0 .ELSE .PARAM VDD=3.3 .ENDIF","condition: logical expression","Conditional parameter setting","Process variation analysis","param, control" +control_structures,for_loop,for,.FOR ,"Loop control structure",".FOR I 1 10 1 .PARAM R{I}=I*1k .ENDFOR","var: loop variable, start/stop: range, step: increment","Iterative parameter sweeps","Monte Carlo analysis, optimization","while, param" +control_structures,while_loop,while,.WHILE ,"While loop control structure",".WHILE (V(out) < 2.5) alter @R1[resistance]=@R1[resistance]*1.1 run .ENDWHILE","condition: continuation condition","Conditional looping","Iterative circuit optimization","for, if" +control_structures,control_block,control,.CONTROL ... .ENDC,"Defines a control block for scripting",".CONTROL run plot v(out) .ENDC","none","Groups multiple commands","Automated simulation sequences","if, for" +control_structures,repeat,repeat,.REPEAT ,"Repeats a block of commands",".REPEAT 10 alter @R1[resistance]=@R1[resistance]*1.1 run .ENDREP","count: number of repetitions","Fixed iteration loops","Parameter sweeps","for, while" +control_structures,break,break,break,"Breaks out of loop structures","break","none","Exits current loop","Loop control","continue, for" +control_structures,continue,continue,continue,"Continues to next loop iteration","continue","none","Skips to next iteration","Loop control","break, for" +control_structures,function,function,define (),"Defines a user function","define mygain(x) (x*100)","name: function name, args: argument list","User-defined functions","Custom calculations","param, let" +parameters,parameter_definition,param,.PARAM =,"Defines a parameter",".PARAM VDD=5V R1VAL=1k","name: parameter name, value: parameter value","Parameterized circuit design","Design exploration, optimization","global, step" +parameters,global_parameter,global,.GLOBAL ,"Declares global nodes",".GLOBAL VDD VSS","node_list: space-separated node names","Global node declaration","Power and ground distribution","param, subckt" +parameters,step_parameter,step,.STEP ,"Defines parameter stepping",".STEP PARAM VDD 3 5 0.1","param: parameter name, start/stop: range, step: increment","Parameter sweep analysis","Design centering, yield analysis","param, monte" +parameters,alter,alter,alter =,"Modifies device parameters during simulation","alter @R1[resistance]=2k","device: device name, parameter: parameter to change, value: new value","Runtime parameter modification","Interactive circuit tuning","param, step" +parameters,save_parameter,save,save @[],"Saves device parameters for plotting","save @M1[gm] @M1[gds]","device: device name, parameter: parameter to save","Parameter tracking","Device characteristic analysis","plot, print" +parameters,macro,macro,.MACRO ,"Defines a macro",".MACRO OPAMP inp inm out .SUBCKT OPAMP {inp} {inm} {out} ... .ENDS .ENDMACRO","name: macro name, args: argument list","Macro definition","Code reuse, templating","param, subckt" +parameters,define,define,define ,"Defines a constant or expression","define PI 3.14159 define GAIN {VDD/2}","name: constant name, expression: value or expression","Constant definition","Mathematical constants","param, let" +subcircuits,subcircuit_definition,subckt,.SUBCKT [PARAMS:],"Defines a subcircuit",".SUBCKT OPAMP 1 2 3 PARAMS: GAIN=100k .ENDS","name: subcircuit name, node_list: external nodes, PARAMS: optional parameters","Hierarchical circuit design","Reusable circuit blocks","ends, x" +subcircuits,subcircuit_end,ends,.ENDS [name],"Ends a subcircuit definition",".ENDS OPAMP","name: optional subcircuit name","Closes subcircuit definition","Completing circuit hierarchy","subckt" +subcircuits,subcircuit_call,x,X ,"Instantiates a subcircuit","X1 1 2 3 OPAMP","name: instance name, node_list: connection nodes, subckt_name: subcircuit to instantiate","Using defined subcircuits","Building complex systems","subckt, include" +subcircuits,hierarchical_path,hierarchical,.HIER ,"Defines hierarchical subcircuit path",".HIER X1.X2.OPAMP","subcircuit_path: path to nested subcircuit","Nested subcircuit access","Complex system debugging","subckt, x" +subcircuits,protect,protect,.PROTECT ... .UNPROTECT,"Protects subcircuit code from modification",".PROTECT .SUBCKT SECRET 1 2 ... .ENDS .UNPROTECT","none","Code protection","IP protection in libraries","subckt, lib" +subcircuits,interface,interface,.INTERFACE ,"Defines subcircuit interface",".INTERFACE VDD VSS IN OUT","pin_list: external pin names","Interface specification","Standardized subcircuit interfaces","subckt, global" +output_control,print_control,print,print ,"Prints values or expressions","print v(out) i(r1)*@r1[resistance]","expression: vector or mathematical expression","Data output and verification","Result analysis","plot, write" +output_control,write_control,write,write ,"Writes data to file","write output.txt v(out) i(vin)","filename: output file, vector_list: vectors to write","Data export for external analysis","Post-processing, documentation","print, plot" +output_control,echo_control,echo,echo ,"Displays text message","echo Simulation completed successfully","text: message to display","User feedback and status","Script debugging, user interface","print" +output_control,wrdata,wrdata,wrdata ,"Writes data in raw format","wrdata output.raw v(out) i(vin)","filename: output file, vector_list: vectors to write","Binary data export","High-speed data export","write, rawfile" +output_control,format,format,format ,"Sets output format","format scientific","type: format type (scientific, engineering, fixed)","Output formatting","Customized data display","print, write" +output_control,log,log,log ,"Logs commands to file","log simulation.log","filename: log file","Command logging","Session recording","echo, write" +output_control,spool,spool,spool ,"Redirects output to file","spool output.txt","filename: output file","Output redirection","Batch processing","write, log" +output_control,hardcopy,hardcopy,hardcopy ,"Saves plot to file","hardcopy plot.ps plot","filename: output file, plot_type: plot format","Plot export","Documentation, reporting","plot, write" +simulation_control,initial_conditions,ic,.IC =,"Sets initial node voltages",".IC V(1)=2.5 V(2)=0","node: circuit node, value: initial voltage","Initial condition specification","Transient analysis setup","nodeset, uic" +simulation_control,nodeset,nodeset,.NODESET =,"Provides nodeset hints",".NODESET V(1)=2.5","node: circuit node, value: voltage hint","Convergence assistance","Difficult convergence cases","ic, options" +simulation_control,temperature,temp,.TEMP ,"Sets simulation temperature",".TEMP 27 85 125","value: temperature in Celsius","Temperature variation analysis","Thermal design verification","options, param" +simulation_control,options,options,.OPTIONS