Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines67891011121314151617181 unmodified line2021222324252627282930313 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121133 unmodified lines11711811912012112212342 unmodified lines16616716816917017117217317417517617717817918018145 unmodified lines2272282292302312322332342352362372386 unmodified lines24524624724824925025125225325425525613 unmodified lines27027127227327427527643 unmodified lines32032132232332432532680 unmodified lines4074084094104114124134143 unmodified lines4184194204214224234244254264274284294304314324334344354364374384394404414424434441 unmodified line44644744844945045145245345445545645745845946046146246346446515 unmodified lines48148248348448548648723 unmodified lines5115125135145155165175185195205215222 unmodified lines5255265275285295305315325335345355 unmodified lines5415425435445455465475485495505517 unmodified lines5595605615625635645659 unmodified lines5755765775785795 unmodified linesimport os # Still needed for API key potentially, but not model namesfrom pathlib import Pathimport time# --- Configuration ---# Model names are now discovered dynamically. Remove hardcoded names.MAX_PROMPT_TOKENS_ESTIMATE = 800000 # Keep this estimateRESULTS_PAGE_SIZE = 25AVAILABLE_ANALYSES = { # Keep analyses config"generate_docs": "Generate Missing Docstrings/Comments","find_bugs": "Identify Potential Bugs & Anti-patterns","check_style": "Check Style Guide Compliance (General)",1 unmodified line"suggest_refactoring": "Suggest Refactoring Opportunities",}CODE_EXTENSIONS = {'.py', '.js', '.java', '.c', '.cpp', '.h', '.cs', '.go', '.rb','.php', '.swift', '.kt', '.ts', '.html', '.css', '.scss', '.sql'} # Keep extensions# --- Session State Initialization ---# (Keep most session state, add one for the selected model)if 'mock_api_call' not in st.session_state:st.session_state.mock_api_call = Falseif 'analysis_results' not in st.session_state:3 unmodified linesif 'analysis_requested' not in st.session_state:st.session_state.analysis_requested = Falseif 'selected_model_name' not in st.session_state:st.session_state.selected_model_name = None # Will hold the "models/..." nameif 'available_models_dict' not in st.session_state:st.session_state.available_models_dict = {} # Store display_name -> name mapping# --- Gemini API Setup & Model Discovery ---model = None # Global variable for the initialized model instance# --- NEW: Function to list available models ---@st.cache_data(ttl=3600) # Cache model list for an hourdef get_available_models():"""Lists models supporting 'generateContent' using the API key."""model_dict = {}try:if 'GEMINI_API_KEY' not in st.secrets:# Don't stop here, let the main part handle it, but return emptyprint("API key not found in secrets during model listing attempt.")return {}# Configure API key temporarily just for listinggenai.configure(api_key=st.secrets["GEMINI_API_KEY"])print("Listing available models via API...")for m in genai.list_models():# Check if the model supports the 'generateContent' methodif 'generateContent' in m.supported_generation_methods:# Store mapping: user-friendly name -> internal namemodel_dict[m.display_name] = m.nameprint(f"Found {len(model_dict)} compatible models.")return model_dictexcept Exception as e:st.error(f"π¨ Error listing available models: {e}")return {} # Return empty on errordef initialize_gemini_model():"""Initializes the Gemini model based on the selected name."""global modelselected_name = st.session_state.get('selected_model_name')if selected_name and model is None and not st.session_state.mock_api_call:try:if 'GEMINI_API_KEY' not in st.secrets:st.error("π¨ Gemini API Key not found. Add it to `.streamlit/secrets.toml`.")st.stop() # Stop if key missing for initialization# Configure API key (might be redundant if list_models worked, but safe)genai.configure(api_key=st.secrets["GEMINI_API_KEY"])print(f"Initializing Gemini Model: {selected_name}")# Use the selected model name from session statemodel = genai.GenerativeModel(model_name=selected_name)print(f"Gemini Model Initialized ({selected_name}).")return Trueexcept Exception as e:st.error(f"π¨ Error initializing selected Gemini model '{selected_name}': {e}")st.session_state.selected_model_name = None # Reset selection on errorst.stop()return Falseelif st.session_state.mock_api_call:return True # No init needed for mock modeelif model is not None and model.model_name == selected_name:return True # Already initialized with the correct modelelif model is not None and model.model_name != selected_name:print("Model changed. Re-initializing...")model = None # Reset model instancereturn initialize_gemini_model() # Recurse to re-initialize with new nameelif not selected_name and not st.session_state.mock_api_call:# This case happens if no model is selected yetreturn False # Cannot initialize without a selectionreturn False # Default case# --- Helper Functions ---# Updated estimate_token_count to support integers and stringsdef estimate_token_count(text):"""Estimates the token count.If a string is provided, it calculates based on its length.If an integer is provided (e.g., total character count), it uses that directly."""if isinstance(text, int):return text // 33 unmodified linesdef process_zip_file_cached(file_id, file_size, file_content_bytes):"""Processes a ZIP file and extracts code files.Returns a tuple of (code_files dict, total_chars, file_count, ignored_files list)."""code_files = {}total_chars = 042 unmodified linesst.error(f"π¨ ZIP Error: {e}")return None, 0, 0, []if file_count == 0:if not ignored_files:st.warning("No code files found.")else:st.warning("No code files found; some skipped.")return code_files, total_chars, file_count, ignored_filesdef construct_analysis_prompt(code_files_dict, requested_analyses):"""Constructs the prompt for analysis by including code files and JSON structure for expected output.Returns the full prompt and a list of included files."""prompt_parts = ["Analyze the following codebase...\n\n"]current_token_estimate = estimate_token_count(prompt_parts[0])45 unmodified linesdef call_gemini_api(prompt):"""Calls the Gemini API using the provided prompt.Returns the parsed JSON insights or an error message."""if not prompt:return None, "Prompt generation failed."# MOCK MODEif st.session_state.mock_api_call:st.info(" MOCK MODE: Simulating API call...")time.sleep(1)6 unmodified lines})st.success("Mock response generated.")return json.loads(mock_json_response), None# REAL API CALLelse:if not initialize_gemini_model():return None, "Gemini Model Initialization Failed."if model is None:return None, "Gemini model not selected or available." # Added checktry:api_status = st.empty()api_status.info(f"π‘ Sending request to {model.model_name} (Est. prompt tokens: {estimate_token_count(prompt):,})... Please wait.")13 unmodified linesapi_status.empty()try:json_response_text = response.text.strip()# Remove markdown code fences if presentif json_response_text.startswith("```json"):json_response_text = json_response_text[7:]if json_response_text.startswith("```"):43 unmodified linesdef display_results(results_json, requested_analyses):"""Displays the analysis results with pagination and allows JSON download."""st.header("π Analysis Report")if not isinstance(results_json, dict):80 unmodified linesst.set_page_config(page_title="Codebase Audit Assistant", layout="wide")st.title("π€ Codebase Audit & Documentation Assistant")# --- Sidebar ---with st.sidebar:st.header("βοΈ Analysis Controls")st.session_state.mock_api_call = st.toggle("π§ͺ Enable Mock API Mode",3 unmodified linesst.divider()st.header("β Select Model")# --- NEW: Dynamic Model Selection ---if not st.session_state.mock_api_call:# Get available models (uses cache)st.session_state.available_models_dict = get_available_models()model_display_names = list(st.session_state.available_models_dict.keys())if model_display_names:# Try to find the index of the previously selected modelcurrent_model_display_name = Noneif st.session_state.selected_model_name:# Find display name matching the stored internal namefor disp_name, internal_name in st.session_state.available_models_dict.items():if internal_name == st.session_state.selected_model_name:current_model_display_name = disp_namebreaktry:selected_index = model_display_names.index(current_model_display_name) if current_model_display_name in model_display_names else 0except ValueError:selected_index = 0 # Default to first if previous selection not foundselected_display_name = st.selectbox("Choose Gemini model:",options=model_display_names,1 unmodified linekey="model_selector",help="Select the Gemini model to use for analysis.")# Update session state with the internal name based on selectionst.session_state.selected_model_name = st.session_state.available_models_dict.get(selected_display_name)st.info(f"Using REAL Gemini API ({st.session_state.selected_model_name})")elif 'GEMINI_API_KEY' in st.secrets:st.warning("No compatible models found or error listing models. Check API Key permissions.")st.session_state.selected_model_name = None # Ensure no model selectedelse:st.warning("Add GEMINI_API_KEY to secrets to list models.")st.session_state.selected_model_name = Noneelse: # Mock mode is activest.info("Mock API Mode ACTIVE")st.session_state.selected_model_name = "mock_model" # Use a placeholder name for mock mode# --- End Dynamic Model Selection ---st.divider()st.header("π Select Analyses")selected_analyses = [15 unmodified linesst.divider()st.warning("β οΈ **Privacy:** Code sent to Google API if Mock Mode is OFF.")# Update title dynamically based on selected modelif st.session_state.selected_model_name and not st.session_state.mock_api_call:st.markdown(f"Upload codebase (`.zip`) for analysis via **{st.session_state.selected_model_name}**.")elif st.session_state.mock_api_call:23 unmodified linesfile_id, uploaded_file.size, uploaded_file_bytes)if code_files is not None:st.info(f"Found **{file_count}** code files ({total_chars:,} chars). Est. tokens: ~{estimate_token_count(total_chars):,}")if ignored_files:with st.expander(f"View {len(ignored_files)} Skipped/Ignored Files"):st.code("\n".join(ignored_files), language='text')# Disable button if no model selected (and not in mock mode)model_ready = bool(st.session_state.selected_model_name) or st.session_state.mock_api_callanalyze_button_disabled = (not selected_analyses or file_count == 0 or not model_ready)analyze_button_label = "Analyze Codebase"2 unmodified lineselif analyze_button_disabled:analyze_button_label = "Select Analyses or Upload Valid Code"if analysis_button_placeholder.button(analyze_button_label,type="primary",disabled=analyze_button_disabled):st.session_state.analysis_requested = Truest.session_state.analysis_results = Nonest.session_state.error_message = None5 unmodified linesst.warning("Please select a Gemini model from the sidebar.")else:with results_placeholder:spinner_model_name = (st.session_state.selected_model_nameif not st.session_state.mock_api_callelse "Mock Mode")spinner_msg = f"π Preparing prompt & contacting AI ({spinner_model_name})... Please wait."with st.spinner(spinner_msg):analysis_prompt, included_files_in_prompt = construct_analysis_prompt(code_files, selected_analyses)7 unmodified linesst.session_state.error_message = "Failed to generate analysis prompt."st.rerun()# Display results (Keep the same logic)if st.session_state.analysis_requested:with results_placeholder:st.divider()9 unmodified lineselif not uploaded_file:results_placeholder.info("Upload a ZIP file to begin.")results_placeholder.divider()results_placeholder.markdown("_Assistant powered by Google Gemini._")5 unmodified lines6789101112131415161718191 unmodified line21222324252627282930313 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061073 unmodified lines11111211311411511611742 unmodified lines16016116216316416516616716816917017117245 unmodified lines2182192202212222232242252262272286 unmodified lines23523623723823924024124224324424513 unmodified lines25926026126226326443 unmodified lines30830931031131231331480 unmodified lines3953963973983994004014024034044054064074084094104114124134144153 unmodified lines4194204214224234244254264274284294304314324334344354364374381 unmodified line44044144244344444544644744844945045145245345445545645715 unmodified lines47347447547647747847923 unmodified lines5035045055065075085095105115125135145152 unmodified lines5185195205215225235245 unmodified lines5305315325335345355367 unmodified lines5445455465475485495509 unmodified lines5605615625635645655665675685695705715725735745755765775785795805815825835845 unmodified linesimport os # Still needed for API key potentially, but not model namesfrom pathlib import Pathimport timeimport plotly.express as pximport pandas as pd# --- Configuration ---MAX_PROMPT_TOKENS_ESTIMATE = 800000 # Token estimate limitRESULTS_PAGE_SIZE = 25AVAILABLE_ANALYSES = {"generate_docs": "Generate Missing Docstrings/Comments","find_bugs": "Identify Potential Bugs & Anti-patterns","check_style": "Check Style Guide Compliance (General)",1 unmodified line"suggest_refactoring": "Suggest Refactoring Opportunities",}CODE_EXTENSIONS = {'.py', '.js', '.java', '.c', '.cpp', '.h', '.cs', '.go', '.rb','.php', '.swift', '.kt', '.ts', '.html', '.css', '.scss', '.sql'}# --- Session State Initialization ---if 'mock_api_call' not in st.session_state:st.session_state.mock_api_call = Falseif 'analysis_results' not in st.session_state:3 unmodified linesif 'analysis_requested' not in st.session_state:st.session_state.analysis_requested = Falseif 'selected_model_name' not in st.session_state:st.session_state.selected_model_name = None # Internal model nameif 'available_models_dict' not in st.session_state:st.session_state.available_models_dict = {} # Mapping: display -> internalif 'file_count' not in st.session_state:st.session_state.file_count = 0if 'total_chars' not in st.session_state:st.session_state.total_chars = 0# --- Gemini API Setup & Model Discovery ---model = None # Global variable for the initialized model instance@st.cache_data(ttl=3600)def get_available_models():"""Lists models supporting 'generateContent' using the API key."""model_dict = {}try:if 'GEMINI_API_KEY' not in st.secrets:print("API key not found in secrets during model listing attempt.")return {}genai.configure(api_key=st.secrets["GEMINI_API_KEY"])print("Listing available models via API...")for m in genai.list_models():if 'generateContent' in m.supported_generation_methods:model_dict[m.display_name] = m.nameprint(f"Found {len(model_dict)} compatible models.")return model_dictexcept Exception as e:st.error(f"π¨ Error listing available models: {e}")return {}def initialize_gemini_model():"""Initializes the Gemini model based on the selected name."""global modelselected_name = st.session_state.get('selected_model_name')if selected_name and model is None and not st.session_state.mock_api_call:try:if 'GEMINI_API_KEY' not in st.secrets:st.error("π¨ Gemini API Key not found. Add it to `.streamlit/secrets.toml`.")st.stop()genai.configure(api_key=st.secrets["GEMINI_API_KEY"])print(f"Initializing Gemini Model: {selected_name}")model = genai.GenerativeModel(model_name=selected_name)print(f"Gemini Model Initialized ({selected_name}).")return Trueexcept Exception as e:st.error(f"π¨ Error initializing selected Gemini model '{selected_name}': {e}")st.session_state.selected_model_name = Nonest.stop()return Falseelif st.session_state.mock_api_call:return Trueelif model is not None and model.model_name == selected_name:return Trueelif model is not None and model.model_name != selected_name:print("Model changed. Re-initializing...")model = Nonereturn initialize_gemini_model()elif not selected_name and not st.session_state.mock_api_call:return Falsereturn False# --- Helper Functions ---def estimate_token_count(text):"""Estimates the token count.If a string is provided, calculates based on length.If an integer is provided (e.g., total character count), uses that directly."""if isinstance(text, int):return text // 33 unmodified linesdef process_zip_file_cached(file_id, file_size, file_content_bytes):"""Processes a ZIP file and extracts code files.Returns (code_files dict, total_chars, file_count, ignored_files list)."""code_files = {}total_chars = 042 unmodified linesst.error(f"π¨ ZIP Error: {e}")return None, 0, 0, []if file_count == 0:st.warning("No code files found." if not ignored_files else "No code files found; some skipped.")return code_files, total_chars, file_count, ignored_filesdef construct_analysis_prompt(code_files_dict, requested_analyses):"""Constructs the prompt for analysis by including code files and JSON structure.Returns the full prompt and list of included files."""prompt_parts = ["Analyze the following codebase...\n\n"]current_token_estimate = estimate_token_count(prompt_parts[0])45 unmodified linesdef call_gemini_api(prompt):"""Calls the Gemini API using the provided prompt.Returns parsed JSON insights or an error message."""if not prompt:return None, "Prompt generation failed."if st.session_state.mock_api_call:st.info(" MOCK MODE: Simulating API call...")time.sleep(1)6 unmodified lines})st.success("Mock response generated.")return json.loads(mock_json_response), Noneelse:if not initialize_gemini_model():return None, "Gemini Model Initialization Failed."if model is None:return None, "Gemini model not selected or available."try:api_status = st.empty()api_status.info(f"π‘ Sending request to {model.model_name} (Est. prompt tokens: {estimate_token_count(prompt):,})... Please wait.")13 unmodified linesapi_status.empty()try:json_response_text = response.text.strip()if json_response_text.startswith("```json"):json_response_text = json_response_text[7:]if json_response_text.startswith("```"):43 unmodified linesdef display_results(results_json, requested_analyses):"""Displays analysis results with pagination and a downloadable JSON report."""st.header("π Analysis Report")if not isinstance(results_json, dict):80 unmodified linesst.set_page_config(page_title="Codebase Audit Assistant", layout="wide")st.title("π€ Codebase Audit & Documentation Assistant")# --- Sidebar Enhancements ---with st.sidebar:# Dark Mode Toggledark_mode = st.checkbox("Enable Dark Mode", value=False)if dark_mode:st.markdown("""<style>.reportview-container { background-color: #2E2E2E; color: white; }.sidebar .sidebar-content { background-color: #1A1A1A; }</style>""",unsafe_allow_html=True)st.header("βοΈ Analysis Controls")st.session_state.mock_api_call = st.toggle("π§ͺ Enable Mock API Mode",3 unmodified linesst.divider()st.header("β Select Model")if not st.session_state.mock_api_call:st.session_state.available_models_dict = get_available_models()model_display_names = list(st.session_state.available_models_dict.keys())if model_display_names:current_model_display_name = Noneif st.session_state.selected_model_name:for disp_name, internal_name in st.session_state.available_models_dict.items():if internal_name == st.session_state.selected_model_name:current_model_display_name = disp_namebreaktry:selected_index = model_display_names.index(current_model_display_name) if current_model_display_name in model_display_names else 0except ValueError:selected_index = 0selected_display_name = st.selectbox("Choose Gemini model:",options=model_display_names,1 unmodified linekey="model_selector",help="Select the Gemini model to use for analysis.")st.session_state.selected_model_name = st.session_state.available_models_dict.get(selected_display_name)st.info(f"Using REAL Gemini API ({st.session_state.selected_model_name})")elif 'GEMINI_API_KEY' in st.secrets:st.warning("No compatible models found or error listing models. Check API Key permissions.")st.session_state.selected_model_name = Noneelse:st.warning("Add GEMINI_API_KEY to secrets to list models.")st.session_state.selected_model_name = Noneelse:st.info("Mock API Mode ACTIVE")st.session_state.selected_model_name = "mock_model"st.divider()st.header("π Select Analyses")selected_analyses = [15 unmodified linesst.divider()st.warning("β οΈ **Privacy:** Code sent to Google API if Mock Mode is OFF.")# Update title based on selected modelif st.session_state.selected_model_name and not st.session_state.mock_api_call:st.markdown(f"Upload codebase (`.zip`) for analysis via **{st.session_state.selected_model_name}**.")elif st.session_state.mock_api_call:23 unmodified linesfile_id, uploaded_file.size, uploaded_file_bytes)if code_files is not None:# Save these metrics to session state for dashboard usest.session_state.file_count = file_countst.session_state.total_chars = total_charsst.info(f"Found **{file_count}** code files ({total_chars:,} chars). Est. tokens: ~{estimate_token_count(total_chars):,}")if ignored_files:with st.expander(f"View {len(ignored_files)} Skipped/Ignored Files"):st.code("\n".join(ignored_files), language='text')model_ready = bool(st.session_state.selected_model_name) or st.session_state.mock_api_callanalyze_button_disabled = (not selected_analyses or file_count == 0 or not model_ready)analyze_button_label = "Analyze Codebase"2 unmodified lineselif analyze_button_disabled:analyze_button_label = "Select Analyses or Upload Valid Code"if analysis_button_placeholder.button(analyze_button_label, type="primary", disabled=analyze_button_disabled):st.session_state.analysis_requested = Truest.session_state.analysis_results = Nonest.session_state.error_message = None5 unmodified linesst.warning("Please select a Gemini model from the sidebar.")else:with results_placeholder:spinner_model_name = st.session_state.selected_model_name if not st.session_state.mock_api_call else "Mock Mode"spinner_msg = f"π Preparing prompt & contacting AI ({spinner_model_name})... Please wait."with st.spinner(spinner_msg):analysis_prompt, included_files_in_prompt = construct_analysis_prompt(code_files, selected_analyses)7 unmodified linesst.session_state.error_message = "Failed to generate analysis prompt."st.rerun()# Display analysis results if availableif st.session_state.analysis_requested:with results_placeholder:st.divider()9 unmodified lineselif not uploaded_file:results_placeholder.info("Upload a ZIP file to begin.")# --- Audit Dashboard ---# If analysis results exist, display an interactive dashboard summarizing key metrics.if st.session_state.analysis_results:st.subheader("Audit Dashboard")# Compute metrics from session state and analysis resultsmetrics = {"Files Analyzed": st.session_state.file_count,"Total Tokens": estimate_token_count(st.session_state.total_chars)}metrics["Documentation Suggestions"] = len(st.session_state.analysis_results.get("documentation_suggestions", []))metrics["Potential Bugs"] = len(st.session_state.analysis_results.get("potential_bugs", []))metrics["Style Issues"] = len(st.session_state.analysis_results.get("style_issues", []))metrics["Module Summaries"] = len(st.session_state.analysis_results.get("module_summaries", []))metrics["Refactoring Suggestions"] = len(st.session_state.analysis_results.get("refactoring_suggestions", []))# Create a DataFrame and a bar chart using Plotlydf_metrics = pd.DataFrame(list(metrics.items()), columns=["Metric", "Value"])fig = px.bar(df_metrics, x="Metric", y="Value", title="Audit Summary Metrics")st.plotly_chart(fig)results_placeholder.divider()results_placeholder.markdown("_Assistant powered by Google Gemini._")
app.py+77-72