bluenevus's picture
Create app.py
38a29a5 verified
raw
history blame
6.75 kB
import gradio as gr
import google.generativeai as genai
from github import Github
import gitlab
import requests
import tempfile
import docx
def generate_guide(git_provider, repo_url, personal_access_token, gemini_api_key, guide_type):
try:
if git_provider == "GitHub":
g = Github(personal_access_token)
repo = g.get_repo(repo_url)
content = repo.get_contents("")
file_contents = ""
for file in content:
if file.name.endswith('.py'):
file_contents += f"\n\n{file.name}:\n{file.decoded_content.decode()}"
elif git_provider == "GitLab":
gl = gitlab.Gitlab(url='https://gitlab.com', private_token=personal_access_token)
project = gl.projects.get(repo_url)
items = project.repository_tree(recursive=True)
file_contents = ""
for item in items:
if item['type'] == 'blob' and item['name'].endswith('.py'):
file_content = project.files.get(item['path'], ref='main')
file_contents += f"\n\n{item['name']}:\n{file_content.decode().decode()}"
elif git_provider == "Gitea":
base_url = "https://gitea.com/api/v1"
headers = {"Authorization": f"token {personal_access_token}"}
response = requests.get(f"{base_url}/repos/{repo_url}/contents", headers=headers)
response.raise_for_status()
file_contents = ""
for item in response.json():
if item['type'] == 'file' and item['name'].endswith('.py'):
file_content = requests.get(item['download_url']).text
file_contents += f"\n\n{item['name']}:\n{file_content}"
else:
return "Unsupported Git provider", None, None
genai.configure(api_key=gemini_api_key)
model = genai.GenerativeModel('gemini-2.5-pro-preview-03-25')
if guide_type == "User Guide":
prompt = f"""Based on the following Python code, generate a comprehensive user guide:
{file_contents}
Please organize the user guide into sections such as:
1. Introduction
2. Getting Started
3. Features and Functionality
4. How to Use
5. Tips and Best Practices
6. Troubleshooting
7. FAQ
For each section, provide step-by-step instructions on how to use the software's features.
Explain each functionality that the end user will interact with.
Include examples where appropriate.
Important formatting instructions:
- The output should be in plain text
- Use clear section titles
- Number each step within sections
- Provide clear, concise instructions for each step
- Explain the purpose and benefit of each feature for non-technical users
- Do not include any installation or configuration instructions
"""
else: # Administration Guide
prompt = f"""Based on the following Python code, generate a comprehensive administration guide:
{file_contents}
Please organize the administration guide into sections such as:
1. System Overview
2. Security and Access Control
3. Performance Monitoring and Optimization
4. Backup and Recovery
5. Troubleshooting and Maintenance
6. Customization and Configuration
7. Best Practices for Administrators
For each section, provide detailed information and step-by-step instructions for system administrators.
Focus on backend operations, system management, and advanced configurations.
Include examples and potential scenarios an administrator might encounter.
Important formatting instructions:
- The output should be in plain text
- Use clear section titles
- Number each step within sections
- Provide clear, concise instructions for each step
- Explain the purpose and implications of each administrative task
- Include any relevant security considerations
"""
response = model.generate_content(prompt)
guide = response.text
# Create DOCX file
doc = docx.Document()
doc.add_heading(guide_type, 0)
for line in guide.split('\n'):
line = line.strip()
if line.endswith(':'):
doc.add_heading(line, level=1)
elif line.startswith('Step'):
doc.add_paragraph(line, style='List Number')
else:
doc.add_paragraph(line)
with tempfile.NamedTemporaryFile(delete=False, suffix='.docx') as temp_docx:
doc.save(temp_docx.name)
docx_path = temp_docx.name
# Create Markdown file
markdown_content = f"# {guide_type}\n\n"
for line in guide.split('\n'):
line = line.strip()
if line.endswith(':'):
markdown_content += f"\n## {line}\n\n"
elif line.startswith('Step'):
markdown_content += f"1. {line[5:]}\n"
else:
markdown_content += f"{line}\n"
with tempfile.NamedTemporaryFile(delete=False, suffix='.md', mode='w', encoding='utf-8') as temp_md:
temp_md.write(markdown_content)
md_path = temp_md.name
return guide, docx_path, md_path
except Exception as e:
return f"An error occurred: {str(e)}", None, None
iface = gr.Interface(
fn=generate_guide,
inputs=[
gr.Dropdown(
choices=["GitHub", "GitLab", "Gitea"],
label="Git Provider"
),
gr.Textbox(label="Repository URL", placeholder="owner/repo"),
gr.Textbox(label="Personal Access Token", type="password"),
gr.Textbox(label="Gemini API Key", type="password"),
gr.Radio(["User Guide", "Administration Guide"], label="Guide Type")
],
outputs=[
gr.Textbox(label="Generated Guide"),
gr.File(label="Download Guide (DOCX)"),
gr.File(label="Download Guide (Markdown)")
],
title="Automated Guide Generator",
description="Generate a user guide or administration guide based on the Python code in a Git repository using Gemini AI. Select a Git provider, enter repository details, choose the guide type, and let AI create a comprehensive guide.",
allow_flagging="never",
theme="default",
analytics_enabled=False,
)
iface.launch()