import os import json import numpy as np import librosa from datetime import datetime from flask import Flask, send_from_directory, render_template import gradio as gr from transformers import pipeline import requests from dotenv import load_dotenv # 환경변수 로드 load_dotenv() # 상수 정의 WELCOME_MESSAGE = """ # 디지털 굿판에 오신 것을 환영합니다 이곳은 현대 도시 속에서 잊혀진 전통 굿의 정수를 담아낸 디지털 의례의 공간입니다. 이곳에서는 사람들의 목소리와 감정을 통해 영적 교감을 나누고, 자연과 도시의 에너지가 연결됩니다. """ ONCHEON_STORY = """ ## 생명의 공간 ‘온천천’ 🌌 온천천의 물줄기는 신성한 금샘에서 시작됩니다. 금샘은 생명과 창조의 원천이며, 천상의 생명이 지상에서 숨을 틔우는 자리입니다. 도시의 소음 속에서도 신성한 생명력을 느껴보세요. 이곳에서 영적인 교감을 경험하며, 자연과 하나 되는 순간을 맞이해 보시기 바랍니다 이 프로젝트는 부산광역시 동래구 ‘온천장역’ 에서 금정구 ‘장전역’을 잇는 구간의 온천천 산책로의 사운드 스케이프를 기반으로 제작 되었습니다. 산책로를 따라 걸으며 본 프로젝트 체험 시 보다 몰입된 경험이 가능합니다. """ # Flask 앱 초기화 app = Flask(__name__) # 환경변수 로드 load_dotenv() # Flask 라우트 @app.route('/static/') def serve_static(path): return send_from_directory('static', path) @app.route('/') def index(): return render_template('index.html') @app.route('/assets/') def serve_assets(path): try: if path.endswith('.mp3'): return send_from_directory('assets', path, mimetype='audio/mpeg') return send_from_directory('assets', path) except Exception as e: print(f"Asset serving error: {e}") return f"Error serving asset: {path}", 404 @app.route('/wishes/') def serve_wishes(path): return send_from_directory('data/wishes', path) class SimpleDB: def __init__(self, reflections_path="data/reflections.json", wishes_path="data/wishes.json"): self.reflections_path = reflections_path self.wishes_path = wishes_path os.makedirs('data', exist_ok=True) self.reflections = self._load_json(reflections_path) self.wishes = self._load_json(wishes_path) def _load_json(self, file_path): if not os.path.exists(file_path): with open(file_path, 'w', encoding='utf-8') as f: json.dump([], f, ensure_ascii=False, indent=2) try: with open(file_path, 'r', encoding='utf-8') as f: return json.load(f) except Exception as e: print(f"Error loading {file_path}: {e}") return [] def save_reflection(self, name, reflection, sentiment, timestamp=None): if timestamp is None: timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") reflection_data = { "timestamp": timestamp, "name": name, "reflection": reflection, "sentiment": sentiment } self.reflections.append(reflection_data) self._save_json(self.reflections_path, self.reflections) return True def save_wish(self, name, wish, emotion_data=None, timestamp=None): if timestamp is None: timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") wish_data = { "name": name, "wish": wish, "emotion": emotion_data, "timestamp": timestamp } self.wishes.append(wish_data) self._save_json(self.wishes_path, self.wishes) return True def _save_json(self, file_path, data): try: with open(file_path, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) return True except Exception as e: print(f"Error saving to {file_path}: {e}") return False def get_all_reflections(self): return sorted(self.reflections, key=lambda x: x["timestamp"], reverse=True) def get_all_wishes(self): return self.wishes # API 설정 HF_API_TOKEN = os.getenv("roots", "") if not HF_API_TOKEN: print("Warning: HuggingFace API token not found. Some features may be limited.") API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0" headers = {"Authorization": f"Bearer {HF_API_TOKEN}"} if HF_API_TOKEN else {} # AI 모델 초기화 try: speech_recognizer = pipeline( "automatic-speech-recognition", model="kresnik/wav2vec2-large-xlsr-korean" ) text_analyzer = pipeline( "sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment" ) except Exception as e: print(f"Error initializing AI models: {e}") speech_recognizer = None text_analyzer = None # 필요한 디렉토리 생성 os.makedirs("generated_images", exist_ok=True) # 음성 분석 관련 함수들 def calculate_baseline_features(audio_data): try: if isinstance(audio_data, tuple): sr, y = audio_data y = y.astype(np.float32) elif isinstance(audio_data, str): y, sr = librosa.load(audio_data, sr=16000) else: print("Unsupported audio format") return None if len(y) == 0: print("Empty audio data") return None features = { "energy": float(np.mean(librosa.feature.rms(y=y))), "tempo": float(librosa.feature.tempo(y=y, sr=sr)[0]), "pitch": float(np.mean(librosa.feature.zero_crossing_rate(y=y))), "volume": float(np.mean(np.abs(y))), "mfcc": librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13).mean(axis=1).tolist() } return features except Exception as e: print(f"Error calculating baseline: {str(e)}") return None def map_acoustic_to_emotion(features, baseline_features=None): if features is None: return { "primary": "알 수 없음", "intensity": 0, "confidence": 0.0, "secondary": "", "characteristics": ["음성 분석 실패"], "details": { "energy_level": "0%", "speech_rate": "알 수 없음", "pitch_variation": "알 수 없음", "voice_volume": "알 수 없음" } } energy_norm = min(features["energy"] * 100, 100) tempo_norm = min(features["tempo"] / 200, 1) pitch_norm = min(features["pitch"] * 2, 1) if baseline_features: if baseline_features["energy"] > 0 and baseline_features["tempo"] > 0 and baseline_features["pitch"] > 0: energy_norm = (features["energy"] / baseline_features["energy"]) * 50 tempo_norm = (features["tempo"] / baseline_features["tempo"]) pitch_norm = (features["pitch"] / baseline_features["pitch"]) emotions = { "primary": "", "intensity": energy_norm, "confidence": 0.0, "secondary": "", "characteristics": [] } # 감정 매핑 로직 if energy_norm > 70: if tempo_norm > 0.6: emotions["primary"] = "기쁨/열정" emotions["characteristics"].append("빠르고 활기찬 말하기 패턴") else: emotions["primary"] = "분노/강조" emotions["characteristics"].append("강한 음성 강도") emotions["confidence"] = energy_norm / 100 elif pitch_norm > 0.6: if energy_norm > 50: emotions["primary"] = "놀람/흥분" emotions["characteristics"].append("높은 음고와 강한 강세") else: emotions["primary"] = "관심/호기심" emotions["characteristics"].append("음고 변화가 큼") emotions["confidence"] = pitch_norm elif energy_norm < 30: if tempo_norm < 0.4: emotions["primary"] = "슬픔/우울" emotions["characteristics"].append("느리고 약한 음성") else: emotions["primary"] = "피로/무기력" emotions["characteristics"].append("낮은 에너지 레벨") emotions["confidence"] = (30 - energy_norm) / 30 else: if tempo_norm > 0.5: emotions["primary"] = "평온/안정" emotions["characteristics"].append("균형잡힌 말하기 패턴") else: emotions["primary"] = "차분/진지" emotions["characteristics"].append("안정적인 음성 특성") emotions["confidence"] = 0.5 emotions["details"] = { "energy_level": f"{energy_norm:.1f}%", "speech_rate": f"{'빠름' if tempo_norm > 0.6 else '보통' if tempo_norm > 0.4 else '느림'}", "pitch_variation": f"{'높음' if pitch_norm > 0.6 else '보통' if pitch_norm > 0.3 else '낮음'}", "voice_volume": f"{'큼' if features['volume'] > 0.7 else '보통' if features['volume'] > 0.3 else '작음'}" } return emotions def analyze_voice(audio_data, state): if audio_data is None: return state, "음성을 먼저 녹음해주세요.", "", "", "" try: sr, y = audio_data y = y.astype(np.float32) if len(y) == 0: return state, "음성이 감지되지 않았습니다.", "", "", "" acoustic_features = calculate_baseline_features((sr, y)) if acoustic_features is None: return state, "음성 분석에 실패했습니다.", "", "", "" # 음성 인식 if speech_recognizer: try: transcription = speech_recognizer({"sampling_rate": sr, "raw": y.astype(np.float32)}) text = transcription["text"] except Exception as e: print(f"Speech recognition error: {e}") text = "음성 인식 실패" else: text = "음성 인식 모델을 불러올 수 없습니다." # 음성 감정 분석 voice_emotion = map_acoustic_to_emotion(acoustic_features, state.get("baseline_features")) # 텍스트 감정 분석 if text_analyzer and text: try: text_sentiment = text_analyzer(text)[0] text_result = f"텍스트 감정 분석: {text_sentiment['label']} (점수: {text_sentiment['score']:.2f})" except Exception as e: print(f"Text analysis error: {e}") text_sentiment = {"label": "unknown", "score": 0.0} text_result = "텍스트 감정 분석 실패" else: text_sentiment = {"label": "unknown", "score": 0.0} text_result = "텍스트 감정 분석을 수행할 수 없습니다." voice_result = ( f"음성 감정: {voice_emotion['primary']} " f"(강도: {voice_emotion['intensity']:.1f}%, 신뢰도: {voice_emotion['confidence']:.2f})\n" f"특징: {', '.join(voice_emotion['characteristics'])}\n" f"상세 분석:\n" f"- 에너지 레벨: {voice_emotion['details']['energy_level']}\n" f"- 말하기 속도: {voice_emotion['details']['speech_rate']}\n" f"- 음높이 변화: {voice_emotion['details']['pitch_variation']}\n" f"- 음성 크기: {voice_emotion['details']['voice_volume']}" ) # 프롬프트 생성 prompt = generate_detailed_prompt(text, voice_emotion, text_sentiment) state = {**state, "final_prompt": prompt} return state, text, voice_result, text_result, prompt except Exception as e: print(f"Error in analyze_voice: {str(e)}") return state, f"오류 발생: {str(e)}", "", "", "" def generate_detailed_prompt(text, emotions, text_sentiment): emotion_colors = { "기쁨/열정": "밝은 노랑과 따뜻한 주황색", "분노/강조": "강렬한 빨강과 짙은 검정", "놀람/흥분": "선명한 파랑과 밝은 보라", "관심/호기심": "연한 하늘색과 민트색", "슬픔/우울": "어두운 파랑과 회색", "피로/무기력": "탁한 갈색과 짙은 회색", "평온/안정": "부드러운 초록과 베이지", "차분/진지": "차분한 남색과 깊은 보라" } abstract_elements = { "기쁨/열정": "상승하는 나선형과 빛나는 입자들", "분노/강조": "날카로운 지그재그와 폭발하는 형태", "놀람/흥분": "물결치는 동심원과 반짝이는 점들", "관심/호기심": "부드럽게 흐르는 곡선과 floating shapes", "슬픔/우울": "하강하는 흐름과 흐릿한 그림자", "피로/무기력": "느리게 흐르는 물결과 흐려지는 형태", "평온/안정": "부드러운 원형과 조화로운 기하학적 패턴", "차분/진지": "균형잡힌 수직선과 안정적인 구조" } prompt = f"minimalistic abstract art, {emotion_colors.get(emotions['primary'], '자연스러운 색상')} color scheme, " prompt += f"{abstract_elements.get(emotions['primary'], '유기적 형태')}, " prompt += "korean traditional patterns, ethereal atmosphere, sacred geometry, " prompt += "flowing energy, mystical aura, no human figures, no faces, " prompt += "digital art, high detail, luminescent effects. " prompt += "negative prompt: photorealistic, human, face, figurative, text, letters, " prompt += "--ar 2:3 --s 750 --q 2" return prompt def generate_image_from_prompt(prompt): if not prompt: print("No prompt provided") return None try: response = requests.post( API_URL, headers=headers, json={ "inputs": prompt, "parameters": { "negative_prompt": "ugly, blurry, poor quality, distorted", "num_inference_steps": 30, "guidance_scale": 7.5 } } ) if response.status_code == 200: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") image_path = f"generated_images/image_{timestamp}.png" os.makedirs("generated_images", exist_ok=True) with open(image_path, "wb") as f: f.write(response.content) return image_path else: print(f"Error: {response.status_code}") print(f"Response: {response.text}") return None except Exception as e: print(f"Error generating image: {str(e)}") return None def create_pwa_files(): """PWA 필요 파일들 생성""" # manifest.json 생성 manifest_path = 'static/manifest.json' if not os.path.exists(manifest_path): manifest_data = { "name": "디지털 굿판", "short_name": "디지털 굿판", "description": "현대 도시 속 디지털 의례 공간", "start_url": "/", "display": "standalone", "background_color": "#ffffff", "theme_color": "#000000", "orientation": "portrait", "icons": [ { "src": "/static/icons/icon-72x72.png", "sizes": "72x72", "type": "image/png", "purpose": "any maskable" }, { "src": "/static/icons/icon-96x96.png", "sizes": "96x96", "type": "image/png", "purpose": "any maskable" }, { "src": "/static/icons/icon-128x128.png", "sizes": "128x128", "type": "image/png", "purpose": "any maskable" }, { "src": "/static/icons/icon-144x144.png", "sizes": "144x144", "type": "image/png", "purpose": "any maskable" }, { "src": "/static/icons/icon-152x152.png", "sizes": "152x152", "type": "image/png", "purpose": "any maskable" }, { "src": "/static/icons/icon-192x192.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable" }, { "src": "/static/icons/icon-384x384.png", "sizes": "384x384", "type": "image/png", "purpose": "any maskable" }, { "src": "/static/icons/icon-512x512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" } ] } with open(manifest_path, 'w', encoding='utf-8') as f: json.dump(manifest_data, f, ensure_ascii=False, indent=2) # service-worker.js 생성 sw_path = 'static/service-worker.js' if not os.path.exists(sw_path): with open(sw_path, 'w', encoding='utf-8') as f: f.write(''' // 캐시 이름 설정 const CACHE_NAME = 'digital-gutpan-v1'; // 캐시할 파일 목록 const urlsToCache = [ '/', '/static/icons/icon-72x72.png', '/static/icons/icon-96x96.png', '/static/icons/icon-128x128.png', '/static/icons/icon-144x144.png', '/static/icons/icon-152x152.png', '/static/icons/icon-192x192.png', '/static/icons/icon-384x384.png', '/static/icons/icon-512x512.png', '/assets/main_music.mp3' ]; // 서비스 워커 설치 시 self.addEventListener('install', event => { event.waitUntil( caches.open(CACHE_NAME) .then(cache => cache.addAll(urlsToCache)) .then(() => self.skipWaiting()) ); }); // 서비스 워커 활성화 시 self.addEventListener('activate', event => { event.waitUntil( caches.keys().then(cacheNames => { return Promise.all( cacheNames.map(cacheName => { if (cacheName !== CACHE_NAME) { return caches.delete(cacheName); } }) ); }).then(() => self.clients.claim()) ); }); // 네트워크 요청 처리 self.addEventListener('fetch', event => { event.respondWith( caches.match(event.request) .then(response => { if (response) { return response; } return fetch(event.request); }) ); }); '''.strip()) # index.html 파일에 화면 꺼짐 방지 스크립트 추가 index_path = 'templates/index.html' if not os.path.exists(index_path): with open(index_path, 'w', encoding='utf-8') as f: f.write(''' 디지털 굿판
''') def safe_state_update(state, updates): try: new_state = {**state, **updates} # 중요 상태값 검증 if "user_name" in updates: new_state["user_name"] = str(updates["user_name"]).strip() or "익명" if "baseline_features" in updates: if updates["baseline_features"] is None: return state # baseline이 None이면 상태 업데이트 하지 않음 return new_state except Exception as e: print(f"State update error: {e}") return state def create_interface(): db = SimpleDB() import base64 # initial_state 정의 initial_state = { "user_name": "", "baseline_features": None, "reflections": [], "wish": None, "final_prompt": "", "image_path": None, "current_tab": 0 } def encode_image_to_base64(image_path): try: with open(image_path, "rb") as img_file: return base64.b64encode(img_file.read()).decode() except Exception as e: print(f"이미지 로딩 에러 ({image_path}): {e}") return "" # 로고 이미지 인코딩 mobile_logo = encode_image_to_base64("static/DIGITAL_GUTPAN_LOGO_m.png") desktop_logo = encode_image_to_base64("static/DIGITAL_GUTPAN_LOGO_w.png") main_image = encode_image_to_base64("static/main-image.png") if not mobile_logo or not desktop_logo: logo_html = """

디지털 굿판

""" else: logo_html = f""" """ main_image_html = f"""
디지털 굿판 메인 이미지
""" # 모바일 및 데스크톱용 위치 이미지를 Base64로 인코딩 location_image_mobile = encode_image_to_base64("static/location.png") location_image_desktop = encode_image_to_base64("static/location_w.png") # location_html 정의 if not location_image_mobile or not location_image_desktop: location_html = """

위치 안내

""" else: location_html = f""" 위치 안내 이미지 (모바일) 위치 안내 이미지 (데스크톱) """ css = """ /* 전체 컨테이너 width 제한 */ .gradio-container { margin: 0 auto !important; max-width: 800px !important; padding: 1rem !important; } /* 모바일 뷰 */ @media (max-width: 600px) { .location-image-desktop { display: none !important; } .location-image-mobile { display: block !important; width: 100%; height: auto; } .mobile-logo { display: none !important; } .desktop-logo { display: block !important; width: 100%; height: auto; max-width: 800px; margin: 0 auto; } .main-image { width: 100%; max-width: 100%; } .gradio-container, .gradio-container *, body { font-size: 17px !important; } .markdown-style h1, .markdown-style h1 * { font-size: 22px !important; } .markdown-style h2, .markdown-style h2 * { font-size: 20px !important; } .markdown-style h3, .markdown-style h3 * { font-size: 18px !important; } } /* 데스크톱 뷰 (601px 이상) */ @media (min-width: 601px) { .location-image-mobile { display: none !important; } .location-image-desktop { display: block !important; width: 100%; height: auto; } .main-image { width: 600px; max-width: 600px; } .container { padding: 10px !important; } .gradio-row { flex-direction: column !important; gap: 10px !important; } .gradio-button { width: 100% !important; margin: 5px 0 !important; min-height: 44px !important; } .gradio-textbox { width: 100% !important; } .gradio-audio { width: 100% !important; } .gradio-image { width: 100% !important; } #audio-recorder { width: 100% !important; } #result-image { width: 100% !important; } .gradio-dataframe { overflow-x: auto !important; max-width: 100% !important; } .logo-container { padding: 20px 0; width: 100%; max-width: 800px; margin: 0 auto; } .desktop-logo { display: none !important; } .mobile-logo { display: block !important; width: 100% !important; height: auto !important; max-width: 300px !important; margin: 0 auto !important; } /* 데스크탑에서 2단 컬럼 레이아웃 보완 */ .gradio-row { gap: 20px !important; } .gradio-row > .gradio-column { flex: 1 !important; min-width: 0 !important; } } /* 전반적인 UI 개선 */ .gradio-button { transition: all 0.3s ease; border-radius: 8px !important; } .main-image-container { width: 100%; margin: 0 auto 2rem auto; text-align: center; } .main-image { width: 100%; height: auto; max-width: 100%; display: block; margin: 0 auto; } .gradio-button:active { transform: scale(0.98); } /* 컴포넌트 간격 조정 */ .gradio-column > *:not(:last-child) { margin-bottom: 1rem !important; } /* 데이터프레임 스타일링 */ .gradio-dataframe { border: 1px solid #e0e0e0; border-radius: 8px; overflow: hidden; } .gradio-dataframe table { font-size: 16px !important; } /* 오디오 플레이어 컨테이너 */ .audio-player-container { max-width: 800px; margin: 20px auto; padding: 0 1rem; } .audio-player { margin: 20px auto; width: 100%; max-width: 300px; /* 탭 스타일링 */ .tabs { max-width: 800px; margin: 0 auto; } /* 마크다운 컨텐츠 */ .markdown-content { max-width: 800px; margin: 0 auto; padding: 0 1rem; } /* 기본 텍스트 크기 증가 */ .gradio-container, .gradio-container *, body { font-size: 17px !important; line-height: 1.7 !important; } /* 마크다운 기본 텍스트 */ .markdown-style { font-size: 17px !important; line-height: 1.7 !important; } /* 마크다운 제목 크기 조정 */ .markdown-style h1, .markdown-style h1 * { font-size: 22px !important; line-height: 1.4 !important; margin-bottom: 0.8em !important; } .markdown-style h2, .markdown-style h2 * { font-size: 20px !important; line-height: 1.4 !important; margin-bottom: 0.7em !important; } .markdown-style h3, .markdown-style h3 * { font-size: 18px !important; line-height: 1.4 !important; margin-bottom: 0.6em !important; } /* 입력 필드와 버튼 */ .gradio-textbox input, .gradio-textbox textarea { font-size: 17px !important; line-height: 1.5 !important; padding: 12px !important; } .gradio-button { font-size: 17px !important; padding: 12px 20px !important; min-height: 48px !important; } /* 탭과 라벨 */ .tabs .tab-nav * { font-size: 17px !important; } label, .label-text { font-size: 17px !important; margin-bottom: 8px !important; } /* 이미지 컨테이너 */ .gradio-image { border-radius: 8px; overflow: hidden; max-width: 800px; margin: 0 auto; } .blessing-status-box { min-height: 200px !important; max-height: 300px !important; overflow-y: auto !important; padding: 15px !important; border: 1px solid #ddd !important; border-radius: 8px !important; background-color: #f8f9fa !important; margin: 10px 0 !important; } .blessing-status-box { min-height: 250px !important; max-height: 400px !important; overflow-y: auto !important; padding: 20px !important; border: 1px solid #ddd !important; border-radius: 12px !important; background-color: #f8f9fa !important; margin: 15px 0 !important; font-size: 16px !important; line-height: 1.6 !important; } .blessing-status-box h3 { color: #2a5d8f !important; margin-bottom: 15px !important; } .blessing-status-box strong { color: #4a90e2 !important; } } /* Hugging Face 로고 숨기기 */ .div.gr-header { display: none !important; } /* 다크 테마 기본 스타일 */ body { margin: 0; padding: 0; background: #0b0f19 !important; overflow-x: hidden; position: relative; min-height: 100vh; color: #ffffff; } /* 메인 컨테이너 스타일링 */ .gradio-container { margin: 0 auto !important; padding: 0 !important; max-width: 800px !important; background: #0b0f19 !important; min-height: 100vh; box-shadow: 0 0 10px rgba(0,0,0,0.3); position: relative; } /* 상단 상태바 스타일 */ .status-bar { position: fixed; top: 0; left: 0; right: 0; height: env(safe-area-inset-top); background: #000000; z-index: 1000; } /* 하단 여백 조정 */ .footer-spacing { height: env(safe-area-inset-bottom); background: #0b0f19; } /* 앱 스크롤 동작 */ .app-scroll { -webkit-overflow-scrolling: touch; scroll-behavior: smooth; } /* 모든 탭 컨텐츠 배경색 */ .tabs > div { background: #0b0f19 !important; } /* 입력 필드 스타일링 */ .gradio-textbox input, .gradio-textbox textarea { background: #1a1f2e !important; color: #ffffff !important; border: 1px solid #2a2f3e !important; } /* 버튼 스타일링 유지 */ .gradio-button { background: #2a2f3e !important; color: #ffffff !important; border: none !important; } .gradio-button:hover { background: #3a3f4e !important; } /* 데이터프레임/테이블 스타일링 */ .gradio-dataframe { background: #1a1f2e !important; color: #ffffff !important; } /* 모달과 팝업의 배경색 */ .modal-content { background: #0b0f19 !important; color: #ffffff !important; } /* iOS 상태바용 메타 태그 색상 */ @supports (-webkit-touch-callout: none) { .status-bar { height: max(env(safe-area-inset-top), 20px); background: #000000; } } /* 로딩 상태 표시 */ .processing-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(11, 15, 25, 0.8); display: flex; justify-content: center; align-items: center; z-index: 1000; } .loading-spinner { width: 50px; height: 50px; border: 5px solid #f3f3f3; border-top: 5px solid #4a90e2; border-radius: 50%; animation: spin 1s linear infinite; } .loading-text { position: absolute; top: 60%; left: 50%; transform: translateX(-50%); color: white; font-size: 18px; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } /* 버튼 비활성화 스타일 */ .gradio-button:disabled { opacity: 0.6; cursor: not-allowed; } /* 이미지 컨테이너 스타일 */ .location-image-container { width: 100%; max-width: 800px; margin: 20px auto; text-align: center; } .location-image { width: 100%; max-width: 100%; height: auto; border-radius: 12px; margin: 0 auto; } } """ with gr.Blocks(theme=gr.themes.Soft(), css=css) as app: state = gr.State(value=initial_state) processing_status = gr.State("") with gr.Column(elem_classes="logo-container"): gr.HTML(logo_html) with gr.Tabs(selected=0) as tabs: # 입장 탭 (축원 포함) with gr.TabItem("입장") as tab_entrance: gr.HTML(main_image_html) # 1단계: 첫 화면 welcome_section = gr.Column(visible=True) with welcome_section: gr.Markdown(WELCOME_MESSAGE) name_input = gr.Textbox( label="이름을 알려주세요", placeholder="이름을 입력해주세요", interactive=True ) name_submit_btn = gr.Button("축원의식 준비하기", variant="primary") # 2단계: 세계관 설명 story_section = gr.Column(visible=False) with story_section: gr.Markdown(ONCHEON_STORY) continue_btn = gr.Button("축원의식 시작하기", variant="primary") # 3단계: 축원 의식 blessing_section = gr.Column(visible=False) with blessing_section: gr.Markdown("### 축원의식을 시작하겠습니다") gr.Markdown(""" 축원 문장을 읽어주세요: '명짐 복짐 짊어지고 안가태평하시기를 비도발원 축원 드립니다' """) # 축원 문장 녹음하기 baseline_audio = gr.Audio( label="축원 문장 녹음하기", sources=["microphone"], type="numpy", streaming=False ) # 분석 버튼을 바로 녹음기 아래에 배치 set_baseline_btn = gr.Button("축원문 분석하기", variant="primary") # 상태 표시창 - 분석 결과 표시 blessing_status = gr.Markdown( value="축원 문장을 녹음한 후 분석하기 버튼을 눌러주세요.", elem_id="blessing-status", elem_classes="blessing-status-box" ) # 4단계: 굿판 입장 안내 entry_guide_section = gr.Column(visible=False) with entry_guide_section: gr.Markdown("## 굿판으로 입장하기") gr.Markdown(""" 굿판에 들어가기 전에 마음을 고요히 하고 신과 연결될 준비를 하세요. 이 경험은 부산 동래구 온천장역에서 시작하여, 온천천을 따라 신화적 공간과 연결될 수 있도록 설계되었습니다. 특히 이곳에서 시작하면 온천천의 자연스러운 소리와 금샘의 생명력을 더욱 깊이 느낄 수 있습니다. 온천천을 따라 걷다 보면, 금샘과 연결된 물의 정화 에너지가 스며들며 신성을 느끼게 될 것입니다. 본격적인 의식을 시작하기 전, 마음을 정화하고 감각을 열어 경험에 몰입할 준비를 마치세요. **청신 의식을 시작하려면 아래 버튼을 눌러주세요.** """) enter_btn = gr.Button("청신 의식 시작하기", variant="primary") with gr.TabItem("청신") as tab_listen: gr.Markdown("## 청신 - 신을 부르기 위한 정화 의식") # 온천 이미지 추가 oncheon_image = encode_image_to_base64("static/oncheon.png") gr.HTML(f"""
온천천 이미지
""") gr.Markdown(""" **청신(淸神)** 단계는 신을 부르는 의식으로, 정화와 연결의 의미를 담고 있습니다. 이 단계에서는 참여자가 도시의 번잡함에서 벗어나 내면의 고요함을 찾고 신성과의 교감을 시작하게 됩니다. 본격적인 의식을 시작하기 전, 마음을 정화하고 감각을 열어 경험에 몰입할 준비를 마치세요 """) with gr.Column(): gr.HTML(location_html) gr.Markdown(""" **보다 몰입된 경험을 위해** 이 경험은 부산 동래구 온천장역에서 시작하여, 금정구 장전역까지 온천천을 따라 신화적 공간과 연결될 수 있도록 설계되었습니다. 특히 이곳에서 시작하면 온천천의 자연스러운 소리와 금샘의 생명력을 더욱 깊이 느낄 수 있습니다. 온천천을 따라 걷다 보면, 금샘과 연결된 물의 정화 에너지가 스며들며 신성을 느끼게 될 것입니다. 청신 단계의 목적은 참여자들이 자연과 신화적 요소를 통해 감각을 깨우고 자신의 감정을 정화하며, 초자연적 존재와 소통할 준비를 하는 데 있습니다. 특히 온천천의 물소리와 자연의 소리는 신을 부르는 소리처럼 참여자의 마음을 고요하게 하고, 금샘 신화의 정화와 생명력의 상징성을 통해 신을 맞이할 준비를 갖추게 합니다. **이제 음악을 들으며 감정을 기록해보세요.** 음악을 통해 내면의 평온을 되찾고, 이 과정에서 느껴지는 감정과 생각들을 자유롭게 적어보세요. 이 기록은 이후 과정에서 소망과 의식을 구체화하는 데 큰 도움이 될 것입니다. """) # 커스텀 오디오 플레이어 gr.Markdown("## 聽身, 請神 (몸의 소리를 듣고 신을 청하다) ") gr.HTML("""