Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506import gradio as grimport osimport jsonimport timeimport argparsefrom typing import Dict, List, Anyfrom pathlib import Path# Assume the helper classes and functions are in the same directory as before or refactored below# ----- Prompt Analyzer Code (Refactored) -----import reimport google.generativeai as genaifrom tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_typefrom threading import Lock# ----- Simplified Rate Limiter (for Gradio) -----class RateLimiter:def __init__(self, rate: int, per: int):self.rate = rateself.per = perself.tokens = rateself.last_update = time.time()self.lock = Lock()def _add_tokens(self):now = time.time()time_passed = now - self.last_updatenew_tokens = time_passed * (self.rate / self.per)if new_tokens > 0:self.tokens = min(self.rate, self.tokens + new_tokens)self.last_update = nowdef acquire(self) -> float:with self.lock:self._add_tokens()if self.tokens >= 1:self.tokens -= 1return 0.0wait_time = (1 - self.tokens) * (self.per / self.rate)return wait_time# ----- Constants and Utility Functions (Simplified) -----RELEVANT_EXTENSIONS = {".py", ".js", ".ts", ".jsx", ".tsx", ".java", ".cpp", ".c", ".h", ".hpp", ".rb", ".php",".go", ".rs", ".swift", ".kt", ".kts", ".scala", ".pl", ".pm", ".r", ".sh", ".bat", ".ps1",".lua", ".sql", ".html", ".css", ".xml", ".json", ".yaml", ".yml", ".md", ".ipynb", ".m", ".mm",".vb", ".cs", ".fs", ".fsx", ".erl", ".hrl", ".ex", ".exs", ".dart", ".groovy", ".jl", ".clj",".cljs", ".coffee", ".litcoffee", ".rkt", ".hs", ".lhs", ".ml", ".mli", ".nim", ".cr",".nimble", ".hx", ".hxsl", ".hxproj", ".hxcpp", ".hxcs", ".hxjava", ".hxcpp", ".hxnode",".hxphp", ".hxpy", ".hxrb", ".hxswf", ".hxvm", ".hxweb", ".hxwin", ".hxwpf", ".sol", ".vy",}LANGUAGE_EXTENSIONS = {".py": "Python", ".js": "JavaScript", ".ts": "TypeScript", ".jsx": "React", ".tsx": "React TypeScript",".java": "Java", ".cpp": "C++", ".c": "C", ".h": "C/C++ Header", ".hpp": "C++ Header", ".rb": "Ruby",".php": "PHP", ".go": "Go", ".rs": "Rust", ".swift": "Swift", ".kt": "Kotlin", ".kts": "Kotlin Script",".scala": "Scala", ".pl": "Perl", ".pm": "Perl Module", ".r": "R", ".sh": "Shell", ".bat": "Batch",".ps1": "PowerShell", ".lua": "Lua", ".sql": "SQL", ".html": "HTML", ".css": "CSS", ".xml": "XML",".json": "JSON", ".yaml": "YAML", ".yml": "YAML", ".md": "Markdown", ".ipynb": "Jupyter Notebook",".m": "MATLAB/Objective-C", ".mm": "Objective-C++", ".vb": "Visual Basic", ".cs": "C#", ".fs": "F#",".fsx": "F# Script", ".erl": "Erlang", ".hrl": "Erlang Header", ".ex": "Elixir", ".exs": "Elixir Script",".dart": "Dart", ".groovy": "Groovy", ".jl": "Julia", ".clj": "Clojure", ".cljs": "ClojureScript",".coffee": "CoffeeScript", ".litcoffee": "Literate CoffeeScript", ".rkt": "Racket", ".hs": "Haskell",".lhs": "Literate Haskell", ".ml": "OCaml", ".mli": "OCaml Interface", ".nim": "Nim", ".cr": "Crystal",".nimble": "Nimble", ".hx": "Haxe", ".hxsl": "Haxe Shader", ".hxproj": "Haxe Project", ".hxcpp": "Haxe C++",".hxcs": "Haxe C#", ".hxjava": "Haxe Java", ".hxnode": "Haxe Node.js", ".hxphp": "Haxe PHP", ".hxpy": "Haxe Python",".hxrb": "Haxe Ruby", ".hxswf": "Haxe SWF", ".hxvm": "Haxe VM", ".hxweb": "Haxe Web", ".hxwin": "Haxe Windows",".hxwpf": "Haxe WPF", ".sol": "Solidity", ".vy": "Vyper",}PACKAGE_FILES = {"package.json": "npm", "requirements.txt": "pip", "setup.py": "python", "pom.xml": "maven","build.gradle": "gradle", "Gemfile": "bundler", "Cargo.toml": "cargo", "go.mod": "go", "go.sum": "go","composer.json": "composer", "pubspec.yaml": "dart", "Project.toml": "julia", "mix.exs": "elixir","Makefile": "make", "CMakeLists.txt": "cmake", "SConstruct": "scons", "build.xml": "ant","Rakefile": "rake", "shard.yml": "crystal", "nim.cfg": "nim", "default.nix": "nix","stack.yaml": "haskell", "rebar.config": "erlang", "rebar.lock": "erlang","rebar3.config": "erlang", "rebar3.lock": "erlang", "project.clj": "leiningen", "deps.edn": "clojure","build.boot": "boot", "build.sbt": "sbt", "Brewfile": "homebrew", "Vagrantfile": "vagrant","Dockerfile": "docker", "docker-compose.yml": "docker-compose", "Procfile": "heroku", "tox.ini": "tox","pyproject.toml": "poetry", "Pipfile": "pipenv", "Pipfile.lock": "pipenv","environment.yml": "conda", "meta.yaml": "conda",}def _clean_diff(diff_output: str) -> str:lines = diff_output.split("\n")cleaned_lines = []for line in lines:if line.startswith("diff --git") or line.startswith("index ") or line.startswith("new file mode ") or line.startswith("deleted file mode "):continueif line.startswith("--- ") or line.startswith("+++ "):if "/dev/null" in line:continuecleaned_lines.append(line.split("/")[-1])continueif line.startswith("@@ ") or line.startswith("+") or line.startswith("-") or line.startswith(" "):cleaned_lines.append(line)return "\n".join(cleaned_lines)# ----- PromptAnalyzer (Integrated into Gradio App) -----class PromptAnalyzer:SYSTEM_PROMPT = ("You are an experienced software engineer and data analyst tasked with building a report on developer's ""coding style, technical background, approach to problem solving, architectural thinking, technology ""choices, re-used frameworks etc,. There will be a set of prompts, divided into CODE STYLE ANALYSIS, ""TEMPORAL ANALYSIS, PROJECT PREFERENCES ANALYSIS and IDENTITY CONFIDENCE CALCULATION together with ""data samples provided to you. You'll summarize your findings from all of the modules in a single ""comprehensive IDENTITY CALCULATION CONFIDENCE output. Output a valid JSON, avoid including to many ""strings into the list objects! Follow the instructions provided for this section:")def __init__(self, api_key: str):self.api_key = api_keygenai.configure(api_key=self.api_key)self.model = genai.GenerativeModel(model_name="gemini-1.5-flash-001",system_instruction=self.SYSTEM_PROMPT)self.token_count = 0self.rate_limiter = RateLimiter(rate=5, per=60) # Simplified rate limiterself.prompt_count = 0 # Track prompt countdef count_tokens(self, text: str) -> int:try:return self.model.count_tokens(text).total_tokensexcept Exception:return len(text) // 4 # Fallbackdef _clean_json_response(self, response_text: str) -> str:match = re.search(r"```(?:json)?\n(.*?)```", response_text, re.DOTALL)return match.group(1).strip() if match else response_text.strip()@retry(retry=retry_if_exception_type(Exception), # Use simplified retrystop=stop_after_attempt(3),wait=wait_exponential(multiplier=2, min=1, max=10) # Shorter wait times)def _rate_limited_generate(self, prompt: str) -> Any:while True:wait_time = self.rate_limiter.acquire()if wait_time == 0:return self.model.generate_content(prompt)#print(f"Rate limit: Wait {wait_time:.2f}s")time.sleep(wait_time)def generate_json_response(self, prompt: str) -> Dict[str, Any]:"""Generate and parse JSON response with error handling for Gradio."""self.prompt_count += 1try:input_tokens = self.count_tokens(prompt)response = self._rate_limited_generate(prompt) # Simplified, retries internallyoutput_token_count = response.usage_metadata.total_token_count #Correct output tokenstotal_tokens = input_tokens + output_token_countself.token_count += total_tokens # Update global token countcleaned_response = self._clean_json_response(response.text)return json.loads(cleaned_response)except json.JSONDecodeError:return {"error": "Invalid JSON response from model. Check API Key and Prompt."}except Exception as e: # Added Exception clausereturn {"error": f"Error during generation: {str(e)}"}# ----- Analysis Functions (Adapted for Gradio) -----def analyze_repository_structure(repo_path: Path) -> Dict[str, Any]:"""Simplified structure analysis."""def create_tree(path: Path, depth=0):if depth > 3: # Limit recursionreturn {"type": "note", "message": "Depth limit reached"}tree = {"type": "directory", "name": path.name,"path": str(path.relative_to(repo_path)), "children": []}if path.name in {".git", "node_modules", "__pycache__"}:return treetry:for item in path.iterdir():if item.is_file() and item.suffix.lower() in RELEVANT_EXTENSIONS:tree["children"].append({"type": "file","name": item.name,"path": str(item.relative_to(repo_path)),"extension": item.suffix.lower(),"size": item.stat().st_size})elif item.is_dir():tree["children"].append(create_tree(item, depth+1))except PermissionError:passreturn treestructure = create_tree(repo_path)# Simplified: only return structure. No language/doc extraction for demo.return {"structure": structure}def _read_source_file(full_path: Path) -> str:if not full_path.is_file() or full_path.suffix.lower() not in RELEVANT_EXTENSIONS:return ""encodings = ["utf-8", "latin-1", "cp1252"]for encoding in encodings:try:with open(full_path, "r", encoding=encoding) as f:content = f.read()if "\0" not in content: # Simple binary checkreturn contentexcept UnicodeDecodeError:continuereturn ""def _extract_code_samples(repo_path: Path, structure, prompt_analyzer: PromptAnalyzer) -> Dict:"""Extract core/config code samples."""#Simplified logic - include some larger filesdef gather_files(node, files_list):if node["type"] == "file" :files_list.append(node)elif node["type"] == "directory":for child in node.get("children", []):gather_files(child, files_list)all_files = []gather_files(structure, all_files)all_files_sorted = sorted(all_files, key=lambda x: x.get("size", 0), reverse=False) # Sort ascending by size# Prepare structurefiltered_structure = analyze_repository_structure(repo_path)# Filter function, simplifieddef filter_large_files(node):if node.get("type") == "directory":node["children"] = [child for child in node.get("children", []) if child.get("type") == "directory" or child.get("type") == "file"]# Apply the simplified filterfilter_large_files(filtered_structure["structure"]) # Access the structure directly# Simplified file identification logic (no LLM call)prompt = f"""Analyze the repository structures and identify the most relevant files for codebase analysis.Focus on files that would reveal:1. Core functionality and architecture2. Main business logic3. Key utilities and helpers4. Configuration and setupResults will be used for further code analysis. Remember to include ALL relevant files, especially for fullstack applications. Be thorough but concise. Avoid including non-original code, e.g., dependencies or libraries code. AVOID INCLUDING MORE THAN 50 FILES PER REPOSITORY!!! TRY TO INCLUDE LESS THAN 20 IF POSSIBLE. CORE_FILES ARE THE PRIORITY, YOU CAN OMITT THE REST IF IT EXCEEDS THE LIMIT.Return a JSON object with these categories:{{"repositories": {{"repo_name": {{"core_files": ["list of most important files"],"secondary_files": ["list of supporting files"],"config_files": ["list of relevant config files"]}},}}}}CRITICAL REQUIREMENTS:Limit each list of most important files to a maximum of 20 files!!!Avoid including binary files or large data files. Only include files that are essential for understanding the codebase. Avoid including too many files, focus on the most important ones. Avoid including files that user did not write, e.g., dependencies or libraries code. Avoid including utility files that are not essential for understanding the codebase. Focus on including only source code, some repositories may have a lot of files, but only a few are essential for understanding the codebase. Do not include long .json files or other artifact type of files - notice "size" of the file in the structure.Repository structures:{json.dumps(filtered_structure, indent=2)}Only include files that exist in the structure. Return valid JSON format.DO NOT wrap the JSON in markdown code blocks."""# Simplified file categorization (replace LLM call here if needed)core_files = [f["path"] for f in all_files_sorted if "main" in f["name"].lower() or "app" in f["name"].lower()][:20]config_files = [f["path"] for f in all_files_sorted if f["name"].lower() in PACKAGE_FILES][:10]samples = {"core_files": {}, "config_files": {}}for file_path in core_files + config_files:category = "core_files" if file_path in core_files else "config_files"full_file_path = repo_path / file_pathsource_code = _read_source_file(full_file_path) # Use absolute pathif source_code:samples[category][file_path] = source_codereturn samplesdef analyze_code_style(repo_path: Path, structure, prompt_analyzer: PromptAnalyzer) -> Dict:"""Analyze code style, integrated with Gradio UI."""samples = _extract_code_samples(repo_path, structure, prompt_analyzer)repo_name = repo_path.namecombined_samples = {"samples": samples}prompt = f"""CODE STYLE ANALYSISYou are an expert in code stylometry and developer behavior analysis. Analyze this repository to create a detailed profile of the developer's coding patterns, preferences, and habits.Repository: {repo_name}Code samples and structure:{json.dumps(combined_samples, indent=2)}Focus on identifying unique, individual coding patterns that could distinguish this developer's style. Analyze how they:- Structure their code and control flow- Handle data and state- Approach problem-solving- Maintain code quality- Handle edge cases and errorsIMPORTANT CONSTRAINTS:- Maximum 10 patterns per list category- No repeating similar patterns- Use "Unknown" if pattern cannot be determined- Focus on distinctive, personal coding traitsGenerate a JSON profile with this EXACT structure:... (Rest of the prompt as provided)"""try:response = prompt_analyzer.generate_json_response(prompt)#print("RAW:", response)return response if not isinstance(response, str) else {"error": response} # Corrected responseexcept Exception as e:return {"error": f"Error in analyze_code_style: {str(e)}"}def analyze_project_preferences(repo_path: Path, structure, samples, prompt_analyzer: PromptAnalyzer) -> Dict:"""Analyze project preferences with error handling for Gradio."""repo_name = repo_path.name# Simplified language determination (can be expanded)languages = ", ".join(set(LANGUAGE_EXTENSIONS.get(file["extension"].lower(), "")for file in (structure.get("structure", {}).get("children", []))if file["type"] == "file"))combined_data = {"languages": languages,"structure": structure,"samples": samples,}prompt = f"""PROJECT PREFERENCES ANALYSISYou are an expert in developer profiling and technical background analysis. Study this repository to build a comprehensive profile of the developer's technical preferences and knowledge domains.Repository: {repo_name}Languages: {combined_data.get('languages', 'Unknown')}Project Structure: {json.dumps(combined_data.get('structure', {}), indent=2)}Core Files: {json.dumps(combined_data.get('samples', {}).get('core_files', {}), indent=2)}Dependencies:{json.dumps(combined_data.get('samples', {}).get('package_files', {}), indent=2)}Analyze deeply to infer:1. Technical background and expertise level2. Problem-solving approaches and mathematical foundations3. Security awareness and defensive programming practices4. Development environment preferencesGenerate detailed JSON analysis:... (Rest of the prompt as provided, similar to original version) ..."""try:result = prompt_analyzer.generate_json_response(prompt)return result if not isinstance(result, str) else {"error": result} # Corrected response handlingexcept Exception as e:return {"error": f"Error in project preferences analysis: {e}"}# --- Main Gradio App ---def analyze_code(username: str, api_key: str, repo_name_input: str = "") -> str:if not api_key or not username:return "Error: Please provide both a GitHub username and a valid Gemini API key."# Create directory and initial filesbase_output_dir = Path("out")user_output_dir = base_output_dir / usernametry:if not user_output_dir.exists():os.makedirs(user_output_dir, exist_ok=True)# Placeholder content for initial report.json.with open(user_output_dir / "report.json", "w") as f:json.dump({"message": "Placeholder, waiting for repository input. Please run `gh-analyze` CLI first."}, f)repo_structure_file = user_output_dir / "stylometry_repo_structure.json"#Check if file is already processed and we can load cached filesif repo_structure_file.exists():with open(repo_structure_file, "r") as f:sources_data = json.load(f).get("stylometry_repo_structure")repo_names = list(sources_data.keys()) if 'sources_data' in locals() else []except (FileNotFoundError, json.JSONDecodeError, OSError) as e:return f"Error setting up initial files: {e}"if repo_names:# Pre-populate repo name if only one repo is availableif len(repo_names) == 1:repo_name_input = repo_names[0]elif not repo_name_input: # If more than one and none providedreturn "Error: Please provide a valid repository name."elif not repo_name_input:return "Error: Please enter repository or re-run github downloader and parser CLI, `gh-analyze <username>`, command and set username"#Ensure we select repo pathrepo_name = repo_name_input# --- Main analysis logic (simplified) ---prompt_analyzer = PromptAnalyzer(api_key) # Key handlingrepo_path = user_output_dir / f"{username}_{repo_name}.git"if not repo_path.exists():return f"Repository path {repo_path} does not exist. Check your input and rerun `gh-analyze <username>` tool first to make sure repositories have been downloaded correctly."#return# 1. Analyze repository structuretry:if 'sources_data' not in locals():sources_data = analyze_repository_structure(repo_path)else:if repo_name not in sources_data:return f"Repository data for '{repo_name}' not found. Check report.json."repo_structure = sources_data.get(repo_name, {})if repo_structure:# Update structure with analyzed informationrepo_structure.update(analyze_repository_structure(repo_path).get(repo_name, {}))structure = repo_structure.get("structure", {}) # Pass structure here# Save (cache) data againif not repo_structure_file.exists():output_path = user_output_dir / "stylometry_repo_structure.json"with open(output_path, "w") as f:json.dump({"stylometry_repo_structure": { repo_name :repo_structure }}, f, indent=2)except Exception as e: # Better exception handlingreturn f"Structure Analysis Error: {str(e)}"# 2. Code style analysis (within the same try-except block)code_style_result = analyze_code_style(repo_path, structure, prompt_analyzer)if "error" in code_style_result:return f"Code Style Analysis Error: {code_style_result['error']}"samples = _extract_code_samples(repo_path, structure, prompt_analyzer) # Pass file_categories, get only samples# 3. Analyze Project Preferences (still inside the same try-except)project_preferences_result = analyze_project_preferences(repo_path, structure, samples, prompt_analyzer)if "error" in project_preferences_result:return f"Project Preferences Error: {project_preferences_result['error']}"# 4. Add TEMPORAL_PATTERNS (Optional for the simple Gradio App)# Final Report Compilationtry:final_report = {"repository_name": repo_name,"code_style": code_style_result,"project_preferences": project_preferences_result,}output_path = user_output_dir / "stylometry_profile.json"with open(output_path, "w") as f:json.dump({"stylometric_profile": final_report}, f, indent=2)return json.dumps(final_report, indent=2)except Exception as e:return f"Final Report Compilation Error: {e}"# Gradio Interface Setupiface = gr.Interface(fn=analyze_code,inputs=[gr.Textbox(label="GitHub Username"),gr.Textbox(label="Gemini API Key", type="password"),gr.Textbox(label="Repository Name (Optional - select from preprocessed or use default one if single repository found. Run CLI tools from gh-fake-analyzer project first)")],outputs=gr.Textbox(label="Analysis Result"),title="Code Style Analyzer",description="Analyze the code style of a GitHub repository using Gemini 1.5 Flash.",)if __name__ == "__main__":iface.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152import gradio as grimport osimport jsonimport tempfileimport shutilfrom pathlib import Pathfrom typing import Dict, Any, Tuple, Listfrom dotenv import load_dotenv# Import all the analyzer modulesfrom analyze_repository_structure import analyze_repository_structurefrom analyze_code_style import analyze_code_stylefrom analyze_temportal_patterns import analyze_temporal_patternsfrom analyze_project_preferences import analyze_project_preferencesfrom calculate_identity_confidence import calculate_identity_confidencefrom repository_selector import RepositorySelectorfrom prompt_analyzer import create_handler# Load environment variablesload_dotenv()class StyleAnalyzerApp:def __init__(self):self.temp_dir = tempfile.mkdtemp()self.handler = create_handler()def cleanup(self):"""Clean up temporary files"""shutil.rmtree(self.temp_dir)def process_upload(self,files: List[tempfile.NamedTemporaryFile],username: str,github_token: str = None,gemini_key: str = None) -> Tuple[str, Dict]:"""Process uploaded files and perform analysis"""# Set environment variables if providedif github_token:os.environ["GH_TOKEN"] = github_tokenif gemini_key:os.environ["GEMINI_API_KEY"] = gemini_key# Create user directoryuser_path = Path(self.temp_dir) / usernameuser_path.mkdir(parents=True, exist_ok=True)# Process uploaded filesreport_data = Nonefor file in files:if file.name.endswith('report.json'):with open(file.name, 'r') as f:report_data = json.load(f)# Save to user directorywith open(user_path / 'report.json', 'w') as out_f:json.dump(report_data, out_f)else:# Copy other files to user directoryshutil.copy2(file.name, user_path)if not report_data:return "Error: No report.json file found in uploads", Nonetry:# Initialize repository selectorrepo_selector = RepositorySelector(self.temp_dir, username)sources_to_analyze = repo_selector.select_repositories(report_data)# Analyze repository structuresources_data = analyze_repository_structure(sources_to_analyze, user_path)# Perform analysescode_style = analyze_code_style(sources_data)temporal_patterns = analyze_temporal_patterns(sources_data, report_data)project_preferences = analyze_project_preferences(sources_data)# Calculate final identity confidenceidentity_confidence = calculate_identity_confidence(sources_data,code_style,project_preferences,temporal_patterns)# Combine resultsanalysis_results = {"code_style_metrics": code_style,"temporal_patterns": temporal_patterns,"project_preferences": project_preferences,"identity_confidence": identity_confidence,}return "Analysis completed successfully!", analysis_resultsexcept Exception as e:return f"Error during analysis: {str(e)}", Nonedef create_interface(self):"""Create the Gradio interface"""with gr.Blocks(title="GitHub Stylometry Analyzer") as interface:gr.Markdown("""# GitHub Stylometry AnalyzerUpload your GitHub repository files and analyze coding patterns and style.""")with gr.Row():with gr.Column():username = gr.Textbox(label="GitHub Username")github_token = gr.Textbox(label="GitHub Token (optional)",placeholder="Your GitHub API token",type="password")gemini_key = gr.Textbox(label="Google Gemini API Key (optional)",placeholder="Your Gemini API key",type="password")files = gr.File(label="Upload Repository Files",file_count="multiple")analyze_btn = gr.Button("Analyze")with gr.Column():status = gr.Textbox(label="Status")results = gr.JSON(label="Analysis Results")analyze_btn.click(fn=self.process_upload,inputs=[files, username, github_token, gemini_key],outputs=[status, results])return interfacedef main():app = StyleAnalyzerApp()interface = app.create_interface()try:interface.launch(share=True,enable_queue=True,max_threads=4)finally:app.cleanup()if __name__ == "__main__":main()
app.py+140-494