GitHub Actions commited on
Commit
581a236
·
1 Parent(s): cc7e10f

🚀 Auto-deploy from GitHub Actions

Browse files

Deployed from: bpmbox/AUTOCREATE
Commit: 0a496d766aaf3f22d91a621228c185e2f5c9dbcf
Branch: main
Workflow: 🚀 Deploy to Hugging Face Space

Updated files:
- System workflow analysis notebook
- Core Python modules
- Controllers and routers
- Documentation and configs

Files changed (1) hide show
  1. app.py +20 -910
app.py CHANGED
@@ -1,927 +1,37 @@
1
  #!/usr/bin/env python3
2
  """
3
- FastAPI Laravel-style Application with Gradio Integration
4
  ========================================================
5
-
6
- Laravel風のPythonアプリケーション
7
- 改善されたGradio読み込みとデータベース接続エラー修正
8
  """
9
 
10
- import gradio as gr
11
  import os
12
- import shutil
13
  import sys
14
  from dotenv import load_dotenv
15
 
16
- # .envファイルから環境変数を読み込み
17
  load_dotenv()
18
 
19
  # プロジェクトルートをパスに追加
20
  project_root = os.path.dirname(os.path.abspath(__file__))
21
  sys.path.append(project_root)
22
 
23
-
24
- def check_missing_databases():
25
- """不足しているデータベースをチェック"""
26
- try:
27
- from config.database import get_db_connection
28
-
29
- required_dbs = [
30
- 'prompts.db',
31
- 'approval_system.db',
32
- 'chat_history.db',
33
- 'conversation_history.db',
34
- 'github_issues.db',
35
- 'users.db'
36
- ]
37
-
38
- missing = []
39
- db_dir = os.path.join(project_root, 'database')
40
-
41
- for db_name in required_dbs:
42
- db_path = os.path.join(db_dir, db_name)
43
- if not os.path.exists(db_path):
44
- missing.append(db_name.replace('.db', ''))
45
-
46
- return missing
47
-
48
- except Exception as e:
49
- print(f"⚠️ Database check error: {e}")
50
- return []
51
-
52
-
53
- def initialize_laravel_style_gradio():
54
- """Laravel風のGradio初期化"""
55
- try:
56
- # 環境変数の設定(個別起動完全防止)
57
- os.environ['GRADIO_ANALYTICS_ENABLED'] = 'false'
58
- os.environ['GRADIO_SERVER_HOST'] = '0.0.0.0'
59
- os.environ['GRADIO_SERVER_PORT'] = '7860'
60
- os.environ['GRADIO_ROOT_PATH'] = '' # ルートパス設定(空文字でルート)
61
-
62
- # 自動起動を完全に無効化(強化版 + 内部メソッドオーバーライド)
63
- os.environ['GRADIO_AUTO_LAUNCH'] = 'false'
64
- os.environ['GRADIO_SHARE'] = 'false'
65
- os.environ['GRADIO_DISABLE_LAUNCH'] = 'true' # 起動完全無効化
66
- os.environ['GRADIO_LAUNCH_PREVENT'] = 'true' # 起動防止フラグ
67
-
68
- # キュー無効化環境変数を追加
69
- os.environ['GRADIO_ENABLE_QUEUE'] = 'false' # キュー完全無効化
70
- os.environ['GRADIO_QUEUE_DISABLED'] = 'true' # キュー無効フラグ
71
-
72
- # Gradioの内部起動メソッドを無効化
73
- import gradio as gr
74
-
75
- # Interface.launchメソッドを無効化
76
- def disabled_launch(self, *args, **kwargs):
77
- print(
78
- f"🚫 LAUNCH PREVENTED for {getattr(self, 'title', 'Interface')}")
79
- return None
80
-
81
- # TabbedInterface.launchメソッドを無効化
82
- def disabled_tabbed_launch(self, *args, **kwargs):
83
- print(f"🚫 TABBED LAUNCH PREVENTED")
84
- return None
85
-
86
- # Blocks.launchメソッドを無効化
87
- def disabled_blocks_launch(self, *args, **kwargs):
88
- print(f"🚫 BLOCKS LAUNCH PREVENTED")
89
- return None
90
-
91
- # Queue メソッドも無効化
92
- def disabled_queue(self, *args, **kwargs):
93
- print(
94
- f"🚫 QUEUE PREVENTED for {getattr(self, 'title', 'Interface')}")
95
- return self # チェインメソッドなのでselfを返す
96
-
97
- # 起動メソッドをオーバーライド
98
- if hasattr(gr.Interface, 'launch'):
99
- gr.Interface.launch = disabled_launch
100
- if hasattr(gr.TabbedInterface, 'launch'):
101
- gr.TabbedInterface.launch = disabled_tabbed_launch
102
- if hasattr(gr.Blocks, 'launch'):
103
- gr.Blocks.launch = disabled_blocks_launch
104
-
105
- # Queueメソッドをオーバーライド
106
- if hasattr(gr.Interface, 'queue'):
107
- gr.Interface.queue = disabled_queue
108
- if hasattr(gr.TabbedInterface, 'queue'):
109
- gr.TabbedInterface.queue = disabled_queue
110
- if hasattr(gr.Blocks, 'queue'):
111
- gr.Blocks.queue = disabled_queue
112
-
113
- print("🚀 Initializing Laravel-style Gradio (LAUNCH & QUEUE PREVENTION MODE)...")
114
- print("⚠️ INDIVIDUAL LAUNCHES COMPLETELY DISABLED!")
115
- print("⚠️ QUEUE METHODS COMPLETELY DISABLED!")
116
- print("🔒 Gradio launch & queue methods OVERRIDDEN!")
117
-
118
- # データベース初期化
119
- from database.init_databases import create_databases
120
- missing_dbs = check_missing_databases()
121
- if missing_dbs:
122
- print(f"⚠️ Missing databases: {missing_dbs}")
123
- create_databases()
124
- print("✅ Databases initialized successfully")
125
- else:
126
- print("✅ All databases are present")
127
-
128
- # Laravel風Controller経由でGradio初期化
129
- from routes.web import initialize_gradio_with_error_handling
130
- tabbed_interface = initialize_gradio_with_error_handling()
131
-
132
- # 追加のキュー無効化処理(フロントエンド側も対応)
133
- try:
134
- # Gradioの内部設定でキューを完全無効化
135
- if hasattr(tabbed_interface, 'config'):
136
- if isinstance(tabbed_interface.config, dict):
137
- tabbed_interface.config['enable_queue'] = False
138
- print("✅ Frontend queue disabled via config")
139
-
140
- # イベントハンドラのキューも無効化
141
- for tab in getattr(tabbed_interface, 'interface_list', []):
142
- if hasattr(tab, 'enable_queue'):
143
- tab.enable_queue = False
144
- if hasattr(tab, '_queue'):
145
- tab._queue = None
146
- print("✅ All tab queues disabled")
147
- except Exception as config_error:
148
- print(f"⚠️ Additional queue config warning: {config_error}")
149
-
150
- print("✅ Laravel-style Gradio initialization completed")
151
-
152
- # 統合起動専用の復元関数を定義
153
- def restore_launch_for_unified():
154
- """統合起動時のみlaunchメソッドを復元(queueは復元しない)"""
155
- import gradio as gr
156
-
157
- # 元のlaunchメソッドを復元(バックアップから)
158
- if hasattr(gr.Interface, '_original_launch'):
159
- gr.Interface.launch = gr.Interface._original_launch
160
- if hasattr(gr.TabbedInterface, '_original_launch'):
161
- gr.TabbedInterface.launch = gr.TabbedInterface._original_launch
162
- if hasattr(gr.Blocks, '_original_launch'):
163
- gr.Blocks.launch = gr.Blocks._original_launch
164
-
165
- # queueメソッドは復元しない(常に無効のまま)
166
- print("🔓 Launch methods RESTORED (queue methods stay DISABLED)")
167
-
168
- # 元のlaunchメソッドをバックアップ(queueはバックアップしない)
169
- if not hasattr(gr.Interface, '_original_launch'):
170
- gr.Interface._original_launch = gr.Interface.launch
171
- if not hasattr(gr.TabbedInterface, '_original_launch'):
172
- gr.TabbedInterface._original_launch = gr.TabbedInterface.launch
173
- if not hasattr(gr.Blocks, '_original_launch'):
174
- gr.Blocks._original_launch = gr.Blocks.launch
175
-
176
- return tabbed_interface
177
-
178
- except Exception as e:
179
- print(f"❌ Laravel-style Gradio initialization failed: {e}")
180
- import traceback
181
- traceback.print_exc()
182
-
183
- # フォールバック用の簡単なインターフェース
184
- def error_handler(message):
185
- return f"🚨 Gradio Error: {str(e)}\n\nPlease check the server logs for more details."
186
-
187
- fallback_interface = gr.Interface(
188
- fn=error_handler,
189
- inputs=gr.Textbox(label="Error Details",
190
- value="Gradio initialization failed"),
191
- outputs=gr.Textbox(label="Status"),
192
- title="🚨 Gradio Setup Error"
193
- )
194
-
195
- # キュー設定は個別インスタンスでは行わない
196
- print("⚠️ Fallback interface created - NO QUEUE SETUP")
197
-
198
- return fallback_interface
199
-
200
-
201
- def create_fastapi_with_gradio():
202
- """GradioをルートにマウントしたLaravel風アプリケーションを作成"""
203
- print("🔄 Creating Laravel-style Gradio application (Gradio at root)...")
204
-
205
- # まずGradioインターフェースを作成
206
- try:
207
- print("🔄 Starting unified Gradio interface collection...")
208
- tabbed_interface = initialize_laravel_style_gradio()
209
-
210
- if tabbed_interface is None:
211
- raise Exception("Failed to create tabbed interface")
212
-
213
- # キュー設定を完全に無効化
214
- try:
215
- print("🚫 Disabling ALL queue functionality...")
216
- if hasattr(tabbed_interface, 'enable_queue'):
217
- tabbed_interface.enable_queue = False
218
- print("✅ App: enable_queue set to False")
219
-
220
- # TabbedInterfaceのキューを適切に初期化
221
- if not hasattr(tabbed_interface, '_queue'):
222
- tabbed_interface._queue = None
223
- print("✅ App: _queue initialized as None")
224
-
225
- # 各インターフェースのキューも無効化
226
- if hasattr(tabbed_interface, 'interface_list'):
227
- for interface in tabbed_interface.interface_list:
228
- if hasattr(interface, 'enable_queue'):
229
- interface.enable_queue = False
230
- if not hasattr(interface, '_queue'):
231
- interface._queue = None
232
- print(
233
- f"✅ App: All {len(tabbed_interface.interface_list)} interfaces queue disabled")
234
-
235
- print("⚠️ App: NO queue() method called - completely disabled")
236
-
237
- except Exception as queue_error:
238
- print(f"⚠️ App: Queue disable warning: {queue_error}")
239
-
240
- # 直接FastAPIアプリを作成し、そこにGradioをマウント
241
- try:
242
- print("🔄 Creating Gradio FastAPI app for root path mounting...")
243
-
244
- from fastapi import FastAPI
245
- from fastapi.middleware.cors import CORSMiddleware
246
-
247
- # 新しいFastAPIアプリを作成
248
- gradio_app = FastAPI(
249
- title="🚀 AI Development Platform - Laravel風統合システム",
250
- description="Laravel風のGradio統合プラットフォーム - ルートパスでGradio動作",
251
- version="1.0.0"
252
- )
253
-
254
- # CORS設定を追加
255
- gradio_app.add_middleware(
256
- CORSMiddleware,
257
- allow_origins=["*"],
258
- allow_credentials=True,
259
- allow_methods=["*"],
260
- allow_headers=["*"],
261
- )
262
- print("✅ FastAPI app created and CORS configured")
263
-
264
- # 静的ファイルの設定
265
- from fastapi.staticfiles import StaticFiles
266
- import mimetypes
267
-
268
- try:
269
- # MIME type設定
270
- mimetypes.add_type('text/css', '.css')
271
- mimetypes.add_type('application/javascript', '.js')
272
- mimetypes.add_type('application/json', '.json')
273
-
274
- gradio_app.mount(
275
- "/static", StaticFiles(directory="static"), name="static")
276
- print("✅ Static files mounted at /static on Gradio app")
277
- except Exception as static_error:
278
- print(f"⚠️ Static files mount failed: {static_error}")
279
-
280
- # Laravel風のルーティングをAPIエンドポイントとして追加
281
- try:
282
- from routes.web import router as web_router
283
- gradio_app.include_router(web_router, prefix="/api")
284
- print("✅ Laravel-style web routes loaded at /api on Gradio app")
285
- except ImportError as e:
286
- print(f"⚠️ Web routes not loaded: {e}")
287
-
288
- # 追加のAPIエンドポイント(Laravel風)
289
- try:
290
- # データベース関連のAPIルート
291
- from fastapi import APIRouter
292
- laravel_api = APIRouter(
293
- prefix="/laravel", tags=["Laravel API"])
294
-
295
- @laravel_api.get("/status")
296
- async def laravel_status():
297
- return {
298
- "status": "success",
299
- "message": "Laravel-style API is working with Gradio",
300
- "gradio_mounted": True,
301
- "gradio_path": "/",
302
- "app_mode": "full_laravel_gradio",
303
- "endpoints": [
304
- "/api/*",
305
- "/laravel/status",
306
- "/laravel/db-status"
307
- ]
308
- }
309
-
310
- @laravel_api.get("/db-status")
311
- async def database_status():
312
- try:
313
- missing_dbs = check_missing_databases()
314
- return {
315
- "status": "success",
316
- "databases": {
317
- "missing": missing_dbs,
318
- "total_required": 6,
319
- "available": 6 - len(missing_dbs)
320
- }
321
- }
322
- except Exception as e:
323
- return {
324
- "status": "error",
325
- "message": str(e)
326
- }
327
-
328
- gradio_app.include_router(laravel_api)
329
- print("✅ Laravel-style API endpoints added")
330
-
331
- except Exception as api_error:
332
- print(f"⚠️ Laravel API setup failed: {api_error}")
333
-
334
- # GradioインターフェースをFastAPIにマウント(ルートパス)
335
- import gradio as gr
336
- gradio_app = gr.mount_gradio_app(
337
- gradio_app, tabbed_interface, path="/")
338
- print("✅ Gradio mounted to FastAPI app at root path /")
339
-
340
- print("🚀 ✅ Gradio mounted at ROOT (/) with Laravel-style features!")
341
- return gradio_app
342
-
343
- except Exception as create_error:
344
- print(f"❌ Gradio app creation failed: {create_error}")
345
- import traceback
346
- traceback.print_exc()
347
-
348
- except Exception as e:
349
- print(f"❌ Failed to create Gradio-first app: {e}")
350
- import traceback
351
- traceback.print_exc()
352
-
353
- # フォールバック: 通常のFastAPIアプリを返す
354
- print("⚠️ Falling back to standard FastAPI app with Laravel features")
355
-
356
- from fastapi import FastAPI
357
- from fastapi.middleware.cors import CORSMiddleware
358
-
359
- app = FastAPI(
360
- title="AI Development Platform (Laravel Fallback)",
361
- description="Laravel風のGradio統合プラットフォーム(フォールバック)",
362
- version="1.0.0"
363
- )
364
-
365
- # CORS設定
366
- app.add_middleware(
367
- CORSMiddleware,
368
- allow_origins=["*"],
369
- allow_credentials=True,
370
- allow_methods=["*"],
371
- allow_headers=["*"],
372
- )
373
-
374
- # 静的ファイルの設定
375
- from fastapi.staticfiles import StaticFiles
376
- import mimetypes
377
-
378
- mimetypes.add_type('text/css', '.css')
379
- mimetypes.add_type('application/javascript', '.js')
380
- mimetypes.add_type('application/json', '.json')
381
-
382
- try:
383
- app.mount("/static", StaticFiles(directory="static"), name="static")
384
- print("✅ Static files mounted (fallback)")
385
- except Exception as static_error:
386
- print(f"⚠️ Static files mount failed: {static_error}")
387
-
388
- # Laravel風のルーティング設定
389
- try:
390
- from routes.web import router as web_router
391
- app.include_router(web_router, prefix="/api")
392
- print("✅ Laravel-style web routes loaded at /api (fallback)")
393
- except ImportError as e:
394
- print(f"❌ Failed to load web routes: {e}")
395
-
396
- # フォールバック用のエンドポイント
397
- @app.get("/")
398
- async def fallback_root():
399
- return {
400
- "message": "Laravel風アプリ(フォールバック)",
401
- "status": "fallback"
402
- }
403
-
404
- return app
405
-
406
-
407
- def initialize_laravel_style_gradio():
408
- gr.HTML("""
409
- <div style="text-align: center; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
410
- color: white; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
411
- <h1>🚀 AI Development Platform</h1>
412
- <h2>Laravel風統合システム</h2>
413
- <p>✨ 15のGradioインターフェースを統合 ✨</p>
414
- </div>
415
- """)
416
-
417
- chatbot = gr.Chatbot(label="💬 Laravel風AIチャット", height=400)
418
- msg = gr.Textbox(label="メッセージ", placeholder="Laravel風AIに質問してください...")
419
- send_btn = gr.Button("送信 📤", variant="primary")
420
-
421
- send_btn.click(simple_chat, inputs=[
422
- msg, chatbot], outputs=[chatbot, msg])
423
- msg.submit(simple_chat, inputs=[msg, chatbot], outputs=[chatbot, msg])
424
-
425
- print("✅ Simple Gradio interface created successfully")
426
-
427
- # FastAPIアプリを作成
428
- from fastapi import FastAPI
429
- from fastapi.middleware.cors import CORSMiddleware
430
-
431
- app = FastAPI(
432
- title="AI Development Platform - Laravel風",
433
- description="Laravel風のGradio統合プラットフォーム",
434
- version="1.0.0"
435
- )
436
-
437
- # CORS設定
438
- app.add_middleware(
439
- CORSMiddleware,
440
- allow_origins=["*"],
441
- allow_credentials=True,
442
- allow_methods=["*"],
443
- allow_headers=["*"],
444
- )
445
-
446
- # GradioをFastAPIにマウント(ルートパス)
447
- app = gr.mount_gradio_app(app, demo, path="/")
448
- print("✅ Gradio mounted at root path (/) successfully")
449
-
450
- # 静的ファイルの設定
451
- from fastapi.staticfiles import StaticFiles
452
- try:
453
- app.mount("/static", StaticFiles(directory="static"), name="static")
454
- print("✅ Static files mounted at /static")
455
- except Exception as static_error:
456
- print(f"⚠️ Static files mount failed: {static_error}")
457
-
458
- # Laravel風のAPIエンドポイント
459
- @app.get("/api/status")
460
- async def api_status():
461
- return {
462
- "status": "success",
463
- "message": "Laravel風AI Development Platform",
464
- "gradio_mounted": True,
465
- "root_path": "/",
466
- "features": [
467
- "📄 ドキュメント生成",
468
- "🌐 HTML表示",
469
- "🚀 統合管理ダッシュボード",
470
- "💬 AIチャット",
471
- "📁 ファイル管理"
472
- ]
473
- }
474
-
475
- @app.get("/api/laravel/info")
476
- async def laravel_info():
477
- return {
478
- "framework": "Laravel-style Python",
479
- "platform": "FastAPI + Gradio",
480
- "interfaces": 15,
481
- "databases": ["SQLite", "PostgreSQL"],
482
- "features": "AI Development Platform"
483
- }
484
-
485
- print("✅ Laravel-style API endpoints added")
486
- print("🚀 ✅ Laravel-style Gradio app created successfully at ROOT PATH!")
487
-
488
- return app
489
-
490
- except Exception as e:
491
- print(f"❌ Failed to create Laravel-style Gradio app: {e}")
492
- import traceback
493
- traceback.print_exc()
494
-
495
- # 最小限のフォールバック
496
- print("⚠️ Falling back to standard FastAPI app with Laravel features")
497
-
498
- from fastapi import FastAPI
499
- from fastapi.middleware.cors import CORSMiddleware
500
-
501
- app = FastAPI(
502
- title="AI Development Platform (Laravel Fallback)",
503
- description="Laravel風のGradio統合プラットフォーム(フォールバック)",
504
- version="1.0.0"
505
- )
506
-
507
- # CORS設定
508
- app.add_middleware(
509
- CORSMiddleware,
510
- allow_origins=["*"],
511
- allow_credentials=True,
512
- allow_methods=["*"],
513
- allow_headers=["*"],
514
- )
515
-
516
- @app.get("/")
517
- async def fallback_root():
518
- return {"message": "Laravel風アプリ(フォールバック)", "status": "fallback"}
519
-
520
- @app.get("/api/status")
521
- async def api_status():
522
- return {"status": "ok", "mode": "fallback"}
523
-
524
- @app.post("/automation/trigger")
525
- async def automation_trigger(request: dict):
526
- return {"message": "自動化トリガー(フォールバック)", "received": request}
527
-
528
- return app
529
- allow_credentials=True,
530
- allow_methods=["*"],
531
- allow_headers=["*"],
532
- )
533
-
534
- # 静的ファイルの設定
535
- from fastapi.staticfiles import StaticFiles
536
- import mimetypes
537
-
538
- mimetypes.add_type('text/css', '.css')
539
- mimetypes.add_type('application/javascript', '.js')
540
- mimetypes.add_type('application/json', '.json')
541
-
542
- try:
543
- app.mount("/static", StaticFiles(directory="static"), name="static")
544
- print("✅ Static files mounted (fallback)")
545
- except Exception as static_error:
546
- print(f"⚠️ Static files mount failed: {static_error}")
547
-
548
- # Laravel風のルーティング設定
549
- try:
550
- from routes.web import router as web_router
551
- app.include_router(web_router, prefix="/api")
552
- print("✅ Laravel-style web routes loaded at /api (fallback)")
553
- except ImportError as e:
554
- print(f"❌ Failed to load web routes: {e}")
555
-
556
- return app
557
-
558
- # Gradioインターフェースをマウント(統合起動・重複防止)
559
- if not hasattr(app, '_gradio_mounted'):
560
- try:
561
- print("🔄 Starting unified Gradio interface collection...")
562
- tabbed_interface = initialize_laravel_style_gradio()
563
-
564
- # 統合起動時のみlaunchメソッドを復元
565
- import gradio as gr
566
- if hasattr(gr.TabbedInterface, '_original_launch'):
567
- gr.TabbedInterface.launch = gr.TabbedInterface._original_launch
568
- print("🔓 Launch method RESTORED for unified TabbedInterface")
569
-
570
- # キュー設定を完全に無効化(過去の設定に戻す)
571
- try:
572
- print("🚫 Disabling ALL queue functionality...")
573
- # キューを完全に無効化
574
- if hasattr(tabbed_interface, 'enable_queue'):
575
- tabbed_interface.enable_queue = False
576
- print("✅ App: enable_queue set to False")
577
-
578
- if hasattr(tabbed_interface, '_queue'):
579
- tabbed_interface._queue = None
580
- print("✅ App: _queue cleared")
581
-
582
- # queue()メソッドも呼び出さない
583
- print("⚠️ App: NO queue() method called - completely disabled")
584
-
585
- except Exception as queue_error:
586
- print(f"⚠️ App: Queue disable warning: {queue_error}")
587
-
588
- # 安全なマウント方法(循環参照を回避)
589
- try:
590
- print("🔄 Creating safe Gradio mount...")
591
-
592
- # 1. 単純な最初のインターフェースのみをマウント(安全)
593
- if hasattr(tabbed_interface, 'interface_list') and tabbed_interface.interface_list:
594
- first_interface = tabbed_interface.interface_list[0]
595
- print(f"🎯 Using first interface: {first_interface.title}")
596
-
597
- # 安全なマウント方法
598
- gradio_app = gr.routes.App.create_app(first_interface)
599
- app.mount("/gradio", gradio_app)
600
- print("✅ First interface mounted successfully")
601
-
602
- # 他のインターフェースも個別にマウント
603
- for i, interface in enumerate(tabbed_interface.interface_list[1:], 1):
604
- try:
605
- mount_path = f"/gradio_{i}"
606
- individual_app = gr.routes.App.create_app(interface)
607
- app.mount(mount_path, individual_app)
608
- print(f"✅ Interface {i} mounted at {mount_path}")
609
- except Exception as individual_error:
610
- print(f"⚠️ Individual interface {i} mount failed: {individual_error}")
611
- else:
612
- print("❌ No interfaces available for mounting")
613
-
614
- except Exception as mount_error:
615
- print(f"❌ Safe mount failed: {mount_error}")
616
- # 最後の手段:非常に簡単なインターフェース
617
- try:
618
- def simple_test(text):
619
- return f"Echo: {text}"
620
-
621
- simple_interface = gr.Interface(
622
- fn=simple_test,
623
- inputs=gr.Textbox(label="Input"),
624
- outputs=gr.Textbox(label="Output"),
625
- title="🚀 Simple Test Interface"
626
- )
627
-
628
- simple_app = gr.routes.App.create_app(simple_interface)
629
- app.mount("/gradio", simple_app)
630
- print("✅ Emergency simple interface mounted")
631
- except Exception as emergency_error:
632
- print(f"❌ Emergency mount also failed: {emergency_error}")
633
-
634
- app._gradio_mounted = True # 重複防止フラグ
635
-
636
- print("� ✅ SAFE Gradio mounted at /gradio (avoiding circular references)!")
637
- except Exception as e:
638
- print(f"❌ Failed to mount Gradio: {e}")
639
- else:
640
- print("⚠️ Gradio already mounted - preventing duplicate mount")
641
-
642
- return app
643
-
644
- def test_laravel_gradio_integration():
645
- """Laravel風のGradio統合をテスト"""
646
- print("🚀 Testing Laravel-style Gradio Integration...")
647
- print("="*50)
648
-
649
- # 1. データベース接続テスト
650
- print("\n1. Database Connection Test:")
651
- try:
652
- from config.database import get_db_connection, DATABASE_PATHS
653
- for db_name, db_path in DATABASE_PATHS.items():
654
- exists = os.path.exists(db_path)
655
- status = "✅ EXISTS" if exists else "❌ MISSING"
656
- print(f" {db_name}: {status}")
657
-
658
- # 接続テスト
659
- conn = get_db_connection('chat_history')
660
- conn.close()
661
- print(" ✅ Database connection successful")
662
- except Exception as e:
663
- print(f" ❌ Database error: {e}")
664
-
665
- # 2. Laravel風Controller テスト
666
- print("\n2. Laravel-style Controller Test:")
667
- try:
668
- from app.Http.Controllers.Gradio.GradioController import GradioController
669
- controller = GradioController()
670
- print(" ✅ GradioController loaded successfully")
671
- print(f" Controller type: {type(controller)}")
672
- except Exception as e:
673
- print(f" ❌ Controller error: {e}")
674
-
675
- # 3. Gradio初期化テスト
676
- print("\n3. Gradio Initialization Test:")
677
- try:
678
- interface = initialize_laravel_style_gradio()
679
- print(f" ✅ Gradio interface created: {type(interface)}")
680
- except Exception as e:
681
- print(f" ❌ Gradio initialization error: {e}")
682
-
683
- # 4. FastAPI統合テスト
684
- print("\n4. FastAPI Integration Test:")
685
- try:
686
- app = create_fastapi_with_gradio()
687
- print(f" ✅ FastAPI app created: {type(app)}")
688
- print(f" Routes count: {len(app.routes)}")
689
- except Exception as e:
690
- print(f" ❌ FastAPI integration error: {e}")
691
-
692
- print("\n" + "="*50)
693
- print("🎯 Laravel-style Gradio Integration Test Completed!")
694
-
695
- def test_connections():
696
- """データベースとAPI接続をテスト"""
697
- print("🔍 Connection Testing Started...")
698
- print("=" * 50)
699
-
700
- # 環境変数確認
701
- print("📋 Environment Variables Check:")
702
- important_vars = [
703
- 'GROQ_API_KEY', 'POSTGRES_URL', 'LINE_CHANNEL_ACCESS_TOKEN',
704
- 'GITHUB_TOKEN', 'DATABASE_URL'
705
- ]
706
-
707
- for var in important_vars:
708
- value = os.getenv(var)
709
- if value:
710
- # APIキーなどは最初と最後の数文字のみ表示
711
- if 'key' in var.lower() or 'token' in var.lower():
712
- display_value = f"{value[:8]}...{value[-8:]}" if len(value) > 16 else "***"
713
- else:
714
- display_value = value
715
- print(f" ✅ {var}: {display_value}")
716
- else:
717
- print(f" ❌ {var}: Not set")
718
-
719
- print("\n🗄️ Database Connection Test:")
720
- try:
721
- # SQLiteデータベーステスト
722
- from config.database import get_db_connection, DATABASE_PATHS
723
-
724
- # データベースディレクトリの存在確認
725
- db_dir = os.path.dirname(list(DATABASE_PATHS.values())[0])
726
- if not os.path.exists(db_dir):
727
- os.makedirs(db_dir, exist_ok=True)
728
- print(f" 📁 Created database directory: {db_dir}")
729
-
730
- # データベース初期化
731
- from database.init_databases import main as init_db
732
- init_db()
733
- print(" ✅ Database initialization completed")
734
-
735
- # 接続テスト
736
- conn = get_db_connection('chat_history')
737
- cursor = conn.cursor()
738
- cursor.execute("SELECT COUNT(*) FROM sqlite_master WHERE type='table';")
739
- table_count = cursor.fetchone()[0]
740
- conn.close()
741
- print(f" ✅ SQLite connection successful - {table_count} tables found")
742
-
743
- except Exception as e:
744
- print(f" ❌ Database connection failed: {e}")
745
-
746
- print("\n🌐 Laravel-style Gradio Test:")
747
- try:
748
- from app.Http.Controllers.Gradio.GradioController import GradioController
749
- controller = GradioController()
750
- print(" ✅ GradioController imported successfully")
751
-
752
- # 簡単なインターフェーステスト
753
- interface = controller.create_main_interface()
754
- print(f" ✅ Main interface created: {type(interface)}")
755
-
756
- except Exception as e:
757
- print(f" ❌ Gradio controller test failed: {e}")
758
- import traceback
759
- traceback.print_exc()
760
-
761
- print("\n🔗 API Connection Test:")
762
- try:
763
- import requests
764
-
765
- # 簡単なHTTPテスト(Google API)
766
- response = requests.get("https://www.googleapis.com/", timeout=5)
767
- if response.status_code == 200:
768
- print(" ✅ Internet connection working")
769
- else:
770
- print(f" ⚠️ Internet connection issue: {response.status_code}")
771
- except Exception as e:
772
- print(f" ❌ Internet connection test failed: {e}")
773
-
774
- print("\n" + "=" * 50)
775
- print("🎯 Connection test completed!")
776
-
777
- # デバッグサーバーの設定
778
- def setup_debug_server():
779
- """デバッグサーバーをセットアップ"""
780
- try:
781
- import debugpy
782
- if not debugpy.is_client_connected():
783
- print("🔧 デバッグサーバーを起動中...")
784
- debugpy.listen(("0.0.0.0", 5678))
785
- print("✅ デバッグサーバーがポート5678で待機中")
786
- print("💡 VS Codeで 'Remote Attach' を使用してアタッチできます")
787
- else:
788
- print("🔗 デバッグクライアントが既に接続されています")
789
- except ImportError:
790
- print("⚠️ debugpy がインストールされていません。通常のデバッグモードで継続します")
791
- except Exception as e:
792
- print(f"⚠️ デバッグサーバー起動エラー: {e}")
793
-
794
- from fastapi import FastAPI
795
- from fastapi import Request
796
- from fastapi.templating import Jinja2Templates
797
- from fastapi.staticfiles import StaticFiles
798
- import requests
799
- import uvicorn
800
- from groq import Groq
801
-
802
- from fastapi import FastAPI, HTTPException, Header
803
- from pydantic import BaseModel
804
- from typing import Any, Coroutine, List
805
-
806
- from starlette.middleware.cors import CORSMiddleware
807
- from sse_starlette.sse import EventSourceResponse
808
-
809
- from groq import AsyncGroq, AsyncStream, Groq
810
- from groq.lib.chat_completion_chunk import ChatCompletionChunk
811
- from groq.resources import Models
812
- from groq.types import ModelList
813
- from groq.types.chat.completion_create_params import Message
814
-
815
- import async_timeout
816
- import asyncio
817
- from interpreter import interpreter
818
- import os
819
-
820
- GENERATION_TIMEOUT_SEC = 60
821
 
