kenken999 commited on
Commit
de235e2
1 Parent(s): 1a1dee2
models/ride.py CHANGED
@@ -1,5 +1,5 @@
1
  import gradio as gr
2
- from mysite.libs.utilities import chat_with_interpreter, completion, process_file,no_process_file
3
  from interpreter import interpreter
4
  import mysite.interpreter.interpreter_config # インポートするだけで設定が適用されます
5
  import duckdb
 
1
  import gradio as gr
2
+ #from mysite.libs.utilities import chat_with_interpreter, completion, process_file,no_process_file
3
  from interpreter import interpreter
4
  import mysite.interpreter.interpreter_config # インポートするだけで設定が適用されます
5
  import duckdb
mysite/asgi.py CHANGED
@@ -9,19 +9,13 @@ from starlette.middleware.cors import CORSMiddleware
9
  import gradio as gr
10
  from mysite.routers.gradio import setup_gradio_interfaces
11
  from mysite.routers.fastapi import setup_webhook_routes,include_routers
12
- from mysite.database.database import setup_database_routes
13
  from mysite.config.asgi_config import init_django_app
14
  from interpreter import interpreter
15
  import mysite.interpreter.interpreter_config # インポートするだけで設定が適用されます
16
  # ロガーの設定
17
- import logging
18
- logging.basicConfig(level=logging.INFO)
19
- logger = logging.getLogger(__name__)
20
- file_handler = logging.FileHandler("app.log")
21
- file_handler.setLevel(logging.INFO)
22
- formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
23
- file_handler.setFormatter(formatter)
24
- logger.addHandler(file_handler)
25
 
26
  os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
27
  application = get_asgi_application()
 
9
  import gradio as gr
10
  from mysite.routers.gradio import setup_gradio_interfaces
11
  from mysite.routers.fastapi import setup_webhook_routes,include_routers
12
+ from mysite.routers.database import setup_database_routes
13
  from mysite.config.asgi_config import init_django_app
14
  from interpreter import interpreter
15
  import mysite.interpreter.interpreter_config # インポートするだけで設定が適用されます
16
  # ロガーの設定
17
+ from mysite.logger import logger
18
+
 
 
 
 
 
 
19
 
20
  os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
21
  application = get_asgi_application()
mysite/database/rides.py DELETED
File without changes
mysite/interpreter/interpreter.py CHANGED
@@ -5,7 +5,7 @@ import hashlib
5
  import base64
6
  import subprocess
7
  import time
8
- from mysite.libs.logger import logger
9
  import async_timeout
10
  import asyncio
11
  import mysite.interpreter.interpreter_config
 
5
  import base64
6
  import subprocess
7
  import time
8
+ from mysite.logger import logger
9
  import async_timeout
10
  import asyncio
11
  import mysite.interpreter.interpreter_config
mysite/interpreter/process.py CHANGED
@@ -5,7 +5,7 @@ import hashlib
5
  import base64
6
  import subprocess
7
  import time
8
- from mysite.libs.logger import logger
9
  import async_timeout
10
  import asyncio
11
  import mysite.interpreter.interpreter_config
 
5
  import base64
6
  import subprocess
7
  import time
8
+ from mysite.logger import logger
9
  import async_timeout
10
  import asyncio
11
  import mysite.interpreter.interpreter_config
mysite/libs/utilities.py CHANGED
@@ -5,209 +5,12 @@ import hashlib
5
  import base64
6
  import subprocess
7
  import time
8
- from mysite.libs.logger import logger
9
  import async_timeout
10
  import asyncio
11
  import mysite.interpreter.interpreter_config
12
-
13
-
14
-
15
  GENERATION_TIMEOUT_SEC=60
16
 
