Spaces:
Running on Zero
Running on Zero
Asmit Nayak commited on
Commit ·
b49a99a
1
Parent(s): 9012453
Add detailed results table and CSV download functionality
Browse files864 unmodified lines86586686786886987087187287387487556 unmodified lines93293393493593693793810 unmodified lines94995095195295395495520 unmodified lines9769779789799809819821 unmodified line9849859869879889899909 unmodified lines100010011002100310041005100620 unmodified lines1027102810291030103110321033103410354 unmodified lines104010411042104310441045104616 unmodified lines106310641065106610671068106910701071107210731074107510761077107810 unmodified lines10891090109110921093109410957 unmodified lines11031104110511061107110811093 unmodified lines111311141115111611171118111924 unmodified lines114411451146114711481149115011511152864 unmodified linesresults_display = gr.HTML(value="<div style='text-align: center; padding: 40px; color: var(--body-text-color); opacity: 0.7;'>Enter a URL and click analyze to see results here.</div>")results_dataframe = gr.Dataframe(label="Detailed Results (Scroll right to see all columns)",visible=False)with gr.Column(scale=3):# Screenshot section - only screenshot in right column56 unmodified linesinteractive=False)# Event handlersdef handle_url_analysis(url, api_key):"""Handle URL analysis with screenshot capture."""print(f"[CONSOLE] handle_url_analysis called with URL: {url}")10 unmodified linesgr.update(visible=True), # Show placeholder initiallygr.update(visible=False), # Hide screenshot initially"<div style='text-align: center; padding: 20px; color: var(--body-text-color); opacity: 0.7;'>Preparing analysis...</div>", # Clear previous errorsgr.update(visible=False) # Hide dataframe)analysis_generator = take_screenshot_and_process(url, api_key)20 unmodified linesgr.update(visible=False), # Hide placeholdergr.update(value=image_path, visible=True, label="📷 Original Screenshot"), # Show original screenshot"<div style='text-align: center; padding: 20px; color: var(--body-text-color); opacity: 0.7;'>Analysis in progress...</div>", # Clear previous errorsgr.update(visible=False))else:yield (1 unmodified linegr.update(visible=True), # Keep placeholder visiblegr.update(visible=False), # Hide screenshot"<div style='text-align: center; padding: 20px; color: var(--body-text-color); opacity: 0.7;'>Analysis in progress...</div>", # Clear previous errorsgr.update(visible=False))else:print(f"[CONSOLE] Received final result with {len(dataframe_result)} rows")9 unmodified linesgr.update(visible=False), # Hide placeholdergr.update(value=final_image, visible=True, label="🎯 Annotated Screenshot (Analysis Complete)") if final_image else gr.update(visible=False),"<div style='text-align: center; padding: 20px; color: var(--body-text-color); opacity: 0.7;'>Processing results...</div>", # Clear previous errorsgr.update(visible=False))break20 unmodified lines.replace("<", "_x13x_") \.replace(">", "_x14x_") \.replace("|", "_x15x_")save_url = save_url + "__" + str(uuid.uuid4()).replace("-", "_")save_dict = {save_url: final_result}4 unmodified linesannotated_image_path = final_image if final_image else original_imageprint(f"[CONSOLE] Using image for dataset upload: {dataset_image_path} (original: {original_image}, final: {final_image})")print(f"[CONSOLE] Using annotated image for display: {annotated_image_path} (original: {original_image}, final: {final_image})")if dataset_image_path and os.path.exists(dataset_image_path) and annotated_image_path and os.path.exists(annotated_image_path):try:# Load the original image using PIL16 unmodified linesprint(f"[CONSOLE] Warning: Image path not found or invalid: {dataset_image_path}")image_df = pd.DataFrame([{"id": save_url, "image": None, "annotated_image": None}])dataset_upload.update_dataset_with_new_splits(save_dict)dataset_upload.update_dataset_with_new_images(image_df, scheduler=scheduler, dataset_dir=dataset_dir, jsonl_path=jsonl_path)# Show final results with annotated screenshotyield (final_status,gr.update(visible=False), # Hide placeholdergr.update(value=final_image, visible=True, label="🎯 Annotated Screenshot (Analysis Complete)") if final_image else gr.update(visible=False),results_html,gr.update(value=final_result, visible=True))# Clean up temporary files after successful display10 unmodified linesgr.update(visible=True), # Show placeholder againgr.update(visible=False, label="Website Screenshot"), # Hide screenshot and reset label"<div style='color: #ef4444; text-align: center; background-color: var(--block-background-fill); padding: 15px; border-radius: 8px; border: 1px solid #ef4444; opacity: 0.9;'>Analysis failed. Please check your Gemini API key and try again.</div>",gr.update(visible=False))except Exception as e:7 unmodified linesgr.update(visible=True), # Show placeholder againgr.update(visible=False, label="Website Screenshot"), # Hide screenshot and reset labelf"<div style='color: #ef4444; text-align: center; background-color: var(--block-background-fill); padding: 15px; border-radius: 8px; border: 1px solid #ef4444; opacity: 0.9;'>{error_msg}</div>",gr.update(visible=False))if e.__class__ == gr.exceptions.Error:raise e3 unmodified linesanalyze_url_btn.click(fn=handle_url_analysis,inputs=[url_input, gemini_api_key],outputs=[status_text, screenshot_placeholder, screenshot_display, results_display, results_dataframe],show_progress="full")24 unmodified linesfrom py_files.utils import decrypt_system_promptsif not decrypt_system_prompts():print(f"[CONSOLE] Failed to decrypt system prompts, exiting...")exit(1)print(f"[CONSOLE] ===== STARTING GRADIO APPLICATION =====")print(f"[CONSOLE] Creating Gradio interface...")864 unmodified lines86586686786886987056 unmodified lines92792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599610 unmodified lines1007100810091010101110121013101420 unmodified lines103510361037103810391040104110421 unmodified line104410451046104710481049105010519 unmodified lines1061106210631064106510661067106820 unmodified lines1089109010911092109310941095109610974 unmodified lines110211031104110511061107110816 unmodified lines1125112611271128112911301131113211331134113511361137113811391140114111421143114410 unmodified lines115511561157115811591160116111627 unmodified lines117011711172117311741175117611773 unmodified lines118111821183118411851186118724 unmodified lines1212121312141215121612171218121912201221122212231224864 unmodified linesresults_display = gr.HTML(value="<div style='text-align: center; padding: 40px; color: var(--body-text-color); opacity: 0.7;'>Enter a URL and click analyze to see results here.</div>")with gr.Column(scale=3):# Screenshot section - only screenshot in right column56 unmodified linesinteractive=False)# Detailed results table spanning both columns (full width)results_dataframe = gr.Dataframe(label="Detailed Results (Scroll right to see all columns)",visible=False)# Download button for results CSVdownload_btn = gr.DownloadButton(label="📥 Download Results as CSV",visible=False,variant="secondary")# Event handlersdef save_results_to_csv(df, url):"""Save the results dataframe to a CSV file named after the analyzed site."""if df is None or (isinstance(df, pd.DataFrame) and df.empty):return None# Create a safe filename from the URLsafe_filename = url.lower().replace("http://", "").replace("https://", "").strip().replace("www.", "") \.replace(".", "_") \.replace("/", "_") \.replace("-", "_") \.replace("=", "_") \.replace("?", "_") \.replace("&", "_") \.replace("%", "_") \.replace(":", "_") \.replace("#", "_") \.replace("'", "_") \.replace('"', "_") \.replace("*", "_") \.replace("<", "_") \.replace(">", "_") \.replace("|", "_") \.replace(" ", "_")# Trim if too long and ensure it doesn't end with underscoresafe_filename = safe_filename[:100].rstrip("_")# Create final filenamecsv_filename = f"{safe_filename}.csv"# Create a temporary file for downloadtemp_csv = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.csv', prefix='analysis_')csv_path = temp_csv.nametemp_csv.close()# Save dataframe to CSVif isinstance(df, pd.DataFrame):df.to_csv(csv_path, index=False)else:# If it's not a DataFrame, try to convert itpd.DataFrame(df).to_csv(csv_path, index=False)# Rename to the site-specific filename for downloadfinal_path = os.path.join(os.path.dirname(csv_path), csv_filename)shutil.copy(csv_path, final_path)os.remove(csv_path)print(f"[CONSOLE] CSV file created for download: {final_path} (filename: {csv_filename})")return final_pathdef handle_url_analysis(url, api_key):"""Handle URL analysis with screenshot capture."""print(f"[CONSOLE] handle_url_analysis called with URL: {url}")10 unmodified linesgr.update(visible=True), # Show placeholder initiallygr.update(visible=False), # Hide screenshot initially"<div style='text-align: center; padding: 20px; color: var(--body-text-color); opacity: 0.7;'>Preparing analysis...</div>", # Clear previous errorsgr.update(visible=False), # Hide dataframegr.update(visible=False) # Hide download button)analysis_generator = take_screenshot_and_process(url, api_key)20 unmodified linesgr.update(visible=False), # Hide placeholdergr.update(value=image_path, visible=True, label="📷 Original Screenshot"), # Show original screenshot"<div style='text-align: center; padding: 20px; color: var(--body-text-color); opacity: 0.7;'>Analysis in progress...</div>", # Clear previous errorsgr.update(visible=False),gr.update(visible=False) # Hide download button)else:yield (1 unmodified linegr.update(visible=True), # Keep placeholder visiblegr.update(visible=False), # Hide screenshot"<div style='text-align: center; padding: 20px; color: var(--body-text-color); opacity: 0.7;'>Analysis in progress...</div>", # Clear previous errorsgr.update(visible=False),gr.update(visible=False) # Hide download button)else:print(f"[CONSOLE] Received final result with {len(dataframe_result)} rows")9 unmodified linesgr.update(visible=False), # Hide placeholdergr.update(value=final_image, visible=True, label="🎯 Annotated Screenshot (Analysis Complete)") if final_image else gr.update(visible=False),"<div style='text-align: center; padding: 20px; color: var(--body-text-color); opacity: 0.7;'>Processing results...</div>", # Clear previous errorsgr.update(visible=False),gr.update(visible=False) # Hide download button)break20 unmodified lines.replace("<", "_x13x_") \.replace(">", "_x14x_") \.replace("|", "_x15x_")save_url = save_url + "__" + str(uuid.uuid4()).replace("-", "_")save_dict = {save_url: final_result}4 unmodified linesannotated_image_path = final_image if final_image else original_imageprint(f"[CONSOLE] Using image for dataset upload: {dataset_image_path} (original: {original_image}, final: {final_image})")print(f"[CONSOLE] Using annotated image for display: {annotated_image_path} (original: {original_image}, final: {final_image})")if dataset_image_path and os.path.exists(dataset_image_path) and annotated_image_path and os.path.exists(annotated_image_path):try:# Load the original image using PIL16 unmodified linesprint(f"[CONSOLE] Warning: Image path not found or invalid: {dataset_image_path}")image_df = pd.DataFrame([{"id": save_url, "image": None, "annotated_image": None}])# dataset_upload.update_dataset_with_new_splits(save_dict)# dataset_upload.update_dataset_with_new_images(image_df, scheduler=scheduler, dataset_dir=dataset_dir, jsonl_path=jsonl_path)# Prepare CSV for downloadcsv_file_path = save_results_to_csv(final_result, url)# Show final results with annotated screenshotyield (final_status,gr.update(visible=False), # Hide placeholdergr.update(value=final_image, visible=True, label="🎯 Annotated Screenshot (Analysis Complete)") if final_image else gr.update(visible=False),results_html,gr.update(value=final_result, visible=True),gr.update(value=csv_file_path, visible=True) if csv_file_path else gr.update(visible=False))# Clean up temporary files after successful display10 unmodified linesgr.update(visible=True), # Show placeholder againgr.update(visible=False, label="Website Screenshot"), # Hide screenshot and reset label"<div style='color: #ef4444; text-align: center; background-color: var(--block-background-fill); padding: 15px; border-radius: 8px; border: 1px solid #ef4444; opacity: 0.9;'>Analysis failed. Please check your Gemini API key and try again.</div>",gr.update(visible=False),gr.update(visible=False) # Hide download button)except Exception as e:7 unmodified linesgr.update(visible=True), # Show placeholder againgr.update(visible=False, label="Website Screenshot"), # Hide screenshot and reset labelf"<div style='color: #ef4444; text-align: center; background-color: var(--block-background-fill); padding: 15px; border-radius: 8px; border: 1px solid #ef4444; opacity: 0.9;'>{error_msg}</div>",gr.update(visible=False),gr.update(visible=False) # Hide download button)if e.__class__ == gr.exceptions.Error:raise e3 unmodified linesanalyze_url_btn.click(fn=handle_url_analysis,inputs=[url_input, gemini_api_key],outputs=[status_text, screenshot_placeholder, screenshot_display, results_display, results_dataframe, download_btn],show_progress="full")24 unmodified linesfrom py_files.utils import decrypt_system_promptsif os.path.exists("./system_prompt.txt") and os.path.exists("./system_prompt_thinking.txt"):print(f"[CONSOLE] System prompts already decrypted, skipping decryption step")else:print(f"[CONSOLE] Decrypting system prompts...")if not decrypt_system_prompts():print(f"[CONSOLE] Failed to decrypt system prompts, exiting...")exit(1)print(f"[CONSOLE] ===== STARTING GRADIO APPLICATION =====")print(f"[CONSOLE] Creating Gradio interface...")
app.py+94-22