822
  if __name__ == "__main__":
823
- import sys
824
-
825
- print("🚀 AI Development Platform - Laravel風統合システム 起動中!")
826
- print(f"🔍 実行引数: {sys.argv}")
827
- print(f"🔍 SPACE_ID環境変数: {os.getenv('SPACE_ID')}")
828
- print(f"🔍 カレントディレクトリ: {os.getcwd()}")
829
-
830
- # テストモードの確認
831
- if "--test" in sys.argv:
832
- print("🧪 テストモード実行中")
833
- test_connections()
834
- sys.exit(0)
835
-
836
- # デバッグモードかどうかを判定
837
- is_debug = "--debug" in sys.argv or any("debugpy" in arg for arg in sys.argv)
838
-
839
- # デバッグモードの場合、デバッグサーバーをセットアップ
840
- if is_debug:
841
- setup_debug_server()
842
- print("🐛 デバッグモード: デバッガーアタッチ待機中...")
843
-
844
- # 実行環境の表示
845
- if os.getenv("SPACE_ID"):
846
- print("🤗 Hugging Face Spaces環境で実行中")
847
- else:
848
- print("💻 ローカル開発環境で実行中")
849
-
850
- try:
851
- print("🚀 Laravel風統合システムを開始しています...")
852
-
853
- # 新しい基盤システムの初期化
854
- print("🔧 システム監視・API基盤の初期化...")
855
-
856
- # データベース初���化
857
- from database.init_databases import create_databases
858
- missing_dbs = check_missing_databases()
859
- if missing_dbs:
860
- print(f"⚠️ 不足データベース: {missing_dbs}")
861
- create_databases()
862
- print("✅ データベース初期化完了")
863
- else:
864
- print("✅ 全データベース確認済み")
865
-
866
- # Laravel風Gradio初期化テスト
867
- print("🧪 Laravel風 Gradio 統合システム初期化テスト...")
868
- try:
869
- tabbed_interface = initialize_laravel_style_gradio()
870
- print(f"✅ Laravel風 Gradio 初期化成功: {type(tabbed_interface)}")
871
- except Exception as e:
872
- print(f"❌ Laravel風 Gradio 初期化失敗: {e}")
873
- import traceback
874
- traceback.print_exc()
875
-
876
- # 基盤システムの起動確認
877
- print("🔧 基盤システム起動確認...")
878
- print(" 📊 システム監視: gra_11_system_monitor")
879
- print(" 🌐 API基盤: routes/api.py")
880
- print(" 🔗 Laravel風ルーティング: mysite/asgi.py")
881
-
882
- # デバッグサーバーのセットアップ
883
- if is_debug:
884
- setup_debug_server()
885
-
886
- print("🌐 Uvicornサーバー起動中...")
887
- print("📍 アクセスURL: http://localhost:7860")
888
- print("📊 システム監視: http://localhost:7863")
889
- print("🌐 API基盤テスト: http://localhost:8001")
890
-
891
- if is_debug:
892
- print("🐛 デバッグモード: リロード無効・ブレークポイント有効")
893
- # デバッグモード: reloadを無効にしてブレークポイントを使用可能に
894
- import uvicorn
895
- uvicorn.run(
896
- "mysite.asgi:app",
897
- host="0.0.0.0",
898
- port=7860,
899
- reload=False, # デバッグ時はリロード無効
900
- log_level="debug",
901
- access_log=True,
902
- use_colors=True
903
- )
904
- else:
905
- print("📍 開発モード: ホットリロード有効・高速開発")
906
- # 開発モード: reloadを有効にして高速開発
907
- import uvicorn
908
- uvicorn.run(
909
- "mysite.asgi:app",
910
- host="0.0.0.0",
911
- port=7860,
912
- reload=True, # 開発時はリロード有効
913
- log_level="debug",
914
- access_log=True,
915
- use_colors=True,
916
- reload_dirs=["/workspaces/AUTOCREATE"]
917
- )
918
-
919
- except Exception as e:
920
- print(f"❌ アプリケーション起動エラー: {e}")
921
- import traceback
922
- traceback.print_exc()
923
- print("\n🔧 トラブルシューティング:")
924
- print("1. 依存関係確認: pip install -r requirements.txt")
925
- print("2. データベース確認: python3 app.py --test")
926
- print("3. デバッグモード: python3 app.py --debug")
927
- print("4. システム監視確認: python3 app/Http/Controllers/Gradio/gra_11_system_monitor/system_monitor.py")
 
