Skip to content

Commit 5463493

Browse files
committed
fixes done
1 parent df24c4c commit 5463493

5 files changed

Lines changed: 318 additions & 19 deletions

File tree

app.py

Lines changed: 68 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,9 @@
3030

3131
# Import AI models
3232
try:
33-
from ai_models.github_analyzer import GitHubAnalyzer
34-
from ai_models.documentation_generator import DocumentationGenerator
35-
from ai_models.rag_pipeline import RAGPipeline
33+
from ai_models.github_analyzer import GitHubAnalyzer as GitHubAnalyzerModel
34+
from ai_models.documentation_generator import DocumentationGenerator as DocumentationGeneratorModel
35+
from ai_models.rag_pipeline import RAGPipeline as RAGPipelineModel
3636
logger = logging.getLogger(__name__)
3737
logger.info("AI models imported successfully")
3838
except ImportError as e:
@@ -48,13 +48,15 @@ def parse_github_url(self, repo_url: str) -> Dict[str, str]:
4848
def analyze_repository(self, repo_url: str) -> Dict[str, Any]:
4949
raise Exception("AI models not available - import failed")
5050

51-
class DocumentationGenerator:
52-
def generate_documentation(self, analysis_result: Dict[str, Any]) -> Dict[str, Any]:
51+
class DummyDocumentationGenerator:
52+
def generate_documentation(self, analysis_result: Dict[str, Any], rag_result: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
5353
raise Exception("AI models not available - import failed")
5454

5555
class RAGPipeline:
5656
def process(self, analysis_result: Dict[str, Any]) -> Dict[str, Any]:
5757
raise Exception("AI models not available - import failed")
58+
def process_repository(self, analysis_result: Dict[str, Any]) -> Dict[str, Any]:
59+
raise Exception("AI models not available - import failed")
5860

5961
# Load environment variables
6062
load_dotenv()
@@ -333,7 +335,7 @@ class DocumentationGenerator:
333335
def __init__(self):
334336
self.template_path = Path(__file__).parent / 'templates'
335337

336-
def generate_documentation(self, analysis_result: Dict[str, Any]) -> Dict[str, Any]:
338+
def generate_documentation(self, analysis_result: Dict[str, Any], rag_result: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
337339
"""Generate complete documentation package"""
338340
try:
339341
repo_info = analysis_result.get('repository_info', {})
@@ -1433,7 +1435,11 @@ def cleanup(self):
14331435

14341436
# Initialize components with better error handling
14351437
try:
1436-
github_analyzer = GitHubAnalyzer()
1438+
# Check if GitHubAnalyzerModel was successfully imported
1439+
if 'GitHubAnalyzerModel' in locals() or 'GitHubAnalyzerModel' in globals():
1440+
github_analyzer = GitHubAnalyzerModel()
1441+
else:
1442+
github_analyzer = GitHubAnalyzer()
14371443
logger.info("✅ GitHubAnalyzer initialized successfully")
14381444
except Exception as e:
14391445
logger.error(f"❌ Failed to initialize GitHubAnalyzer: {e}")
@@ -1447,19 +1453,19 @@ def analyze_repository(self, repo_url: str) -> Dict[str, Any]:
14471453
github_analyzer = FallbackGitHubAnalyzer()
14481454

14491455
try:
1450-
doc_generator = DocumentationGenerator()
1456+
doc_generator = DocumentationGeneratorModel() if 'DocumentationGeneratorModel' in globals() else DocumentationGenerator()
14511457
logger.info("✅ DocumentationGenerator initialized successfully")
14521458
except Exception as e:
14531459
logger.error(f"❌ Failed to initialize DocumentationGenerator: {e}")
14541460
logger.error(traceback.format_exc())
14551461
# Create a fallback class
14561462
class FallbackDocumentationGenerator:
1457-
def generate_documentation(self, analysis_result: Dict[str, Any]) -> Dict[str, Any]:
1463+
def generate_documentation(self, analysis_result: Dict[str, Any], rag_result: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
14581464
raise Exception(f"DocumentationGenerator initialization failed: {e}")
14591465
doc_generator = FallbackDocumentationGenerator()
14601466

14611467
try:
1462-
rag_pipeline = RAGPipeline()
1468+
rag_pipeline = RAGPipelineModel() if 'RAGPipelineModel' in globals() else RAGPipeline()
14631469
logger.info("✅ RAGPipeline initialized successfully")
14641470
except Exception as e:
14651471
logger.error(f"❌ Failed to initialize RAGPipeline: {e}")
@@ -1496,6 +1502,35 @@ def favicon():
14961502
"""Handle favicon requests"""
14971503
return '', 204 # No Content
14981504

1505+
# Handle malformed API URLs with double slashes
1506+
@app.route('/api//<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
1507+
def handle_double_slash_api(path):
1508+
"""Redirect malformed API URLs with double slashes"""
1509+
logger.warning(f"Received malformed API URL with double slash: /api//{path}")
1510+
1511+
# For analyze endpoint, handle directly instead of redirecting
1512+
if path == 'analyze':
1513+
if request.method == 'GET':
1514+
return jsonify({
1515+
'message': 'Repository analysis endpoint',
1516+
'method': 'POST',
1517+
'required_fields': ['repo_url'],
1518+
'description': 'Submit a GitHub repository URL to generate AI documentation',
1519+
'example': {
1520+
'repo_url': 'https://github.com/owner/repository'
1521+
},
1522+
'note': 'URL was corrected from double slash'
1523+
})
1524+
elif request.method == 'POST':
1525+
# Forward to the actual analyze function
1526+
return analyze_repository()
1527+
1528+
# For other endpoints, redirect to the corrected URL
1529+
corrected_url = f"/api/{path}"
1530+
logger.info(f"Redirecting to: {corrected_url}")
1531+
from flask import redirect
1532+
return redirect(corrected_url)
1533+
14991534
@app.route('/api/health')
15001535
def health_check():
15011536
"""Enhanced health check endpoint with detailed system status"""
@@ -1575,6 +1610,7 @@ def health_check():
15751610
}), 500
15761611

15771612
@app.route('/api/analyze', methods=['GET', 'POST'])
1613+
@app.route('/api/analyze/', methods=['GET', 'POST'])
15781614
def analyze_repository():
15791615
"""Handle repository analysis requests"""
15801616
if request.method == 'GET':
@@ -1680,10 +1716,29 @@ def analyze_repository():
16801716
}
16811717
}), 500
16821718

