File size: 22,060 Bytes
59de368
 
2c5e855
 
 
 
 
 
 
 
 
 
 
 
59de368
2c5e855
 
 
 
 
 
 
 
 
 
 
 
59de368
2c5e855
 
 
 
 
 
59de368
2c5e855
 
 
 
59de368
 
2c5e855
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59de368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb3909a
 
59de368
bb3909a
59de368
 
bb3909a
59de368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c5e855
 
 
 
 
 
59de368
 
 
 
2c5e855
 
 
59de368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e92524
 
 
 
 
 
 
 
 
 
2c5e855
 
59de368
2c5e855
 
 
 
 
59de368
2c5e855
59de368
 
2c5e855
59de368
2c5e855
 
 
59de368
2c5e855
59de368
2c5e855
 
 
 
 
 
 
 
 
 
 
59de368
2c5e855
 
 
59de368
2c5e855
 
 
 
 
 
 
 
 
 
a929e66
2c5e855
 
a929e66
 
2c5e855
a929e66
59de368
 
 
 
 
 
 
 
2c5e855
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59de368
 
2c5e855
 
 
59de368
2c5e855
 
59de368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c5e855
59de368
 
 
 
0e92524
59de368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73f15b1
59de368
 
 
 
 
 
2c5e855
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59de368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c5e855
 
 
59de368
 
 
2c5e855
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59de368
 
 
0e92524
59de368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c5e855
 
 
 
 
 
59de368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c5e855
 
 
 
 
 
 
 
 
 
 
 
 
59de368
 
 
 
 
 
 
 
 
 
 
 
 
2c5e855
 
59de368
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
# PDF Analysis & Orchestrator
# Extracted core functionality from Sharmaji ka PDF Blaster V1
import os
import asyncio
import uuid
from pathlib import Path
from typing import Optional, List, Tuple
import time

import gradio as gr
from agents import (
    AnalysisAgent,
    CollaborationAgent,
    ConversationAgent,
    ResearchAnalystAgent,
    MasterOrchestrator,
)
from utils import load_pdf_text
from utils.session import make_user_session
from utils.validation import validate_file_size
from utils.prompts import PromptManager
from utils.export import ExportManager
from config import Config

# ------------------------
# Initialize Components
# ------------------------
Config.ensure_directories()

# Agent Roster - Focused on Analysis & Orchestration
AGENTS = {
    "analysis": AnalysisAgent(name="AnalysisAgent", model=Config.OPENAI_MODEL, tasks_completed=0),
    "collab": CollaborationAgent(name="CollaborationAgent", model=Config.OPENAI_MODEL, tasks_completed=0),
    "conversation": ConversationAgent(name="ConversationAgent", model=Config.OPENAI_MODEL, tasks_completed=0),
    "research": ResearchAnalystAgent(name="ResearchAnalystAgent", model=Config.OPENAI_MODEL, tasks_completed=0),
}
ORCHESTRATOR = MasterOrchestrator(agents=AGENTS)

# Initialize managers
PROMPT_MANAGER = PromptManager()
EXPORT_MANAGER = ExportManager()

# ------------------------
# File Handling
# ------------------------
def save_uploaded_file(uploaded, username: str = "anonymous", session_dir: Optional[str] = None) -> str:
    if session_dir is None:
        session_dir = make_user_session(username)
    Path(session_dir).mkdir(parents=True, exist_ok=True)
    dst = Path(session_dir) / f"upload_{uuid.uuid4().hex}.pdf"

    if isinstance(uploaded, str) and os.path.exists(uploaded):
        from shutil import copyfile
        copyfile(uploaded, dst)
        return str(dst)
    if hasattr(uploaded, "read"):
        with open(dst, "wb") as f:
            f.write(uploaded.read())
        return str(dst)
    if isinstance(uploaded, dict) and "name" in uploaded and os.path.exists(uploaded["name"]):
        from shutil import copyfile
        copyfile(uploaded["name"], dst)
        return str(dst)
    raise RuntimeError("Unable to save uploaded file.")

# ------------------------
# Async wrapper
# ------------------------
def run_async(func, *args, **kwargs):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    return loop.run_until_complete(func(*args, **kwargs))

