Spaces:
Paused
Paused
Update app.py
Browse files5 unmodified lines6789101112131415161718192021222 unmodified lines25262728293031323334353637383911 unmodified lines515253545556577 unmodified lines6566676869707115 unmodified lines8788899091929317 unmodified lines11111211311411511611711811912012112212312412512612712812913013113213313413513613713 unmodified lines15115215315415515615715815916 unmodified lines17617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520 unmodified lines2262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872883 unmodified lines2922932942952962972982 unmodified lines3013023033043053063073083093103113123133143153163173183195 unmodified lines3253263273283293303312 unmodified lines3343353363373383395 unmodified linesfrom 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,2 unmodified lines"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."""try:reader = PdfReader(pdf_path)11 unmodified lineslogging.error(f"Error reading PDF file: {e}")return f"Error reading PDF file: {e}"def format_content(text, format_type):"""Format extracted text according to specified format."""if format_type == 'txt':return text7 unmodified lineslogging.error(f"Unsupported format: {format_type}")return f"Unsupported format: {format_type}"def split_into_snippets(text, context_size):"""Split text into manageable snippets based on context size."""sentences = re.split(r'(?<=[.!?]) +', text)snippets = []15 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):17 unmodified linesreturn "\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():13 unmodified linesgr.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,16 unmodified lines)model_choice = gr.Radio(choices=["OpenAI ChatGPT", "Hugging Face Model"],value="OpenAI ChatGPT",label="π€ Model Selection")hf_model = gr.Dropdown(choices=list(HUGGINGFACE_MODELS.keys()),label="π§ 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):with gr.Row():process_button = gr.Button("π Process PDF", variant="primary")progress_status = gr.Textbox(label="π Progress",interactive=False20 unmodified lines)# 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)# 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(process_pdf,inputs=[3 unmodified linessnippet_number,custom_prompt,model_choice,hf_model],outputs=[progress_status,2 unmodified linesdownload_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]5 unmodified lines1. 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 needed2 unmodified lines- Support for multiple PDF formats- Flexible text formatting options- Predefined context window sizes (4K to 200K)- Copy to clipboard functionality- Direct ChatGPT integration- Downloadable outputs5 unmodified lines6789101112131415161718192 unmodified lines2223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697011 unmodified lines828384858687887 unmodified lines9697989910010110215 unmodified lines11811912012112212312417 unmodified lines14214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026113 unmodified lines27527627727827928028128228328416 unmodified lines30130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234320 unmodified lines3643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134143 unmodified lines4184194204214224234244254264274282 unmodified lines4314324334344354364374384394404414424434444454464474484495 unmodified lines4554564574584594604614624634642 unmodified lines4674684694704714724735 unmodified linesfrom PyPDF2 import PdfReaderimport loggingimport webbrowserfrom huggingface_hub import InferenceClientfrom typing import Dict, List, Optional, Tupleimport time# Set up logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')# ConstantsCONTEXT_SIZES = {"4K": 4000,"8K": 8000,2 unmodified lines"200K": 200000}class ModelRegistry:def __init__(self):self.hf_models = {"Phi-3 Mini 128k": "microsoft/Phi-3-mini-128k-instruct","Custom Model": ""}self.groq_models = self._fetch_groq_models()def _fetch_groq_models(self) -> Dict[str, str]:"""Fetch available Groq models"""try:headers = {"Authorization": f"Bearer {os.getenv('GROQ_API_KEY')}","Content-Type": "application/json"}response = requests.get("https://api.groq.com/openai/v1/models", headers=headers)if response.status_code == 200:models = response.json().get("data", [])return {model["id"]: model["id"] for model in models}else:logging.error(f"Failed to fetch Groq models: {response.status_code}")return self._get_default_groq_models()except Exception as e:logging.error(f"Error fetching Groq models: {e}")return self._get_default_groq_models()def _get_default_groq_models(self) -> Dict[str, str]:"""Return default Groq models when API is unavailable"""return {"llama-3.1-70b-versatile": "llama-3.1-70b-versatile","mixtral-8x7b-32768": "mixtral-8x7b-32768","llama-3.1-8b-instant": "llama-3.1-8b-instant"}def refresh_groq_models(self) -> Dict[str, str]:"""Refresh the list of available Groq models"""self.groq_models = self._fetch_groq_models()return self.groq_models# Initialize model registrymodel_registry = ModelRegistry()def extract_text_from_pdf(pdf_path: str) -> str:"""Extract text content from PDF file."""try:reader = PdfReader(pdf_path)11 unmodified lineslogging.error(f"Error reading PDF file: {e}")return f"Error reading PDF file: {e}"def format_content(text: str, format_type: str) -> str:"""Format extracted text according to specified format."""if format_type == 'txt':return text7 unmodified lineslogging.error(f"Unsupported format: {format_type}")return f"Unsupported format: {format_type}"def split_into_snippets(text: str, context_size: int) -> List[str]:"""Split text into manageable snippets based on context size."""sentences = re.split(r'(?<=[.!?]) +', text)snippets = []15 unmodified linesreturn snippetsdef build_prompts(snippets: List[str], prompt_instruction: str, custom_prompt: Optional[str], snippet_num: Optional[int] = None) -> str:"""Build formatted prompts from text snippets."""if snippet_num is not None:if 1 <= snippet_num <= len(snippets):17 unmodified linesreturn "\n\n".join(prompts)def send_to_hf_inference(prompt: str, model_name: str, api_key: str) -> str:"""Send prompt to HuggingFace using Inference API"""try:client = InferenceClient(api_key=api_key)messages = [{"role": "user", "content": prompt}]completion = client.chat.completions.create(model=model_name,messages=messages,max_tokens=500)return completion.choices[0].message.contentexcept Exception as e:logging.error(f"Error with HF inference: {e}")return f"Error with HF inference: {e}"def send_to_groq(prompt: str, model_name: str, api_key: str) -> str:"""Send prompt to Groq API"""try:headers = {"Authorization": f"Bearer {api_key}","Content-Type": "application/json"}data = {"model": model_name,"messages": [{"role": "user", "content": prompt}]}response = requests.post("https://api.groq.com/openai/v1/chat/completions",headers=headers,json=data)return response.json()["choices"][0]["message"]["content"]except Exception as e:logging.error(f"Error with Groq API: {e}")return f"Error with Groq API: {e}"def copy_to_clipboard(text: str) -> str:"""Copy text to clipboard"""return "Text copied to clipboard!"def open_chatgpt() -> str:"""Open ChatGPT in browser"""webbrowser.open('https://chat.openai.com/')return "Opening ChatGPT in browser..."def process_pdf(pdf, fmt, ctx_size, snippet_num, prompt, model_selection,hf_model_choice, hf_custom_model, hf_api_key,groq_model_choice, groq_api_key) -> Tuple[str, str, str, List[str]]:"""Process PDF and generate summary"""try:if not pdf:return "Please upload a PDF file.", "", "", []# Extract texttext = extract_text_from_pdf(pdf.name)if text.startswith("Error"):return text, "", "", []# Format contentformatted_text = format_content(text, fmt)# 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, "", "", []# Process with selected modelif model_selection == "HuggingFace Inference":if not hf_api_key:return "HuggingFace API key required.", full_prompt, "", []model_id = hf_custom_model if hf_model_choice == "Custom Model" else model_registry.hf_models[hf_model_choice]summary = send_to_hf_inference(full_prompt, model_id, hf_api_key)elif model_selection == "Groq API":if not groq_api_key:return "Groq API key required.", full_prompt, "", []summary = send_to_groq(full_prompt, groq_model_choice, groq_api_key)else: # OpenAI ChatGPTsummary = "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)}", "", "", []# Main Interfacewith gr.Blocks(theme=gr.themes.Default()) as demo:# Store context size valuecontext_size_value = gr.State(value=32000)# Headergr.Markdown("# π Smart PDF Summarizer")gr.Markdown("Upload a PDF document and get AI-powered summaries using various AI models.")# Main Contentwith gr.Row():13 unmodified linesgr.Markdown("### Context Window Size")with gr.Row():context_buttons = []for size_name, size_value in CONTEXT_SIZES.items():btn = gr.Button(size_name)context_buttons.append((btn, size_value))context_size = gr.Slider(minimum=1000,16 unmodified lines)model_choice = gr.Radio(choices=["OpenAI ChatGPT", "HuggingFace Inference", "Groq API"],value="OpenAI ChatGPT",label="π€ Model Selection")with gr.Column(visible=False) as hf_options:hf_model = gr.Dropdown(choices=list(model_registry.hf_models.keys()),label="π§ HuggingFace Model",value="Phi-3 Mini 128k")hf_custom_model = gr.Textbox(label="Custom Model ID",placeholder="Enter custom model ID...",visible=False)hf_api_key = gr.Textbox(label="π HuggingFace API Key",type="password")with gr.Column(visible=False) as groq_options:groq_model = gr.Dropdown(choices=list(model_registry.groq_models.keys()),label="π§ Groq Model",value=list(model_registry.groq_models.keys())[0])groq_refresh_btn = gr.Button("π Refresh Models")groq_api_key = gr.Textbox(label="π Groq API Key",type="password")# Right Column - Outputwith gr.Column(scale=1):process_button = gr.Button("π Process PDF", variant="primary")progress_status = gr.Textbox(label="π Progress",interactive=False20 unmodified lines)# Event Handlersdef update_context_size(size):return gr.update(value=size)def toggle_model_options(choice):return (gr.update(visible=choice == "HuggingFace Inference"),gr.update(visible=choice == "Groq API"))def refresh_groq_models_list():updated_models = model_registry.refresh_groq_models()return gr.update(choices=list(updated_models.keys()))def toggle_custom_model(model_name):return gr.update(visible=model_name == "Custom Model")# Connect event handlersmodel_choice.change(toggle_model_options,inputs=[model_choice],outputs=[hf_options, groq_options])for btn, size_value in context_buttons:btn.click(update_context_size,inputs=[],outputs=[context_size]).then(lambda x=size_value: x,None,context_size)hf_model.change(toggle_custom_model,inputs=[hf_model],outputs=[hf_custom_model])groq_refresh_btn.click(refresh_groq_models_list,outputs=[groq_model])process_button.click(process_pdf,inputs=[3 unmodified linessnippet_number,custom_prompt,model_choice,hf_model,hf_custom_model,hf_api_key,groq_model,groq_api_key],outputs=[progress_status,2 unmodified linesdownload_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]5 unmodified lines1. Upload a PDF document2. Choose output format and context window size3. Select snippet number (default: 1) or enter custom prompt4. Select your preferred model:- OpenAI ChatGPT: Manual copy/paste workflow- HuggingFace Inference: Direct API integration- Groq API: High-performance inference5. Click 'Process PDF' to generate summary6. Use 'Copy Prompt' and 'Open ChatGPT' for manual processing7. Download generated files as needed2 unmodified lines- Support for multiple PDF formats- Flexible text formatting options- Predefined context window sizes (4K to 200K)- Multiple model integrations- Copy to clipboard functionality- Direct ChatGPT integration- Downloadable outputs
app.py+237-103