bogeumkim commited on
Commit
1eb338d
Β·
1 Parent(s): b392fc5

Add json.loads() to handle result

Browse files
Files changed (2) hide show
  1. app.py +19 -62
  2. server.py +64 -58
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import requests
2
  import gradio as gr
3
 
@@ -11,7 +12,8 @@ def generate_readme(repo_url):
11
  timeout=120
12
  )
13
  if response.status_code == 200:
14
- return response.json().get("result", "No result returned.")
 
15
  else:
16
  return f"Error: {response.status_code}\n{response.text}"
17
  except Exception as e:
@@ -19,14 +21,14 @@ def generate_readme(repo_url):
19
 
20
  DEFAULT_VALUE = (
21
  "## Hello, World!\n"
22
- "Regardless of the outcome, it was **a truly informative and enjoyable hackathon.** \n"
23
  "As someone who likes and is good at using Hugging Face, I hope there will be more opportunities like this! πŸ€—"
24
  )
25
 
26
  with gr.Blocks(gr.themes.Origin()) as demo:
27
  gr.HTML("<h1 style='text-align:center;'>πŸ€– ARA: Auto README.md Agent πŸ“</h1>")
28
  with gr.Tabs():
29
- with gr.TabItem("README Generator"):
30
  repo_input = gr.Textbox(
31
  label="GitHub Repository URL",
32
  placeholder="Enter the GitHub repository URL (e.g. https://github.com/username/repo)"
@@ -60,68 +62,23 @@ with gr.Blocks(gr.themes.Origin()) as demo:
60
  with gr.TabItem("About"):
61
  with gr.Row():
62
  with gr.Column(scale=1):
63
- gr.Markdown("### Service Description")
64
- gr.Textbox(
65
- value="This service generates README.md files for GitHub repositories using AI agents.",
66
- lines=8,
67
- interactive=False
68
  )
69
  with gr.Column(scale=1):
70
- gr.Markdown("### Features")
71
- gr.Textbox(
72
- value="- Generate README.md from GitHub repo\n- Preview generated README\n- Demo video included",
73
- lines=4,
74
- interactive=False
75
  )
76
- gr.Markdown("### Future Features")
77
- gr.Textbox(
78
- value="- Support for multiple branches\n- Enhanced code analysis\n- User authentication",
79
- lines=4,
80
- interactive=False
81
  )
82
-
83
- # with gr.Blocks() as demo:
84
- # gr.HTML("<h1 style='text-align:center;'>πŸ€– ARA: Auto README.md Agent πŸ“</h1>")
85
- # repo_input = gr.Textbox(
86
- # label="GitHub Repository URL",
87
- # placeholder="Enter the GitHub repository URL (e.g. https://github.com/username/repo)"
88
- # )
89
-
90
- # generate_btn = gr.Button("Generate README.md")
91
-
92
- # DEFAULT_VALUE = (
93
- # "## Hello, World!\n"
94
- # "Regardless of the outcome, it was **a truly informative and enjoyable hackathon.** \n"
95
- # "As someone who likes and is good at using Hugging Face, I hope there will be more opportunities like this! πŸ€—"
96
- # )
97
-
98
- # with gr.Row():
99
- # with gr.Column():
100
- # gr.Markdown("### πŸ“ Draft")
101
- # readme_preview = gr.Textbox(
102
- # lines=24,
103
- # label="Generated by agent",
104
- # interactive=True,
105
- # value=DEFAULT_VALUE
106
- # )
107
- # with gr.Column():
108
- # gr.Markdown("### πŸ–ΌοΈ Preview")
109
- # readme_markdown = gr.Markdown(value=DEFAULT_VALUE, show_copy_button=True)
110
-
111
- # generate_btn.click(
112
- # generate_readme,
113
- # inputs=repo_input,
114
- # outputs=readme_preview
115
- # )
116
-
117
- # readme_preview.change(
118
- # lambda md: md,
119
- # inputs=readme_preview,
120
- # outputs=readme_markdown
121
- # )
122
 
123
  if __name__ == "__main__":
124
- demo.launch()
125
-
126
- #Error: 422
127
- #{"detail":[{"type":"missing","loc":["body","repo_url"],"msg":"Field required","input":{"query":"https://github.com/nsbg/nsbg.github.io"}}]}
 
1
+ import json
2
  import requests
3
  import gradio as gr
4
 
 
12
  timeout=120
13
  )
14
  if response.status_code == 200:
15
+ data = json.loads(response.text)
16
+ return data["readme"]
17
  else:
18
  return f"Error: {response.status_code}\n{response.text}"