# ------------------------
# Analysis Handlers - Core Features
# ------------------------
def handle_analysis(file, prompt, username="anonymous", use_streaming=False):
    if file is None:
        return "Please upload a PDF.", None, None
    
    validate_file_size(file)
    path = save_uploaded_file(file, username)
    
    if use_streaming:
        return handle_analysis_streaming(path, prompt, username)
    else:
        result = run_async(
            ORCHESTRATOR.handle_user_prompt,
            user_id=username,
            prompt=prompt,
            file_path=path,
            targets=["analysis"]
        )
        return result.get("analysis", "No analysis result."), None, None

def handle_analysis_streaming(file_path, prompt, username="anonymous"):
    """Handle analysis with streaming output"""
    def stream_generator():
        async def async_stream():
            async for chunk in ORCHESTRATOR.handle_user_prompt_streaming(
                user_id=username,
                prompt=prompt,
                file_path=file_path,
                targets=["analysis"]
            ):
                yield chunk
        
        # Convert async generator to sync generator
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            async_gen = async_stream()
            while True:
                try:
                    chunk = loop.run_until_complete(async_gen.__anext__())
                    yield chunk
                except StopAsyncIteration:
                    break
        finally:
            loop.close()
    
    return stream_generator(), None, None

def handle_batch_analysis(files, prompt, username="anonymous"):
    """Handle batch analysis of multiple PDFs"""
    if not files or len(files) == 0:
        return "Please upload at least one PDF.", None, None
    
    # Validate all files
    file_paths = []
    for file in files:
        try:
            validate_file_size(file)
            path = save_uploaded_file(file, username)
            file_paths.append(path)
        except Exception as e:
            return f"Error with file {file}: {str(e)}", None, None
    
    result = run_async(
        ORCHESTRATOR.handle_batch_analysis,
        user_id=username,
        prompt=prompt,
        file_paths=file_paths,
        targets=["analysis"]
    )
    
    # Format batch results
    batch_summary = result.get("summary", {})
    batch_results = result.get("batch_results", [])
    
    formatted_output = f"πŸ“Š Batch Analysis Results\n"
    formatted_output += f"Total files: {batch_summary.get('processing_stats', {}).get('total_files', 0)}\n"
    formatted_output += f"Successful: {batch_summary.get('processing_stats', {}).get('successful', 0)}\n"
    formatted_output += f"Failed: {batch_summary.get('processing_stats', {}).get('failed', 0)}\n"
    formatted_output += f"Success rate: {batch_summary.get('processing_stats', {}).get('success_rate', '0%')}\n\n"
    
    if batch_summary.get("batch_analysis"):
        formatted_output += f"πŸ“‹ Batch Summary:\n{batch_summary['batch_analysis']}\n\n"
    
    formatted_output += "πŸ“„ Individual Results:\n"
    for i, file_result in enumerate(batch_results):
        formatted_output += f"\n--- File {i+1}: {Path(file_result.get('file_path', 'Unknown')).name} ---\n"
        if "error" in file_result:
            formatted_output += f"❌ Error: {file_result['error']}\n"
        else:
            formatted_output += f"βœ… {file_result.get('analysis', 'No analysis')}\n"
    
    return formatted_output, None, None

def handle_research_analysis(file, prompt, username="anonymous", use_streaming=False):
    """Handle research analysis with R&D pipeline focus"""
    if file is None:
        return "Please upload a PDF.", None, None
    
    validate_file_size(file)
    path = save_uploaded_file(file, username)
    
    # For now, always use non-streaming approach for research analysis
    # Streaming can be added later with proper Gradio integration
    result = run_async(
        ORCHESTRATOR.handle_user_prompt,
        user_id=username,
        prompt=prompt,
        file_path=path,
        targets=["research"]
    )
    return result.get("research_analysis", "No research analysis result."), None, None

def handle_export(result_text, export_format, username="anonymous"):
    """Handle export of analysis results"""
    if not result_text or result_text.strip() == "":
        return "No content to export.", None
    
    try:
        if export_format == "txt":
            filepath = EXPORT_MANAGER.export_text(result_text, username=username)
        elif export_format == "json":
            data = {"analysis": result_text, "exported_by": username, "timestamp": time.time()}
            filepath = EXPORT_MANAGER.export_json(data, username=username)
        elif export_format == "pdf":
            filepath = EXPORT_MANAGER.export_pdf(result_text, username=username)
        else:
            return f"Unsupported export format: {export_format}", None
        
        return f"βœ… Export successful! File saved to: {filepath}", filepath
    except Exception as e:
        return f"❌ Export failed: {str(e)}", None