17
- def validate_signature(body: str, signature: str, secret: str) -> bool:
18
- if secret is None:
19
- logger.error("Secret is None")
20
- return False
21
-
22
- hash = hmac.new(
23
- secret.encode("utf-8"), body.encode("utf-8"), hashlib.sha256
24
- ).digest()
25
- expected_signature = base64.b64encode(hash).decode("utf-8")
26
- return hmac.compare_digest(expected_signature, signature)
27
-
28
- def no_process_file(prompt, foldername):
29
- set_environment_variables()
30
- try:
31
- proc = subprocess.Popen(["mkdir", f"/home/user/app/controllers/{foldername}"])
32
- except subprocess.CalledProcessError as e:
33
- return f"Processed Content:\n{e.stdout}\n\nMake Command Error:\n{e.stderr}"
34
-
35
- no_extension_path = f"/home/user/app/controllers/{foldername}/prompt"
36
- time.sleep(1)
37
- with open(no_extension_path, "a") as f:
38
- f.write(prompt)
39
- time.sleep(1)
40
- try:
41
- prompt_file_path = no_extension_path
42
- with open(prompt_file_path, "w") as prompt_file:
43
- prompt_file.write(prompt)
44
- except Exception as e:
45
- return f"Error writing prompt to file: {str(e)}"
46
- time.sleep(1)
47
- try:
48
- proc = subprocess.Popen(
49
- ["make", "run", foldername],
50
- stdin=subprocess.PIPE,
51
- stdout=subprocess.PIPE,
52
- stderr=subprocess.PIPE,
53
- text=True,
54
- )
55
- stdout, stderr = proc.communicate(input="n\ny\ny\n")
56
- return f"Processed Content:\n{stdout}\n\nMake Command Output:\n{stdout}\n\nMake Command Error:\n{stderr}"
57
- except subprocess.CalledProcessError as e:
58
- return f"Processed Content:\n{e.stdout}\n\nMake Command Error:\n{e.stderr}"
59
-
60
- def set_environment_variables():
61
- os.environ["OPENAI_API_BASE"] = "https://api.groq.com/openai/v1"
62
- os.environ["OPENAI_API_KEY"] = "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"
63
- os.environ["MODEL_NAME"] = "llama3-8b-8192"
64
- os.environ["LOCAL_MODEL"] = "true"
65
-
66
- # Set the environment variable.
67
- def chat_with_interpreter(
68
- message, history, a=None, b=None, c=None, d=None
69
- ): # , openai_api_key):
70
- # Set the API key for the interpreter
71
- # interpreter.llm.api_key = openai_api_key
72
- if message == "reset":
73
- interpreter.reset()
74
- return "Interpreter reset", history
75
- full_response = ""
76
- # add_conversation(history,20)
77
- user_entry = {"role": "user", "type": "message", "content": message}
78
- #messages.append(user_entry)
79
- # Call interpreter.chat and capture the result
80
- messages = []
81
- recent_messages = history[-20:]
82
- for conversation in recent_messages:
83
- user_message = conversation[0]
84
- user_entry = {"role": "user", "content": user_message}
85
- messages.append(user_entry)
86
- assistant_message = conversation[1]
87
- assistant_entry = {"role": "assistant", "content": assistant_message}
88
- messages.append(assistant_entry)
89
-
90
- user_entry = {"role": "user", "content": message}
91
- messages.append(user_entry)
92
- #system_prompt = {"role": "system", "content": "あなたは日本語の優秀なアシスタントです。"}
93
- #messages.insert(0, system_prompt)
94
-
95
- for chunk in interpreter.chat(messages, display=False, stream=True):
96
- # print(chunk)
97
- # output = '\n'.join(item['content'] for item in result if 'content' in item)
98
- full_response = format_response(chunk, full_response)
99
- yield full_response # chunk.get("content", "")
100
-
101
- # Extract the 'content' field from all elements in the result
102
- def insert(full_response,message):
103
- age = 28
104
- # データベースファイルのパス
105
- db_path = "./workspace/sample.duckdb"
106
-
107
- # DuckDBに接続(データベースファイルが存在しない場合は新規作成)
108
- con = duckdb.connect(database=db_path)
109
- con.execute(
110
- """
111
- CREATE SEQUENCE IF NOT EXISTS sample_id_seq START 1;
112
- CREATE TABLE IF NOT EXISTS samples (
113
- id INTEGER DEFAULT nextval('sample_id_seq'),
114
- name VARCHAR,
115
- age INTEGER,
116
- PRIMARY KEY(id)
117
- );
118
- """
119
- )
120
- cur = con.cursor()
121
- con.execute("INSERT INTO samples (name, age) VALUES (?, ?)", (full_response, age))
122
- con.execute("INSERT INTO samples (name, age) VALUES (?, ?)", (message, age))
123
- # データをCSVファイルにエクスポート
124
- con.execute("COPY samples TO 'sample.csv' (FORMAT CSV, HEADER)")
125
- # データをコミット
126
- con.commit()
127
- # データを選択
128
- cur = con.execute("SELECT * FROM samples")
129
- # 結果をフェッチ
130
- res = cur.fetchall()
131
- rows = ""
132
- # 結果を表示
133
- # 結果を文字列に整形
134
- rows = "\n".join([f"name: {row[0]}, age: {row[1]}" for row in res])
135
- # コネクションを閉じる
136
- con.close()
137
- # print(cur.fetchall())
138
- insert(full_response,message)
139
- yield full_response + rows # , history
140
- return full_response, history
141
-
142
- async def completion(message: str, history, c=None, d=None):
143
- from groq import Groq
144
- client = Groq(api_key=os.getenv("api_key"))
145
- messages = []
146
- recent_messages = history[-20:]
147
- for conversation in recent_messages:
148
- user_message = conversation[0]
149
- user_entry = {"role": "user", "content": user_message}
150
- messages.append(user_entry)
151
- assistant_message = conversation[1]
152
- assistant_entry = {"role": "assistant", "content": assistant_message}
153
- messages.append(assistant_entry)
154
-
155
- user_entry = {"role": "user", "content": message}
156
- messages.append(user_entry)
157
- system_prompt = {"role": "system", "content": "あなたは日本語で答えるプログラム開発の優秀ななアシスタントです。"}
158
- messages.insert(0, system_prompt)
159
- async with async_timeout.timeout(GENERATION_TIMEOUT_SEC):
160
- try:
161
- stream = client.chat.completions.create(
162
- model="llama3-8b-8192",
163
- messages=messages,
164
- temperature=1,
165
- max_tokens=1024,
166
- top_p=1,
167
- stream=True,
168
- stop=None,
169
- )
170
- all_result = ""
171
- for chunk in stream:
172
- current_content = chunk.choices[0].delta.content or ""
173
- all_result += current_content
174
- yield current_content
175
- yield all_result
176
- #return all_result
177
- except asyncio.TimeoutError:
178
- raise HTTPException(status_code=504, detail="Stream timed out")
179
-
180
- def process_file(fileobj, prompt, foldername):
181
- set_environment_variables()
182
- try:
183
- proc = subprocess.Popen(["mkdir", f"/home/user/app/controllers/{foldername}"])
184
- except subprocess.CalledProcessError as e:
185
- return f"Processed Content:\n{e.stdout}\n\nMake Command Error:\n{e.stderr}"
186
- time.sleep(2)
187
- path = f"/home/user/app/controllers/{foldername}/" + os.path.basename(fileobj)
188
- shutil.copyfile(fileobj.name, path)
189
- base_name = os.path.splitext(os.path.basename(fileobj))[0]
190
- no_extension_path = f"/home/user/app/controllers/{foldername}/{base_name}"
191
- shutil.copyfile(fileobj, no_extension_path)
192
- with open(no_extension_path, "a") as f:
193
- f.write(prompt)
194
- try:
195
- prompt_file_path = no_extension_path
196
- with open(prompt_file_path, "w") as prompt_file:
197
- prompt_file.write(prompt)
198
- except Exception as e:
199
- return f"Error writing prompt to file: {str(e)}"
200
- time.sleep(1)
201
- try:
202
- proc = subprocess.Popen(
203
- ["make", "run", foldername],
204
- stdin=subprocess.PIPE,
205
- stdout=subprocess.PIPE,
206
- stderr=subprocess.PIPE,
207
- text=True,
208
- )
209
- stdout, stderr = proc.communicate(input="n\ny\ny\n")
210
- return f"Processed Content:\n{stdout}\n\nMake Command Output:\n{stdout}\n\nMake Command Error:\n{stderr}"
211
- except subprocess.CalledProcessError as e:
212
- return f"Processed Content:\n{stdout}\n\nMake Command Error:\n{e.stderr}"
213
-
 
5
  import base64
6
  import subprocess
7
  import time
8
+ from mysite.logger import logger
9
  import async_timeout
10
  import asyncio
11
  import mysite.interpreter.interpreter_config
12
+ from mysite.interpreter.process import process_file,no_process_file,validate_signature
13
+ from mysite.interpreter.interpreter import completion,chat_with_interpreter
14
+
15
  GENERATION_TIMEOUT_SEC=60
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
mysite/{libs/logger.py → logger.py} RENAMED
File without changes
mysite/routers/database.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import duckdb
2
+ import pandas as pd
3
+ from fastapi import FastAPI
4
+ import gradio as gr
5
+
6
+ con = duckdb.connect(database="./workspace/mydatabase.duckdb")
7
+ con.execute("CREATE TABLE IF NOT EXISTS items (id INTEGER, name VARCHAR);")
8
+
9
+ # Extract the 'content' field from all elements in the result
10
+ def insert(full_response,message):
11
+ age = 28
12
+ # データベースファイルのパス
13
+ db_path = "./workspace/sample.duckdb"
14
+
15
+ # DuckDBに接続(データベースファイルが存在しない場合は新規作成)
16
+ con = duckdb.connect(database=db_path)
17
+ con.execute(
18
+ """
19
+ CREATE SEQUENCE IF NOT EXISTS sample_id_seq START 1;
20
+ CREATE TABLE IF NOT EXISTS samples (
21
+ id INTEGER DEFAULT nextval('sample_id_seq'),
22
+ name VARCHAR,
23
+ age INTEGER,
24
+ PRIMARY KEY(id)
25
+ );
26
+ """
27
+ )
28
+ cur = con.cursor()
29
+ con.execute("INSERT INTO samples (name, age) VALUES (?, ?)", (full_response, age))
30
+ con.execute("INSERT INTO samples (name, age) VALUES (?, ?)", (message, age))
31
+ # データをCSVファイルにエクスポート
32
+ con.execute("COPY samples TO 'sample.csv' (FORMAT CSV, HEADER)")
33
+ # データをコミット
34
+ con.commit()
35
+ # データを選択
36
+ cur = con.execute("SELECT * FROM samples")
37
+ # 結果をフェッチ
38
+ res = cur.fetchall()
39
+ rows = ""
40
+ # 結果を表示
41
+ # 結果を文字列に整形
42
+ rows = "\n".join([f"name: {row[0]}, age: {row[1]}" for row in res])
43
+ # コネクションを閉じる
44
+ con.close()
45
+ # print(cur.fetchall())
46
+ insert(full_response,message)
47
+
48
+ def setup_database_routes(app: FastAPI):
49
+ def create_item(name):
50
+ con.execute("INSERT INTO items (name) VALUES (?);", (name,))
51
+ con.commit()
52
+ return "Item created successfully!"
53
+
54
+ def read_items():
55
+ cursor = con.cursor()
56
+ cursor.execute("SELECT * FROM items;")
57
+ items = cursor.fetchall()
58
+ df = pd.DataFrame(items, columns=["ID", "Name"])
59
+ return df
60
+
61
+ def update_item(id, name):
62
+ con.execute("UPDATE items SET name = ? WHERE id = ?;", (name, id))
63
+ con.commit()
64
+ return "Item updated successfully!"
65
+
66
+ def delete_item(id):
67
+ con.execute("DELETE FROM items WHERE id = ?;", (id,))
68
+ con.commit()
69
+ return "Item deleted successfully!"
70
+
71
+ with gr.Blocks() as appdb:
72
+ gr.Markdown("CRUD Application")
73
+ with gr.Row():
74
+ with gr.Column():
75
+ create_name = gr.Textbox(label="Create Item")
76
+ create_btn = gr.Button("Create")
77
+ with gr.Column():
78
+ read_btn = gr.Button("Read Items")
79
+ with gr.Row():
80
+ with gr.Column():
81
+ update_id = gr.Textbox(label="Update Item ID")
82
+ update_name = gr.Textbox(label="Update Item Name")
83
+ update_btn = gr.Button("Update")
84
+ with gr.Column():
85
+ delete_id = gr.Textbox(label="Delete Item ID")
86
+ delete_btn = gr.Button("Delete")
87
+ output_text = gr.Textbox(label="Output")
88
+ output_table = gr.DataFrame(label="Items")
89
+
90
+ create_btn.click(fn=create_item, inputs=create_name, outputs=output_text)
91
+ read_btn.click(fn=read_items, outputs=output_table)
92
+ update_btn.click(fn=update_item, inputs=[update_id, update_name], outputs=output_text)
93
+ delete_btn.click(fn=delete_item, inputs=delete_id, outputs=output_text)
94
+
95
+ app.mount("/db", appdb, name="database_app")
mysite/routers/gradio.py CHANGED
@@ -1,6 +1,6 @@
1
  import shutil
2
  import gradio as gr
3
- from mysite.libs.utilities import chat_with_interpreter, completion, process_file
4
  from interpreter import interpreter
5
  import mysite.interpreter.interpreter_config # インポートするだけで設定が適用されます
6
  import importlib
 
1
  import shutil
2
  import gradio as gr
3
+ #from mysite.libs.utilities import chat_with_interpreter, completion, process_file
4
  from interpreter import interpreter
5
  import mysite.interpreter.interpreter_config # インポートするだけで設定が適用されます
6
  import importlib