File size: 4,312 Bytes
4581d8b
0fe3d71
 
 
 
 
4581d8b
 
3cc9662
 
7ce2809
4581d8b
2753ae3
 
9ea67e1
de82a80
 
 
73046f3
 
 
7ce2809
4581d8b
 
0f91692
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1568641
0f91692
 
 
1568641
 
 
 
0f91692
 
 
 
9ea67e1
73046f3
0f91692
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ea67e1
73046f3
 
 
 
4581d8b
73046f3
 
 
 
 
 
 
 
 
 
4581d8b
73046f3
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import os

current_directory = os.getcwd()
os.environ['HOME'] = current_directory
print(f"New HOME directory: {os.environ['HOME']}")

import io
import requests
import zipfile
import hmac
# from metagpt.config import Config
from metagpt.software_company import generate_repo, ProjectRepo
import streamlit as st

CONFIG_FILE_PATH = 'config/config2.yaml'
if not os.path.exists(CONFIG_FILE_PATH):
    os.mkdir(os.path.dirname(CONFIG_FILE_PATH))

if not os.path.exists(CONFIG_FILE_PATH):
    with open(CONFIG_FILE_PATH, 'w') as f:
        f.write(os.environ['METAGPT_CONFIG_WITH_ANTHROPIC_API'])
# config = Config(CONFIG_FILE_PATH)

st.title("AI Software Coder")
def check_password():
    """Returns `True` if the user had the correct password."""

    def password_entered():
        """Checks whether a password entered by the user is correct."""
        if hmac.compare_digest(st.session_state["password"], os.environ['PAGE_PASSWORD']):
            st.session_state["password_correct"] = True
            del st.session_state["password"]  # Don't store the password.
        else:
            st.session_state["password_correct"] = False

    # Return True if the password is validated.
    if st.session_state.get("password_correct", False):
        return True

    # Show input for password.
    st.text_input(
        "Password", type="password", on_change=password_entered, key="password"
    )
    if "password_correct" in st.session_state:
        st.error("πŸ˜• Password incorrect")
    return False


if not check_password():
    st.stop()  # Do not continue if check_password is not True.

def generate_zip(filenames: list):
    """Generates a zip file containing the input files."""
    zip_buffer = io.BytesIO()
    with zipfile.ZipFile(zip_buffer, 'w') as zip_file:
        for filename in filenames:
            with open(filename, 'rb') as f:
                file_content = f.read()
                zip_file.writestr(filename, file_content)
    zip_buffer.seek(0)
    return zip_buffer

text_input = st.text_area("Enter your software development requirements here:", 
                          height=2000 if 'button' not in st.session_state else None,
                          value="""The goal.

The instructions of the task for each file example, things to do with input and output.

Here are some examples.

<example>
### filename.json
Original document:
```markdown
## policy title
detailed section
- blah blah
```

Configuration:
```json
{
    "income_limit": 50
}
```
</example>

<example>
### filename.py
Original document:
```markdown
## policy title
detailed section
- blah blah
```

Configuration:
```py
class AgeCalculator:
    def __init__(self, birth_year):
        self.birth_year = birth_year

    def calculate_age(self, current_year):
        age = current_year - self.birth_year
        return self._validate_and_format_age(age)

    def _validate_and_format_age(self, age):
        if age < 0:
            raise ValueError("Invalid age calculated")
        return f"User is {age} years old"

def get_user_age(birth_year, current_year):
    calculator = AgeCalculator(birth_year)
    return calculator.calculate_age(current_year)
```
</example>

Here is the additional input from a lawer:

<input>
comments from Nick/Marc/...
</input>
""")

if st.button("Generate Code"):
    st.session_state.button = True
    def download_content(url):
        response = requests.get(url)
        response.raise_for_status()
        return response.text
    
    def replace_urls_with_content(text):
        lines = text.splitlines()
        for i, line in enumerate(lines):
            if line.startswith('http://') or line.startswith('https://'):
                try:
                    content = download_content(line)
                    lines[i] = line.split('/')[-1] + '\n```\n' + content + '\n```'
                except requests.exceptions.RequestException as e:
                    print(f"Error downloading content from {line}: {e}")
        return '\n'.join(lines)
    
    text_input = replace_urls_with_content(text_input)
    repo: ProjectRepo = generate_repo(text_input)
    zip_buffer = generate_zip(repo.all_files)
    st.download_button(
        label="Download Code Repository",
        data=zip_buffer,
        file_name="output.zip",
        mime="application/zip"
    )