Spaces:
Paused
Paused
Update app.py
Browse files3 unmodified lines45678910111213141516171819202149 unmodified lines71727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351369 unmodified lines14614714814915015115215315415515615715815916016116216314 unmodified lines17817918018118218310 unmodified lines1941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272281 unmodified line2302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902915 unmodified lines2972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313 unmodified linesimport requestsimport gradio as grfrom PyPDF2 import PdfReaderimport openaiimport logging# Set up logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')# Initialize Hugging Face modelsHUGGINGFACE_MODELS = {"Phi-3 Mini 128k Instruct by EswardiVI": "eswardivi/Phi-3-mini-128k-instruct","Phi-3 Mini 128k Instruct by TaufiqDP": "taufiqdp/phi-3-mini-128k-instruct"}# Utility Functionsdef extract_text_from_pdf(pdf_path):"""Extract text content from PDF file."""49 unmodified linesreturn snippetsdef build_prompts(snippets, prompt_instruction, custom_prompt):"""Build formatted prompts from text snippets."""prompts = []for idx, snippet in enumerate(snippets, start=1):current_prompt = custom_prompt if custom_prompt else prompt_instructionframed_prompt = f"---\nPart {idx} of {len(snippets)}:\n{current_prompt}\n\n{snippet}\n\nEnd of Part {idx}.\n---"prompts.append(framed_prompt)return promptsdef send_to_huggingface(prompt, model_name):"""Send prompt to Hugging Face model."""try:payload = {"inputs": prompt}response = requests.post(f"https://api-inference.huggingface.co/models/{model_name}",json=payload)if response.status_code == 200:return response.json()[0].get('generated_text', 'No generated text found.')else:error_info = response.json()error_message = error_info.get('error', 'Unknown error occurred.')logging.error(f"Error from Hugging Face model: {error_message}")return f"Error from Hugging Face model: {error_message}"except Exception as e:logging.error(f"Error interacting with Hugging Face model: {e}")return f"Error interacting with Hugging Face model: {e}"def authenticate_openai(api_key):"""Authenticate with OpenAI API."""if api_key:try:openai.api_key = api_keyopenai.Model.list()return "OpenAI Authentication Successful!"except Exception as e:logging.error(f"OpenAI API Key Error: {e}")return f"OpenAI API Key Error: {e}"return "No OpenAI API key provided."# Main Interfacewith gr.Blocks(theme=gr.themes.Default()) as demo:# Headergr.Markdown("# π Smart PDF Summarizer")gr.Markdown("Upload a PDF document and get AI-powered summaries using OpenAI or Hugging Face models.")# Authentication Sectionwith gr.Row():with gr.Column(scale=1):openai_api_key = gr.Textbox(label="π OpenAI API Key",type="password",placeholder="Enter your OpenAI API key (optional)")auth_status = gr.Textbox(label="Authentication Status",interactive=False)auth_button = gr.Button("π Authenticate", variant="primary")# Main Contentwith gr.Row():# Left Column - Input Options9 unmodified linesvalue="txt",label="π Output Format")context_size = gr.Slider(minimum=4000,maximum=128000,step=4000,value=32000,label="π Context Window Size")snippet_number = gr.Number(label="π’ Snippet Number (Optional)",value=None,precision=0)14 unmodified lineslabel="π§ Hugging Face Model",visible=False)# Right Column - Outputwith gr.Column(scale=1):10 unmodified lineslines=10)summary_output = gr.Textbox(label="π Summary",lines=15)with gr.Row():download_prompt = gr.File(label="π₯ Download Prompt")download_summary = gr.File(label="π₯ Download Summary")# Event Handlersdef toggle_hf_model(choice):return gr.update(visible=choice == "Hugging Face Model")def handle_authentication(api_key):return authenticate_openai(api_key)def process_pdf(pdf, fmt, ctx_size, snippet_num, prompt, model_selection, hf_model_choice, api_key):try:if not pdf:return "Please upload a PDF file.", "", "", None, None# Extract texttext = extract_text_from_pdf(pdf.name)if text.startswith("Error"):return text, "", "", None, None# Format contentformatted_text = format_content(text, fmt)1 unmodified line# Split into snippetssnippets = split_into_snippets(formatted_text, ctx_size)# Process specific snippet or allif snippet_num is not None:if 1 <= snippet_num <= len(snippets):selected_snippets = [snippets[snippet_num - 1]]else:return f"Invalid snippet number. Please choose between 1 and {len(snippets)}.", "", "", None, Noneelse:selected_snippets = snippets# Build promptsdefault_prompt = "Summarize the following text:"prompts = build_prompts(selected_snippets, default_prompt, prompt)full_prompt = "\n".join(prompts)# Generate summaryif model_selection == "OpenAI ChatGPT":if not api_key:return "OpenAI API key required.", full_prompt, "", None, Nonetry:openai.api_key = api_keyresponse = openai.ChatCompletion.create(model="gpt-3.5-turbo",messages=[{"role": "user", "content": full_prompt}])summary = response.choices[0].message.contentexcept Exception as e:return f"OpenAI API error: {str(e)}", full_prompt, "", None, Noneelse:summary = send_to_huggingface(full_prompt, HUGGINGFACE_MODELS[hf_model_choice])# Save files for downloadwith tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as prompt_file:prompt_file.write(full_prompt)prompt_path = prompt_file.namewith tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as summary_file:summary_file.write(summary)summary_path = summary_file.namereturn "Processing complete!", full_prompt, summary, prompt_path, summary_pathexcept Exception as e:logging.error(f"Error processing PDF: {e}")return f"Error processing PDF: {str(e)}", "", "", None, None# Connect event handlersmodel_choice.change(toggle_hf_model,inputs=[model_choice],outputs=[hf_model])auth_button.click(handle_authentication,inputs=[openai_api_key],outputs=[auth_status])process_button.click(5 unmodified linessnippet_number,custom_prompt,model_choice,hf_model,openai_api_key],outputs=[progress_status,generated_prompt,summary_output,download_prompt,download_summary])# Instructionsgr.Markdown("""### π Instructions:1. (Optional) Enter your OpenAI API key and authenticate2. Upload a PDF document3. Choose output format and context window size4. Optionally specify a snippet number or custom prompt5. Select between OpenAI ChatGPT or Hugging Face model6. Click 'Process PDF' to generate summary7. Download the generated prompt and summary as needed### βοΈ Features:- Support for multiple PDF formats- Flexible text formatting options- Custom prompt creation- Multiple AI model options- Snippet-based processing- Downloadable outputs""")3 unmodified lines4567891011121314151617181920212223242526272829303132333435363749 unmodified lines878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371389 unmodified lines14814915015115215315415515615715815916016116216316416516616716816917017114 unmodified lines18618718818919019119219319419519619719819910 unmodified lines2102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422431 unmodified line2452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852865 unmodified lines2922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413 unmodified linesimport requestsimport gradio as grfrom PyPDF2 import PdfReaderimport loggingimport webbrowserfrom gradio_client import Client# Set up logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')# Initialize Hugging Face modelsHUGGINGFACE_MODELS = {"Phi-3 Mini 128k": "eswardivi/Phi-3-mini-128k-instruct",}# Common context window sizesCONTEXT_SIZES = {"4K": 4000,"8K": 8000,"32K": 32000,"128K": 128000,"200K": 200000}def copy_to_clipboard(text):return textdef open_chatgpt():webbrowser.open('https://chat.openai.com/')return "Opening ChatGPT in browser..."# Utility Functionsdef extract_text_from_pdf(pdf_path):"""Extract text content from PDF file."""49 unmodified linesreturn snippetsdef build_prompts(snippets, prompt_instruction, custom_prompt, snippet_num=None):"""Build formatted prompts from text snippets."""if snippet_num is not None:if 1 <= snippet_num <= len(snippets):selected_snippets = [snippets[snippet_num - 1]]else:return f"Error: Invalid snippet number. Please choose between 1 and {len(snippets)}."else:selected_snippets = snippetsprompts = []base_prompt = custom_prompt if custom_prompt else prompt_instructionfor idx, snippet in enumerate(selected_snippets, start=1):if len(selected_snippets) > 1:prompt_header = f"{base_prompt} Part {idx} of {len(selected_snippets)}: ---\n"else:prompt_header = f"{base_prompt} ---\n"framed_prompt = f"{prompt_header}{snippet}\n---"prompts.append(framed_prompt)return "\n\n".join(prompts)def send_to_huggingface(prompt, model_name):"""Send prompt to Hugging Face model using gradio_client."""try:client = Client(model_name)response = client.predict(prompt, # message0.9, # temperatureTrue, # sampling512, # max_new_tokensapi_name="/chat")return responseexcept Exception as e:logging.error(f"Error interacting with Hugging Face model: {e}")return f"Error interacting with Hugging Face model: {e}"# Main Interfacewith gr.Blocks(theme=gr.themes.Default()) as demo:# Headergr.Markdown("# π Smart PDF Summarizer")gr.Markdown("Upload a PDF document and get AI-powered summaries using OpenAI or Hugging Face models.")# Main Contentwith gr.Row():# Left Column - Input Options9 unmodified linesvalue="txt",label="π Output Format")gr.Markdown("### Context Window Size")with gr.Row():for size_name, size_value in CONTEXT_SIZES.items():if gr.Button(size_name).click:context_size.value = size_valuecontext_size = gr.Slider(minimum=1000,maximum=200000,step=1000,value=32000,label="π Custom Context Size")snippet_number = gr.Number(label="π’ Snippet Number",value=1,precision=0)14 unmodified lineslabel="π§ Hugging Face Model",visible=False)# Authentication moved downwith gr.Row(visible=False) as auth_row:openai_api_key = gr.Textbox(label="π OpenAI API Key",type="password",placeholder="Enter your OpenAI API key (optional)")# Right Column - Outputwith gr.Column(scale=1):10 unmodified lineslines=10)with gr.Row():copy_prompt_button = gr.Button("π Copy Prompt")open_chatgpt_button = gr.Button("π Open ChatGPT")summary_output = gr.Textbox(label="π Summary",lines=15)with gr.Row():copy_summary_button = gr.Button("π Copy Summary")download_files = gr.Files(label="π₯ Download Files")# Event Handlersdef toggle_hf_model(choice):return gr.update(visible=choice == "Hugging Face Model"), gr.update(visible=choice == "OpenAI ChatGPT")def process_pdf(pdf, fmt, ctx_size, snippet_num, prompt, model_selection, hf_model_choice):try:if not pdf:return "Please upload a PDF file.", "", "", None# Extract texttext = extract_text_from_pdf(pdf.name)if text.startswith("Error"):return text, "", "", None# Format contentformatted_text = format_content(text, fmt)1 unmodified line# Split into snippetssnippets = split_into_snippets(formatted_text, ctx_size)# Build promptsdefault_prompt = "Summarize the following text:"full_prompt = build_prompts(snippets, default_prompt, prompt, snippet_num)if isinstance(full_prompt, str) and full_prompt.startswith("Error"):return full_prompt, "", "", None# Generate summary based on model choiceif model_selection == "Hugging Face Model":summary = send_to_huggingface(full_prompt, HUGGINGFACE_MODELS[hf_model_choice])else:summary = "Please use the Copy Prompt button and paste into ChatGPT."# Save files for downloadfiles_to_download = []with tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as prompt_file:prompt_file.write(full_prompt)files_to_download.append(prompt_file.name)if summary != "Please use the Copy Prompt button and paste into ChatGPT.":with tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.txt') as summary_file:summary_file.write(summary)files_to_download.append(summary_file.name)return "Processing complete!", full_prompt, summary, files_to_downloadexcept Exception as e:logging.error(f"Error processing PDF: {e}")return f"Error processing PDF: {str(e)}", "", "", None# Connect event handlersmodel_choice.change(toggle_hf_model,inputs=[model_choice],outputs=[hf_model, auth_row])process_button.click(5 unmodified linessnippet_number,custom_prompt,model_choice,hf_model],outputs=[progress_status,generated_prompt,summary_output,download_files])copy_prompt_button.click(copy_to_clipboard,inputs=[generated_prompt],outputs=[progress_status])copy_summary_button.click(copy_to_clipboard,inputs=[summary_output],outputs=[progress_status])open_chatgpt_button.click(open_chatgpt,outputs=[progress_status])# Instructionsgr.Markdown("""### π Instructions:1. Upload a PDF document2. Choose output format and context window size3. Select snippet number (default: 1) or enter custom prompt4. Select between OpenAI ChatGPT or Hugging Face model5. Click 'Process PDF' to generate summary6. Use 'Copy Prompt' and 'Open ChatGPT' for manual processing7. Download generated files as needed### βοΈ Features:- Support for multiple PDF formats- Flexible text formatting options- Predefined context window sizes (4K to 200K)- Copy to clipboard functionality- Direct ChatGPT integration- Downloadable outputs""")
app.py+127-117