Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -147,138 +147,52 @@ def get_last_user_and_assistant(history):
|
|
| 147 |
return last_user, last_assistant
|
| 148 |
|
| 149 |
# -----------------------------
|
| 150 |
-
# File helpers
|
| 151 |
# -----------------------------
|
| 152 |
-
def
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
with open(path, "w", encoding="utf-8") as f:
|
| 157 |
-
json.dump(obj, f, indent=2, ensure_ascii=False)
|
| 158 |
-
return path
|
| 159 |
|
| 160 |
-
def
|
| 161 |
if not history:
|
| 162 |
return None
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
writer.writerow(["role", "content"])
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
return path
|
| 172 |
|
| 173 |
# -----------------------------
|
| 174 |
-
# Gradio callbacks
|
| 175 |
# -----------------------------
|
| 176 |
-
def respond(message, state, category):
|
| 177 |
-
"""
|
| 178 |
-
Called by Send button or Enter.
|
| 179 |
-
Returns: cleared input, updated state, updated chatbot display (state replicated)
|
| 180 |
-
"""
|
| 181 |
-
history = state or []
|
| 182 |
-
if not (message and message.strip()):
|
| 183 |
-
return "", history, history
|
| 184 |
-
|
| 185 |
-
# generate 3-fold reply
|
| 186 |
-
summary, fusion, reference = generate_three_fold(category, message)
|
| 187 |
-
assistant_text = f"{summary}\n\n{fusion}\n\n{reference}"
|
| 188 |
-
|
| 189 |
-
history = append_user_assistant(history, message, assistant_text)
|
| 190 |
-
return "", history, history
|
| 191 |
-
|
| 192 |
-
def clear_all():
|
| 193 |
-
# clears textbox, state and chatbot
|
| 194 |
-
return "", [], []
|
| 195 |
-
|
| 196 |
-
def upload_json(filepath):
|
| 197 |
-
"""Load uploaded dataset file (filepath is local path inside container)"""
|
| 198 |
-
global dataset, DATA_PATH
|
| 199 |
-
try:
|
| 200 |
-
with open(filepath, "r", encoding="utf-8") as f:
|
| 201 |
-
data = json.load(f)
|
| 202 |
-
if not isinstance(data, dict):
|
| 203 |
-
return "Upload failed: root must be an object", gr.update(choices=sorted(list(dataset.keys())), value=None)
|
| 204 |
-
# ensure staged_responses exists
|
| 205 |
-
if "staged_responses" not in data:
|
| 206 |
-
data["staged_responses"] = []
|
| 207 |
-
dataset = data
|
| 208 |
-
DATA_PATH = os.path.basename(filepath)
|
| 209 |
-
cats = sorted([k for k in dataset.keys() if k != "staged_responses"])
|
| 210 |
-
status = f"Loaded {len(cats)} categories from {DATA_PATH}."
|
| 211 |
-
return status, gr.update(choices=cats, value=(cats[0] if cats else None))
|
| 212 |
-
except Exception as e:
|
| 213 |
-
return f"Error loading file: {e}", gr.update(choices=sorted(list(dataset.keys())), value=None)
|
| 214 |
-
|
| 215 |
-
def stage_last_conversation(state, target_category):
|
| 216 |
-
"""
|
| 217 |
-
Stage the last user + assistant pair into dataset['staged_responses']
|
| 218 |
-
(stored as {"question":..., "answer":..., "category":...})
|
| 219 |
-
"""
|
| 220 |
-
if not state:
|
| 221 |
-
return "No conversation in memory."
|
| 222 |
-
last_user, last_assistant = get_last_user_and_assistant(state)
|
| 223 |
-
if not last_user:
|
| 224 |
-
return "No user message to stage."
|
| 225 |
-
entry = {"question": last_user, "answer": last_assistant or "", "category": target_category}
|
| 226 |
-
if "staged_responses" not in dataset:
|
| 227 |
-
dataset["staged_responses"] = []
|
| 228 |
-
dataset["staged_responses"].append(entry)
|
| 229 |
-
return f"Staged last Q/A into '{target_category}'."
|
| 230 |
-
|
| 231 |
def download_conversation_csv(state):
|
| 232 |
-
|
| 233 |
-
path = write_temp_csv_from_history(state or [])
|
| 234 |
-
if not path:
|
| 235 |
-
return gr.File.update(value=None)
|
| 236 |
-
return gr.File.update(value=path)
|
| 237 |
|
| 238 |
def download_current_dataset():
|
| 239 |
-
|
| 240 |
-
path = write_temp_json(dataset, suffix=".json")
|
| 241 |
-
return gr.File.update(value=path)
|
| 242 |
|
| 243 |
# -----------------------------
|
| 244 |
-
# Gradio UI
|
| 245 |
# -----------------------------
|
| 246 |
with gr.Blocks() as demo:
|
| 247 |
gr.Markdown("## Campus Life — 3-fold responses, staging, CSV/JSON downloads")
|
| 248 |
|
| 249 |
-
# dropdown
|
| 250 |
-
category_choices = sorted([k for k in dataset.keys() if k != "staged_responses"])
|
| 251 |
-
with gr.Row():
|
| 252 |
-
category = gr.Dropdown(label="Category", choices=category_choices,
|
| 253 |
-
value=(category_choices[0] if category_choices else None))
|
| 254 |
-
|
| 255 |
-
chatbot = gr.Chatbot(label="Conversation", height=360, type="messages")
|
| 256 |
-
state = gr.State([]) # holds list of {"role":..,"content":..}
|
| 257 |
-
msg = gr.Textbox(label="Your message", placeholder="Type and press Enter (or click Send)", autofocus=True)
|
| 258 |
-
send = gr.Button("Send")
|
| 259 |
-
clear = gr.Button("Clear")
|
| 260 |
-
|
| 261 |
-
with gr.Row():
|
| 262 |
-
stage_btn = gr.Button("Stage last Q/A to category")
|
| 263 |
-
stage_status = gr.Textbox(label="Stage status", interactive=False, value="")
|
| 264 |
|
| 265 |
with gr.Row():
|
| 266 |
upload = gr.File(label="Upload dataset (.json)", file_types=[".json"], type="filepath")
|
| 267 |
upload_status = gr.Textbox(label="Upload status", interactive=False, value="")
|
| 268 |
download_json_btn = gr.Button("Download current dataset (JSON)")
|
| 269 |
-
download_json_file = gr.File(label="Download JSON", interactive=
|
| 270 |
download_csv_btn = gr.Button("Download conversation (CSV)")
|
| 271 |
-
download_csv_file = gr.File(label="Download CSV", interactive=
|
| 272 |
|
| 273 |
# events
|
| 274 |
-
|
| 275 |
-
send.click(respond, [msg, state, category], [msg, state, chatbot])
|
| 276 |
-
clear.click(clear_all, [], [msg, state, chatbot])
|
| 277 |
-
|
| 278 |
-
stage_btn.click(stage_last_conversation, [state, category], stage_status)
|
| 279 |
-
|
| 280 |
-
upload.upload(upload_json, upload, [upload_status, category])
|
| 281 |
-
|
| 282 |
download_csv_btn.click(download_conversation_csv, state, download_csv_file)
|
| 283 |
download_json_btn.click(download_current_dataset, None, download_json_file)
|
| 284 |
|
|
|
|
| 147 |
return last_user, last_assistant
|
| 148 |
|
| 149 |
# -----------------------------
|
| 150 |
+
# File helpers
|
| 151 |
# -----------------------------
|
| 152 |
+
def prepare_json_download(obj):
|
| 153 |
+
text = json.dumps(obj, indent=2, ensure_ascii=False)
|
| 154 |
+
return {"name": f"dataset_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
|
| 155 |
+
"data": text.encode("utf-8")}
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
+
def prepare_csv_download(history):
|
| 158 |
if not history:
|
| 159 |
return None
|
| 160 |
+
from io import StringIO
|
| 161 |
+
s = StringIO()
|
| 162 |
+
writer = csv.writer(s)
|
| 163 |
+
writer.writerow(["role", "content"])
|
| 164 |
+
for m in history:
|
| 165 |
+
writer.writerow([m.get("role", ""), m.get("content", "")])
|
| 166 |
+
return {"name": f"conversation_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
|
| 167 |
+
"data": s.getvalue().encode("utf-8")}
|
|
|
|
| 168 |
|
| 169 |
# -----------------------------
|
| 170 |
+
# Gradio callbacks
|
| 171 |
# -----------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
def download_conversation_csv(state):
|
| 173 |
+
return prepare_csv_download(state or [])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
def download_current_dataset():
|
| 176 |
+
return prepare_json_download(dataset)
|
|
|
|
|
|
|
| 177 |
|
| 178 |
# -----------------------------
|
| 179 |
+
# Gradio UI
|
| 180 |
# -----------------------------
|
| 181 |
with gr.Blocks() as demo:
|
| 182 |
gr.Markdown("## Campus Life — 3-fold responses, staging, CSV/JSON downloads")
|
| 183 |
|
| 184 |
+
# dropdown, chatbot, textbox, send, clear (UNCHANGED) ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
with gr.Row():
|
| 187 |
upload = gr.File(label="Upload dataset (.json)", file_types=[".json"], type="filepath")
|
| 188 |
upload_status = gr.Textbox(label="Upload status", interactive=False, value="")
|
| 189 |
download_json_btn = gr.Button("Download current dataset (JSON)")
|
| 190 |
+
download_json_file = gr.File(label="Download JSON", interactive=True)
|
| 191 |
download_csv_btn = gr.Button("Download conversation (CSV)")
|
| 192 |
+
download_csv_file = gr.File(label="Download CSV", interactive=True)
|
| 193 |
|
| 194 |
# events
|
| 195 |
+
# ... unchanged ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
download_csv_btn.click(download_conversation_csv, state, download_csv_file)
|
| 197 |
download_json_btn.click(download_current_dataset, None, download_json_file)
|
| 198 |
|