Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,12 +5,19 @@ from flask import Flask, request, jsonify, render_template_string
|
|
| 5 |
import git
|
| 6 |
import json
|
| 7 |
import google.generativeai as genai
|
|
|
|
| 8 |
|
| 9 |
-
# ---
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
# Create the Flask app instance
|
| 16 |
app = Flask(__name__)
|
|
@@ -76,63 +83,54 @@ HTML_TEMPLATE = """
|
|
| 76 |
"""
|
| 77 |
|
| 78 |
def generate_readme_with_llm(repo_path):
|
| 79 |
-
""
|
| 80 |
-
Analyzes the repo and uses an LLM to generate the README content.
|
| 81 |
-
"""
|
| 82 |
file_structure = ""
|
| 83 |
file_contents = ""
|
| 84 |
-
file_limit = 5
|
| 85 |
-
char_limit_per_file = 2000
|
| 86 |
-
|
| 87 |
for root, _, files in os.walk(repo_path):
|
| 88 |
if '.git' in root:
|
| 89 |
continue
|
| 90 |
-
|
| 91 |
level = root.replace(repo_path, '').count(os.sep)
|
| 92 |
indent = ' ' * 4 * level
|
| 93 |
file_structure += f"{indent}{os.path.basename(root)}/\n"
|
| 94 |
-
|
| 95 |
sub_indent = ' ' * 4 * (level + 1)
|
| 96 |
-
for f in files[:
|
| 97 |
file_structure += f"{sub_indent}{f}\n"
|
| 98 |
try:
|
| 99 |
with open(os.path.join(root, f), 'r', errors='ignore') as file:
|
| 100 |
-
content = file.read(
|
| 101 |
file_contents += f"\n--- Start of {f} ---\n{content}\n--- End of {f} ---\n"
|
| 102 |
except Exception:
|
| 103 |
continue
|
| 104 |
-
|
| 105 |
prompt = f"""
|
| 106 |
-
You are an expert technical writer
|
| 107 |
-
Analyze the following repository context and generate a comprehensive and user-friendly README.
|
| 108 |
|
| 109 |
-
**
|
| 110 |
-
**1. File Structure:**
|
| 111 |
```
|
| 112 |
{file_structure}
|
| 113 |
```
|
| 114 |
-
|
|
|
|
| 115 |
```
|
| 116 |
{file_contents}
|
| 117 |
```
|
| 118 |
-
|
| 119 |
Generate a README.md with these sections: Project Title, About the Project, Getting Started, and Usage.
|
| 120 |
-
- Infer
|
| 121 |
-
-
|
| 122 |
-
- If a command is unknown, suggest a common default (e.g., `npm install`).
|
| 123 |
"""
|
| 124 |
-
|
| 125 |
-
print("Sending request to Gemini API...")
|
| 126 |
-
model = genai.GenerativeModel('gemini-1.5-flash-latest')
|
| 127 |
-
response = model.generate_content(prompt)
|
| 128 |
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
@app.route('/')
|
| 138 |
def index():
|
|
@@ -140,42 +138,40 @@ def index():
|
|
| 140 |
|
| 141 |
@app.route('/generate', methods=['POST'])
|
| 142 |
def generate():
|
|
|
|
|
|
|
|
|
|
| 143 |
data = request.get_json()
|
| 144 |
if not data or 'url' not in data:
|
| 145 |
return jsonify({"error": "Request body must be JSON with a 'url' key."}), 400
|
| 146 |
|
| 147 |
repo_url = data.get('url')
|
| 148 |
|
| 149 |
-
|
| 150 |
-
if not repo_url or "github.com/" not in repo_url.lower():
|
| 151 |
print(f"Validation failed for URL: {repo_url}")
|
| 152 |
return jsonify({"error": "A valid public GitHub repository URL is required."}), 400
|
| 153 |
|
| 154 |
-
if not
|
| 155 |
return jsonify({"error": "Server is missing the GOOGLE_API_KEY. Cannot contact the LLM."}), 500
|
| 156 |
|
| 157 |
temp_dir = tempfile.mkdtemp()
|
| 158 |
try:
|
| 159 |
-
print(f"Cloning repository: {repo_url} into {temp_dir}")
|
| 160 |
git.Repo.clone_from(repo_url, temp_dir)
|
| 161 |
-
print("Cloning successful.")
|
| 162 |
|
| 163 |
readme_content = generate_readme_with_llm(temp_dir)
|
| 164 |
|
|
|
|
| 165 |
return jsonify({"readme": readme_content})
|
| 166 |
|
| 167 |
-
except git.exc.GitCommandError as e:
|
| 168 |
-
error_message = str(e).lower()
|
| 169 |
-
print(f"Git error: {error_message}")
|
| 170 |
-
if "authentication failed" in error_message or "not found" in error_message:
|
| 171 |
-
return jsonify({"error": "Failed to clone. Please ensure the URL is correct and the repository is public."}), 400
|
| 172 |
-
else:
|
| 173 |
-
return jsonify({"error": f"A Git error occurred during cloning."}), 500
|
| 174 |
except Exception as e:
|
| 175 |
-
print
|
| 176 |
-
|
|
|
|
|
|
|
| 177 |
finally:
|
| 178 |
-
print(f"Cleaning up temporary directory: {temp_dir}")
|
| 179 |
shutil.rmtree(temp_dir)
|
| 180 |
|
| 181 |
if __name__ == '__main__':
|
|
|
|
| 5 |
import git
|
| 6 |
import json
|
| 7 |
import google.generativeai as genai
|
| 8 |
+
import traceback # Import traceback for detailed error logging
|
| 9 |
|
| 10 |
+
# --- Configure API Key ---
|
| 11 |
+
# This block is essential for checking if the key is loaded.
|
| 12 |
+
API_KEY = os.environ.get("GOOGLE_API_KEY")
|
| 13 |
+
if API_KEY:
|
| 14 |
+
try:
|
| 15 |
+
genai.configure(api_key=API_KEY)
|
| 16 |
+
print("β
Google API Key configured successfully.")
|
| 17 |
+
except Exception as e:
|
| 18 |
+
print(f"π¨ ERROR: Failed to configure Google API Key. Error: {e}")
|
| 19 |
+
else:
|
| 20 |
+
print("π¨ WARNING: GOOGLE_API_KEY secret not set in Hugging Face Spaces.")
|
| 21 |
|
| 22 |
# Create the Flask app instance
|
| 23 |
app = Flask(__name__)
|
|
|
|
| 83 |
"""
|
| 84 |
|
| 85 |
def generate_readme_with_llm(repo_path):
|
| 86 |
+
print("Step 4: Starting to analyze repository files.")
|
|
|
|
|
|
|
| 87 |
file_structure = ""
|
| 88 |
file_contents = ""
|
|
|
|
|
|
|
|
|
|
| 89 |
for root, _, files in os.walk(repo_path):
|
| 90 |
if '.git' in root:
|
| 91 |
continue
|
|
|
|
| 92 |
level = root.replace(repo_path, '').count(os.sep)
|
| 93 |
indent = ' ' * 4 * level
|
| 94 |
file_structure += f"{indent}{os.path.basename(root)}/\n"
|
|
|
|
| 95 |
sub_indent = ' ' * 4 * (level + 1)
|
| 96 |
+
for f in files[:5]:
|
| 97 |
file_structure += f"{sub_indent}{f}\n"
|
| 98 |
try:
|
| 99 |
with open(os.path.join(root, f), 'r', errors='ignore') as file:
|
| 100 |
+
content = file.read(2000)
|
| 101 |
file_contents += f"\n--- Start of {f} ---\n{content}\n--- End of {f} ---\n"
|
| 102 |
except Exception:
|
| 103 |
continue
|
| 104 |
+
|
| 105 |
prompt = f"""
|
| 106 |
+
You are an expert technical writer. Analyze the repository context below and generate a professional README.md.
|
|
|
|
| 107 |
|
| 108 |
+
**File Structure:**
|
|
|
|
| 109 |
```
|
| 110 |
{file_structure}
|
| 111 |
```
|
| 112 |
+
|
| 113 |
+
**Key File Contents:**
|
| 114 |
```
|
| 115 |
{file_contents}
|
| 116 |
```
|
| 117 |
+
|
| 118 |
Generate a README.md with these sections: Project Title, About the Project, Getting Started, and Usage.
|
| 119 |
+
- Infer purpose, technologies, and setup commands.
|
| 120 |
+
- Output must be valid Markdown.
|
|
|
|
| 121 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
+
try:
|
| 124 |
+
print("Step 5: Sending request to Gemini API...")
|
| 125 |
+
model = genai.GenerativeModel('gemini-1.5-flash-latest')
|
| 126 |
+
response = model.generate_content(prompt)
|
| 127 |
+
print("Step 6: Received response from Gemini API.")
|
| 128 |
+
readme_text = response.text.strip().replace("```markdown", "").replace("```", "")
|
| 129 |
+
return readme_text
|
| 130 |
+
except Exception as e:
|
| 131 |
+
print(f"π¨π¨π¨ CRITICAL ERROR during Gemini API call: {e}")
|
| 132 |
+
# Re-raise the exception to be caught by the main handler
|
| 133 |
+
raise
|
| 134 |
|
| 135 |
@app.route('/')
|
| 136 |
def index():
|
|
|
|
| 138 |
|
| 139 |
@app.route('/generate', methods=['POST'])
|
| 140 |
def generate():
|
| 141 |
+
print("\n--- NEW REQUEST ---")
|
| 142 |
+
print("Step 1: Received request to /generate.")
|
| 143 |
+
|
| 144 |
data = request.get_json()
|
| 145 |
if not data or 'url' not in data:
|
| 146 |
return jsonify({"error": "Request body must be JSON with a 'url' key."}), 400
|
| 147 |
|
| 148 |
repo_url = data.get('url')
|
| 149 |
|
| 150 |
+
if not repo_url or "github.com" not in repo_url.lower():
|
|
|
|
| 151 |
print(f"Validation failed for URL: {repo_url}")
|
| 152 |
return jsonify({"error": "A valid public GitHub repository URL is required."}), 400
|
| 153 |
|
| 154 |
+
if not API_KEY:
|
| 155 |
return jsonify({"error": "Server is missing the GOOGLE_API_KEY. Cannot contact the LLM."}), 500
|
| 156 |
|
| 157 |
temp_dir = tempfile.mkdtemp()
|
| 158 |
try:
|
| 159 |
+
print(f"Step 2: Cloning repository: {repo_url} into {temp_dir}")
|
| 160 |
git.Repo.clone_from(repo_url, temp_dir)
|
| 161 |
+
print("Step 3: Cloning successful.")
|
| 162 |
|
| 163 |
readme_content = generate_readme_with_llm(temp_dir)
|
| 164 |
|
| 165 |
+
print("Step 7: Successfully generated README. Sending response.")
|
| 166 |
return jsonify({"readme": readme_content})
|
| 167 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
except Exception as e:
|
| 169 |
+
# This will now print the true error to your logs
|
| 170 |
+
print(f"π¨π¨π¨ AN UNEXPECTED ERROR OCCURRED in /generate route π¨π¨π¨")
|
| 171 |
+
traceback.print_exc() # Print the full traceback for detailed debugging
|
| 172 |
+
return jsonify({"error": "An unexpected server error occurred. Please check the logs."}), 500
|
| 173 |
finally:
|
| 174 |
+
print(f"Step 8: Cleaning up temporary directory: {temp_dir}")
|
| 175 |
shutil.rmtree(temp_dir)
|
| 176 |
|
| 177 |
if __name__ == '__main__':
|