Spaces:
Paused
Paused
Update app-backup1.py
Browse files50 unmodified lines5152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714815 unmodified lines1641651661671681691701711721731748 unmodified lines18318418518618718818919019119219319419519619719819920020120220320420520620720820921021112 unmodified lines2242252262272282292302315 unmodified lines2372382392402412422432442452462472482492503 unmodified lines2542552562572582592601 unmodified line2622632642652662672682692702719 unmodified lines2812822832842852862876 unmodified lines29429529629729829930030130230330430530630730830931031131231315 unmodified lines3293303313323333343353363373383393403415 unmodified lines347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403123 unmodified lines527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598173 unmodified lines77277377477577677777877978078150 unmodified lines์ ๋๋ก ๋์ ๋ชจ๋ธ๋ช ๊ณผ ์ง์๋ฌธ์ ๋ ธ์ถํ์ง ๋ง๊ฒ"""# config.py์์ DEMO_LIST๋ง importfrom config import DEMO_LISTimport sqlite3from datetime import datetimedef init_db():try:conn = sqlite3.connect('chat_history.db')c = conn.cursor()# ํ ์ด๋ธ์ด ์์ ๋๋ง ์์ฑc.execute('''CREATE TABLE IF NOT EXISTS sessions(session_id TEXT PRIMARY KEY,created_at TIMESTAMP)''')c.execute('''CREATE TABLE IF NOT EXISTS chat_history(id INTEGER PRIMARY KEY AUTOINCREMENT,session_id TEXT,prompt TEXT,response TEXT,timestamp TIMESTAMP,FOREIGN KEY (session_id) REFERENCES sessions(session_id))''')conn.commit()print("Database initialized successfully")except sqlite3.Error as e:print(f"Database error: {e}")raisefinally:if conn:conn.close()def check_db_status():try:conn = sqlite3.connect('chat_history.db')c = conn.cursor()# ํ ์ด๋ธ ์กด์ฌ ์ฌ๋ถ ํ์ธc.execute("SELECT name FROM sqlite_master WHERE type='table'")tables = c.fetchall()print(f"Existing tables: {tables}")# ๋ฐ์ดํฐ ๊ฐ์ ํ์ธc.execute("SELECT COUNT(*) FROM chat_history")chat_count = c.fetchone()[0]print(f"Number of chat records: {chat_count}")conn.close()except Exception as e:print(f"Error checking database status: {e}")def create_session():max_attempts = 5for attempt in range(max_attempts):try:# ๋ฐ๋ฆฌ์ด๊น์ง ํฌํจํ ๋ ์์ธํ ํ์์คํฌํ ์ฌ์ฉsession_id = datetime.now().strftime("%Y%m%d_%H%M%S_%f")conn = sqlite3.connect('chat_history.db')c = conn.cursor()c.execute("INSERT INTO sessions VALUES (?, ?)", (session_id, datetime.now()))conn.commit()conn.close()return session_idexcept sqlite3.IntegrityError:if attempt == max_attempts - 1:raisetime.sleep(0.1) # ์ ์ ๋๊ธฐ ํ ์ฌ์๋finally:if 'conn' in locals():conn.close()raise Exception("Failed to create unique session ID after multiple attempts")# ์ธ์ ๋ณ ํ์คํ ๋ฆฌ ์กฐํdef get_session_history(session_id):conn = sqlite3.connect('chat_history.db')c = conn.cursor()c.execute("SELECT prompt, response, timestamp FROM chat_history WHERE session_id = ? ORDER BY timestamp",(session_id,))history = c.fetchall()conn.close()return historydef get_image_base64(image_path):with open(image_path, "rb") as image_file:encoded_string = base64.b64encode(image_file.read()).decode()return encoded_stringclass Role:SYSTEM = "system"USER = "user"15 unmodified linesfor q, r in zip(messages[1::2], messages[2::2]):history.append([q['content'], r['content']])return history# API ํด๋ผ์ด์ธํธ ์ด๊ธฐํYOUR_ANTHROPIC_TOKEN = ""YOUR_OPENAI_TOKEN = ""claude_client = anthropic.Anthropic(api_key=YOUR_ANTHROPIC_TOKEN)openai_client = openai.OpenAI(api_key=YOUR_OPENAI_TOKEN)8 unmodified linesmessages=claude_messages) as stream:collected_content = ""for chunk in stream: # async for ์ ๊ฑฐ, ์ผ๋ฐ for ์ฌ์ฉcurrent_time = time.time()if current_time - start_time > timeout:print(f"Claude API response time: {current_time - start_time:.2f} seconds")raise TimeoutError("Claude API timeout")if chunk.type == "content_block_delta":collected_content += chunk.delta.textyield collected_content # ๊ฐ ์ฒญํฌ๋ง๋ค ์ฆ์ yieldawait asyncio.sleep(0) # ์คํธ๋ฆฌ๋ฐ์ ์ํ ๋น๋๊ธฐ ์๋ณด# ๊ฐ ์ฒญํฌ๋ง๋ค ํ์์์ ์นด์ดํฐ ๋ฆฌ์ start_time = current_timeexcept Exception as e:print(f"Claude API error: {str(e)}")raise easync def try_openai_api(openai_messages):try:stream = openai_client.chat.completions.create(model="gpt-4o", # ๋ชจ๋ธ๋ช ์ ์งmessages=openai_messages,stream=True,max_tokens=4096,12 unmodified linesclass Demo:def __init__(self):init_db()self.current_session = create_session()async def generation_code(self, query: Optional[str], _setting: Dict[str, str], _history: Optional[History]):if not query or query.strip() == '':5 unmodified linesmessages = history_to_messages(_history, _setting['system'])system_message = messages[0]['content']# Claude ๋ฉ์์ง ํฌ๋งทclaude_messages = [{"role": msg["role"] if msg["role"] != "system" else "user", "content": msg["content"]}for msg in messages[1:] + [{'role': Role.USER, 'content': query}]if msg["content"].strip() != '']# OpenAI ๋ฉ์์ง ํฌ๋งทopenai_messages = [{"role": "system", "content": system_message}]for msg in messages[1:]:openai_messages.append({3 unmodified linesopenai_messages.append({"role": "user", "content": query})try:# ๋จผ์ ์ฝ๋ ๋ทฐ์ด๋ฅผ ์ด๊ธฐyield ["Generating code...",_history,1 unmodified linegr.update(active_key="loading"),gr.update(open=True)]await asyncio.sleep(0) # UI ์ ๋ฐ์ดํธ๋ฅผ ์ํ ์๋ณดcollected_content = None# Claude API ์๋try:async for content in try_claude_api(system_message, claude_messages):yield [9 unmodified linesexcept Exception as claude_error:print(f"Falling back to OpenAI API due to Claude error: {str(claude_error)}")# OpenAI API๋ก ํด๋ฐฑasync for content in try_openai_api(openai_messages):yield [content,6 unmodified linescollected_content = contentif collected_content:try:print(f"Attempting to save chat with session_id: {self.current_session}")print(f"Query: {query}")print(f"Content length: {len(collected_content)}")# ์ฑํ ๋ด์ฉ ์ ์ฅsave_chat(self.current_session, query, collected_content)print("Chat saved successfully")except Exception as save_error:print(f"Error saving chat: {save_error}")_history = messages_to_history([{'role': Role.SYSTEM, 'content': system_message}] + claude_messages + [{15 unmodified linesprint(f"Error details: {str(e)}")raise ValueError(f'Error calling APIs: {str(e)}')def clear_history(self):self.current_session = create_session()return []def remove_code_block(text):pattern = r'```html\n(.+?)\n```'match = re.search(pattern, text, re.DOTALL)5 unmodified linesdef history_render(history: History):return gr.update(open=True), historydef send_to_sandbox(code):encoded_html = base64.b64encode(code.encode('utf-8')).decode('utf-8')data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"return f"<iframe src=\"{data_uri}\" width=\"100%\" height=\"920px\"></iframe>"theme = gr.themes.Soft()def clear_expired_sessions():"""30์ผ ์ด์ ๋ ์ธ์ ์ญ์ """conn = sqlite3.connect('chat_history.db')try:c = conn.cursor()c.execute("""DELETE FROM chat_history WHERE session_id IN(SELECT session_id FROM sessionsWHERE created_at < datetime('now', '-30 days'))""")c.execute("DELETE FROM sessions WHERE created_at < datetime('now', '-30 days')")conn.commit()finally:conn.close()def update_session_list():try:conn = sqlite3.connect('chat_history.db')c = conn.cursor()# ์ธ์ ๊ณผ ๊ฐ์ฅ ์ต๊ทผ ๋ํ ์๊ฐ์ ํจ๊ป ๊ฐ์ ธ์ดc.execute("""SELECT s.session_id, MAX(ch.timestamp) as last_chatFROM sessions sLEFT JOIN chat_history ch ON s.session_id = ch.session_idGROUP BY s.session_idORDER BY last_chat DESC NULLS LAST""")sessions = c.fetchall()conn.close()# ์ธ์ ID์ ์๊ฐ์ ํฌ๋งทํformatted_sessions = []for session_id, last_chat in sessions:if last_chat:time_str = datetime.strptime(last_chat, '%Y-%m-%d %H:%M:%S.%f').strftime('%Y-%m-%d %H:%M:%S')formatted_sessions.append(f"{session_id} ({time_str})")else:formatted_sessions.append(session_id)return gr.update(choices=formatted_sessions)except Exception as e:print(f"Error updating session list: {e}")return gr.update(choices=[])def load_json_data():# ํ๋์ฝ๋ฉ๋ ๋ฐ์ดํฐ ๋ฐํreturn [123 unmodified linesprint(f"Error in load_session_history: {str(e)}")return gr.HTML("Error loading templates")# ํ์คํ ๋ฆฌ ์์ดํ ์ ํ ์ฒ๋ฆฌ ํจ์def handle_history_selection(evt: gr.SelectData):try:prompt = evt.value["prompt"]response = evt.value["response"]# ์ฝ๋ ์ถ์ถcode = responseif "```html" in response:match = re.search(r'```html\n(.*?)\n```', response, re.DOTALL)if match:code = match.group(1)return (prompt, # ์ ๋ ฅ ํ๋์ ํ๋กฌํํธ ์ค์ send_to_sandbox(code), # ์ฝ๋ ์คํgr.update(active_key="render"), # ํญ ์ํ ์ ๋ฐ์ดํธgr.update(open=False) # ์ธ์ ๋๋ก์ด ๋ซ๊ธฐ)except Exception as e:print(f"Error handling history selection: {e}")return None, None, gr.update(active_key="empty"), gr.update(open=True)def save_chat(session_id, prompt, response):print(f"Starting save_chat with session_id: {session_id}")conn = Nonetry:conn = sqlite3.connect('chat_history.db')c = conn.cursor()# ์ธ์ ์ด ์กด์ฌํ๋์ง ํ์ธc.execute("SELECT 1 FROM sessions WHERE session_id = ?", (session_id,))if not c.fetchone():print(f"Session {session_id} not found, creating new session")c.execute("INSERT INTO sessions (session_id, created_at) VALUES (?, ?)",(session_id, datetime.now()))# ์ฑํ ์ ์ฅc.execute("""INSERT INTO chat_history (session_id, prompt, response, timestamp)VALUES (?, ?, ?, ?)""", (session_id, prompt, response, datetime.now()))conn.commit()print(f"Successfully saved chat for session {session_id}")except sqlite3.Error as e:print(f"Database error: {e}")if conn:conn.rollback()raiseexcept Exception as e:print(f"Unexpected error: {e}")if conn:conn.rollback()raisefinally:if conn:conn.close()# Demo ์ธ์คํด์ค ๋จผ์ ์์ฑdemo_instance = Demo()with gr.Blocks(css_paths="app.css",theme=theme) as demo:history = gr.State([])173 unmodified linesoutputs=[history])if __name__ == "__main__":try:init_db()clear_expired_sessions()demo_instance = Demo()demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)except Exception as e:50 unmodified lines515253545556575815 unmodified lines747576777879808182838 unmodified lines929394959697989910010110210310410510610710810911011111211311411511611712 unmodified lines1301311321331341351365 unmodified lines1421431441451461471481491501511521533 unmodified lines1571581591601611621 unmodified line1641651661671681691701711729 unmodified lines1821831841851861876 unmodified lines19419519619719819915 unmodified lines2152162172182192202212222235 unmodified lines229230231232233234235236237238239240241242243244245246123 unmodified lines370371372373374375376377378379380173 unmodified lines55455555655755855956056156256350 unmodified lines์ ๋๋ก ๋์ ๋ชจ๋ธ๋ช ๊ณผ ์ง์๋ฌธ์ ๋ ธ์ถํ์ง ๋ง๊ฒ"""from config import DEMO_LISTclass Role:SYSTEM = "system"USER = "user"15 unmodified linesfor q, r in zip(messages[1::2], messages[2::2]):history.append([q['content'], r['content']])return history# API ํด๋ผ์ด์ธํธ ์ด๊ธฐํYOUR_ANTHROPIC_TOKEN = os.getenv('ANTHROPIC_API_KEY')YOUR_OPENAI_TOKEN = os.getenv('OPENAI_API_KEY')claude_client = anthropic.Anthropic(api_key=YOUR_ANTHROPIC_TOKEN)openai_client = openai.OpenAI(api_key=YOUR_OPENAI_TOKEN)8 unmodified linesmessages=claude_messages) as stream:collected_content = ""for chunk in stream:current_time = time.time()if current_time - start_time > timeout:print(f"Claude API response time: {current_time - start_time:.2f} seconds")raise TimeoutError("Claude API timeout")if chunk.type == "content_block_delta":collected_content += chunk.delta.textyield collected_contentawait asyncio.sleep(0)start_time = current_timeexcept Exception as e:print(f"Claude API error: {str(e)}")raise easync def try_openai_api(openai_messages):try:stream = openai_client.chat.completions.create(model="gpt-4o",messages=openai_messages,stream=True,max_tokens=4096,12 unmodified linesclass Demo:def __init__(self):passasync def generation_code(self, query: Optional[str], _setting: Dict[str, str], _history: Optional[History]):if not query or query.strip() == '':5 unmodified linesmessages = history_to_messages(_history, _setting['system'])system_message = messages[0]['content']claude_messages = [{"role": msg["role"] if msg["role"] != "system" else "user", "content": msg["content"]}for msg in messages[1:] + [{'role': Role.USER, 'content': query}]if msg["content"].strip() != '']openai_messages = [{"role": "system", "content": system_message}]for msg in messages[1:]:openai_messages.append({3 unmodified linesopenai_messages.append({"role": "user", "content": query})try:yield ["Generating code...",_history,1 unmodified linegr.update(active_key="loading"),gr.update(open=True)]await asyncio.sleep(0)collected_content = Nonetry:async for content in try_claude_api(system_message, claude_messages):yield [9 unmodified linesexcept Exception as claude_error:print(f"Falling back to OpenAI API due to Claude error: {str(claude_error)}")async for content in try_openai_api(openai_messages):yield [content,6 unmodified linescollected_content = contentif collected_content:_history = messages_to_history([{'role': Role.SYSTEM, 'content': system_message}] + claude_messages + [{15 unmodified linesprint(f"Error details: {str(e)}")raise ValueError(f'Error calling APIs: {str(e)}')def clear_history(self):return []def remove_code_block(text):pattern = r'```html\n(.+?)\n```'match = re.search(pattern, text, re.DOTALL)5 unmodified linesdef history_render(history: History):return gr.update(open=True), historydef send_to_sandbox(code):encoded_html = base64.b64encode(code.encode('utf-8')).decode('utf-8')data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"return f"<iframe src=\"{data_uri}\" width=\"100%\" height=\"920px\"></iframe>"def get_image_base64(image_path):with open(image_path, "rb") as image_file:encoded_string = base64.b64encode(image_file.read()).decode()return encoded_stringtheme = gr.themes.Soft()def load_json_data():# ํ๋์ฝ๋ฉ๋ ๋ฐ์ดํฐ ๋ฐํreturn [123 unmodified linesprint(f"Error in load_session_history: {str(e)}")return gr.HTML("Error loading templates")# Demo ์ธ์คํด์ค ์์ฑdemo_instance = Demo()with gr.Blocks(css_paths="app.css",theme=theme) as demo:history = gr.State([])173 unmodified linesoutputs=[history])# ๋ง์ง๋ง ๋ถ๋ถ์ ๋ค์๊ณผ ๊ฐ์ด ์์ ํ์ธ์if __name__ == "__main__":try:demo_instance = Demo()demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)except Exception as e:
app-backup1.py+17-235