def get_custom_prompts():
    """Get available custom prompts"""
    prompts = PROMPT_MANAGER.get_all_prompts()
    return list(prompts.keys())

def load_custom_prompt(prompt_id):
    """Load a custom prompt template"""
    return PROMPT_MANAGER.get_prompt(prompt_id) or ""

# ------------------------
# Gradio UI - Enhanced Interface
# ------------------------
with gr.Blocks(title="PDF Analysis & Orchestrator", theme=gr.themes.Soft()) as demo:
    gr.Markdown("# πŸ“„ PDF Analysis & Orchestrator - Intelligent Document Processing")
    gr.Markdown("Upload PDFs and provide instructions for analysis, summarization, or explanation. Now with enhanced features!")

    with gr.Tabs():
        # Single Document Analysis Tab
        with gr.Tab("πŸ“„ Single Document Analysis"):
            with gr.Row():
                with gr.Column(scale=1):
                    pdf_in = gr.File(label="Upload PDF", file_types=[".pdf"], elem_id="file_upload")
                    username_input = gr.Textbox(label="Username (optional)", placeholder="anonymous", elem_id="username")
                    
                    # Custom Prompts Section
                    with gr.Accordion("🎯 Custom Prompts", open=False):
                        prompt_dropdown = gr.Dropdown(
                            choices=get_custom_prompts(),
                            label="Select Custom Prompt",
                            value=None
                        )
                        load_prompt_btn = gr.Button("Load Prompt", size="sm")
                    
                    # Analysis Options
                    with gr.Accordion("βš™οΈ Analysis Options", open=False):
                        use_streaming = gr.Checkbox(label="Enable Streaming Output", value=False)
                        chunk_size = gr.Slider(
                            minimum=5000, maximum=30000, value=15000, step=1000,
                            label="Chunk Size (for large documents)"
                        )
                
                with gr.Column(scale=2):
                    gr.Markdown("### Analysis Instructions")
                    prompt_input = gr.Textbox(
                        lines=4, 
                        placeholder="Describe what you want to do with the document...\nExamples:\n- Summarize this document in 3 key points\n- Explain this technical paper for a 10-year-old\n- Segment this document by themes\n- Analyze the key findings", 
                        label="Instructions"
                    )
                    
                    with gr.Row():
                        submit_btn = gr.Button("πŸ” Analyze & Orchestrate", variant="primary", size="lg")
                        clear_btn = gr.Button("πŸ—‘οΈ Clear", size="sm")

            # Results Section
            with gr.Row():
                with gr.Column(scale=2):
                    output_box = gr.Textbox(label="Analysis Result", lines=15, max_lines=25, show_copy_button=True)
                    status_box = gr.Textbox(label="Status", value="Ready to analyze documents", interactive=False)
                
                with gr.Column(scale=1):
                    # Export Section
                    with gr.Accordion("πŸ’Ύ Export Results", open=False):
                        export_format = gr.Dropdown(
                            choices=["txt", "json", "pdf"],
                            label="Export Format",
                            value="txt"
                        )
                        export_btn = gr.Button("πŸ“₯ Export", variant="secondary")
                        export_status = gr.Textbox(label="Export Status", interactive=False)
                    
                    # Document Info
                    with gr.Accordion("πŸ“Š Document Info", open=False):
                        doc_info = gr.Textbox(label="Document Information", interactive=False, lines=6)

        # Senior Research Analyst Tab
        with gr.Tab("πŸ”¬ Senior Research Analyst"):
            gr.Markdown("### 🎯 R&D Pipeline Analysis")
            gr.Markdown("Act as a senior research analyst: extract high-value, novel ideas and convert them into concrete R&D pipeline outcomes (experiments β†’ prototypes β†’ product decisions)")
            
            with gr.Row():
                with gr.Column(scale=1):
                    research_pdf_in = gr.File(label="Upload Research Document", file_types=[".pdf"], elem_id="research_file_upload")
                    research_username_input = gr.Textbox(label="Username (optional)", placeholder="anonymous", elem_id="research_username")
                    
                    # Research-Specific Prompts Section
                    with gr.Accordion("🎯 Research Prompts", open=False):
                        research_prompt_dropdown = gr.Dropdown(
                            choices=[pid for pid, prompt in PROMPT_MANAGER.get_all_prompts().items() if prompt.get("category") == "research"],
                            label="Select Research Prompt",
                            value="research_pipeline"
                        )
                        load_research_prompt_btn = gr.Button("Load Research Prompt", size="sm")
                    
                    # Research Analysis Options
                    with gr.Accordion("βš™οΈ Research Options", open=False):
                        gr.Markdown("Research analysis uses comprehensive processing for detailed R&D pipeline insights.")
                
                with gr.Column(scale=2):
                    gr.Markdown("### Research Analysis Instructions")
                    research_prompt_input = gr.Textbox(
                        lines=4, 
                        placeholder="Focus on extracting novel ideas with high product/engineering impact...\nExamples:\n- Identify breakthrough concepts for R&D pipeline\n- Assess commercial viability of technical innovations\n- Design experimental frameworks for validation\n- Create prototype development roadmaps", 
                        label="Research Instructions"
                    )
                    
                    with gr.Row():
                        research_submit_btn = gr.Button("πŸ”¬ Research Analysis", variant="primary", size="lg")
                        research_clear_btn = gr.Button("πŸ—‘οΈ Clear", size="sm")

            # Research Results Section
            with gr.Row():
                with gr.Column(scale=2):
                    research_output_box = gr.Textbox(label="Research Analysis Result", lines=20, max_lines=30, show_copy_button=True)
                    research_status_box = gr.Textbox(label="Research Status", value="Ready for research analysis", interactive=False)
                
                with gr.Column(scale=1):
                    # Research Export Section
                    with gr.Accordion("πŸ’Ύ Export Research Results", open=False):
                        research_export_format = gr.Dropdown(
                            choices=["txt", "json", "pdf"],
                            label="Export Format",
                            value="txt"
                        )
                        research_export_btn = gr.Button("πŸ“₯ Export Research", variant="secondary")
                        research_export_status = gr.Textbox(label="Export Status", interactive=False)
                    
                    # Research Insights Summary
                    with gr.Accordion("πŸ“Š Research Insights", open=False):
                        research_insights = gr.Textbox(label="Key Insights Summary", interactive=False, lines=8)

        # Batch Processing Tab
        with gr.Tab("πŸ“š Batch Processing"):
            with gr.Row():
                with gr.Column(scale=1):
                    batch_files = gr.File(
                        label="Upload Multiple PDFs", 
                        file_count="multiple", 
                        file_types=[".pdf"]
                    )
                    batch_username = gr.Textbox(label="Username (optional)", placeholder="anonymous")
                
                with gr.Column(scale=2):
                    batch_prompt = gr.Textbox(
                        lines=3,
                        placeholder="Enter analysis instructions for all documents...",
                        label="Batch Analysis Instructions"
                    )
                    batch_submit = gr.Button("πŸš€ Process Batch", variant="primary", size="lg")
            
            batch_output = gr.Textbox(label="Batch Results", lines=20, max_lines=30, show_copy_button=True)
            batch_status = gr.Textbox(label="Batch Status", interactive=False)

        # Custom Prompts Management Tab
        with gr.Tab("🎯 Manage Prompts"):
            with gr.Row():
                with gr.Column(scale=1):
                    gr.Markdown("### Add New Prompt")
                    new_prompt_id = gr.Textbox(label="Prompt ID", placeholder="my_custom_prompt")
                    new_prompt_name = gr.Textbox(label="Prompt Name", placeholder="My Custom Analysis")
                    new_prompt_desc = gr.Textbox(label="Description", placeholder="What this prompt does")
                    new_prompt_template = gr.Textbox(
                        lines=4,
                        label="Prompt Template",
                        placeholder="Enter your custom prompt template..."
                    )
                    new_prompt_category = gr.Dropdown(
                        choices=["custom", "business", "technical", "explanation", "analysis"],
                        label="Category",
                        value="custom"
                    )
                    add_prompt_btn = gr.Button("βž• Add Prompt", variant="primary")
                
                with gr.Column(scale=1):
                    gr.Markdown("### Existing Prompts")
                    prompt_list = gr.Dataframe(
                        headers=["ID", "Name", "Category", "Description"],
                        datatype=["str", "str", "str", "str"],
                        interactive=False,
                        label="Available Prompts"
                    )
                    refresh_prompts_btn = gr.Button("πŸ”„ Refresh List")
                    delete_prompt_id = gr.Textbox(label="Prompt ID to Delete", placeholder="prompt_id")
                    delete_prompt_btn = gr.Button("πŸ—‘οΈ Delete Prompt", variant="stop")

    # Event Handlers
    # Single document analysis
    submit_btn.click(
        fn=handle_analysis, 
        inputs=[pdf_in, prompt_input, username_input, use_streaming], 
        outputs=[output_box, status_box, doc_info]
    )
    
    # Load custom prompt
    load_prompt_btn.click(
        fn=load_custom_prompt,
        inputs=[prompt_dropdown],
        outputs=[prompt_input]
    )
    
    # Export functionality
    export_btn.click(
        fn=handle_export,
        inputs=[output_box, export_format, username_input],
        outputs=[export_status, gr.State()]
    )
    
    # Clear functionality
    clear_btn.click(
        fn=lambda: ("", "", "", "Ready"),
        inputs=[],
        outputs=[pdf_in, prompt_input, output_box, status_box]
    )
    
    # Research analysis event handlers
    research_submit_btn.click(
        fn=handle_research_analysis, 
        inputs=[research_pdf_in, research_prompt_input, research_username_input], 
        outputs=[research_output_box, research_status_box, research_insights]
    )
    
    # Load research prompt
    load_research_prompt_btn.click(
        fn=load_custom_prompt,
        inputs=[research_prompt_dropdown],
        outputs=[research_prompt_input]
    )
    
    # Research export functionality
    research_export_btn.click(
        fn=handle_export,
        inputs=[research_output_box, research_export_format, research_username_input],
        outputs=[research_export_status, gr.State()]
    )
    
    # Research clear functionality
    research_clear_btn.click(
        fn=lambda: ("", "", "", "Ready for research analysis", ""),
        inputs=[],
        outputs=[research_pdf_in, research_prompt_input, research_output_box, research_status_box, research_insights]
    )
    
    # Batch processing
    batch_submit.click(
        fn=handle_batch_analysis,
        inputs=[batch_files, batch_prompt, batch_username],
        outputs=[batch_output, batch_status, gr.State()]
    )
    
    # Prompt management
    add_prompt_btn.click(
        fn=lambda id, name, desc, template, cat: PROMPT_MANAGER.add_prompt(id, name, desc, template, cat),
        inputs=[new_prompt_id, new_prompt_name, new_prompt_desc, new_prompt_template, new_prompt_category],
        outputs=[]
    )
    
    refresh_prompts_btn.click(
        fn=lambda: [[pid, prompt["name"], prompt["category"], prompt["description"]] 
                   for pid, prompt in PROMPT_MANAGER.get_all_prompts().items()],
        inputs=[],
        outputs=[prompt_list]
    )
    
    delete_prompt_btn.click(
        fn=lambda pid: PROMPT_MANAGER.delete_prompt(pid),
        inputs=[delete_prompt_id],
        outputs=[]
    )

    # Examples
    gr.Examples(
        examples=[
            ["Summarize this document in 3 key points"],
            ["Explain this technical content for a general audience"],
            ["Segment this document by main themes or topics"],
            ["Analyze the key findings and recommendations"],
            ["Create an executive summary of this document"],
        ],
        inputs=prompt_input,
        label="Example Instructions"
    )
    
    # Research Examples
    gr.Examples(
        examples=[
            ["Identify breakthrough concepts with high product/engineering impact and design specific experiments to validate them"],
            ["Assess the commercial viability of technical innovations and create prototype development roadmaps"],
            ["Extract novel methodologies and convert them into concrete R&D pipeline outcomes"],
            ["Analyze technical concepts for transformative potential and generate strategic product decisions"],
            ["Design experimental frameworks to validate key hypotheses with measurable success criteria"],
        ],
        inputs=research_prompt_input,
        label="Research Analysis Examples"
    )

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))