SCISKETCH / app.py
zihang93's picture
Create app.py
0124d05 verified
# import os
# import sys
# sys.path.append(os.path.join(os.path.dirname(__file__), "src"))
# import tempfile
# from pathlib import Path
# import base64
# import subprocess
# import json
# import gradio as gr
# import requests
# from src.custom_main import generate_diagram_demo
# # Import your project's modules here
# # from diagram_generator import generate_diagram
# # from paper_processor import process_paper
# def process_pdf(pdf_file) -> str:
# """Extract text from PDF file using local API service"""
# print(f"====> Processing PDF: {pdf_file.name}")
# try:
# with open(pdf_file.name, "rb") as f:
# files = {"file": (pdf_file.name, f, "application/pdf")}
# response = requests.post(
# "https://amusing-presently-chow.ngrok-free.app/parse-pdf",
# files=files
# )
# # Call local API service to process PDF
# # response = requests.post(
# # "http://amusing-presently-chow.ngrok-free.app/parse-pdf",
# # json={"pdf_path": pdf_file}
# # )
# # Check if the request was successful
# response.raise_for_status()
# # Parse the JSON response
# output = response.json()
# return output
# except requests.RequestException as e:
# print(f"Error calling PDF processing API: {e}")
# return f"Error calling PDF processing API: {str(e)}"
# except json.JSONDecodeError as e:
# print(f"Error parsing API response: {e}")
# return f"Error parsing API response: {response.text}"
# except Exception as e:
# print(f"Unexpected error: {e}")
# return f"Unexpected error: {str(e)}"
# def encode_image(image_path: str) -> str:
# """Encode image to base64 string"""
# with open(image_path, "rb") as image_file:
# return base64.b64encode(image_file.read()).decode('utf-8')
# def create_demo():
# """Create and launch the Gradio demo interface"""
# with gr.Blocks(title="SCISKETCH Demo") as demo:
# gr.Markdown("SCISKETCH Demo")
# gr.Markdown("Upload a PDF, provide a caption, and optionally upload images to generate a diagram.")
# # State variable to store PDF processing result
# pdf_text_state = gr.State("")
# with gr.Row():
# with gr.Column(scale=1):
# pdf_input = gr.File(label="Upload PDF", file_types=[".pdf"])
# process_pdf_btn = gr.Button("Process PDF", variant="secondary")
# caption_input = gr.Textbox(label="Caption", placeholder="Enter a caption for the diagram...")
# image_input = gr.File(label="Upload Images (Optional)", file_types=[".png", ".jpg", ".jpeg"], file_count="multiple")
# submit_btn = gr.Button("Generate Diagram", variant="primary")
# with gr.Column(scale=1):
# pdf_text_display = gr.Textbox(label="PDF Processing Result", lines=10)
# output_display = gr.Textbox(label="Final Result", lines=20)
# # Process PDF button handler
# def process_pdf_handler(pdf_file):
# if pdf_file is None:
# return "No PDF file uploaded", ""
# pdf_text = process_pdf(pdf_file)
# # Format the dictionary output for better display
# if isinstance(pdf_text, dict):
# formatted_output = "## Paper Information\n\n"
# # Display title and authors if available
# if "title" in pdf_text and pdf_text["title"]:
# formatted_output += f"**Title:** {pdf_text['title']}\n\n"
# if "authors" in pdf_text and pdf_text["authors"]:
# formatted_output += f"**Authors:** {pdf_text['authors']}\n\n"
# if "pub_date" in pdf_text and pdf_text["pub_date"]:
# formatted_output += f"**Publication Date:** {pdf_text['pub_date']}\n\n"
# # Display abstract if available
# if "abstract" in pdf_text and pdf_text["abstract"]:
# formatted_output += f"**Abstract:**\n{pdf_text['abstract']}\n\n"
# # Display section count if available
# if "sections" in pdf_text and isinstance(pdf_text["sections"], list):
# formatted_output += f"**Sections:** {len(pdf_text['sections'])}\n\n"
# # Display section headings
# formatted_output += "**Section Headings:**\n"
# for i, section in enumerate(pdf_text["sections"]):
# if "heading" in section and section["heading"]:
# formatted_output += f"{i+1}. {section['heading']}\n"
# # Display reference count if available
# if "references" in pdf_text and isinstance(pdf_text["references"], list):
# formatted_output += f"\n**References:** {len(pdf_text['references'])}\n"
# # Keep the raw JSON for the state
# return formatted_output, pdf_text
# else:
# # If it's not a dictionary, return as is
# return str(pdf_text), pdf_text
# process_pdf_btn.click(
# fn=process_pdf_handler,
# inputs=[pdf_input],
# outputs=[pdf_text_display, pdf_text_state]
# )
# # Generate diagram button handler
# def analyze_with_pdf_text(pdf_file, pdf_text, caption, image_files):
# print(f"Analyzing with PDF_file {pdf_file}, caption {caption}, image_files {image_files}")
# result = generate_diagram_demo(pdf_text, caption, image_files)
# # # Use the processed PDF text
# # if pdf_text:
# # result += f"Using processed PDF text ({len(pdf_text)} characters).\n\n"
# # elif pdf_file is not None:
# # # Process PDF if not already processed
# # pdf_text = process_pdf(pdf_file.name)
# # result += f"Extracted {len(pdf_text)} characters from PDF.\n\n"
# # Process caption
# # if caption:
# # result += f"Caption: {caption}\n\n"
# # Process images if provided
# # if image_files:
# # result += f"Processed {len(image_files)} images:\n"
# # for i, img in enumerate(image_files):
# # result += f"- Image {i+1}: {Path(img.name).name}\n"
# # Here you would call your actual diagram generation code
# # result = generate_diagram(pdf_text, caption, image_files)
# # For demo purposes, return a placeholder
# # result += "\n\nDiagram generation would happen here based on the inputs."
# return result
# submit_btn.click(
# fn=analyze_with_pdf_text,
# inputs=[pdf_input, pdf_text_state, caption_input, image_input],
# outputs=output_display
# )
# return demo
# if __name__ == "__main__":
# demo = create_demo()
# demo.launch(server_port=7860)
import gradio as gr
def show_link():
return """
<div style="text-align: center; font-family: sans-serif; padding: 40px;">
<h2>This app has moved.</h2>
<p>Please click the link below to visit the new version:</p>
<a href="https://amusing-presently-chow.ngrok-free.app/" target="_blank" style="font-size: 18px; color: #1f6feb;">
πŸ‘‰ Go to the new app
</a>
</div>
"""
demo = gr.Interface(fn=show_link, inputs=[], outputs=gr.HTML())
demo.launch()