Spaces:
Running
Running
File size: 4,724 Bytes
b931367 6e4938d b931367 3f80c6a b931367 6e4938d b931367 439ab17 b931367 439ab17 b931367 439ab17 b931367 439ab17 b931367 6e4938d b931367 3f80c6a b931367 40b06b6 b931367 a4e9ea3 b931367 3f80c6a a4e9ea3 3f80c6a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
import gradio as gr
import uuid
import logging
from datetime import datetime
from gradio.analytics import ANALYTICS_URL
import pandas as pd
from model_handler import ModelHandler
from tab_chat import create_chat_tab
from tab_code import create_code_tab
from tab_smart_writer import create_smart_writer_tab
from tab_test import run_model_handler_test, run_clear_chat_test
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def get_history_df(history):
if not history:
return pd.DataFrame({'ID': [], '对话': []})
df = pd.DataFrame(history)
return df[['id', 'title']].rename(columns={'id': 'ID', 'title': '对话'})
def on_app_load(history, conv_id):
"""
Handles the application's initial state on load.
- If no history exists, creates a new conversation.
- If the last conversation ID is invalid, loads the most recent one.
- Otherwise, loads the last active conversation.
"""
if not history:
# First time ever loading, create a new chat
conv_id = str(uuid.uuid4())
new_convo = { "id": conv_id, "title": "(新对话)", "messages": [], "timestamp": datetime.now().isoformat() }
history = [new_convo]
return conv_id, history, gr.update(value=get_history_df(history)), []
# Check if the last used conv_id is valid
if conv_id and any(c["id"] == conv_id for c in history):
# It's valid, load it
for convo in history:
if convo["id"] == conv_id:
return conv_id, history, gr.update(value=get_history_df(history)), convo["messages"]
# Last used conv_id is invalid or doesn't exist, load the most recent conversation
most_recent_convo = history[0] # Assumes history is sorted by timestamp desc
conv_id = most_recent_convo["id"]
return conv_id, history, gr.update(value=get_history_df(history)), most_recent_convo["messages"]
CSS = """
#chatbot {
height: calc(100vh - 21px - 16px);
max-height: 1500px;
}
footer {
display: none !important;
}
/* Disable transition and animation for no-transition class */
.no-transition, .no-transition * {
transition: none !important;
animation: none !important;
animation-play-state: paused !important;
}
"""
if __name__ == "__main__":
# Instantiate the model handler with the configuration
logger.info("Starting Ling Space Application...")
model_handler = ModelHandler()
with gr.Blocks(analytics_enabled=False,
fill_height=True,
fill_width=True) as demo:
with gr.Tabs(elem_id='indicator-space-app') as tabs:
with gr.TabItem("文本聊天") as chat_tab:
conversation_store, current_conversation_id, history_df, chatbot = create_chat_tab()
chat_tab.select(
fn=None,
js="() => {window.dispatchEvent(new CustomEvent('tabSelect.chat')); console.log('this'); return null;}",
)
with gr.TabItem("代码生成") as code_tab:
create_code_tab()
code_tab.select(
fn=None,
js="() => {window.dispatchEvent(new CustomEvent('tabSelect.code')); return null;}",
)
with gr.TabItem("写作助手") as writer_tab:
create_smart_writer_tab()
writer_tab.select(
fn=None,
js="() => {window.dispatchEvent(new CustomEvent('tabSelect.writing')); return null;}",
)
with gr.TabItem("测试", visible=False):
gr.Markdown("# 功能测试")
with gr.Column():
test_log_output = gr.Textbox(label="测试日志", interactive=False, lines=10)
gr.Button("运行 ModelHandler 测试").click(run_model_handler_test, outputs=test_log_output)
gr.Button("运行 清除聊天 测试").click(run_clear_chat_test, outputs=test_log_output)
# Bind on_app_load to demo.load
demo.load(
on_app_load,
inputs=[conversation_store, current_conversation_id],
outputs=[current_conversation_id, conversation_store, history_df, chatbot],
js="() => {window.dispatchEvent(new CustomEvent('appStart')); console.log('appStart'); return {};}"
)
demo.queue(default_concurrency_limit=32,
max_size=128)
# Launch the Gradio application
demo.launch(theme=gr.themes.Default(),
ssr_mode=False,
max_threads=64,
css=CSS,
head="",
head_paths=['./static/toastify.html', './static/app.html'])
|