efayguo commited on
Commit
6231986
·
verified ·
1 Parent(s): a668469

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -1,12 +1,6 @@
1
  ---
2
- title: Python Coder
3
- emoji: 🐢
4
- colorFrom: pink
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 5.29.1
8
  app_file: app.py
9
- pinned: false
 
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: python_coder
 
 
 
 
 
3
  app_file: app.py
4
+ sdk: gradio
5
+ sdk_version: 5.29.0
6
  ---
 
 
app.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from dotenv import load_dotenv
3
+ from coder.crew import Coder
4
+
5
+ load_dotenv(override=True)
6
+
7
+
8
+
9
+
10
+ def run(assignment):
11
+
12
+
13
+ inputs = {
14
+ 'assignment': assignment,
15
+ }
16
+
17
+ result= Coder().crew().kickoff(inputs=inputs)
18
+ output = result.raw
19
+ return output
20
+
21
+
22
+
23
+
24
+ # Build the UI
25
+ with gr.Blocks(theme="soft") as ui:
26
+ gr.Markdown(
27
+ """
28
+ # 👨‍💻 Python Coder by Efay Guo
29
+ This is a code writing tool that generates any Python code you want and explain it line by line and show your the final result.
30
+
31
+ 这是一个用于写Pyton代码的Agent,不仅可以帮你写代码,也会给你每行进行解释,展示程序最后的结果
32
+
33
+ """
34
+ )
35
+
36
+
37
+ query_textbox = gr.Textbox(label="What code would you like to write? / 您想实现什么代码功能?", placeholder="write a a beautifulsoup micro service or 写一个flask微服务框架")
38
+ run_button = gr.Button("Start Writing Code / 开始写代码", variant="huggingface")
39
+ report = gr.Markdown(label="Report")
40
+
41
+ run_button.click(fn=run, inputs=query_textbox, outputs=report,show_progress="full")
42
+ query_textbox.submit(fn=run, inputs=query_textbox, outputs=report, show_progress="full")
43
+
44
+ ui.launch(inbrowser=True)
coder/README.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: python_coder
3
+ app_file: app.py
4
+ sdk: gradio
5
+ sdk_version: 5.29.0
6
+ emoji: 🧑‍💻
7
+ ---
coder/__init__.py ADDED
File without changes
coder/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (197 Bytes). View file
 
coder/__pycache__/crew.cpython-311.pyc ADDED
Binary file (2.03 kB). View file
 
coder/__pycache__/main.cpython-311.pyc ADDED
Binary file (815 Bytes). View file
 