1
  #!/usr/bin/env python3
2
  """
3
+ Django ASGI + FastAPI + Gradio 統合起動
4
  ========================================================
5
+ app.py から asgi.py を起動してすべて統合
 
 
6
  """
7
 
8
+ import uvicorn
9
  import os
 
10
  import sys
11
  from dotenv import load_dotenv
12
 
13
+ # 環境変数読み込み
14
  load_dotenv()
15
 
16
  # プロジェクトルートをパスに追加
17
  project_root = os.path.dirname(os.path.abspath(__file__))
18
  sys.path.append(project_root)
19
 
20
+ # Django設定
21
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  if __name__ == "__main__":
24
+ print("🚀 Django ASGI + FastAPI + Gradio 統合アプリ起動中...")
25
+ print("📡 メインURL: http://localhost:8000")
26
+ print("🔧 Django Admin: http://localhost:8000/admin")
27
+ print(" Gradio Chat: http://localhost:8000/gradio")
28
+ print(" API Docs: http://localhost:8000/docs")
29
+
30
+ # mysite.asgi:app を起動(Django + FastAPI + Gradio統合)
31
+ uvicorn.run(
32
+ "mysite.asgi:app",
33
+ host="0.0.0.0",
34
+ port=8000,
35
+ reload=False, # リロード無効(安定性向上)
36
+ log_level="info"
37
+ )