1683-
# Step 2: Generate documentation
1719+
# Step 2: Process with RAG pipeline
1720+
try:
1721+
logger.info("Step 2: Processing with RAG pipeline")
1722+
rag_result = rag_pipeline.process_repository(analysis_result)
1723+
logger.info("RAG pipeline processing completed successfully")
1724+
except Exception as e:
1725+
logger.error(f"RAG pipeline processing failed: {e}")
1726+
logger.error(traceback.format_exc())
1727+
# Continue with empty rag_result as fallback
1728+
rag_result = {
1729+
'processing_status': 'failed',
1730+
'error': str(e),
1731+
'semantic_insights': [],
1732+
'code_patterns': [],
1733+
'knowledge_graph': {},
1734+
'document_count': 0,
1735+
'embedding_dimension': 0
1736+
}
1737+
1738+
# Step 3: Generate documentation
16841739
try:
1685-
logger.info("Step 2: Generating documentation")
1686-
documentation = doc_generator.generate_documentation(analysis_result)
1740+
logger.info("Step 3: Generating documentation")
1741+
documentation = doc_generator.generate_documentation(analysis_result, rag_result)
16871742
logger.info("Documentation generation completed successfully")
16881743
except Exception as e:
16891744
logger.error(f"Documentation generation failed: {e}")

diagnostic_start.sh

Lines changed: 75 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,70 @@ wait_for_service() {
4343
return 1
4444
}
4545