19
  except Exception as e:
 
21
 
22
  DEFAULT_VALUE = (
23
  "## Hello, World!\n"
24
+ "Regardless of the result, it was **a truly informative and enjoyable hackathon.** \n"
25
  "As someone who likes and is good at using Hugging Face, I hope there will be more opportunities like this! πŸ€—"
26
  )
27
 
28
  with gr.Blocks(gr.themes.Origin()) as demo:
29
  gr.HTML("<h1 style='text-align:center;'>πŸ€– ARA: Auto README.md Agent πŸ“</h1>")
30
  with gr.Tabs():
31
+ with gr.TabItem("README.md Generator"):
32
  repo_input = gr.Textbox(
33
  label="GitHub Repository URL",
34
  placeholder="Enter the GitHub repository URL (e.g. https://github.com/username/repo)"
 
62
  with gr.TabItem("About"):
63
  with gr.Row():
64
  with gr.Column(scale=1):
65
+ gr.Markdown("# πŸ‘©β€πŸ« Service Description")
66
+ gr.Markdown(
67
+ "This service generates README.md files for GitHub repositories using AI agents."
 
 
68
  )
69
  with gr.Column(scale=1):
70
+ gr.Markdown("# πŸ”› Current Features")
71
+ gr.Markdown(
72
+ "- Generate README.md from GitHub repo\n"
73
+ "- Preview generated README\n"
74
+ "- Demo video included"
75
  )
76
+ gr.Markdown("# πŸ”œ Future Features")
77
+ gr.Markdown(
78
+ "- Support for multiple branches\n"
79
+ "- Enhanced code analysis\n"
80
+ "- User authentication"
81
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  if __name__ == "__main__":
84
+ demo.launch()
 
 
 
server.py CHANGED
@@ -1,17 +1,19 @@
1
  import modal
2
 
3
  HF_SECRET_NAME = "hf-secret"
4
- MODEL_ID = "mistralai/Mistral-7B-Instruct-v0.2"
5
 
6
  image = (
7
  modal.Image.debian_slim(python_version="3.12")
 
8
  .pip_install(
9
  "smolagents[toolkit]",
10
  "huggingface_hub",
11
  "transformers",
12
  "duckduckgo-search",
13
  "fastapi",
14
- "uvicorn"
 
15
  )
16
  )
17
 
@@ -23,51 +25,23 @@ app = modal.App("auto-readme-agent")
23
  secrets=[modal.Secret.from_name("hf-secret")],
24
  timeout=180,
25
  )
26
- # @modal.asgi_app()
27
- # def fastapi_app():
28
- # from fastapi import FastAPI, HTTPException
29
- # from pydantic import BaseModel
30
- # from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
31
-
32
- # class AgentRequest(BaseModel):
33
- # query: str
34
-
35
- # # Use DuckDuckGoSearchTool as an example tool
36
- # agent = CodeAgent(
37
- # tools=[DuckDuckGoSearchTool()],
38
- # model=HfApiModel(
39
- # model_id=MODEL_ID
40
- # ), # Uses Hugging Face Inference API with your token
41
- # stream_outputs=True
42
- # )
43
-
44
- # app = FastAPI()
45
-
46
- # @app.post("/")
47
- # async def run_agent(req: AgentRequest):
48
- # try:
49
- # result = agent.run(req.query)
50
- # return {"result": result}
51
- # except Exception as e:
52
- # raise HTTPException(status_code=500, detail=str(e))
53
-
54
- # return app
55
  @modal.asgi_app()
56
  def fastapi_app():
57
- from fastapi import FastAPI, HTTPException
58
- from pydantic import BaseModel
59
- from smolagents import CodeAgent, HfApiModel
60
  import os
61
  import tempfile
62
  import shutil
63
- import subprocess
64
- from git import Repo
65
 
 
 
 
 
 
66
  class RepoRequest(BaseModel):
67
  repo_url: str
68
 
69
  agent = CodeAgent(
70
  model=HfApiModel(),
 
71
  stream_outputs=True
72
  )
73
 
@@ -83,15 +57,24 @@ def fastapi_app():
83
  repo_summary.append(f"Directory: {rel_path}")
84
 
85
  for file in files:
86
- if file.endswith(('.py', '.md', '.txt', '.json', '.yaml')):
87
  file_path = os.path.join(root, file)
88
  try:
89
  with open(file_path, 'r', encoding='utf-8') as f:
90
- content = f.read(1000) # Read first 1000 characters
91
- repo_summary.append(f" File: {file}\n Content: {content[:500]}...")
92
- except Exception as e:
93
- repo_summary.append(f" File: {file} [Error reading file]")
94
- return "\n".join(repo_summary)
 
 
 
 
 
 
 
 
 
95
 
96
  @app.post("/")
97
  async def generate_readme(req: RepoRequest):
@@ -102,26 +85,49 @@ def fastapi_app():
102
 
103
  # Analyze repository
104
  repo_analysis = analyze_repo(temp_dir)
105
-
106
  # Create prompt
107
- prompt = f"""Create a comprehensive README.md for this GitHub repository based on its structure and contents:
108
-
109
- Repository Structure:
110
- {repo_analysis}
111
-
112
- The README should include:
113
- - Project description
114
- - Installation instructions
115
- - Usage examples
116
- - Contributing guidelines
117
- - License information if available
118
-
119
- Format using markdown with proper sections."""
120
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  # Generate README
122
  result = agent.run(prompt)
123
- return {"readme": result}
124
 
 
125
  except Exception as e:
126
  raise HTTPException(status_code=500, detail=str(e))
127
  finally:
 
1
  import modal
2
 
3
  HF_SECRET_NAME = "hf-secret"
4
+ MODEL_ID = "google/gemma-3-12b-it"
5
 
6
  image = (
7
  modal.Image.debian_slim(python_version="3.12")
8
+ .apt_install("git")
9
  .pip_install(
10
  "smolagents[toolkit]",
11
  "huggingface_hub",
12
  "transformers",
13
  "duckduckgo-search",
14
  "fastapi",
15
+ "uvicorn",
16
+ "GitPython"
17
  )
18
  )
19
 
 
25
  secrets=[modal.Secret.from_name("hf-secret")],
26
  timeout=180,
27
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  @modal.asgi_app()
29
  def fastapi_app():
 
 
 
30
  import os
31
  import tempfile
32
  import shutil
 
 
33
 
34
+ from git import Repo
35
+ from fastapi import FastAPI, HTTPException
36
+ from pydantic import BaseModel
37
+ from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool
38
+
39
  class RepoRequest(BaseModel):
40
  repo_url: str
41
 
42
  agent = CodeAgent(
43
  model=HfApiModel(),
44
+ tools=[],
45
  stream_outputs=True
46
  )
47
 
 
57
  repo_summary.append(f"Directory: {rel_path}")
58
 
59
  for file in files:
60
+ if file.endswith(('.py')):
61
  file_path = os.path.join(root, file)
62
  try:
63
  with open(file_path, 'r', encoding='utf-8') as f:
64
+ content = f.read() # Read first 1000 characters
65
+ filtered_lines = [
66
+ line for line in content.splitlines()
67
+ if not (
68
+ line.strip().startswith('#')
69
+ or line.strip().startswith('import')
70
+ or line.strip().startswith('from')
71
+ )
72
+ ]
73
+ filtered_content = "\n".join(filtered_lines)
74
+ repo_summary.append(f"File: {file}\n Content: {filtered_content}...")
75
+ except Exception:
76
+ raise f"File: {file} [Error reading file]"
77
+ return "\n".join(repo_summary)[:500]
78
 
79
  @app.post("/")
80
  async def generate_readme(req: RepoRequest):
 
85
 
86
  # Analyze repository
87
  repo_analysis = analyze_repo(temp_dir)
88
+
89
  # Create prompt
90
+ prompt = f"""Create a comprehensive README.md for this GitHub repository based on its structure and contents.
91
+
92
+ Repository Structure:
93
+ {repo_analysis}
94
+
95
+ It would be good if the README.md includes the following contents:
96
+ - Repository name
97
+ - Project description
98
+ - Contributing guidelines
99
+
100
+ Format using markdown with proper sections.
101
+
102
+ Here is an example of the style and detail you should provide:
103
+ ---
104
+ # ExampleProject
105
+
106
+ A Python package for advanced data analysis and visualization.
107
+
108
+ ## Installation
109
+ ```
110
+ pip install exampleproject
111
+ ```
112
+
113
+ ## Usage
114
+ ```
115
+ from exampleproject import analyze
116
+
117
+ analyze('data.csv')
118
+ ```
119
+
120
+ ## Contribution
121
+
122
+ Contributions are welcome! Please open an issue or submit a pull request.
123
+
124
+ ...
125
+ """
126
+
127
  # Generate README
128
  result = agent.run(prompt)
 
129
 
130
+ return {"readme": result}
131
  except Exception as e:
132
  raise HTTPException(status_code=500, detail=str(e))
133
  finally: