GitHub Action commited on
Commit
41f215f
·
1 Parent(s): 5c5ca8d

🚀 Auto-deploy from GitHub Actions

Browse files
controllers/gra_03_programfromdocgas/programfromdocAI.py CHANGED
@@ -1,17 +1,35 @@
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
6
- import gradio as gr
7
- import psycopg2
8
- from dataclasses import dataclass, field
9
- from typing import List, Optional
10
- from mysite.interpreter.process import no_process_file,process_file
11
- #from controllers.gra_04_database.rides import test_set_lide
12
-
13
- val = """
14
- # gradio で miiboのナレッジに登録する画面の作成
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  gradio_interface interfacec name
16
 
17
  # fastapi
@@ -26,21 +44,15 @@ plantumlで図にする
26
  import requests
27
  import json
28
  import os
29
- # current_user: User = Depends(get_current_active_user)):
30
- # oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token")
31
- # current_user: User = Depends(get_current_active_user)):
32
- # oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token")
33
 
34
  from fastapi import APIRouter, HTTPException
35
  from gradio_client import Client
36
 
37
- #router = APIRouter()
38
  router = APIRouter(prefix="/gradio", tags=["gradio"])
39
  @router.get("/route/gradio")
40
 
41
  def get_senario(id,res):
42
  table = "LOG"
43
-
44
  client = Client("kenken999/fastapi_django_main_live")
45
  result = client.predict(
46
  message="Hello!!",
@@ -49,19 +61,227 @@ def get_senario(id,res):
49
  api_name="/chat"
50
  )
51
  return result
 
 
 
 
 
 
 
 
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
 
 
57
 
58
- gradio_interface = gr.Interface(
59
- fn=process_file,
60
- inputs=[
61
- "file",
62
- gr.Textbox(label="Additional Notes", lines=10, value=val),
63
- gr.Textbox(label="Folder Name", value="test_folders"),
64
- gr.Textbox(label="github token", value="***********************"),
65
- ],
66
- outputs="text"
67
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 sqlite3
6
+ import os
7
+ from datetime import datetime
8
+ from typing import List, Tuple, Optional
9
+
10
+ # データベース設定
11
+ DB_PATH = "prompts.db"
12
+
13
+ def init_db():
14
+ """プロンプトデータベースの初期化"""
15
+ conn = sqlite3.connect(DB_PATH)
16
+ cursor = conn.cursor()
17
+
18
+ cursor.execute('''
19
+ CREATE TABLE IF NOT EXISTS prompts (
20
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
21
+ title TEXT NOT NULL,
22
+ url TEXT,
23
+ content TEXT NOT NULL,
24
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
25
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
26
+ )
27
+ ''')
28
+
29
+ # デフォルトプロンプトの追加(初回のみ)
30
+ cursor.execute('SELECT COUNT(*) FROM prompts')
31
+ if cursor.fetchone()[0] == 0:
32
+ default_prompt = """# gradio で miiboのナレッジに登録する画面の作成
33
  gradio_interface interfacec name
34
 
35
  # fastapi
 
44
  import requests
45
  import json
46
  import os
 
 
 
 
47
 
48
  from fastapi import APIRouter, HTTPException
49
  from gradio_client import Client
50
 
 
51
  router = APIRouter(prefix="/gradio", tags=["gradio"])
52
  @router.get("/route/gradio")
53
 
54
  def get_senario(id,res):
55
  table = "LOG"
 
56
  client = Client("kenken999/fastapi_django_main_live")
57
  result = client.predict(
58
  message="Hello!!",
 
61
  api_name="/chat"
62
  )
63
  return result