46+
# Function to setup Python environment
47+
setup_python_environment() {
48+
echo -e "${BLUE}� Setting up Python environment...${NC}"
49+
50+
# Check if virtual environment exists
51+
if [ ! -d ".venv" ]; then
52+
echo -e "${YELLOW}📦 Creating virtual environment...${NC}"
53+
python3 -m venv .venv
54+
if [ $? -ne 0 ]; then
55+
echo -e "${RED}❌ Failed to create virtual environment${NC}"
56+
return 1
57+
fi
58+
fi
59+
60+
# Activate virtual environment
61+
source .venv/bin/activate
62+
63+
# Upgrade pip
64+
echo -e "${YELLOW}📦 Upgrading pip...${NC}"
65+
pip install --upgrade pip
66+
67+
# Install essential dependencies first
68+
echo -e "${YELLOW}📦 Installing essential dependencies...${NC}"
69+
pip install flask flask-cors flask-sqlalchemy python-dotenv requests
70+
71+
if [ $? -eq 0 ]; then
72+
echo -e "${GREEN}✅ Essential dependencies installed${NC}"
73+
74+
# Test Flask import
75+
python -c "import flask; print('✅ Flask version:', flask.__version__)" 2>/dev/null
76+
if [ $? -eq 0 ]; then
77+
echo -e "${GREEN}✅ Flask import test successful${NC}"
78+
else
79+
echo -e "${RED}❌ Flask import test failed${NC}"
80+
return 1
81+
fi
82+
83+
# Install remaining dependencies if requirements.txt exists
84+
if [ -f "requirements.txt" ]; then
85+
echo -e "${YELLOW}📦 Installing remaining dependencies from requirements.txt...${NC}"
86+
pip install -r requirements.txt
87+
fi
88+
89+
return 0
90+
else
91+
echo -e "${RED}❌ Failed to install essential dependencies${NC}"
92+
return 1
93+
fi
94+
}
95+
4696
# Check environment configuration
4797
echo -e "${BLUE}🔍 Environment Configuration:${NC}"
4898
cd /Users/mantejsingh/Desktop/Documentation.AI
49-
python -c "
99+
100+
# Setup Python environment
101+
if setup_python_environment; then
102+
PYTHON_CMD=".venv/bin/python"
103+
echo -e "${GREEN}✅ Using virtual environment Python${NC}"
104+
else
105+
PYTHON_CMD="python3"
106+
echo -e "${YELLOW}⚠️ Falling back to system Python${NC}"
107+
fi
108+
109+
$PYTHON_CMD -c "
50110
import os
51111
from dotenv import load_dotenv
52112
load_dotenv()
@@ -89,9 +149,18 @@ fi
89149

90150
echo ""
91151
echo -e "${BLUE}🔍 Dependencies Check:${NC}"
92-
if command -v python &> /dev/null; then
93-
python_version=$(python --version 2>&1)
152+
if command -v $PYTHON_CMD &> /dev/null; then
153+
python_version=$($PYTHON_CMD --version 2>&1)
94154
echo -e "${GREEN}✅ Python: $python_version${NC}"
155+
156+
# Test Flask import
157+
if $PYTHON_CMD -c "import flask" 2>/dev/null; then
158+
flask_version=$($PYTHON_CMD -c "import flask; print(flask.__version__)" 2>/dev/null)
159+
echo -e "${GREEN}✅ Flask: $flask_version${NC}"
160+
else
161+
echo -e "${RED}❌ Flask not installed${NC}"
162+
echo -e "${YELLOW}💡 Run: pip install flask or use virtual environment${NC}"
163+
fi
95164
else
96165
echo -e "${RED}❌ Python not found${NC}"
97166
exit 1
@@ -136,7 +205,7 @@ if [[ $REPLY =~ ^[Yy]$ ]]; then
136205

137206
# Start backend
138207
echo -e "${BLUE}🎯 Starting backend server...${NC}"
139-
python app.py > backend.log 2>&1 &
208+
$PYTHON_CMD app.py > backend.log 2>&1 &
140209
BACKEND_PID=$!
141210

142211
# Wait for backend to be ready
@@ -145,7 +214,7 @@ if [[ $REPLY =~ ^[Yy]$ ]]; then
145214

