Spaces:
Runtime error
Runtime error
Modify Gradio UI
Browse filesFiles changed (3)
- app.py+67-12
- modal/server.pyDeleted-103
- server.pyAdded+130
53 unmodified lines545556575859606162636465666768697071727374757677787980818283848553 unmodified lines# if __name__ == "__main__":# demo.launch(debug=True)import gradio as grimport requestsMODAL_API_URL = "https://agents-mcp-hackathon--smolagents-modal-agent-readme-agen-eb6ccb.modal.run" # Replace with your deployed Modal endpointdef generate_readme_from_github(repo_url):try:response = requests.post(MODAL_API_URL,json={"repo_url": repo_url},timeout=600,)if response.status_code == 200:return response.json().get("readme", "No README generated.")else:return f"Error: {response.status_code}\n{response.text}"except Exception as e:return f"Exception: {str(e)}"with gr.Blocks() as demo:gr.Markdown("# 📝 GitHub Repo → README.md Generator\nPaste a public GitHub repo link to generate a draft README.md using AI.")repo_input = gr.Textbox(label="GitHub Repository URL", placeholder="https://github.com/owner/repo")output = gr.Textbox(label="Generated README.md", lines=20)btn = gr.Button("Generate README")btn.click(generate_readme_from_github, inputs=repo_input, outputs=output)if __name__ == "__main__":demo.launch()53 unmodified lines5455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914053 unmodified lines# if __name__ == "__main__":# demo.launch(debug=True)import reimport requestsimport gradio as grfrom markdownify import markdownifyMODAL_API_URL = "https://agents-mcp-hackathon--auto-readme-agent-fastapi-app.modal.run" # Replace with your deployed Modal endpoint# def generate_readme_from_github(repo_url):# try:# response = requests.post(# MODAL_API_URL,# json={"repo_url": repo_url},# timeout=180,# )# if response.status_code == 200:# return response.json().get("readme", "No README generated.")# else:# return f"Error: {response.status_code}\n{response.text}"# except Exception as e:# return f"Exception: {str(e)}"# with gr.Blocks() as demo:# gr.Markdown("# 📝 GitHub Repo → README.md Generator\nPaste a public GitHub repo link to generate a draft README.md using AI.")# repo_input = gr.Textbox(label="GitHub Repository URL", placeholder="https://github.com/owner/repo")# output = gr.Textbox(label="Generated README.md", lines=20)# btn = gr.Button("Generate README")# btn.click(generate_readme_from_github, inputs=repo_input, outputs=output)# if __name__ == "__main__":# demo.launch()def generate_readme(query):try:response = requests.post(MODAL_API_URL,json={"query": query},timeout=120)if response.status_code == 200:return response.json().get("result", "No result returned.")else:return f"Error: {response.status_code}\n{response.text}"except Exception as e:return f"Exception: {str(e)}"def fetch_github_content(url: str) -> str:try:response = requests.get(url, timeout=20)response.raise_for_status()markdown_content = markdownify(response.text)markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)return markdown_contentexcept Exception as e:return f"Error fetching content: {str(e)}"with gr.Blocks() as demo:gr.Markdown("# 🤖 ARA: Auto README.md Agent 📝")repo_input = gr.Textbox(label="GitHub Repository URL",placeholder="Enter the GitHub repository URL (e.g. https://github.com/username/repo)")readme_output = gr.Textbox(label="Generated README.md")with gr.Row():with gr.Column():gr.Markdown("#### 🖼️ Preview (Markdown Rendered)")readme_preview = gr.Markdown()with gr.Column():gr.Markdown("#### 📝 Markdown File (Copyable)")readme_markdown = gr.Textbox(lines=24, label="Markdown", interactive=True, show_copy_button=True)generate_btn = gr.Button("Generate README.md")# When generating, fill both preview and markdowndef dual_output(readme):return readme, readmegenerate_btn.click(generate_readme,inputs=repo_input,outputs=[readme_preview, readme_markdown])if __name__ == "__main__":demo.launch()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import modal
image = ( modal.Image.debian_slim(python_version="3.12") .pip_install( "smolagents[toolkit]", "huggingface_hub", "transformers", "duckduckgo-search", "fastapi", "uvicorn", "PyGithub", "gitpython" ))
app = modal.App("smolagents-modal-agent-readme")
HF_SECRET_NAME = "hf-secret"MODEL_ID = "mistralai/Mistral-7B-Instruct-v0.2"
@app.function( image=image, gpu="A10G", secrets=[modal.Secret.from_name(HF_SECRET_NAME)], timeout=600,)@modal.fastapi_endpoint()def agent_server(): import os from fastapi import FastAPI, HTTPException, Request import uvicorn from huggingface_hub import login as hf_login from smolagents import CodeAgent, WebSearchTool, InferenceClientModel import tempfile import shutil import subprocess
hf_token = os.environ.get("HF_TOKEN") hf_login(token=hf_token)
model = InferenceClientModel( model_id=MODEL_ID, provider="huggingface", token=hf_token, )
agent = CodeAgent( tools=[WebSearchTool()], model=model, stream_outputs=True, )
app = FastAPI()
@app.post("/generate_readme") async def generate_readme(request: Request): try: data = await request.json() repo_url = data.get("repo_url") if not repo_url: raise HTTPException(status_code=400, detail="Missing 'repo_url' in request body")
temp_dir = tempfile.mkdtemp() try: subprocess.run( ["git", "clone", "--depth", "1", "--branch", "main", repo_url, temp_dir], check=True )
repo_summary = [] for root, dirs, files in os.walk(temp_dir): depth = root[len(temp_dir):].count(os.sep) if depth > 2: continue rel_root = os.path.relpath(root, temp_dir) repo_summary.append(f"Directory: {rel_root}") for file in files: if file.endswith((".py", ".md", ".txt", ".json", ".yaml", ".yml")): file_path = os.path.join(root, file) try: with open(file_path, "r", encoding="utf-8") as f: content = f.read(500) except Exception: content = "[Could not read file content]" repo_summary.append(f"File: {file} Content Preview: {content}")
prompt = ( "You are an AI assistant that drafts a detailed README.md for a GitHub repository. " "Based on the following repository structure and code snippets, create a comprehensive README.md content. " "Repository summary:\n" + "\n".join(repo_summary) )
readme_text = agent.run(prompt) return {"readme": readme_text} finally: shutil.rmtree(temp_dir)
except Exception as e: raise HTTPException(status_code=500, detail=str(e))
# Start Uvicorn in blocking mode uvicorn.run(app, host="0.0.0.0", port=8000)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130import modal
HF_SECRET_NAME = "hf-secret"MODEL_ID = "mistralai/Mistral-7B-Instruct-v0.2"
image = ( modal.Image.debian_slim(python_version="3.12") .pip_install( "smolagents[toolkit]", "huggingface_hub", "transformers", "duckduckgo-search", "fastapi", "uvicorn" ))
app = modal.App("auto-readme-agent")
@app.function( image=image, gpu="A10G", secrets=[modal.Secret.from_name("hf-secret")], timeout=180,)# @modal.asgi_app()# def fastapi_app():# from fastapi import FastAPI, HTTPException# from pydantic import BaseModel# from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
# class AgentRequest(BaseModel):# query: str
# # Use DuckDuckGoSearchTool as an example tool# agent = CodeAgent(# tools=[DuckDuckGoSearchTool()],# model=HfApiModel(# model_id=MODEL_ID# ), # Uses Hugging Face Inference API with your token# stream_outputs=True# )
# app = FastAPI()
# @app.post("/")# async def run_agent(req: AgentRequest):# try:# result = agent.run(req.query)# return {"result": result}# except Exception as e:# raise HTTPException(status_code=500, detail=str(e))
# return app@modal.asgi_app()def fastapi_app(): from fastapi import FastAPI, HTTPException from pydantic import BaseModel from smolagents import CodeAgent, HfApiModel import os import tempfile import shutil import subprocess from git import Repo
class RepoRequest(BaseModel): repo_url: str
agent = CodeAgent( model=HfApiModel(), stream_outputs=True )
app = FastAPI()
def analyze_repo(repo_path): repo_summary = [] for root, dirs, files in os.walk(repo_path): # Skip hidden directories dirs[:] = [d for d in dirs if not d.startswith('.')] rel_path = os.path.relpath(root, repo_path) repo_summary.append(f"Directory: {rel_path}") for file in files: if file.endswith(('.py', '.md', '.txt', '.json', '.yaml')): file_path = os.path.join(root, file) try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read(1000) # Read first 1000 characters repo_summary.append(f" File: {file}\n Content: {content[:500]}...") except Exception as e: repo_summary.append(f" File: {file} [Error reading file]") return "\n".join(repo_summary)
@app.post("/") async def generate_readme(req: RepoRequest): temp_dir = tempfile.mkdtemp() try: # Clone repository Repo.clone_from(req.repo_url, temp_dir, branch='main', depth=1) # Analyze repository repo_analysis = analyze_repo(temp_dir) # Create prompt prompt = f"""Create a comprehensive README.md for this GitHub repository based on its structure and contents: Repository Structure: {repo_analysis} The README should include: - Project description - Installation instructions - Usage examples - Contributing guidelines - License information if available Format using markdown with proper sections.""" # Generate README result = agent.run(prompt) return {"readme": result} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: shutil.rmtree(temp_dir, ignore_errors=True)
return appapp.py+67-12
modal/server.pyDeleted-103
server.pyAdded+130