coder/config/agents.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ coder:
2
+ role: >
3
+ Python Coder
4
+ goal: >
5
+ You write python code to achieve this assignment: {assignment}
6
+ First you plan how the code will work, then you write the code, then you explain the code line by line in the language of the input language, then you run it and show the output.
7
+ backstory: >
8
+ You're a seasoned python developer with a knack for writing clean, efficient code.
9
+ llm: openai/gpt-4o-mini
10
+
coder/config/tasks.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ coding_task:
2
+ description: >
3
+ Write a clean pyton code to achieve this: {assignment}
4
+ expected_output: >
5
+ A text file that includes the code itself, along with the line by line explaination in the langue of the input, and the output of the code.
6
+ agent: coder
coder/crew.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from crewai import Agent, Crew, Process, Task
2
+ from crewai.project import CrewBase, agent, crew, task
3
+ from crewai.agents.agent_builder.base_agent import BaseAgent
4
+ from typing import List
5
+ # If you want to run a snippet of code before or after the crew starts,
6
+ # you can use the @before_kickoff and @after_kickoff decorators
7
+ # https://docs.crewai.com/concepts/crews#example-crew-class-with-decorators
8
+
9
+ @CrewBase
10
+ class Coder():
11
+ """Coder crew"""
12
+
13
+ agents_config = 'config/agents.yaml'
14
+ tasks_config = 'config/tasks.yaml'
15
+
16
+ # Learn more about YAML configuration files here:
17
+ # Agents: https://docs.crewai.com/concepts/agents#yaml-configuration-recommended
18
+ # Tasks: https://docs.crewai.com/concepts/tasks#yaml-configuration-recommended
19
+
20
+ # If you would like to add tools to your agents, you can learn more about it here:
21
+ # https://docs.crewai.com/concepts/agents#agent-tools
22
+ @agent
23
+ def coder(self) -> Agent:
24
+ return Agent(
25
+ config=self.agents_config['coder'], # type: ignore[index]
26
+ verbose=True,
27
+ allow_code_excution = True,
28
+ code_execution_mode = "safe",
29
+ max_execution_time = 30,
30
+ max_retry_limit=5
31
+ )
32
+
33
+
34
+ # To learn more about structured task outputs,
35
+ # task dependencies, and task callbacks, check out the documentation:
36
+ # https://docs.crewai.com/concepts/tasks#overview-of-a-task
37
+ @task
38
+ def coding_task(self) -> Task:
39
+ return Task(
40
+ config=self.tasks_config['coding_task'], # type: ignore[index]
41
+ )
42
+
43
+
44
+ @crew
45
+ def crew(self) -> Crew:
46
+ """Creates the Coder crew"""
47
+ # To learn how to add knowledge sources to your crew, check out the documentation:
48
+ # https://docs.crewai.com/concepts/knowledge#what-is-knowledge
49
+
50
+ return Crew(
51
+ agents=self.agents, # Automatically created by the @agent decorator
52
+ tasks=self.tasks, # Automatically created by the @task decorator
53
+ process=Process.sequential,
54
+ verbose=True,
55
+ # process=Process.hierarchical, # In case you wanna use that instead https://docs.crewai.com/how-to/Hierarchical/
56
+ )
coder/main.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ import sys
3
+ import warnings
4
+
5
+ from datetime import datetime
6
+
7
+ from coder.crew import Coder
8
+
9
+ warnings.filterwarnings("ignore", category=SyntaxWarning, module="pysbd")
10
+
11
+ # This main file is intended to be a way for you to run your
12
+ # crew locally, so refrain from adding unnecessary logic into this file.
13
+ # Replace with inputs you want to test with, it will automatically
14
+ # interpolate any tasks and agents information
15
+
16
+ def run(assignment):
17
+ """
18
+ Run the crew.
19
+ """
20
+ # assignment = "Write a python program to calculate the first 10,000 terms \
21
+ # of this series, multiplying the total by 4: 1 - 1/3 + 1/5 - 1/7 + ..."
22
+
23
+ inputs = {
24
+ 'assignment': assignment,
25
+ }
26
+
27
+ return Coder().crew().kickoff(inputs=inputs)
28
+
29
+ # try:
30
+ # return Coder().crew().kickoff(inputs=inputs)
31
+ # # print(result.raw)
32
+ # # return result.raw
33
+ # except Exception as e:
34
+ # raise Exception(f"An error occurred while running the crew: {e}")
35
+
36
+
37
+ # def train():
38
+ # """
39
+ # Train the crew for a given number of iterations.
40
+ # """
41
+ # inputs = {
42
+ # "topic": "AI LLMs",
43
+ # 'current_year': str(datetime.now().year)
44
+ # }
45
+ # try:
46
+ # Coder().crew().train(n_iterations=int(sys.argv[1]), filename=sys.argv[2], inputs=inputs)
47
+
48
+ # except Exception as e:
49
+ # raise Exception(f"An error occurred while training the crew: {e}")
50
+
51
+ # def replay():
52
+ # """
53
+ # Replay the crew execution from a specific task.
54
+ # """
55
+ # try:
56
+ # Coder().crew().replay(task_id=sys.argv[1])
57
+
58
+ # except Exception as e:
59
+ # raise Exception(f"An error occurred while replaying the crew: {e}")
60
+
61
+ # def test():
62
+ # """
63
+ # Test the crew execution and returns the results.
64
+ # """
65
+ # inputs = {
66
+ # "topic": "AI LLMs",
67
+ # "current_year": str(datetime.now().year)
68
+ # }
69
+
70
+ # try:
71
+ # Coder().crew().test(n_iterations=int(sys.argv[1]), eval_llm=sys.argv[2], inputs=inputs)
72
+
73
+ # except Exception as e:
74
+ # raise Exception(f"An error occurred while testing the crew: {e}")
coder/output/code_and_output.tx ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ```python
2
+ # First, we will need to install the required packages if not already installed.
3
+ # You can do this by running: pip install Flask beautifulsoup4 requests
4
+
5
+ from flask import Flask, request, jsonify
6
+ from bs4 import BeautifulSoup
7
+ import requests
8
+
9
+ # Create Flask app
10
+ app = Flask(__name__)
11
+
12
+ # Define a route for the micro service to scrape URLs
13
+ @app.route('/scrape', methods=['POST'])
14
+ def scrape():
15
+ # Get JSON data from the request
16
+ data = request.get_json()
17
+ url = data.get('url')
18
+
19
+ if not url:
20
+ return jsonify({"error": "URL not provided"}), 400
21
+
22
+ try:
23
+ # Send a GET request to the URL
24
+ response = requests.get(url)
25
+ response.raise_for_status() # Raise an error for bad responses
26
+
27
+ # Parse the content using BeautifulSoup
28
+ soup = BeautifulSoup(response.content, 'html.parser')
29
+
30
+ # Extract title of the page
31
+ title = soup.title.string if soup.title else 'No title found'
32
+
33
+ # Extract all paragraphs from the page
34
+ paragraphs = [p.get_text() for p in soup.find_all('p')]
35
+
36
+ # Prepare the output
37
+ result = {
38
+ "url": url,
39
+ "title": title,
40
+ "paragraphs": paragraphs
41
+ }
42
+
43
+ return jsonify(result), 200
44
+
45
+ except requests.exceptions.RequestException as e:
46
+ # Handle request exceptions
47
+ return jsonify({"error": str(e)}), 500
48
+
49
+ # Run the application
50
+ if __name__ == '__main__':
51
+ app.run(debug=True)
52
+ ```
53
+
54
+ ### Instructions to Run and Test the Microservice
55
+
56
+ 1. **Save the code** in a file named `scrape_service.py`.
57
+ 2. **Install required packages** (if not already installed) by running:
58
+ ```
59
+ pip install Flask beautifulsoup4 requests
60
+ ```
61
+ 3. **Run the Flask application**:
62
+ ```
63
+ python scrape_service.py
64
+ ```
65
+ The application will start at `http://127.0.0.1:5000/`.
66
+
67
+ 4. **Test the service** with a POST request. You can use `curl` from the terminal or a tool like Postman. Here’s an example using `curl`:
68
+
69
+ ```bash
70
+ curl -X POST http://127.0.0.1:5000/scrape -H "Content-Type: application/json" -d '{"url": "https://www.example.com"}'
71
+ ```
72
+
73
+ 5. **Expected Output**: The service will respond with a JSON object containing the URL, the title of the page, and the paragraphs.
74
+
75
+ Example response:
76
+ ```json
77
+ {
78
+ "url": "https://www.example.com",
79
+ "title": "Example Domain",
80
+ "paragraphs": [
81
+ "This domain is for use in illustrative examples...",
82
+ "More information..."
83
+ ]
84
+ }
85
+ ```
86
+
87
+ This microservice uses Flask to accept a POST request with a URL, scrapes that URL using BeautifulSoup, and returns the page title and paragraphs as a JSON response.
88
+
89
+ The service is designed to be robust, handling HTTP errors gracefully and returning appropriate error messages if the input URL is missing or invalid.
coder/output/code_and_output.txt ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Here is the complete content for the assignment:
2
+
3
+ ```python
4
+ # This Python code will read from a text file, process its content, and write the output to another text file.
5
+
6
+ # Step 1: Reading from a source text file
7
+ input_file = 'input.txt' # the name of the input file
8
+ output_file = 'output.txt' # the name of the output file
9
+
10
+ try:
11
+ # Step 2: Open the input file for reading
12
+ with open(input_file, 'r') as file:
13
+ # Read the content of the file
14
+ data = file.readlines()
15
+
16
+ # Step 3: Process the content of the file (for demo, we will just convert it to uppercase)
17
+ processed_data = [line.upper() for line in data]
18
+
19
+ # Step 4: Write the processed content to the output file
20
+ with open(output_file, 'w') as file:
21
+ file.writelines(processed_data)
22
+
23
+ print(f"Processing complete. Check the '{output_file}' for the output.")
24
+
25
+ except FileNotFoundError:
26
+ print(f"Error: The file '{input_file}' does not exist.")
27
+ except Exception as e:
28
+ print(f"An error occurred: {e}")
29
+ ```
30
+
31
+ ### Explanation of the Code Line by Line:
32
+
33
+ 1. We define the names for our input and output files.
34
+ - `input_file`: the name of the file from which we will read data.
35
+ - `output_file`: the name of the file to which we will write the processed data.
36
+
37
+ 2. We use a `try` block to safely attempt to read from the file and handle potential errors.
38
+
39
+ 3. We open the input file in read mode using a `with` statement, which ensures proper management of file resources.
40
+
41
+ 4. We read all lines from the file into a list called `data`.
42
+
43
+ 5. We process each line in `data` by converting it to uppercase and store the results in `processed_data`. This is done using a list comprehension.
44
+
45
+ 6. We open the output file in write mode and write the processed data into it.
46
+
47
+ 7. Finally, we print a success message to indicate that processing is complete.
48
+
49
+ 8. In case of an error (like the file not found), we catch that with an exception and print an appropriate error message.
50
+
51
+ ### Running the Code
52
+
53
+ To run the code, we would need an `input.txt` file with some text content in the same directory. When we execute the above script, it processes the data and creates an `output.txt` file with the text converted to uppercase.
54
+
55
+ ### Sample Input File (`input.txt`)
56
+
57
+ ```
58
+ Hello World
59
+ This is a test file.
60
+ Python Coding is fun!
61
+ ```
62
+
63
+ ### Sample Output File (`output.txt`)
64
+
65
+ ```
66
+ HELLO WORLD
67
+ THIS IS A TEST FILE.
68
+ PYTHON CODING IS FUN!
69
+ ```
70
+
71
+ This is the complete content including the code and the expected output file's content.
coder/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ requests
2
+ python-dotenv
3
+ gradio
4
+ pypdf2
5
+ openai
6
+ openai-agents
7
+ crewai
coder/tools/__init__.py ADDED
File without changes
coder/tools/custom_tool.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from crewai.tools import BaseTool
2
+ from typing import Type
3
+ from pydantic import BaseModel, Field
4
+
5
+
6
+ class MyCustomToolInput(BaseModel):
7
+ """Input schema for MyCustomTool."""
8
+ argument: str = Field(..., description="Description of the argument.")
9
+
10
+ class MyCustomTool(BaseTool):
11
+ name: str = "Name of my tool"
12
+ description: str = (
13
+ "Clear description for what this tool is useful for, your agent will need this information to use it."
14
+ )
15
+ args_schema: Type[BaseModel] = MyCustomToolInput
16
+
17
+ def _run(self, argument: str) -> str:
18
+ # Implementation goes here
19
+ return "this is an example of a tool output, ignore it and move along."