146215
# Test backend health
147216
echo -e "${BLUE}🔬 Testing backend health...${NC}"
148-
curl -s http://localhost:5002/api/health | python -m json.tool 2>/dev/null || echo "Health check returned non-JSON response"
217+
curl -s http://localhost:5002/api/health | $PYTHON_CMD -m json.tool 2>/dev/null || echo "Health check returned non-JSON response"
149218

150219
else
151220
echo -e "${RED}❌ Backend failed to start. Check backend.log:${NC}"
@@ -204,6 +273,6 @@ else
204273
echo -e "${YELLOW}✋ Startup cancelled. You can run this script again when ready.${NC}"
205274
echo ""
206275
echo -e "${BLUE}🔧 Manual startup commands:${NC}"
207-
echo -e " Backend: python app.py"
276+
echo -e " Backend: $PYTHON_CMD app.py"
208277
echo -e " Frontend: cd frontend && npm start"
209278
fi

quick_setup.sh

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#!/bin/bash
2+
echo "Creating virtual environment..."
3+
cd /Users/mantejsingh/Desktop/Documentation.AI
4+
python3 -m venv .venv
5+
echo "Activating virtual environment..."
6+
source .venv/bin/activate
7+
echo "Installing Flask..."
8+
pip install flask
9+
echo "Testing Flask..."
10+
python -c "import flask; print('Flask installed successfully')"

sample-enhanced-docs.md

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# Sample Documentation Enhancement
2+
3+
## 🚀 Enhanced GitHub-Style Documentation
4+
5+
This is an example of enhanced markdown rendering with proper GitHub-style formatting.
6+
7+
### Features
8+
9+
- **Syntax Highlighting**: Code blocks are properly highlighted
10+
- **Interactive Elements**: Tables, links, and images are rendered beautifully
11+
- **Responsive Design**: Works perfectly on all screen sizes
12+
13+
### Code Example
14+
15+
```javascript
16+
// Example React component
17+
import React from 'react';
18+
19+
const MyComponent = ({ title }) => {
20+
return (
21+
<div className="container">
22+
<h1>{title}</h1>
23+
<p>This is a sample component</p>
24+
</div>
25+
);
26+
};
27+
28+
export default MyComponent;
29+
```
30+
31+
### Python Example
32+
33+
```python
34+
def analyze_repository(repo_url):
35+
"""
36+
Analyze a GitHub repository and generate documentation.
37+
38+
Args:
39+
repo_url (str): The GitHub repository URL
40+
41+
Returns:
42+
dict: Analysis results
43+
"""
44+
print(f"Analyzing repository: {repo_url}")
45+
return {"status": "success", "data": []}
46+
```
47+
48+
### Installation
49+
50+
```bash
51+
# Install dependencies
52+
npm install
53+
54+
# Start development server
55+
npm start
56+
57+
# Build for production
58+
npm run build
59+
```
60+
61+
### Configuration Table
62+
63+
| Option | Type | Default | Description |
64+
|--------|------|---------|-------------|
65+
| `theme` | string | `"light"` | Application theme |
66+
| `autoSave` | boolean | `true` | Enable auto-save |
67+
| `maxFiles` | number | `100` | Maximum files to process |
68+
69+
### Links and References
70+
71+
- [GitHub Repository](https://github.com/example/repo)
72+
- [Documentation](https://docs.example.com)
73+
- [API Reference](https://api.example.com)
74+
75+
### Blockquote Example
76+
77+
> This is an important note about the implementation.
78+
>
79+
> Make sure to follow the security guidelines when implementing authentication.
80+
81+
### Task List
82+
83+
- [x] Setup project structure
84+
- [x] Implement basic features
85+
- [ ] Add advanced features
86+
- [ ] Write comprehensive tests
87+
- [ ] Deploy to production
88+
89+
### Images
90+
91+
![Architecture Diagram](https://via.placeholder.com/600x300/4F46E5/FFFFFF?text=Architecture+Diagram)
92+
93+
---
94+
95+
*This documentation is auto-generated by Documentation.AI*

0 commit comments

Comments
 (0)