Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1115,12 +1115,13 @@ def ui_upload_kb_from_image_fn(uploaded_image_filepath: str, password: str, prog
|
|
1115 |
if not uploaded_image_filepath:
|
1116 |
return "No image file provided or pasted."
|
1117 |
|
1118 |
-
progress(0, desc="Loading image...")
|
1119 |
try:
|
1120 |
-
|
|
|
1121 |
except Exception as e:
|
1122 |
-
logger.error(f"KB ImgUL: Open fail: {e}")
|
1123 |
-
return f"Error: Could not open image file: {e}"
|
1124 |
|
1125 |
progress(0.2, desc="Extracting data from image...")
|
1126 |
try:
|
@@ -1144,11 +1145,12 @@ def ui_upload_kb_from_image_fn(uploaded_image_filepath: str, password: str, prog
|
|
1144 |
progress(0.4, desc="Parsing decrypted data...")
|
1145 |
else: return "Data appears encrypted, but no password was provided."
|
1146 |
except (UnicodeDecodeError, InvalidTag, ValueError) as e:
|
1147 |
-
if isinstance(e,
|
|
|
1148 |
return "Data is binary and requires a password for decryption."
|
1149 |
except Exception as e:
|
1150 |
-
logger.error(f"KB ImgUL: Decrypt error: {e}", exc_info=True)
|
1151 |
-
return f"Unexpected decryption
|
1152 |
|
1153 |
if not kv_string: return "Could not get data from image (after potential decryption)."
|
1154 |
try:
|
@@ -1178,7 +1180,7 @@ def ui_upload_kb_from_image_fn(uploaded_image_filepath: str, password: str, prog
|
|
1178 |
if s: added_rules += 1
|
1179 |
elif m == "duplicate": skip_r += 1
|
1180 |
else: err_r += 1
|
1181 |
-
if total > 0: progress(0.5 + (0.4 * (
|
1182 |
|
1183 |
progress(0.9, desc=f"Adding {len(memories_to_add)} memories...")
|
1184 |
for i, mem in enumerate(memories_to_add):
|
@@ -1224,7 +1226,6 @@ try:
|
|
1224 |
except Exception as e:
|
1225 |
logger.error(f"Could not create placeholder image. The examples may not load correctly. Error: {e}")
|
1226 |
|
1227 |
-
|
1228 |
def ui_create_kb_image_fn(password: str, content_to_include: list, progress=gr.Progress()):
|
1229 |
include_rules = "Include Rules" in content_to_include
|
1230 |
include_memories = "Include Memories" in content_to_include
|
@@ -1233,7 +1234,7 @@ def ui_create_kb_image_fn(password: str, content_to_include: list, progress=gr.P
|
|
1233 |
gr.Warning("Nothing selected to save.")
|
1234 |
return gr.update(value=None, visible=False), gr.update(value=None, visible=False), "Nothing selected to save."
|
1235 |
|
1236 |
-
progress(0, desc="Fetching knowledge base...")
|
1237 |
rules = get_all_rules_cached() if include_rules else []
|
1238 |
memories = get_all_memories_cached() if include_memories else []
|
1239 |
|
@@ -1246,35 +1247,35 @@ def ui_create_kb_image_fn(password: str, content_to_include: list, progress=gr.P
|
|
1246 |
data_bytes = kv_string.encode('utf-8')
|
1247 |
|
1248 |
if password and password.strip():
|
1249 |
-
progress(0.
|
1250 |
try:
|
1251 |
data_bytes = encrypt_data(data_bytes, password.strip())
|
1252 |
except Exception as e:
|
1253 |
logger.error(f"KB ImgDL: Encrypt failed: {e}")
|
1254 |
return gr.update(value=None, visible=False), gr.update(value=None, visible=False), f"Error: {e}"
|
1255 |
|
1256 |
-
progress(0.
|
1257 |
carrier_image = generate_brain_carrier_image(w=800, h=800)
|
1258 |
|
1259 |
-
|
1260 |
-
progress(0.7, desc="Embedding data...")
|
1261 |
-
embedded_image = embed_data_in_image(carrier_image, data_bytes)
|
1262 |
-
except ValueError as e:
|
1263 |
-
logger.error(f"KB ImgDL: Embed failed: {e}")
|
1264 |
-
return gr.update(value=None, visible=False), gr.update(value=None, visible=False), f"Error: {e}"
|
1265 |
-
|
1266 |
-
progress(0.8, desc="Adding visual overlay...")
|
1267 |
keys_for_overlay = []
|
1268 |
if include_rules: keys_for_overlay.append(f"Rule Count: {len(rules)}")
|
1269 |
if include_memories: keys_for_overlay.append(f"Memory Count: {len(memories)}")
|
1270 |
|
1271 |
-
title_overlay = "Encrypted
|
1272 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1273 |
|
1274 |
progress(0.9, desc="Preparing final image and download file...")
|
1275 |
try:
|
1276 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmpfile:
|
1277 |
-
|
1278 |
tmp_path = tmpfile.name
|
1279 |
progress(1.0, desc="Image created!")
|
1280 |
return gr.update(value=tmp_path, visible=True), gr.update(value=tmp_path, visible=True), "Success! Image created."
|
@@ -1282,6 +1283,8 @@ def ui_create_kb_image_fn(password: str, content_to_include: list, progress=gr.P
|
|
1282 |
logger.error(f"KB ImgDL: Save failed: {e}")
|
1283 |
return gr.update(value=None, visible=False), gr.update(value=None, visible=False), f"Error: {e}"
|
1284 |
|
|
|
|
|
1285 |
def ui_load_from_sources_fn(image_filepath: str, rules_file_obj: object, mems_file_obj: object, password: str, progress=gr.Progress()):
|
1286 |
if image_filepath:
|
1287 |
progress(0.1, desc="Image source detected. Starting image processing...")
|
@@ -1326,12 +1329,12 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gr-button { margin: 5px; } .gr-text
|
|
1326 |
with gr.Row():
|
1327 |
with gr.Column(scale=3):
|
1328 |
gr.Markdown("### AI Chat Interface")
|
1329 |
-
main_chat_disp = gr.Chatbot(label=None, height=450, bubble_full_width=False,avatar_images=(None, "https://
|
1330 |
with gr.Row(variant="compact"):
|
1331 |
user_msg_tb = gr.Textbox(show_label=False, placeholder="Ask your research question...", scale=7, lines=1, max_lines=3)
|
1332 |
send_btn = gr.Button("Send", variant="primary", scale=1, min_width=100)
|
1333 |
with gr.Accordion("📝 Detailed Response & Research Log", open=True):
|
1334 |
-
research_log_html = gr.HTML(label="Research Log", value="<p><i>Waiting for a new task to begin...</i></p>")
|
1335 |
fmt_report_tb = gr.Textbox(label="Full AI Response", lines=8, interactive=True, show_copy_button=True)
|
1336 |
dl_report_btn = gr.DownloadButton("Download Report", value=None, interactive=False, visible=False)
|
1337 |
|
@@ -1368,7 +1371,7 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gr-button { margin: 5px; } .gr-text
|
|
1368 |
save_kb_password_tb = gr.Textbox(label="Password (optional for encryption)", type="password")
|
1369 |
save_kb_include_cbg = gr.CheckboxGroup(label="Content to Include", choices=["Include Rules", "Include Memories"], value=["Include Rules", "Include Memories"])
|
1370 |
create_kb_img_btn = gr.Button("✨ Create KB Image", variant="secondary")
|
1371 |
-
kb_image_display_output = gr.Image(label="Generated Image (Right-click to copy)", visible=False)
|
1372 |
kb_image_download_output = gr.DownloadButton("⬇️ Download Image File", visible=False)
|
1373 |
|
1374 |
with gr.TabItem("📂 Load KB"):
|
@@ -1384,7 +1387,7 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gr-button { margin: 5px; } .gr-text
|
|
1384 |
load_master_btn = gr.Button("⬆️ Load from Sources", variant="primary", interactive=not DEMO_MODE)
|
1385 |
gr.Examples(
|
1386 |
examples=[
|
1387 |
-
[
|
1388 |
],
|
1389 |
inputs=[upload_kb_img_fobj, load_kb_password_tb],
|
1390 |
label="Click an Example to Load Data"
|
@@ -1433,7 +1436,6 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gr-button { margin: 5px; } .gr-text
|
|
1433 |
app_load_outputs = [agent_stat_tb, rules_disp_ta, mems_disp_json, research_log_html, fmt_report_tb, dl_report_btn]
|
1434 |
demo.load(fn=app_load_fn, inputs=None, outputs=app_load_outputs, show_progress="full")
|
1435 |
|
1436 |
-
|
1437 |
if __name__ == "__main__":
|
1438 |
logger.info(f"Starting Gradio AI Research Mega Agent (v9.1 - Correct 1-Click JS Download, Memory: {MEMORY_STORAGE_BACKEND})...")
|
1439 |
app_port = int(os.getenv("GRADIO_PORT", 7860))
|
|
|
1115 |
if not uploaded_image_filepath:
|
1116 |
return "No image file provided or pasted."
|
1117 |
|
1118 |
+
progress(0, desc="Loading and standardizing image...")
|
1119 |
try:
|
1120 |
+
img_temp = Image.open(uploaded_image_filepath)
|
1121 |
+
img = set_pil_image_format_to_png(img_temp)
|
1122 |
except Exception as e:
|
1123 |
+
logger.error(f"KB ImgUL: Open/Standardize fail: {e}")
|
1124 |
+
return f"Error: Could not open or process image file: {e}"
|
1125 |
|
1126 |
progress(0.2, desc="Extracting data from image...")
|
1127 |
try:
|
|
|
1145 |
progress(0.4, desc="Parsing decrypted data...")
|
1146 |
else: return "Data appears encrypted, but no password was provided."
|
1147 |
except (UnicodeDecodeError, InvalidTag, ValueError) as e:
|
1148 |
+
if "decryption" in str(e).lower() or isinstance(e, InvalidTag):
|
1149 |
+
return f"Decryption Failed. Check password or file integrity. Details: {e}"
|
1150 |
return "Data is binary and requires a password for decryption."
|
1151 |
except Exception as e:
|
1152 |
+
logger.error(f"KB ImgUL: Decrypt/Parse error: {e}", exc_info=True)
|
1153 |
+
return f"Unexpected error during decryption or parsing: {e}"
|
1154 |
|
1155 |
if not kv_string: return "Could not get data from image (after potential decryption)."
|
1156 |
try:
|
|
|
1180 |
if s: added_rules += 1
|
1181 |
elif m == "duplicate": skip_r += 1
|
1182 |
else: err_r += 1
|
1183 |
+
if total > 0: progress(0.5 + (0.4 * (i+1)/total) if total else 0)
|
1184 |
|
1185 |
progress(0.9, desc=f"Adding {len(memories_to_add)} memories...")
|
1186 |
for i, mem in enumerate(memories_to_add):
|
|
|
1226 |
except Exception as e:
|
1227 |
logger.error(f"Could not create placeholder image. The examples may not load correctly. Error: {e}")
|
1228 |
|
|
|
1229 |
def ui_create_kb_image_fn(password: str, content_to_include: list, progress=gr.Progress()):
|
1230 |
include_rules = "Include Rules" in content_to_include
|
1231 |
include_memories = "Include Memories" in content_to_include
|
|
|
1234 |
gr.Warning("Nothing selected to save.")
|
1235 |
return gr.update(value=None, visible=False), gr.update(value=None, visible=False), "Nothing selected to save."
|
1236 |
|
1237 |
+
progress(0.1, desc="Fetching knowledge base...")
|
1238 |
rules = get_all_rules_cached() if include_rules else []
|
1239 |
memories = get_all_memories_cached() if include_memories else []
|
1240 |
|
|
|
1247 |
data_bytes = kv_string.encode('utf-8')
|
1248 |
|
1249 |
if password and password.strip():
|
1250 |
+
progress(0.3, desc="Encrypting data...")
|
1251 |
try:
|
1252 |
data_bytes = encrypt_data(data_bytes, password.strip())
|
1253 |
except Exception as e:
|
1254 |
logger.error(f"KB ImgDL: Encrypt failed: {e}")
|
1255 |
return gr.update(value=None, visible=False), gr.update(value=None, visible=False), f"Error: {e}"
|
1256 |
|
1257 |
+
progress(0.5, desc="Generating carrier image...")
|
1258 |
carrier_image = generate_brain_carrier_image(w=800, h=800)
|
1259 |
|
1260 |
+
progress(0.6, desc="Adding visual overlay...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1261 |
keys_for_overlay = []
|
1262 |
if include_rules: keys_for_overlay.append(f"Rule Count: {len(rules)}")
|
1263 |
if include_memories: keys_for_overlay.append(f"Memory Count: {len(memories)}")
|
1264 |
|
1265 |
+
title_overlay = "Encrypted KB" if password and password.strip() else "iLearn KB"
|
1266 |
+
image_with_overlay = draw_key_list_dropdown_overlay(carrier_image, keys=keys_for_overlay, title=title_overlay)
|
1267 |
+
|
1268 |
+
try:
|
1269 |
+
progress(0.8, desc="Embedding data into final image...")
|
1270 |
+
final_image_with_data = embed_data_in_image(image_with_overlay, data_bytes)
|
1271 |
+
except ValueError as e:
|
1272 |
+
logger.error(f"KB ImgDL: Embed failed: {e}")
|
1273 |
+
return gr.update(value=None, visible=False), gr.update(value=None, visible=False), f"Error: {e}"
|
1274 |
|
1275 |
progress(0.9, desc="Preparing final image and download file...")
|
1276 |
try:
|
1277 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmpfile:
|
1278 |
+
final_image_with_data.save(tmpfile, format="PNG")
|
1279 |
tmp_path = tmpfile.name
|
1280 |
progress(1.0, desc="Image created!")
|
1281 |
return gr.update(value=tmp_path, visible=True), gr.update(value=tmp_path, visible=True), "Success! Image created."
|
|
|
1283 |
logger.error(f"KB ImgDL: Save failed: {e}")
|
1284 |
return gr.update(value=None, visible=False), gr.update(value=None, visible=False), f"Error: {e}"
|
1285 |
|
1286 |
+
|
1287 |
+
|
1288 |
def ui_load_from_sources_fn(image_filepath: str, rules_file_obj: object, mems_file_obj: object, password: str, progress=gr.Progress()):
|
1289 |
if image_filepath:
|
1290 |
progress(0.1, desc="Image source detected. Starting image processing...")
|
|
|
1329 |
with gr.Row():
|
1330 |
with gr.Column(scale=3):
|
1331 |
gr.Markdown("### AI Chat Interface")
|
1332 |
+
main_chat_disp = gr.Chatbot(label=None, height=450, bubble_full_width=False,avatar_images=(None, "https://raw.githubusercontent.com/gradio-app/gradio/main/guides/assets/logo.png"), show_copy_button=True, render_markdown=True, sanitize_html=True)
|
1333 |
with gr.Row(variant="compact"):
|
1334 |
user_msg_tb = gr.Textbox(show_label=False, placeholder="Ask your research question...", scale=7, lines=1, max_lines=3)
|
1335 |
send_btn = gr.Button("Send", variant="primary", scale=1, min_width=100)
|
1336 |
with gr.Accordion("📝 Detailed Response & Research Log", open=True):
|
1337 |
+
research_log_html = gr.HTML(label="Research Log", value="<div class='log-container'><p><i>Waiting for a new task to begin...</i></p></div>")
|
1338 |
fmt_report_tb = gr.Textbox(label="Full AI Response", lines=8, interactive=True, show_copy_button=True)
|
1339 |
dl_report_btn = gr.DownloadButton("Download Report", value=None, interactive=False, visible=False)
|
1340 |
|
|
|
1371 |
save_kb_password_tb = gr.Textbox(label="Password (optional for encryption)", type="password")
|
1372 |
save_kb_include_cbg = gr.CheckboxGroup(label="Content to Include", choices=["Include Rules", "Include Memories"], value=["Include Rules", "Include Memories"])
|
1373 |
create_kb_img_btn = gr.Button("✨ Create KB Image", variant="secondary")
|
1374 |
+
kb_image_display_output = gr.Image(label="Generated Image (Right-click to copy)", type="filepath", visible=False)
|
1375 |
kb_image_download_output = gr.DownloadButton("⬇️ Download Image File", visible=False)
|
1376 |
|
1377 |
with gr.TabItem("📂 Load KB"):
|
|
|
1387 |
load_master_btn = gr.Button("⬆️ Load from Sources", variant="primary", interactive=not DEMO_MODE)
|
1388 |
gr.Examples(
|
1389 |
examples=[
|
1390 |
+
[placeholder_filename, ""],
|
1391 |
],
|
1392 |
inputs=[upload_kb_img_fobj, load_kb_password_tb],
|
1393 |
label="Click an Example to Load Data"
|
|
|
1436 |
app_load_outputs = [agent_stat_tb, rules_disp_ta, mems_disp_json, research_log_html, fmt_report_tb, dl_report_btn]
|
1437 |
demo.load(fn=app_load_fn, inputs=None, outputs=app_load_outputs, show_progress="full")
|
1438 |
|
|
|
1439 |
if __name__ == "__main__":
|
1440 |
logger.info(f"Starting Gradio AI Research Mega Agent (v9.1 - Correct 1-Click JS Download, Memory: {MEMORY_STORAGE_BACKEND})...")
|
1441 |
app_port = int(os.getenv("GRADIO_PORT", 7860))
|