64
+ """
65
+ cursor.execute(
66
+ 'INSERT INTO prompts (title, url, content) VALUES (?, ?, ?)',
67
+ ('デフォルト:Gradio + FastAPI作成', 'https://example.com', default_prompt)
68
+ )
69
+
70
+ conn.commit()
71
+ conn.close()
72
 
73
+ def save_prompt(title: str, url: str, content: str) -> str:
74
+ """プロンプトを保存"""
75
+ try:
76
+ conn = sqlite3.connect(DB_PATH)
77
+ cursor = conn.cursor()
78
+
79
+ cursor.execute(
80
+ 'INSERT INTO prompts (title, url, content) VALUES (?, ?, ?)',
81
+ (title, url, content)
82
+ )
83
+
84
+ conn.commit()
85
+ conn.close()
86
+ return f"✅ プロンプト '{title}' を保存しました!"
87
+ except Exception as e:
88
+ return f"❌ エラー: {str(e)}"
89
 
90
+ def get_prompts() -> List[Tuple]:
91
+ """全プロンプトを取得"""
92
+ try:
93
+ conn = sqlite3.connect(DB_PATH)
94
+ cursor = conn.cursor()
95
+
96
+ cursor.execute('SELECT id, title, url, created_at FROM prompts ORDER BY created_at DESC')
97
+ prompts = cursor.fetchall()
98
+
99
+ conn.close()
100
+ return prompts
101
+ except Exception as e:
102
+ print(f"プロンプト取得エラー: {e}")
103
+ return []
104
 
105
+ def get_prompt_content(prompt_id: int) -> str:
106
+ """指定IDのプロンプト内容を取得"""
107
+ try:
108
+ conn = sqlite3.connect(DB_PATH)
109
+ cursor = conn.cursor()
110
+
111
+ cursor.execute('SELECT content FROM prompts WHERE id = ?', (prompt_id,))
112
+ result = cursor.fetchone()
113
+
114
+ conn.close()
115
+ return result[0] if result else ""
116
+ except Exception as e:
117
+ print(f"プロンプト内容取得エラー: {e}")
118
+ return ""
119
+
120
+ def delete_prompt(prompt_id: int) -> str:
121
+ """プロンプトを削除"""
122
+ try:
123
+ conn = sqlite3.connect(DB_PATH)
124
+ cursor = conn.cursor()
125
+
126
+ cursor.execute('DELETE FROM prompts WHERE id = ?', (prompt_id,))
127
+
128
+ if cursor.rowcount > 0:
129
+ conn.commit()
130
+ conn.close()
131
+ return "✅ プロンプトを削除しました"
132
+ else:
133
+ conn.close()
134
+ return "❌ プロンプトが見つかりません"
135
+ except Exception as e:
136
+ return f"❌ 削除エラー: {str(e)}"
137
 
138
+ # データベース初期化
139
+ init_db()
140
 
141
+ def load_prompt_from_db(prompt_id):
142
+ """選択されたプロンプトを読み込み"""
143
+ if prompt_id:
144
+ content = get_prompt_content(int(prompt_id))
145
+ return content
146
+ return ""
147
+
148
+ def refresh_prompt_list():
149
+ """プロンプト一覧を更新"""
150
+ prompts = get_prompts()
151
+ choices = []
152
+ for prompt in prompts:
153
+ id_, title, url, created_at = prompt
154
+ display_text = f"[{id_}] {title} ({created_at[:10]})"
155
+ choices.append((display_text, str(id_)))
156
+ return gr.Dropdown(choices=choices, label="📋 保存済みプロンプト一覧", value=None)
157
+
158
+ # Gradioインターフェース作成
159
+ with gr.Blocks(title="🚀 プロンプト管理 & コード生成") as gradio_interface:
160
+ gr.Markdown("# 🚀 プロンプト管理 & ドキュメントからコード生成")
161
+
162
+ with gr.Tabs():
163
+ # タブ1: プロンプト管理
164
+ with gr.TabItem("📝 プロンプト管理"):
165
+ gr.Markdown("## プロンプトの保存・管理")
166
+
167
+ with gr.Row():
168
+ with gr.Column(scale=1):
169
+ # プロンプト保存フォーム
170
+ save_title = gr.Textbox(label="📋 タイトル", placeholder="例: FastAPI + Gradio作成プロンプト")
171
+ save_url = gr.Textbox(label="🔗 参考URL (任意)", placeholder="https://example.com")
172
+ save_content = gr.Textbox(
173
+ label="📝 プロンプト内容",
174
+ lines=10,
175
+ placeholder="プロンプトの内容を入力してください..."
176
+ )
177
+ save_btn = gr.Button("💾 プロンプトを保存", variant="primary")
178
+ save_status = gr.Textbox(label="保存結果", interactive=False)
179
+
180
+ with gr.Column(scale=1):
181
+ # プロンプト一覧
182
+ prompt_dropdown = gr.Dropdown(
183
+ choices=[],
184
+ label="📋 保存済みプロンプト一覧",
185
+ interactive=True
186
+ )
187
+ refresh_btn = gr.Button("🔄 一覧を更新")
188
+ load_btn = gr.Button("📥 選択したプロンプトを読み込み", variant="secondary")
189
+ delete_btn = gr.Button("🗑️ 選択したプロンプトを削除", variant="stop")
190
+ delete_status = gr.Textbox(label="削除結果", interactive=False)
191
+
192
+ # タブ2: コード生成
193
+ with gr.TabItem("⚡ コード生成"):
194
+ gr.Markdown("## ドキュメントからコード生成")
195
+
196
+ with gr.Row():
197
+ with gr.Column():
198
+ # ファイルアップロード
199
+ input_file = gr.File(label="📄 ドキュメントファイル")
200
+
201
+ # プロンプト表示・編集エリア
202
+ current_prompt = gr.Textbox(
203
+ label="📝 現在のプロンプト",
204
+ lines=15,
205
+ value="",
206
+ placeholder="上のタブでプロンプトを選択するか、直接入力してください..."
207
+ )
208
+
209
+ with gr.Column():
210
+ # 生成設定
211
+ folder_name = gr.Textbox(label="📁 出力フォルダ名", value="generated_code")
212
+ github_token = gr.Textbox(label="🔑 GitHub Token (任意)", type="password", value="")
213
+
214
+ # 生成ボタン
215
+ generate_btn = gr.Button("🚀 コード生成実行", variant="primary", size="lg")
216
+
217
+ # 結果表示
218
+ result_output = gr.Textbox(label="📤 生成結果", lines=10, interactive=False)
219
+
220
+ # イベントハンドラー
221
+ def handle_save_prompt(title, url, content):
222
+ if not title.strip() or not content.strip():
223
+ return "❌ タイトルとプロンプト内容は必須です"
224
+ return save_prompt(title, url, content)
225
+
226
+ def handle_refresh_list():
227
+ prompts = get_prompts()
228
+ choices = []
229
+ for prompt in prompts:
230
+ id_, title, url, created_at = prompt
231
+ display_text = f"[{id_}] {title} ({created_at[:10]})"
232
+ choices.append((display_text, str(id_)))
233
+ return gr.Dropdown(choices=choices, value=None)
234
+
235
+ def handle_load_prompt(selected_prompt):
236
+ if selected_prompt:
237
+ prompt_id = selected_prompt.split(']')[0][1:] # [1] から ] までを取得してIDを抽出
238
+ content = get_prompt_content(int(prompt_id))
239
+ return content
240
+ return ""
241
+
242
+ def handle_delete_prompt(selected_prompt):
243
+ if selected_prompt:
244
+ prompt_id = selected_prompt.split(']')[0][1:] # IDを抽出
245
+ return delete_prompt(int(prompt_id))
246
+ return "❌ プロンプトが選択されていません"
247
+
248
+ def handle_generate_code(file, prompt, folder, token):
249
+ if not prompt.strip():
250
+ return "❌ プロンプトが入力されていません"
251
+ return process_file(file, prompt, folder, token)
252
+
253
+ # イベント接続
254
+ save_btn.click(
255
+ handle_save_prompt,
256
+ inputs=[save_title, save_url, save_content],
257
+ outputs=[save_status]
258
+ )
259
+
260
+ refresh_btn.click(
261
+ handle_refresh_list,
262
+ outputs=[prompt_dropdown]
263
+ )
264
+
265
+ load_btn.click(
266
+ handle_load_prompt,
267
+ inputs=[prompt_dropdown],
268
+ outputs=[current_prompt]
269
+ )
270
+
271
+ delete_btn.click(
272
+ handle_delete_prompt,
273
+ inputs=[prompt_dropdown],
274
+ outputs=[delete_status]
275
+ )
276
+
277
+ generate_btn.click(
278
+ handle_generate_code,
279
+ inputs=[input_file, current_prompt, folder_name, github_token],
280
+ outputs=[result_output]
281
+ )
282
+
283
+ # ページ読み込み時にプロンプト一覧を初期化
284
+ gradio_interface.load(
285
+ handle_refresh_list,
286
+ outputs=[prompt_dropdown]
287
+ )