Spaces:
Sleeping
Sleeping
Update app.py
Browse files3 unmodified lines4567891010 unmodified lines212223242526274 unmodified lines323334353637384 unmodified lines43444546474849505152531 unmodified line5556575859606162636465666768697071727374757677788 unmodified lines87888990919293949596974 unmodified lines1021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992006 unmodified lines2072082092102112122132142152161 unmodified line2182192202212222232243 unmodified linesfrom pypdf import PdfReader# ββ Anthropic client ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Set ANTHROPIC_API_KEY in your HuggingFace Space β Settings β Repository secretsclient = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))SYSTEM_PROMPT = """You are an expert problem analyst and innovation coach helping interns understand real-world problems and brainstorm creative solutions.10 unmodified lines- Identify underlying causes (technical, organizational, process-related)3. **BRAINSTORMING IDEAS**- Generate 5β8 diverse, creative solution directions- Include both quick wins and long-term strategic ideas- Think across technology, process, and people dimensions4 unmodified linesdef extract_text_from_pdf(pdf_file) -> str:"""Extract all text from an uploaded PDF file."""reader = PdfReader(pdf_file)pages_text = []for page in reader.pages:4 unmodified linesdef run_agent(text_input: str, pdf_file, progress=gr.Progress()):"""Core agent function.Accepts either pasted text or a PDF upload, then streams the analysis."""# ββ Determine input source ββββββββββββββββββββββββββββββββββββββββββββββββcontent = ""if pdf_file is not None:1 unmodified linetry:content = extract_text_from_pdf(pdf_file)if not content.strip():yield "β οΈ Could not extract text from this PDF. It may be scanned/image-based. Please paste the text manually."returnexcept Exception as e:yield f"β οΈ Error reading PDF: {str(e)}"returnelif text_input and text_input.strip():content = text_input.strip()else:yield "β οΈ Please paste a transcription or upload a PDF file to get started."returnif len(content) < 50:yield "β οΈ The input seems too short. Please provide more context for a meaningful analysis."return# ββ Truncate very long inputs to stay within token limits βββββββββββββββββMAX_CHARS = 12000if len(content) > MAX_CHARS:content = content[:MAX_CHARS] + "\n\n[... content truncated for length ...]"8 unmodified linesPlease provide a full problem analysis and brainstorming session based on this content."""# ββ Stream from Anthropic API βββββββββββββββββββββββββββββββββββββββββββββoutput = ""try:with client.messages.stream(model="claude-sonnet-4-20250514",max_tokens=2048,system=SYSTEM_PROMPT,messages=[{"role": "user", "content": user_message}],4 unmodified linesyield outputexcept anthropic.AuthenticationError:yield "β οΈ Invalid API key. Please set your ANTHROPIC_API_KEY in the Space secrets."except anthropic.RateLimitError:yield "β οΈ Rate limit hit. Please wait a moment and try again."except Exception as e:yield f"β οΈ Unexpected error: {str(e)}"# ββ Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββwith gr.Blocks(title="Intern Problem Brainstormer",theme=gr.themes.Soft(primary_hue="violet",secondary_hue="slate",font=[gr.themes.GoogleFont("Inter"), "sans-serif"],),css="""#header { text-align: center; padding: 1.5rem 0 0.5rem; }#header h1 { font-size: 2rem; font-weight: 700; margin-bottom: 0.25rem; }#header p { color: #6b7280; font-size: 0.95rem; }.input-box textarea { font-size: 14px !important; line-height: 1.6 !important; }#run-btn { font-size: 1rem !important; padding: 0.65rem 2rem !important; }#output-box { font-size: 14px; line-height: 1.75; }.gr-tab-item { font-weight: 500; }""",) as demo:# Headergr.HTML("""<div id="header"><h1>π§ Intern Problem Brainstormer</h1><p>Paste a meeting transcription or upload a PDF β get instant problem analysis & brainstormed solutions.</p></div>""")gr.Markdown("---")with gr.Row(equal_height=False):# ββ Left column: Input ββββββββββββββββββββββββββββββββββββββββββββββββwith gr.Column(scale=1):gr.Markdown("### π₯ Input")with gr.Tabs():with gr.Tab("π Paste Text"):text_input = gr.Textbox(label="Transcription or problem description",placeholder="Paste your meeting notes, transcription, or problem statement here...",lines=14,max_lines=30,elem_classes=["input-box"],)with gr.Tab("π Upload PDF"):pdf_input = gr.File(label="Upload a PDF document",file_types=[".pdf"],file_count="single",)gr.Markdown("<small style='color:#6b7280'>Text-based PDFs only. Scanned PDFs won't work.</small>")run_btn = gr.Button("β‘ Analyse & Brainstorm",variant="primary",elem_id="run-btn",)with gr.Accordion("βΉοΈ How to use", open=False):gr.Markdown("""**Option 1 β Paste Text**Copy-paste any transcription, meeting notes, or problem description into the text box.**Option 2 β Upload PDF**Upload a text-based PDF (e.g. a research doc, spec, or report).**Then click β‘ Analyse & Brainstorm** to get:- A clear articulation of the core problem- Root cause analysis- 5β8 creative brainstormed ideas- Concrete next steps for you as an intern""")# ββ Right column: Output ββββββββββββββββββββββββββββββββββββββββββββββwith gr.Column(scale=1):gr.Markdown("### π‘ Analysis & Ideas")output = gr.Markdown(value="*Your analysis will appear here...*",elem_id="output-box",)# ββ Examples ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββgr.Markdown("---")gr.Markdown("### π§ͺ Try an example")gr.Examples(examples=[[6 unmodified lines],],inputs=[text_input, pdf_input],label="Click an example to load it, then hit Analyse & Brainstorm",)# ββ Wire up βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββrun_btn.click(fn=run_agent,inputs=[text_input, pdf_input],1 unmodified lineshow_progress="full",)# Also allow Ctrl+Enter from the text boxtext_input.submit(fn=run_agent,inputs=[text_input, pdf_input],3 unmodified lines45678910 unmodified lines202122232425264 unmodified lines3132333435364 unmodified lines4142434445461 unmodified line48495051525354555657585960616263646566676869708 unmodified lines798081828384858687884 unmodified lines939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973986 unmodified lines4054064074084094104114124131 unmodified line4154164174184194203 unmodified linesfrom pypdf import PdfReader# ββ Anthropic client ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclient = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))SYSTEM_PROMPT = """You are an expert problem analyst and innovation coach helping interns understand real-world problems and brainstorm creative solutions.10 unmodified lines- Identify underlying causes (technical, organizational, process-related)3. **BRAINSTORMING IDEAS**- Generate 5-8 diverse, creative solution directions- Include both quick wins and long-term strategic ideas- Think across technology, process, and people dimensions4 unmodified linesdef extract_text_from_pdf(pdf_file) -> str:reader = PdfReader(pdf_file)pages_text = []for page in reader.pages:4 unmodified linesdef run_agent(text_input: str, pdf_file, progress=gr.Progress()):content = ""if pdf_file is not None:1 unmodified linetry:content = extract_text_from_pdf(pdf_file)if not content.strip():yield "Could not extract text from this PDF. It may be scanned or image-based. Please paste the text manually."returnexcept Exception as e:yield f"Error reading PDF: {str(e)}"returnelif text_input and text_input.strip():content = text_input.strip()else:yield "Please paste a transcription or upload a PDF file to get started."returnif len(content) < 50:yield "The input seems too short. Please provide more context for a meaningful analysis."returnMAX_CHARS = 12000if len(content) > MAX_CHARS:content = content[:MAX_CHARS] + "\n\n[... content truncated for length ...]"8 unmodified linesPlease provide a full problem analysis and brainstorming session based on this content."""output = ""try:with client.messages.stream(model="claude-sonnet-4-6",max_tokens=2048,system=SYSTEM_PROMPT,messages=[{"role": "user", "content": user_message}],4 unmodified linesyield outputexcept anthropic.AuthenticationError:yield "Invalid API key. Please set your ANTHROPIC_API_KEY in the Space secrets."except anthropic.RateLimitError:yield "Rate limit reached. Please wait a moment and try again."except Exception as e:yield f"Unexpected error: {str(e)}"# ββ Custom CSS ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββcustom_css = """@import url('https://fonts.googleapis.com/css2?family=Sora:wght@300;400;500;600&family=JetBrains+Mono:wght@400;500&display=swap');* {font-family: 'Sora', sans-serif !important;}body, .gradio-container {background-color: #0d1117 !important;color: #e2e8f0 !important;}.gradio-container {max-width: 1200px !important;margin: 0 auto !important;}/* Header */#app-header {padding: 2.5rem 0 1.5rem;border-bottom: 1px solid #1e2d3d;margin-bottom: 2rem;}#app-header h1 {font-size: 1.6rem;font-weight: 600;color: #e2e8f0;letter-spacing: -0.02em;margin: 0 0 0.3rem 0;}#app-header p {font-size: 0.875rem;color: #64748b;margin: 0;font-weight: 300;}/* Accent bar */#accent-bar {width: 2.5rem;height: 2px;background: linear-gradient(90deg, #0ea5e9, #38bdf8);margin-bottom: 0.75rem;border-radius: 2px;}/* Section labels */.section-label {font-size: 0.7rem !important;font-weight: 500 !important;text-transform: uppercase !important;letter-spacing: 0.12em !important;color: #475569 !important;margin-bottom: 0.75rem !important;}/* Input panels */.input-panel, .output-panel {background: #111827 !important;border: 1px solid #1e2d3d !important;border-radius: 8px !important;padding: 1.25rem !important;}/* Textbox */textarea, .gr-textbox textarea {background: #0d1117 !important;border: 1px solid #1e2d3d !important;border-radius: 6px !important;color: #cbd5e1 !important;font-size: 0.875rem !important;line-height: 1.7 !important;font-family: 'JetBrains Mono', monospace !important;padding: 0.875rem !important;resize: vertical !important;}textarea:focus {border-color: #0ea5e9 !important;outline: none !important;box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.08) !important;}textarea::placeholder {color: #334155 !important;}/* File upload */.gr-file, .upload-button {background: #0d1117 !important;border: 1px dashed #1e2d3d !important;border-radius: 6px !important;color: #64748b !important;}/* Tabs */.tab-nav {border-bottom: 1px solid #1e2d3d !important;margin-bottom: 1rem !important;}.tab-nav button {font-size: 0.8rem !important;font-weight: 500 !important;color: #475569 !important;border: none !important;background: transparent !important;padding: 0.5rem 1rem !important;border-radius: 0 !important;letter-spacing: 0.02em !important;}.tab-nav button.selected {color: #0ea5e9 !important;border-bottom: 2px solid #0ea5e9 !important;}/* Run button */#run-btn {background: #0ea5e9 !important;color: #0d1117 !important;border: none !important;border-radius: 6px !important;font-size: 0.875rem !important;font-weight: 600 !important;padding: 0.7rem 1.75rem !important;letter-spacing: 0.01em !important;transition: background 0.15s ease !important;margin-top: 0.75rem !important;width: 100% !important;}#run-btn:hover {background: #38bdf8 !important;}/* Output markdown */#output-area {background: #0d1117 !important;border: 1px solid #1e2d3d !important;border-radius: 6px !important;padding: 1.25rem !important;min-height: 400px !important;font-size: 0.875rem !important;line-height: 1.8 !important;color: #cbd5e1 !important;}#output-area h1, #output-area h2, #output-area h3 {color: #e2e8f0 !important;font-weight: 600 !important;letter-spacing: -0.01em !important;margin-top: 1.25rem !important;}#output-area strong {color: #0ea5e9 !important;font-weight: 500 !important;}#output-area ul, #output-area ol {padding-left: 1.25rem !important;color: #94a3b8 !important;}#output-area code {background: #1e2d3d !important;border-radius: 3px !important;padding: 0.1em 0.35em !important;font-family: 'JetBrains Mono', monospace !important;font-size: 0.82em !important;color: #38bdf8 !important;}/* Accordion */.gr-accordion {background: #111827 !important;border: 1px solid #1e2d3d !important;border-radius: 6px !important;margin-top: 0.75rem !important;}.gr-accordion .label-wrap {font-size: 0.8rem !important;color: #475569 !important;font-weight: 500 !important;}/* Examples */.gr-examples {margin-top: 1.5rem !important;}.gr-examples table {background: #111827 !important;border: 1px solid #1e2d3d !important;border-radius: 6px !important;}.gr-examples td {color: #64748b !important;font-size: 0.8rem !important;}/* Divider */.divider {border: none !important;border-top: 1px solid #1e2d3d !important;margin: 1.5rem 0 !important;}/* Labels */label, .gr-label {color: #475569 !important;font-size: 0.8rem !important;font-weight: 500 !important;letter-spacing: 0.03em !important;}/* Scrollbar */::-webkit-scrollbar { width: 5px; }::-webkit-scrollbar-track { background: #0d1117; }::-webkit-scrollbar-thumb { background: #1e2d3d; border-radius: 3px; }::-webkit-scrollbar-thumb:hover { background: #0ea5e9; }"""# ββ Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββwith gr.Blocks(title="Problem Brainstormer",css=custom_css,) as demo:gr.HTML("""<div id="app-header"><div id="accent-bar"></div><h1>Problem Brainstormer</h1><p>Paste a meeting transcript or upload a document to get structured problem analysis and solution ideas.</p></div>""")with gr.Row(equal_height=False):with gr.Column(scale=1, elem_classes=["input-panel"]):gr.HTML('<p class="section-label">Input</p>')with gr.Tabs():with gr.Tab("Paste Text"):text_input = gr.Textbox(label="",placeholder="Paste your meeting notes, transcript, or problem description here...",lines=16,max_lines=32,)with gr.Tab("Upload PDF"):pdf_input = gr.File(label="",file_types=[".pdf"],file_count="single",)gr.HTML('<p style="font-size:0.75rem;color:#334155;margin-top:0.5rem">Text-based PDFs only. Scanned documents are not supported.</p>')run_btn = gr.Button("Analyze and Brainstorm",variant="primary",elem_id="run-btn",)with gr.Accordion("How to use", open=False):gr.Markdown("""**Paste Text** β Copy any transcript, meeting notes, or problem statement into the text field.**Upload PDF** β Upload a text-based PDF such as a spec, report, or research document.**Click Analyze** to receive:- A clear articulation of the core problem- Root cause breakdown- 5β8 creative solution directions- Concrete next steps you can take as an intern""")with gr.Column(scale=1, elem_classes=["output-panel"]):gr.HTML('<p class="section-label">Analysis</p>')output = gr.Markdown(value="*Your analysis will appear here once you submit.*",elem_id="output-area",)gr.HTML('<hr class="divider">')gr.HTML('<p class="section-label">Example Inputs</p>')gr.Examples(examples=[[6 unmodified lines],],inputs=[text_input, pdf_input],label="",)run_btn.click(fn=run_agent,inputs=[text_input, pdf_input],1 unmodified lineshow_progress="full",)text_input.submit(fn=run_agent,inputs=[text_input, pdf_input],
app.py+271-75