faizee07's picture
Upload 4 files
e923fbd verified
raw
history blame
5.03 kB
import os
import shutil
import tempfile
from flask import Flask, request, jsonify, render_template
import git
import json
app = Flask(__name__)
def analyze_repo(repo_path):
"""
Analyzes the cloned repository to gather information.
This is a simplified analysis function. A real-world agent
would be much more sophisticated.
"""
project_name = os.path.basename(repo_path)
language = "Not Detected"
dependencies = []
install_command = "No install command found."
run_command = "No run command found."
# --- Technology and Dependency Analysis ---
if os.path.exists(os.path.join(repo_path, 'requirements.txt')):
language = "Python"
with open(os.path.join(repo_path, 'requirements.txt'), 'r') as f:
dependencies = [line.strip() for line in f.readlines() if line.strip()]
install_command = "pip install -r requirements.txt"
# Try to find a common run command
if os.path.exists(os.path.join(repo_path, 'app.py')) or os.path.exists(os.path.join(repo_path, 'main.py')):
run_command = "python app.py # or python main.py"
elif os.path.exists(os.path.join(repo_path, 'package.json')):
language = "JavaScript (Node.js)"
with open(os.path.join(repo_path, 'package.json'), 'r') as f:
package_data = json.load(f)
dependencies = list(package_data.get('dependencies', {}).keys())
install_command = "npm install"
if package_data.get('scripts', {}).get('start'):
run_command = "npm start"
else:
run_command = "node index.js # or appropriate script"
# Simple logic to infer project purpose from file names
purpose = f"A {language} project."
if 'test' in str(os.listdir(repo_path)).lower():
purpose += " It appears to have testing capabilities."
if 'dockerfile' in str(os.listdir(repo_path)).lower():
purpose += " It can be containerized using Docker."
return {
"project_name": project_name,
"language": language,
"dependencies": dependencies,
"install_command": install_command,
"run_command": run_command,
"purpose": purpose
}
def generate_readme_content(analysis):
"""Generates the README.md content from the analysis results."""
readme = f"# {analysis['project_name']}\n\n"
readme += f"## πŸ€– About This Project\n\n{analysis['purpose']}\n\n"
readme += f"This project is primarily written in **{analysis['language']}**.\n\n"
readme += "## πŸš€ Getting Started\n\n"
readme += "### Prerequisites\n\n"
readme += f"Make sure you have {analysis['language']} and the necessary build tools installed on your system.\n\n"
readme += "### Installation\n\n"
readme += "1. Clone the repository:\n"
readme += " ```sh\n git clone <repository_url>\n ```\n"
readme += "2. Navigate to the project directory:\n"
readme += f" ```sh\n cd {analysis['project_name']}\n ```\n"
readme += "3. Install the dependencies:\n"
readme += f" ```sh\n {analysis['install_command']}\n ```\n\n"
if analysis['dependencies']:
readme += "Key dependencies include:\n"
for dep in analysis['dependencies'][:5]: # Show first 5 dependencies
readme += f"- `{dep}`\n"
readme += "\n"
readme += "### Usage\n\n"
readme += "To run the project, execute the following command:\n"
readme += f"```sh\n{analysis['run_command']}\n```\n\n"
readme += "---\n"
readme += "*This README was automatically generated by an AI agent.*"
return readme
@app.route('/')
def index():
return render_template('index.html')
@app.route('/generate', methods=['POST'])
def generate():
data = request.get_json()
repo_url = data.get('url')
if not repo_url:
return jsonify({"error": "GitHub repository URL is required."}), 400
temp_dir = tempfile.mkdtemp()
try:
# --- Agent Tool 1: Git Clone ---
print(f"Cloning repository: {repo_url} into {temp_dir}")
git.Repo.clone_from(repo_url, temp_dir)
# --- Agent Tool 2: File Analysis ---
print("Analyzing repository structure...")
analysis_result = analyze_repo(temp_dir)
# --- Agent Step 3: Write README ---
print("Generating README content...")
readme_content = generate_readme_content(analysis_result)
return jsonify({"readme": readme_content})
except git.exc.GitCommandError as e:
return jsonify({"error": f"Failed to clone repository. Is the URL correct and public? Error: {e}"}), 500
except Exception as e:
return jsonify({"error": f"An unexpected error occurred: {str(e)}"}), 500
finally:
# --- Cleanup ---
print(f"Cleaning up temporary directory: {temp_dir}")
shutil.rmtree(temp_dir)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=int(os.environ.get("PORT", 7860)))