Gyaneshere/CodeAnalysis
0
1<!DOCTYPE html>2<html lang="en">3<head>4 <meta charset="UTF-8">5 <meta name="viewport" content="width=device-width, initial-scale=1.0">6 <title>AI-Powered Code Analysis Platform</title>7 <script src="https://cdn.tailwindcss.com"></script>8 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">9 <style>10 .gradient-bg {11 background: linear-gradient(135deg, #1e3a8a 0%, #7c3aed 100%);12 }13 .code-block {14 font-family: 'Courier New', monospace;15 background-color: #1e293b;16 color: #f8fafc;17 }18 .sidebar-item:hover .sidebar-tooltip {19 display: block;20 }21 .animate-float {22 animation: float 6s ease-in-out infinite;23 }24 @keyframes float {25 0% { transform: translateY(0px); }26 50% { transform: translateY(-20px); }27 100% { transform: translateY(0px); }28 }29 </style>30</head>31<body class="bg-gray-50 min-h-screen">32 <!-- Solution Definition & Architecture Overview -->33 <div class="container mx-auto px-4 py-12 max-w-7xl">34 <div class="gradient-bg text-white rounded-2xl p-8 mb-12 shadow-2xl">35 <h1 class="text-4xl font-bold mb-4">CodeReviewApp Architecture</h1>36 <h2 class="text-2xl font-semibold mb-6">AI-Powered Code Analysis Platform</h2>37 38 <div class="grid grid-cols-1 md:grid-cols-2 gap-8">39 <div>40 <h3 class="text-xl font-semibold mb-3">Use Case Strategy</h3>41 <ul class="space-y-3">42 <li class="flex items-start">43 <i class="fas fa-check-circle mt-1 mr-3 text-emerald-300"></i>44 <span>Automated code quality analysis using AI models</span>45 </li>46 <li class="flex items-start">47 <i class="fas fa-check-circle mt-1 mr-3 text-emerald-300"></i>48 <span>Security vulnerability detection in source code</span>49 </li>50 <li class="flex items-start">51 <i class="fas fa-check-circle mt-1 mr-3 text-emerald-300"></i>52 <span>Technical debt visualization and recommendations</span>53 </li>54 </ul>55 </div>56 57 <div>58 <h3 class="text-xl font-semibold mb-3">Enterprise Benefits</h3>59 <ul class="space-y-3">60 <li class="flex items-start">61 <i class="fas fa-chart-line mt-1 mr-3 text-amber-300"></i>62 <span>30-50% reduction in code review time</span>63 </li>64 <li class="flex items-start">65 <i class="fas fa-shield-alt mt-1 mr-3 text-amber-300"></i>66 <span>Early detection of security vulnerabilities</span>67 </li>68 <li class="flex items-start">69 <i class="fas fa-money-bill-wave mt-1 mr-3 text-amber-300"></i>70 <span>Reduced technical debt maintenance costs</span>71 </li>72 </ul>73 </div>74 </div>75 </div>76 77 <!-- UX/UI Blueprint -->78 <div class="bg-white rounded-2xl shadow-xl p-8 mb-12">79 <h2 class="text-3xl font-bold mb-6 text-gray-800">UX/UI Blueprint</h2>80 81 <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">82 <div class="lg:col-span-2">83 <h3 class="text-xl font-semibold mb-4 text-gray-700">Dashboard Layout</h3>84 <div class="border-2 border-dashed border-gray-300 rounded-xl p-6 h-96 bg-gradient-to-br from-gray-50 to-gray-100">85 <div class="flex h-full">86 <!-- Sidebar -->87 <div class="w-16 bg-gray-800 rounded-l-lg flex flex-col items-center py-4">88 <div class="mb-8 relative sidebar-item">89 <div class="w-10 h-10 bg-indigo-600 rounded-lg flex items-center justify-center text-white">90 <i class="fas fa-code"></i>91 </div>92 <div class="sidebar-tooltip absolute left-full ml-2 bg-gray-900 text-white px-2 py-1 rounded text-xs whitespace-nowrap hidden">93 Code Analysis94 </div>95 </div>96 <div class="mb-8 relative sidebar-item">97 <div class="w-10 h-10 bg-gray-700 rounded-lg flex items-center justify-center text-gray-300">98 <i class="fas fa-shield-alt"></i>99 </div>100 <div class="sidebar-tooltip absolute left-full ml-2 bg-gray-900 text-white px-2 py-1 rounded text-xs whitespace-nowrap hidden">101 Security Scan102 </div>103 </div>104 <div class="mb-8 relative sidebar-item">105 <div class="w-10 h-10 bg-gray-700 rounded-lg flex items-center justify-center text-gray-300">106 <i class="fas fa-chart-pie"></i>107 </div>108 <div class="sidebar-tooltip absolute left-full ml-2 bg-gray-900 text-white px-2 py-1 rounded text-xs whitespace-nowrap hidden">109 Metrics110 </div>111 </div>112 </div>113 114 <!-- Main Content -->115 <div class="flex-1 bg-white rounded-r-lg p-4 flex flex-col">116 <div class="flex justify-between items-center mb-4">117 <h4 class="font-semibold text-gray-700">Code Analysis Report</h4>118 <div class="flex space-x-2">119 <button class="px-3 py-1 bg-indigo-100 text-indigo-700 rounded text-sm">Export</button>120 <button class="px-3 py-1 bg-gray-100 text-gray-700 rounded text-sm">Share</button>121 </div>122 </div>123 124 <div class="flex-1 grid grid-cols-3 gap-4">125 <div class="bg-blue-50 rounded-lg p-3 col-span-2">126 <div class="h-6 bg-blue-200 rounded animate-pulse mb-2"></div>127 <div class="h-4 bg-blue-200 rounded animate-pulse w-3/4"></div>128 </div>129 <div class="bg-purple-50 rounded-lg p-3">130 <div class="h-6 bg-purple-200 rounded animate-pulse mb-2"></div>131 <div class="h-4 bg-purple-200 rounded animate-pulse w-1/2"></div>132 </div>133 <div class="bg-green-50 rounded-lg p-3">134 <div class="h-6 bg-green-200 rounded animate-pulse mb-2"></div>135 <div class="h-4 bg-green-200 rounded animate-pulse w-2/3"></div>136 </div>137 <div class="bg-yellow-50 rounded-lg p-3 col-span-3">138 <div class="h-6 bg-yellow-200 rounded animate-pulse mb-2"></div>139 <div class="h-4 bg-yellow-200 rounded animate-pulse w-full"></div>140 </div>141 </div>142 </div>143 </div>144 </div>145 </div>146 147 <div>148 <h3 class="text-xl font-semibold mb-4 text-gray-700">Design System</h3>149 <div class="space-y-4">150 <div>151 <p class="text-sm font-medium text-gray-500 mb-1">Primary Colors</p>152 <div class="flex space-x-2">153 <div class="w-12 h-12 rounded-lg bg-indigo-600"></div>154 <div class="w-12 h-12 rounded-lg bg-indigo-500"></div>155 <div class="w-12 h-12 rounded-lg bg-indigo-400"></div>156 </div>157 </div>158 <div>159 <p class="text-sm font-medium text-gray-500 mb-1">Secondary Colors</p>160 <div class="flex space-x-2">161 <div class="w-12 h-12 rounded-lg bg-emerald-500"></div>162 <div class="w-12 h-12 rounded-lg bg-amber-500"></div>163 <div class="w-12 h-12 rounded-lg bg-rose-500"></div>164 </div>165 </div>166 <div>167 <p class="text-sm font-medium text-gray-500 mb-1">Typography</p>168 <div class="space-y-2">169 <p class="text-lg font-bold text-gray-800">Heading 1</p>170 <p class="text-base font-medium text-gray-700">Body Text</p>171 <p class="text-sm text-gray-500">Caption</p>172 </div>173 </div>174 </div>175 </div>176 </div>177 178 <div class="bg-gray-50 rounded-xl p-6">179 <h3 class="text-xl font-semibold mb-4 text-gray-700">Accessibility Features</h3>180 <div class="grid grid-cols-1 md:grid-cols-3 gap-4">181 <div class="bg-white p-4 rounded-lg shadow-sm">182 <div class="w-10 h-10 bg-indigo-100 rounded-full flex items-center justify-center text-indigo-600 mb-3">183 <i class="fas fa-eye"></i>184 </div>185 <h4 class="font-medium mb-1">Color Contrast</h4>186 <p class="text-sm text-gray-600">4.5:1 minimum contrast ratio for all text</p>187 </div>188 <div class="bg-white p-4 rounded-lg shadow-sm">189 <div class="w-10 h-10 bg-indigo-100 rounded-full flex items-center justify-center text-indigo-600 mb-3">190 <i class="fas fa-keyboard"></i>191 </div>192 <h4 class="font-medium mb-1">Keyboard Nav</h4>193 <p class="text-sm text-gray-600">Full keyboard navigation support</p>194 </div>195 <div class="bg-white p-4 rounded-lg shadow-sm">196 <div class="w-10 h-10 bg-indigo-100 rounded-full flex items-center justify-center text-indigo-600 mb-3">197 <i class="fas fa-assistive-listening-systems"></i>198 </div>199 <h4 class="font-medium mb-1">Screen Reader</h4>200 <p class="text-sm text-gray-600">ARIA labels and semantic HTML</p>201 </div>202 </div>203 </div>204 </div>205 206 <!-- Frontend Engineering -->207 <div class="bg-white rounded-2xl shadow-xl p-8 mb-12">208 <h2 class="text-3xl font-bold mb-6 text-gray-800">Frontend Engineering</h2>209 210 <div class="mb-8">211 <h3 class="text-xl font-semibold mb-4 text-gray-700">React/TypeScript Architecture</h3>212 <div class="bg-gray-800 rounded-lg p-4 mb-4">213 <div class="flex items-center text-gray-400 text-sm mb-2">214 <i class="fas fa-folder-open mr-2"></i>215 <span>src/</span>216 </div>217 <div class="ml-6">218 <div class="flex items-center text-gray-400 text-sm mb-1">219 <i class="fas fa-folder mr-2"></i>220 <span>components/</span>221 </div>222 <div class="flex items-center text-gray-400 text-sm mb-1 ml-6">223 <i class="fas fa-file-code mr-2"></i>224 <span>CodeEditor.tsx</span>225 </div>226 <div class="flex items-center text-gray-400 text-sm mb-1 ml-6">227 <i class="fas fa-file-code mr-2"></i>228 <span>AnalysisResults.tsx</span>229 </div>230 <div class="flex items-center text-gray-400 text-sm mb-1 ml-6">231 <i class="fas fa-file-code mr-2"></i>232 <span>SecurityFindings.tsx</span>233 </div>234 235 <div class="flex items-center text-gray-400 text-sm mb-1">236 <i class="fas fa-folder mr-2"></i>237 <span>hooks/</span>238 </div>239 <div class="flex items-center text-gray-400 text-sm mb-1 ml-6">240 <i class="fas fa-file-code mr-2"></i>241 <span>useCodeAnalysis.ts</span>242 </div>243 244 <div class="flex items-center text-gray-400 text-sm mb-1">245 <i class="fas fa-folder mr-2"></i>246 <span>store/</span>247 </div>248 <div class="flex items-center text-gray-400 text-sm mb-1 ml-6">249 <i class="fas fa-file-code mr-2"></i>250 <span>analysisSlice.ts</span>251 </div>252 </div>253 </div>254 255 <div class="grid grid-cols-1 md:grid-cols-2 gap-6">256 <div>257 <h4 class="font-medium mb-2 text-gray-700">State Management</h4>258 <div class="bg-gray-50 p-4 rounded-lg">259 <pre class="text-xs code-block overflow-x-auto p-3 rounded">260// analysisSlice.ts261import { createSlice, PayloadAction } from '@reduxjs/toolkit';262 263interface AnalysisState {264 code: string;265 isLoading: boolean;266 results: CodeAnalysisResult | null;267 error: string | null;268}269 270const initialState: AnalysisState = {271 code: '',272 isLoading: false,273 results: null,274 error: null275};276 277const analysisSlice = createSlice({278 name: 'analysis',279 initialState,280 reducers: {281 setCode: (state, action: PayloadAction<string>) => {282 state.code = action.payload;283 },284 analyzeCodeStart: (state) => {285 state.isLoading = true;286 state.error = null;287 },288 analyzeCodeSuccess: (state, action: PayloadAction<CodeAnalysisResult>) => {289 state.isLoading = false;290 state.results = action.payload;291 },292 analyzeCodeFailure: (state, action: PayloadAction<string>) => {293 state.isLoading = false;294 state.error = action.payload;295 }296 }297});298 299export const { 300 setCode, 301 analyzeCodeStart, 302 analyzeCodeSuccess, 303 analyzeCodeFailure 304} = analysisSlice.actions;305 306export default analysisSlice.reducer;</pre>307 </div>308 </div>309 310 <div>311 <h4 class="font-medium mb-2 text-gray-700">Custom Hook</h4>312 <div class="bg-gray-50 p-4 rounded-lg">313 <pre class="text-xs code-block overflow-x-auto p-3 rounded">314// useCodeAnalysis.ts315import { useEffect } from 'react';316import { useDispatch, useSelector } from 'react-redux';317import { analyzeCodeStart, analyzeCodeSuccess, analyzeCodeFailure } from '../store/analysisSlice';318import { RootState } from '../store/store';319import api from '../services/api';320 321export const useCodeAnalysis = () => {322 const dispatch = useDispatch();323 const { code, isLoading, results, error } = useSelector(324 (state: RootState) => state.analysis325 );326 327 const analyzeCode = async () => {328 try {329 dispatch(analyzeCodeStart());330 const response = await api.post('/analyze', { code });331 dispatch(analyzeCodeSuccess(response.data));332 } catch (err) {333 dispatch(analyzeCodeFailure(err.message));334 }335 };336 337 return {338 code,339 isLoading,340 results,341 error,342 analyzeCode343 };344};</pre>345 </div>346 </div>347 </div>348 </div>349 350 <div class="mb-8">351 <h3 class="text-xl font-semibold mb-4 text-gray-700">Component Implementation</h3>352 353 <div class="bg-gray-50 p-4 rounded-lg mb-6">354 <pre class="text-xs code-block overflow-x-auto p-3 rounded">355// CodeEditor.tsx356import React, { useState, useEffect } from 'react';357import { useDispatch } from 'react-redux';358import { setCode } from '../store/analysisSlice';359import MonacoEditor from '@monaco-editor/react';360import { LoadingSpinner } from './ui/LoadingSpinner';361 362interface CodeEditorProps {363 initialValue?: string;364 language?: string;365}366 367export const CodeEditor: React.FC<CodeEditorProps> = ({368 initialValue = '',369 language = 'javascript'370}) => {371 const [value, setValue] = useState(initialValue);372 const dispatch = useDispatch();373 374 useEffect(() => {375 const timer = setTimeout(() => {376 dispatch(setCode(value));377 }, 500);378 379 return () => clearTimeout(timer);380 }, [value, dispatch]);381 382 return (383 <div className="border border-gray-200 rounded-lg overflow-hidden">384 <div className="bg-gray-800 px-4 py-2 flex justify-between items-center">385 <span className="text-sm text-gray-300">{language.toUpperCase()}</span>386 <button className="text-xs bg-indigo-600 text-white px-2 py-1 rounded">387 Analyze388 </button>389 </div>390 <MonacoEditor391 height="500px"392 language={language}393 theme="vs-dark"394 value={value}395 onChange={(newValue) => setValue(newValue || '')}396 loading={<LoadingSpinner />}397 options={{398 minimap: { enabled: false },399 fontSize: 14,400 wordWrap: 'on',401 automaticLayout: true402 }}403 />404 </div>405 );406};</pre>407 </div>408 409 <div class="grid grid-cols-1 md:grid-cols-2 gap-6">410 <div class="bg-gray-50 p-4 rounded-lg">411 <pre class="text-xs code-block overflow-x-auto p-3 rounded">412// AnalysisResults.tsx413import React from 'react';414import { CodeIssue } from '../types';415import { IssueSeverityBadge } from './ui/IssueSeverityBadge';416 417interface AnalysisResultsProps {418 issues: CodeIssue[];419 loading?: boolean;420}421 422export const AnalysisResults: React.FC<AnalysisResultsProps> = ({423 issues,424 loading = false425}) => {426 if (loading) {427 return <div className="text-center py-8">Analyzing code...</div>;428 }429 430 if (!issues || issues.length === 0) {431 return <div className="text-center py-8 text-gray-500">No issues found</div>;432 }433 434 return (435 <div className="space-y-4">436 {issues.map((issue, index) => (437 <div key={index} className="border border-gray-200 rounded-lg p-4">438 <div className="flex justify-between items-start mb-2">439 <h4 className="font-medium">{issue.message}</h4>440 <IssueSeverityBadge severity={issue.severity} />441 </div>442 <p className="text-sm text-gray-600 mb-2">443 Line {issue.line}: {issue.codeSnippet}444 </p>445 <p className="text-xs text-gray-500">{issue.ruleId}</p>446 </div>447 ))}448 </div>449 );450};</pre>451 </div>452 453 <div class="bg-gray-50 p-4 rounded-lg">454 <pre class="text-xs code-block overflow-x-auto p-3 rounded">455// SecurityFindings.tsx456import React from 'react';457import { SecurityFinding } from '../types';458import { CveBadge } from './ui/CveBadge';459 460interface SecurityFindingsProps {461 findings: SecurityFinding[];462}463 464export const SecurityFindings: React.FC<SecurityFindingsProps> = ({465 findings466}) => {467 return (468 <div className="space-y-4">469 {findings.map((finding, index) => (470 <div key={index} className="border border-red-200 rounded-lg p-4 bg-red-50">471 <div className="flex justify-between items-start mb-2">472 <h4 className="font-medium text-red-800">{finding.title}</h4>473 <CveBadge cveId={finding.cveId} />474 </div>475 <p className="text-sm text-red-700 mb-2">{finding.description}</p>476 <div className="flex space-x-2">477 <span className="text-xs px-2 py-1 bg-red-100 text-red-800 rounded">478 Severity: {finding.severity}479 </span>480 <span className="text-xs px-2 py-1 bg-red-100 text-red-800 rounded">481 Line: {finding.line}482 </span>483 </div>484 </div>485 ))}486 </div>487 );488};</pre>489 </div>490 </div>491 </div>492 </div>493 494 <!-- Backend & API Architecture -->495 <div class="bg-white rounded-2xl shadow-xl p-8 mb-12">496 <h2 class="text-3xl font-bold mb-6 text-gray-800">Backend & API Architecture</h2>497 498 <div class="mb-8">499 <h3 class="text-xl font-semibold mb-4 text-gray-700">FastAPI Service Structure</h3>500 <div class="bg-gray-800 rounded-lg p-4 mb-4">501 <div class="flex items-center text-gray-400 text-sm mb-2">502 <i class="fas fa-folder-open mr-2"></i>503 <span>app/</span>504 </div>505 <div class="ml-6">506 <div class="flex items-center text-gray-400 text-sm mb-1">507 <i class="fas fa-folder mr-2"></i>508 <span>api/</span>509 </div>510 <div class="flex items-center text-gray-400 text-sm mb-1 ml-6">511 <i class="fas fa-file-code mr-2"></i>512 <span>v1/</span>513 </div>514 <div class="flex items-center text-gray-400 text-sm mb-1 ml-12">515 <i class="fas fa-file-code mr-2"></i>516 <span>endpoints/</span>517 </div>518 <div class="flex items-center text-gray-400 text-sm mb-1 ml-6">519 <i class="fas fa-file-code mr-2"></i>520 <span>dependencies.py</span>521 </div>522 523 <div class="flex items-center text-gray-400 text-sm mb-1">524 <i class="fas fa-folder mr-2"></i>525 <span>core/</span>526 </div>527 <div class="flex items-center text-gray-400 text-sm mb-1 ml-6">528 <i class="fas fa-file-code mr-2"></i>529 <span>config.py</span>530 </div>531 532 <div class="flex items-center text-gray-400 text-sm mb-1">533 <i class="fas fa-folder mr-2"></i>534 <span>services/</span>535 </div>536 <div class="flex items-center text-gray-400 text-sm mb-1 ml-6">537 <i class="fas fa-file-code mr-2"></i>538 <span>code_analysis.py</span>539 </div>540 </div>541 </div>542 543 <div class="grid grid-cols-1 md:grid-cols-2 gap-6">544 <div>545 <h4 class="font-medium mb-2 text-gray-700">Main Application</h4>546 <div class="bg-gray-50 p-4 rounded-lg">547 <pre class="text-xs code-block overflow-x-auto p-3 rounded">548# main.py549from fastapi import FastAPI, Depends550from fastapi.middleware.cors import CORSMiddleware551from app.api.v1.endpoints import code_analysis, auth552from app.core.config import settings553 554app = FastAPI(555 title="Deepsite API",556 description="AI-powered code analysis platform",557 version="1.0.0",558 docs_url="/api/docs",559 redoc_url="/api/redoc"560)561 562# CORS middleware563app.add_middleware(564 CORSMiddleware,565 allow_origins=settings.BACKEND_CORS_ORIGINS,566 allow_credentials=True,567 allow_methods=["*"],568 allow_headers=["*"],569)570 571# Include API routers572app.include_router(573 auth.router,574 prefix="/api/v1/auth",575 tags=["authentication"]576)577app.include_router(578 code_analysis.router,579 prefix="/api/v1/analysis",580 tags=["code analysis"],581 dependencies=[Depends(auth.get_current_active_user)]582)</pre>583 </div>584 </div>585 586 <div>587 <h4 class="font-medium mb-2 text-gray-700">Authentication</h4>588 <div class="bg-gray-50 p-4 rounded-lg">589 <pre class="text-xs code-block overflow-x-auto p-3 rounded">590# auth.py591from datetime import datetime, timedelta592from typing import Optional593from fastapi import Depends, HTTPException, status594from fastapi.security import OAuth2PasswordBearer595from jose import JWTError, jwt596from passlib.context import CryptContext597from pydantic import BaseModel598from app.core.config import settings599 600# Password hashing601pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")602oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")603 604class Token(BaseModel):605 access_token: str606 token_type: str607 608class TokenData(BaseModel):609 username: Optional[str] = None610 611def verify_password(plain_password: str, hashed_password: str):612 return pwd_context.verify(plain_password, hashed_password)613 614def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):615 to_encode = data.copy()616 if expires_delta:617 expire = datetime.utcnow() + expires_delta618 else:619 expire = datetime.utcnow() + timedelta(minutes=15)620 to_encode.update({"exp": expire})621 encoded_jwt = jwt.encode(622 to_encode, 623 settings.SECRET_KEY, 624 algorithm=settings.ALGORITHM625 )626 return encoded_jwt627 628async def get_current_user(token: str = Depends(oauth2_scheme)):629 credentials_exception = HTTPException(630 status_code=status.HTTP_401_UNAUTHORIZED,631 detail="Could not validate credentials",632 headers={"WWW-Authenticate": "Bearer"},633 )634 try:635 payload = jwt.decode(636 token, 637 settings.SECRET_KEY, 638 algorithms=[settings.ALGORITHM]639 )640 username: str = payload.get("sub")641 if username is None:642 raise credentials_exception643 token_data = TokenData(username=username)644 except JWTError:645 raise credentials_exception646 647 user = get_user(fake_db, username=token_data.username)648 if user is None:649 raise credentials_exception650 return user</pre>651 </div>652 </div>653 </div>654 </div>655 656 <div class="mb-8">657 <h3 class="text-xl font-semibold mb-4 text-gray-700">API Endpoints</h3>658 659 <div class="bg-gray-50 p-4 rounded-lg mb-6">660 <pre class="text-xs code-block overflow-x-auto p-3 rounded">661# endpoints/code_analysis.py662from fastapi import APIRouter, Depends, HTTPException663from fastapi import status664from typing import List665from app.services.code_analysis import analyze_code666from app.models.schemas import CodeAnalysisRequest, CodeAnalysisResult667from app.api.v1.dependencies import get_current_active_user668 669router = APIRouter()670 671@router.post(672 "/",673 response_model=CodeAnalysisResult,674 summary="Analyze code for quality and security issues",675 description="""Analyzes the provided code for:676 - Code quality issues677 - Security vulnerabilities678 - Performance anti-patterns679 - Style violations""",680 response_description="Analysis results with found issues"681)682async def analyze_code_endpoint(683 request: CodeAnalysisRequest,684 current_user: str = Depends(get_current_active_user)685) -> CodeAnalysisResult:686 try:687 result = await analyze_code(request.code, request.language)688 return result689 except Exception as e:690 raise HTTPException(691 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,692 detail=f"Error analyzing code: {str(e)}"693 )694 695@router.get(696 "/history/",697 response_model=List[CodeAnalysisResult],698 summary="Get analysis history",699 description="Returns the user's previous code analysis results",700 response_description="List of previous analysis results"701)702async def get_analysis_history(703 current_user: str = Depends(get_current_active_user)704) -> List[CodeAnalysisResult]:705 # Implementation would query database for user's history706 return []</pre>707 </div>708 709 <div class="grid grid-cols-1 md:grid-cols-2 gap-6">710 <div class="bg-gray-50 p-4 rounded-lg">711 <pre class="text-xs code-block overflow-x-auto p-3 rounded">712# services/code_analysis.py713from typing import Optional714from app.models.schemas import CodeAnalysisResult, CodeIssue, SecurityFinding715from app.integrations.huggingface import query_hf_model716from app.integrations.sonarqube import analyze_with_sonarqube717 718async def analyze_code(719 code: str, 720 language: str = "python"721) -> CodeAnalysisResult:722 """Analyze code using multiple analysis methods"""723 724 # Initialize result objects725 quality_issues: List[CodeIssue] = []726 security_findings: List[SecurityFinding] = []727 728 # 1. Static analysis with SonarQube729 sonar_results = await analyze_with_sonarqube(code, language)730 quality_issues.extend(sonar_results.issues)731 732 # 2. AI-powered analysis with HuggingFace733 hf_prompt = f"""734 Analyze this {language} code for quality and security issues:735 {code}736 737 Return findings in JSON format with:738 - issue_type (quality|security|performance|style)739 - severity (low|medium|high|critical)740 - message741 - line_number742 - recommendation743 """744 745 hf_response = await query_hf_model(746 model="codellama/CodeLlama-34b-Instruct-hf",747 prompt=hf_prompt748 )749 750 # Process HF response and add to findings751 if hf_response and hf_response.get("findings"):752 for finding in hf_response["findings"]:753 if finding["issue_type"] == "security":754 security_findings.append(755 SecurityFinding.from_hf_response(finding)756 )757 else:758 quality_issues.append(759 CodeIssue.from_hf_response(finding)760 )761 762 return CodeAnalysisResult(763 quality_issues=quality_issues,764 security_findings=security_findings,765 summary=generate_summary(quality_issues, security_findings)766 )</pre>767 </div>768 769 <div class="bg-gray-50 p-4 rounded-lg">770 <pre class="text-xs code-block overflow-x-auto p-3 rounded">771# models/schemas.py772from pydantic import BaseModel, Field773from typing import List, Optional774from enum import Enum775 776class Severity(str, Enum):777 LOW = "low"778 MEDIUM = "medium"779 HIGH = "high"780 CRITICAL = "critical"781 782class CodeIssue(BaseModel):783 rule_id: str = Field(..., example="S100")784 message: str = Field(..., example="Avoid using 'eval' function")785 severity: Severity = Field(..., example="high")786 line: int = Field(..., example=42)787 code_snippet: str = Field(..., example="eval(user_input)")788 category: str = Field(..., example="security")789 790 @classmethod791 def from_hf_response(cls, data: dict):792 return cls(793 rule_id=data.get("rule_id", "AI-"+data["issue_type"]),794 message=data["message"],795 severity=data["severity"],796 line=data["line_number"],797 code_snippet=data.get("code_snippet", ""),798 category=data["issue_type"]799 )800 801class SecurityFinding(BaseModel):802 cve_id: Optional[str] = Field(None, example="CVE-2021-1234")803 title: str = Field(..., example="SQL Injection Vulnerability")804 description: str = Field(..., example="User input directly concatenated into SQL query")805 severity: Severity = Field(..., example="critical")806 line: int = Field(..., example=15)807 recommendation: str = Field(..., example="Use parameterized queries")808 809 @classmethod810 def from_hf_response(cls, data: dict):811 return cls(812 title=data["message"],813 description=data.get("recommendation", ""),814 severity=data["severity"],815 line=data["line_number"],816 recommendation=data.get("recommendation", "")817 )818 819class CodeAnalysisRequest(BaseModel):820 code: str = Field(..., example="def foo():\n pass")821 language: str = Field("python", example="python")822 823class CodeAnalysisResult(BaseModel):824 quality_issues: List[CodeIssue] = []825 security_findings: List[SecurityFinding] = []826 summary: str = Field(..., example="Found 3 critical issues")</pre>827 </div>828 </div>829 </div>830 </div>831 832 <!-- AI/ML Integration -->833 <div class="bg-white rounded-2xl shadow-xl p-8 mb-12">834 <h2 class="text-3xl font-bold mb-6 text-gray-800">AI/ML Integration</h2>835 836 <div class="grid grid-cols-1 md:grid-cols-2 gap-8 mb-8">837 <div>838 <h3 class="text-xl font-semibold mb-4 text-gray-700">HuggingFace Integration</h3>839 <div class="bg-gray-50 p-4 rounded-lg">840 <pre class="text-xs code-block overflow-x-auto p-3 rounded">841# integrations/huggingface.py842import os843from typing import Optional, Dict, Any844import httpx845from app.core.config import settings846from app.core.logging import logger847 848HF_API_URL = "https://api-inference.huggingface.co/models"849HF_API_KEY = settings.HF_API_KEY850 851async def query_hf_model(852 model: str,853 prompt: str,854 parameters: Optional[Dict[str, Any]] = None855) -> Optional[Dict[str, Any]]:856 """Query HuggingFace inference API"""857 858 headers = {859 "Authorization": f"Bearer {HF_API_KEY}",860 "Content-Type": "application/json"861 }862 863 payload = {864 "inputs": prompt,865 "parameters": parameters or {866 "max_new_tokens": 1024,867 "temperature": 0.7,868 "return_full_text": False869 }870 }871 872 try:873 async with httpx.AsyncClient(timeout=30.0) as client:874 response = await client.post(875 f"{HF_API_URL}/{model}",876 headers=headers,877 json=payload878 )879 880 if response.status_code == 200:881 return response.json()882 elif response.status_code == 503:883 # Model is loading, wait and retry884 logger.info(f"Model {model} is loading, retrying...")885 await asyncio.sleep(10)886 return await query_hf_model(model, prompt, parameters)887 else:888 logger.error(889 f"HF API error: {response.status_code} - {response.text}"890 )891 return None892 893 except Exception as e:894 logger.error(f"Error querying HF API: {str(e)}")895 return None</pre>896 </div>897 </div>898 899 <div>900 <h3 class="text-xl font-semibold mb-4 text-gray-700">Model Selection Strategy</h3>901 <div class="bg-gray-50 p-4 rounded-lg">902 <pre class="text-xs code-block overflow-x-auto p-3 rounded">903# services/model_selector.py904from enum import Enum905from typing import Optional, Dict, Any906from app.integrations.huggingface import query_hf_model907 908class ModelType(str, Enum):909 CODE_ANALYSIS = "code_analysis"910 SECURITY = "security"911 DOCUMENTATION = "documentation"912 913MODEL_MAP = {914 ModelType.CODE_ANALYSIS: "codellama/CodeLlama-34b-Instruct-hf",915 ModelType.SECURITY: "deepset/roberta-base-squad2",916 ModelType.DOCUMENTATION: "bigcode/starcoder"917}918 919def get_model_for_task(task_type: ModelType) -> str:920 """Get appropriate model for given task type"""921 return MODEL_MAP.get(task_type, MODEL_MAP[ModelType.CODE_ANALYSIS])922 923async def analyze_with_model(924 code: str,925 task_type: ModelType,926 language: str = "python"927) -> Optional[Dict[str, Any]]:928 """Analyze code with task-specific model"""929 930 model = get_model_for_task(task_type)931 prompt = generate_prompt_for_task(task_type, code, language)932 933 parameters = {934 "max_new_tokens": 1024,935 "temperature": 0.5 if task_type == ModelType.SECURITY else 0.7936 }937 938 return await query_hf_model(model, prompt, parameters)939 940def generate_prompt_for_task(941 task_type: ModelType,942 code: str,943 language: str944) -> str:945 """Generate task-specific prompt"""946 947 if task_type == ModelType.SECURITY:948 return f"""Analyze this {language} code for security vulnerabilities:949 {code}950 951 Return JSON with:952 - vulnerability_type953 - severity (low/medium/high/critical)954 - description955 - line_number956 - recommendation957 """958 elif task_type == ModelType.DOCUMENTATION:959 return f"""Generate documentation for this {language} code:960 {code}961 962 Include:963 - Function description964 - Parameters965 - Return value966 - Usage example967 """968 else: # Default code analysis969 return f"""Analyze this {language} code for quality issues:970 {code}971 972 Return JSON with:973 - issue_type (style/performance/bug)974 - severity (low/medium/high)975 - message976 - line_number977 - recommendation978 """</pre>979 </div>980 </div>981 </div>982 983 <div class="bg-gray-50 rounded-xl p-6">984 <h3 class="text-xl font-semibold mb-4 text-gray-700">AI Pipeline Architecture</h3>985 <div class="flex justify-center">986 <div class="relative w-full max-w-3xl">987 <!-- AI Pipeline Visualization -->988 <div class="flex flex-col items-center space-y-8">989 <!-- Step 1 -->990 <div class="flex items-center w-full">991 <div class="w-12 h-12 rounded-full bg-indigo-600 flex items-center justify-center text-white z-10">992 <i class="fas fa-code"></i>993 </div>994 <div class="ml-4 bg-white p-4 rounded-lg shadow-sm flex-1">995 <h4 class="font-medium">Code Input</h4>996 <p class="text-sm text-gray-600">User submits code for analysis</p>997 </div>998 </div>999 1000 <!-- Arrow -->1001 <div class="h-8 w-0.5 bg-indigo-300 ml-6 -my-4"></div>1002 1003 <!-- Step 2 -->1004 <div class="flex items-center w-full">1005 <div class="w-12 h-12 rounded-full bg-indigo-600 flex items-center justify-center text-white z-10">1006 <i class="fas fa-shield-alt"></i>1007 </div>1008 <div class="ml-4 bg-white p-4 rounded-lg shadow-sm flex-1">1009 <h4 class="font-medium">Static Analysis</h4>1010 <p class="text-sm text-gray-600">SonarQube scans for common issues</p>1011 </div>1012 </div>1013 1014 <!-- Arrow -->1015 <div class="h-8 w-0.5 bg-indigo-300 ml-6 -my-4"></div>1016 1017 <!-- Step 3 -->1018 <div class="flex items-center w-full">1019 <div class="w-12 h-12 rounded-full bg-indigo-600 flex items-center justify-center text-white z-10">1020 <i class="fas fa-brain"></i>1021 </div>1022 <div class="ml-4 bg-white p-4 rounded-lg shadow-sm flex-1">1023 <h4 class="font-medium">AI Analysis</h4>1024 <p class="text-sm text-gray-600">CodeLlama analyzes for complex patterns</p>1025 </div>1026 </div>1027 1028 <!-- Arrow -->1029 <div class="h-8 w-0.5 bg-indigo-300 ml-6 -my-4"></div>1030 1031 <!-- Step 4 -->1032 <div class="flex items-center w-full">1033 <div class="w-12 h-12 rounded-full bg-indigo-600 flex items-center justify-center text-white z-10">1034 <i class="fas fa-chart-bar"></i>1035 </div>1036 <div class="ml-4 bg-white p-4 rounded-lg shadow-sm flex-1">1037 <h4 class="font-medium">Results Aggregation</h4>1038 <p class="text-sm text-gray-600">Combine findings from all sources</p>1039 </div>1040 </div>1041 1042 <!-- Arrow -->1043 <div class="h-8 w-0.5 bg-indigo-300 ml-6 -my-4"></div>1044 1045 <!-- Step 5 -->1046 <div class="flex items-center w-full">1047 <div class="w-12 h-12 rounded-full bg-indigo-600 flex items-center justify-center text-white z-10">1048 <i class="fas fa-file-alt"></i>1049 </div>1050 <div class="ml-4 bg-white p-4 rounded-lg shadow-sm flex-1">1051 <h4 class="font-medium">Report Generation</h4>1052 <p class="text-sm text-gray-600">Create comprehensive report</p>1053 </div>1054 </div>1055 </div>1056 </div>1057 </div>1058 </div>1059 </div>1060 1061 <!-- Deployment & Scalability -->1062 <div class="bg-white rounded-2xl shadow-xl p-8 mb-12">1063 <h2 class="text-3xl font-bold mb-6 text-gray-800">Deployment & Scalability</h2>1064 1065 <div class="grid grid-cols-1 md:grid-cols-2 gap-8 mb-8">1066 <div>1067 <h3 class="text-xl font-semibold mb-4 text-gray-700">Docker Configuration</h3>1068 <div class="bg-gray-50 p-4 rounded-lg">1069 <pre class="text-xs code-block overflow-x-auto p-3 rounded">1070# Dockerfile1071FROM python:3.9-slim as base1072 1073# Install system dependencies1074RUN apt-get update && apt-get install -y \1075 build-essential \1076 curl \1077 && rm -rf /var/lib/apt/lists/*1078 1079# Create and activate virtual environment1080ENV VIRTUAL_ENV=/opt/venv1081RUN python3 -m venv $VIRTUAL_ENV1082ENV PATH="$VIRTUAL_ENV/bin:$PATH"1083 1084# Install Python dependencies1085WORKDIR /app1086COPY requirements.txt .1087RUN pip install --no-cache-dir -r requirements.txt1088 1089# Copy application code1090COPY . .1091 1092# Frontend build stage1093FROM node:16 as frontend-builder1094WORKDIR /app/frontend1095COPY frontend/package.json frontend/package-lock.json ./1096RUN npm install1097COPY frontend .1098RUN npm run build1099 1100# Final production image1101FROM base as production1102COPY --from=frontend-builder /app/frontend/dist /app/frontend/dist1103 1104# Set environment variables1105ENV PYTHONUNBUFFERED=11106ENV PORT=80001107ENV MODE=production1108 1109# Run application1110CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "$PORT"]</pre>1111 </div>1112 </div>1113 1114 <div>1115 <h3 class="text-xl font-semibold mb-4 text-gray-700">CI/CD Pipeline</h3>1116 <div class="bg-gray-50 p-4 rounded-lg">1117 <pre class="text-xs code-block overflow-x-auto p-3 rounded">1118# .github/workflows/deploy.yml1119name: Deploy to HuggingFace Spaces1120 1121on:1122 push:1123 branches: [ main ]1124 pull_request:1125 branches: [ main ]1126 1127jobs:1128 build-and-deploy:1129 runs-on: ubuntu-latest1130 steps:1131 - uses: actions/checkout@v31132 1133 - name: Set up Python1134 uses: actions/setup-python@v41135 with:1136 python-version: '3.9'1137 1138 - name: Install dependencies1139 run: |1140 python -m pip install --upgrade pip1141 pip install -r requirements.txt1142 1143 - name: Set up Node.js1144 uses: actions/setup-node@v31145 with:1146 node-version: '16'1147 1148 - name: Build frontend1149 working-directory: ./frontend1150 run: |1151 npm install1152 npm run build1153 1154 - name: Configure Docker1155 run: |1156 echo "${{ secrets.HF_TOKEN }}" | docker login \1157 -u ${{ secrets.HF_USERNAME }} \1158 --password-stdin \1159 ghcr.io1160 1161 - name: Build and push Docker image1162 run: |1163 docker build -t ghcr.io/${{ secrets.HF_USERNAME }}/deepsite:latest .1164 docker push ghcr.io/${{ secrets.HF_USERNAME }}/deepsite:latest1165 1166 - name: Deploy to Spaces1167 uses: huggingface/huggingface_hub@main1168 with:1169 huggingface_token: ${{ secrets.HF_TOKEN }}1170 repo_id: ${{ secrets.HF_USERNAME }}/deepsite1171 space_sdk: docker1172 space_hardware: cpu-basic1173 space_storage: small</pre>1174 </div>1175 </div>1176 </div>1177 1178 <div class="grid grid-cols-1 md:grid-cols-2 gap-8">1179 <div>1180 <h3 class="text-xl font-semibold mb-4 text-gray-700">Rate Limiting</h3>1181 <div class="bg-gray-50 p-4 rounded-lg">1182 <pre class="text-xs code-block overflow-x-auto p-3 rounded">1183# app/api/dependencies.py1184from fastapi import Depends, Request1185from fastapi.security import HTTPBearer1186from fastapi import HTTPException, status1187from redis import Redis1188from app.core.config import settings1189 1190security = HTTPBearer()1191redis = Redis.from_url(settings.REDIS_URL)1192 1193async def rate_limit(1194 request: Request,1195 credentials: str = Depends(security)1196) -> None:1197 """Rate limiting middleware"""1198 1199 # Get user ID from token1200 try: