JatsTheAIGen commited on
Commit
624de5a
Β·
1 Parent(s): fc2766c

Major UI improvements: Enhanced formatting, comprehensive custom prompts, fixed export error

Browse files
Files changed (5) hide show
  1. agents.py +16 -1
  2. app.py +39 -7
  3. packages.txt +7 -0
  4. utils/export.py +1 -1
  5. utils/prompts.py +67 -24
agents.py CHANGED
@@ -52,7 +52,22 @@ class AnalysisAgent(BaseAgent):
52
  content = f"User prompt: {prompt}"
53
  metadata = {}
54
 
55
- system = "You are AnalysisAgent: produce concise insights and structured summaries. Adapt your language and complexity to the target audience. Provide clear, actionable insights with appropriate examples and analogies for complex topics."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
  try:
58
  response = await call_openai_chat(
 
52
  content = f"User prompt: {prompt}"
53
  metadata = {}
54
 
55
+ system = """You are AnalysisAgent: produce well-structured, readable insights and summaries.
56
+
57
+ FORMATTING REQUIREMENTS:
58
+ - Use clear section headers with emojis (## πŸ“‹ Key Points, ## πŸ” Analysis, etc.)
59
+ - Use bullet points and numbered lists for better readability
60
+ - Include visual separators (---) between major sections
61
+ - Use bold text for important concepts
62
+ - Add technical details in organized subsections
63
+ - Include actionable insights with clear next steps
64
+
65
+ CONTENT REQUIREMENTS:
66
+ - Adapt language and complexity to the target audience
67
+ - Provide clear, actionable insights with examples
68
+ - Use analogies for complex topics
69
+ - Include quantitative details when available
70
+ - Structure information hierarchically for easy scanning"""
71
 
72
  try:
73
  response = await call_openai_chat(
app.py CHANGED
@@ -196,13 +196,28 @@ with gr.Blocks(title="PDF Analysis & Orchestrator", theme=gr.themes.Soft()) as d
196
  username_input = gr.Textbox(label="Username (optional)", placeholder="anonymous", elem_id="username")
197
 
198
  # Custom Prompts Section
199
- with gr.Accordion("🎯 Custom Prompts", open=False):
 
200
  prompt_dropdown = gr.Dropdown(
201
  choices=get_custom_prompts(),
202
- label="Select Custom Prompt",
203
- value=None
 
204
  )
205
- load_prompt_btn = gr.Button("Load Prompt", size="sm")
 
 
 
 
 
 
 
 
 
 
 
 
 
206
 
207
  with gr.Column(scale=2):
208
  gr.Markdown("### Analysis Instructions")
@@ -219,8 +234,18 @@ with gr.Blocks(title="PDF Analysis & Orchestrator", theme=gr.themes.Soft()) as d
219
  # Results Section
220
  with gr.Row():
221
  with gr.Column(scale=2):
222
- output_box = gr.Textbox(label="Analysis Result", lines=15, max_lines=25, show_copy_button=True)
223
- status_box = gr.Textbox(label="Status", value="Ready to analyze documents", interactive=False)
 
 
 
 
 
 
 
 
 
 
224
 
225
  with gr.Column(scale=1):
226
  # Export Section
@@ -257,8 +282,15 @@ with gr.Blocks(title="PDF Analysis & Orchestrator", theme=gr.themes.Soft()) as d
257
 
258
  # Event Handlers
259
  # Single document analysis
 
 
 
 
 
 
 
260
  submit_btn.click(
261
- fn=handle_analysis,
262
  inputs=[pdf_in, prompt_input, username_input, gr.State(False)],
263
  outputs=[output_box, status_box, gr.State()]
264
  )
 
196
  username_input = gr.Textbox(label="Username (optional)", placeholder="anonymous", elem_id="username")
197
 
198
  # Custom Prompts Section
199
+ with gr.Accordion("🎯 Document Type Analysis", open=True):
200
+ gr.Markdown("**Choose a document type for specialized analysis:**")
201
  prompt_dropdown = gr.Dropdown(
202
  choices=get_custom_prompts(),
203
+ label="πŸ“‹ Select Document Type",
204
+ value=None,
205
+ info="Choose the type of document you're analyzing for better results"
206
  )
207
+ load_prompt_btn = gr.Button("πŸ“₯ Load Analysis Template", size="sm", variant="secondary")
208
+
209
+ # Document type categories
210
+ with gr.Row():
211
+ gr.Markdown("**Quick Categories:**")
212
+ with gr.Row():
213
+ gr.Markdown("πŸ“„ **Business:** Whitepapers, Business Plans")
214
+ gr.Markdown("βš™οΈ **Technical:** User Manuals, Specs")
215
+ with gr.Row():
216
+ gr.Markdown("πŸ’° **Financial:** Reports, Bank Statements")
217
+ gr.Markdown("πŸŽ“ **Academic:** Research Papers")
218
+ with gr.Row():
219
+ gr.Markdown("βš–οΈ **Legal:** Contracts, Agreements")
220
+ gr.Markdown("🎨 **Creative:** Briefs, Marketing")
221
 
222
  with gr.Column(scale=2):
223
  gr.Markdown("### Analysis Instructions")
 
234
  # Results Section
235
  with gr.Row():
236
  with gr.Column(scale=2):
237
+ gr.Markdown("### πŸ“Š Analysis Results")
238
+ output_box = gr.Markdown(
239
+ value="**Ready to analyze documents**\n\nUpload a PDF and enter your analysis instructions to get started.",
240
+ label="Analysis Result",
241
+ show_copy_button=True
242
+ )
243
+ status_box = gr.Textbox(
244
+ label="πŸ”„ Status",
245
+ value="Ready to analyze documents",
246
+ interactive=False,
247
+ info="Current processing status will appear here"
248
+ )
249
 
250
  with gr.Column(scale=1):
251
  # Export Section
 
282
 
283
  # Event Handlers
284
  # Single document analysis
285
+ def handle_analysis_with_markdown(file, prompt, username="anonymous", use_streaming=False):
286
+ result, status, doc_info = handle_analysis(file, prompt, username, use_streaming)
287
+ # Convert to markdown if it's a string
288
+ if isinstance(result, str):
289
+ return result, status, doc_info
290
+ return str(result), status, doc_info
291
+
292
  submit_btn.click(
293
+ fn=handle_analysis_with_markdown,
294
  inputs=[pdf_in, prompt_input, username_input, gr.State(False)],
295
  outputs=[output_box, status_box, gr.State()]
296
  )
packages.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ libgl1-mesa-dri
2
+ libglib2.0-0
3
+ libsm6
4
+ libxext6
5
+ libxrender1
6
+ libgomp1
7
+ libgcc-s1
utils/export.py CHANGED
@@ -59,7 +59,7 @@ class ExportManager:
59
  return str(filepath)
60
 
61
  def export_pdf(self, content: str, filename: str = None,
62
- metadata: Dict[str, Any] = None) -> str:
63
  """Export content as PDF (requires reportlab)"""
64
  try:
65
  from reportlab.lib.pagesizes import letter
 
59
  return str(filepath)
60
 
61
  def export_pdf(self, content: str, filename: str = None,
62
+ metadata: Dict[str, Any] = None, username: str = None) -> str:
63
  """Export content as PDF (requires reportlab)"""
64
  try:
65
  from reportlab.lib.pagesizes import letter
utils/prompts.py CHANGED
@@ -29,41 +29,84 @@ class PromptManager:
29
  def _get_default_prompts(self) -> Dict[str, Dict[str, str]]:
30
  """Get default prompt templates"""
31
  return {
 
32
  "summarize": {
33
- "name": "Summarize Document",
34
- "description": "Create a concise summary of the document",
35
- "template": "Summarize this document in 3-5 key points, highlighting the main ideas and conclusions.",
36
  "category": "basic"
37
  },
38
  "explain_simple": {
39
- "name": "Explain Simply",
40
- "description": "Explain complex content for a general audience",
41
- "template": "Explain this document in simple terms that a 10-year-old could understand. Use analogies and examples where helpful.",
42
  "category": "explanation"
43
  },
44
- "executive_summary": {
45
- "name": "Executive Summary",
46
- "description": "Create an executive summary for decision makers",
47
- "template": "Create an executive summary of this document, focusing on key findings, recommendations, and business implications.",
 
 
48
  "category": "business"
49
  },
50
- "technical_analysis": {
51
- "name": "Technical Analysis",
52
- "description": "Provide detailed technical analysis",
53
- "template": "Provide a detailed technical analysis of this document, including methodology, data analysis, and technical conclusions.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  "category": "technical"
55
  },
56
- "theme_segmentation": {
57
- "name": "Theme Segmentation",
58
- "description": "Break down document by themes and topics",
59
- "template": "Segment this document by main themes and topics. Identify key themes and provide a brief summary of each section.",
60
- "category": "organization"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  },
62
- "key_findings": {
63
- "name": "Key Findings",
64
- "description": "Extract key findings and insights",
65
- "template": "Extract and analyze the key findings, insights, and recommendations from this document. Highlight the most important points.",
66
- "category": "analysis"
 
 
67
  }
68
  }
69
 
 
29
  def _get_default_prompts(self) -> Dict[str, Dict[str, str]]:
30
  """Get default prompt templates"""
31
  return {
32
+ # Basic Analysis
33
  "summarize": {
34
+ "name": "πŸ“‹ Document Summary",
35
+ "description": "Create a structured summary with key points",
36
+ "template": "Create a comprehensive summary of this document with:\n\n## πŸ“‹ Executive Summary\n- Main purpose and scope\n- Key findings (3-5 bullet points)\n- Primary conclusions\n\n## πŸ” Key Insights\n- Most important takeaways\n- Critical data points\n- Actionable recommendations\n\n## πŸ“Š Document Structure\n- Main sections overview\n- Supporting evidence\n- Methodology used",
37
  "category": "basic"
38
  },
39
  "explain_simple": {
40
+ "name": "πŸ‘Ά Explain Simply",
41
+ "description": "Explain complex content for general audience",
42
+ "template": "Explain this document in simple, accessible terms:\n\n## 🎯 Main Concept\n- What is this about? (one sentence)\n- Why does it matter?\n\n## πŸ”§ How It Works\n- Step-by-step explanation\n- Use analogies and examples\n- Avoid jargon\n\n## πŸ’‘ Key Takeaways\n- 3-5 main points anyone can understand\n- Real-world applications\n- Why this matters to everyday people",
43
  "category": "explanation"
44
  },
45
+
46
+ # Business Documents
47
+ "whitepaper_analysis": {
48
+ "name": "πŸ“„ Whitepaper Analysis",
49
+ "description": "Comprehensive analysis for whitepapers and research papers",
50
+ "template": "Analyze this whitepaper/research document:\n\n## 🎯 Executive Summary\n- **Problem Statement**: What problem does this address?\n- **Solution**: What is the proposed solution?\n- **Value Proposition**: Why is this important?\n\n## πŸ”¬ Methodology & Evidence\n- Research approach used\n- Data sources and sample size\n- Key experiments or studies\n- Statistical significance\n\n## πŸ“Š Key Findings\n- Primary research results\n- Supporting evidence\n- Limitations and caveats\n\n## πŸ’Ό Business Implications\n- Market impact\n- Implementation challenges\n- ROI considerations\n- Competitive advantages\n\n## πŸš€ Next Steps\n- Recommended actions\n- Further research needed\n- Implementation timeline",
51
  "category": "business"
52
  },
53
+ "business_plan": {
54
+ "name": "πŸ’Ό Business Plan Analysis",
55
+ "description": "Analyze business plans and strategic documents",
56
+ "template": "Analyze this business plan/strategic document:\n\n## 🎯 Business Overview\n- **Mission & Vision**: Core business purpose\n- **Target Market**: Who are the customers?\n- **Value Proposition**: What makes this unique?\n\n## πŸ“ˆ Market Analysis\n- Market size and opportunity\n- Competitive landscape\n- Market trends and drivers\n- Customer segments\n\n## πŸ’° Financial Projections\n- Revenue model\n- Key financial metrics\n- Funding requirements\n- Break-even analysis\n\n## πŸš€ Strategy & Execution\n- Go-to-market strategy\n- Key milestones\n- Risk factors\n- Success metrics\n\n## ⚠️ Risk Assessment\n- Major risks identified\n- Mitigation strategies\n- Contingency plans",
57
+ "category": "business"
58
+ },
59
+
60
+ # Technical Documents
61
+ "user_manual": {
62
+ "name": "πŸ“– User Manual Analysis",
63
+ "description": "Extract key information from user manuals and guides",
64
+ "template": "Analyze this user manual/guide:\n\n## 🎯 Product Overview\n- **What it does**: Main functionality\n- **Target users**: Who is this for?\n- **Key features**: Primary capabilities\n\n## βš™οΈ Setup & Installation\n- Prerequisites\n- Step-by-step setup\n- Common issues and solutions\n\n## πŸ”§ How to Use\n- Main workflows\n- Key procedures\n- Best practices\n- Tips and tricks\n\n## ⚠️ Important Warnings\n- Safety considerations\n- Common mistakes to avoid\n- Troubleshooting guide\n\n## πŸ“ž Support Information\n- Where to get help\n- Documentation references\n- Contact information",
65
+ "category": "technical"
66
+ },
67
+ "technical_spec": {
68
+ "name": "βš™οΈ Technical Specification",
69
+ "description": "Analyze technical specifications and documentation",
70
+ "template": "Analyze this technical specification:\n\n## 🎯 System Overview\n- **Purpose**: What does this system do?\n- **Architecture**: High-level design\n- **Components**: Main parts and modules\n\n## πŸ”§ Technical Details\n- **Requirements**: System requirements\n- **Dependencies**: External dependencies\n- **Interfaces**: APIs and protocols\n- **Performance**: Speed, capacity, limits\n\n## πŸ› οΈ Implementation\n- **Development approach**: How to build this\n- **Testing strategy**: Quality assurance\n- **Deployment**: Installation and setup\n\n## πŸ“Š Standards & Compliance\n- **Standards followed**: Industry standards\n- **Security**: Security considerations\n- **Compliance**: Regulatory requirements\n\n## πŸ” Technical Risks\n- **Potential issues**: What could go wrong\n- **Mitigation**: How to prevent problems\n- **Monitoring**: How to track performance",
71
  "category": "technical"
72
  },
73
+
74
+ # Financial Documents
75
+ "financial_report": {
76
+ "name": "πŸ’° Financial Report Analysis",
77
+ "description": "Analyze financial reports and statements",
78
+ "template": "Analyze this financial report:\n\n## πŸ“Š Financial Overview\n- **Revenue**: Total income and trends\n- **Expenses**: Major cost categories\n- **Profitability**: Net income and margins\n- **Cash Flow**: Operating, investing, financing\n\n## πŸ“ˆ Key Metrics\n- **Growth rates**: Revenue and profit growth\n- **Efficiency ratios**: How well resources are used\n- **Liquidity ratios**: Ability to meet short-term obligations\n- **Leverage ratios**: Debt levels and risk\n\n## πŸ” Performance Analysis\n- **Strengths**: What's working well\n- **Weaknesses**: Areas of concern\n- **Trends**: Changes over time\n- **Comparisons**: vs. industry benchmarks\n\n## ⚠️ Risk Factors\n- **Financial risks**: Potential problems\n- **Market risks**: External factors\n- **Operational risks**: Internal challenges\n\n## πŸ’‘ Investment Insights\n- **Valuation**: Is this fairly valued?\n- **Outlook**: Future prospects\n- **Recommendations**: Buy, hold, or sell?",
79
+ "category": "financial"
80
+ },
81
+ "bank_statement": {
82
+ "name": "🏦 Bank Statement Analysis",
83
+ "description": "Analyze bank statements and transaction data",
84
+ "template": "Analyze this bank statement:\n\n## πŸ’° Account Overview\n- **Account type**: Checking, savings, etc.\n- **Current balance**: Available funds\n- **Statement period**: Time range covered\n- **Account activity**: Number of transactions\n\n## πŸ“Š Income Analysis\n- **Total deposits**: Money coming in\n- **Income sources**: Where money comes from\n- **Frequency**: How often deposits occur\n- **Trends**: Changes over time\n\n## πŸ’Έ Expense Analysis\n- **Total withdrawals**: Money going out\n- **Major expenses**: Largest transactions\n- **Spending categories**: Where money is spent\n- **Expense patterns**: Regular vs. irregular\n\n## πŸ” Financial Health\n- **Cash flow**: Net positive or negative\n- **Savings rate**: How much is saved\n- **Emergency fund**: Available reserves\n- **Spending habits**: Areas of concern\n\n## πŸ’‘ Recommendations\n- **Budget optimization**: How to improve\n- **Savings opportunities**: Where to cut costs\n- **Financial goals**: Next steps",
85
+ "category": "financial"
86
+ },
87
+
88
+ # Academic & Research
89
+ "academic_paper": {
90
+ "name": "πŸŽ“ Academic Paper Analysis",
91
+ "description": "Analyze academic papers and research studies",
92
+ "template": "Analyze this academic paper:\n\n## 🎯 Research Overview\n- **Research Question**: What is being investigated?\n- **Hypothesis**: What is being tested?\n- **Significance**: Why is this important?\n\n## πŸ”¬ Methodology\n- **Study Design**: How was the research conducted?\n- **Participants**: Who was studied?\n- **Data Collection**: What data was gathered?\n- **Analysis Methods**: How was data analyzed?\n\n## πŸ“Š Results & Findings\n- **Key Results**: Main findings\n- **Statistical Significance**: Are results meaningful?\n- **Effect Sizes**: How large are the effects?\n- **Limitations**: What are the constraints?\n\n## πŸ” Critical Analysis\n- **Strengths**: What was done well?\n- **Weaknesses**: What could be improved?\n- **Bias Assessment**: Potential sources of bias\n- **Reproducibility**: Can this be replicated?\n\n## πŸ’‘ Implications\n- **Theoretical Impact**: How does this advance knowledge?\n- **Practical Applications**: Real-world uses\n- **Future Research**: What should be studied next?\n- **Policy Implications**: How might this influence policy?",
93
+ "category": "academic"
94
+ },
95
+
96
+ # Legal Documents
97
+ "legal_document": {
98
+ "name": "βš–οΈ Legal Document Analysis",
99
+ "description": "Analyze legal documents and contracts",
100
+ "template": "Analyze this legal document:\n\n## πŸ“‹ Document Overview\n- **Document Type**: Contract, agreement, policy, etc.\n- **Parties Involved**: Who are the key parties?\n- **Purpose**: What is this document for?\n- **Effective Date**: When does it take effect?\n\n## πŸ”‘ Key Terms & Conditions\n- **Obligations**: What must each party do?\n- **Rights**: What are each party's rights?\n- **Restrictions**: What is prohibited?\n- **Timeline**: Important dates and deadlines\n\n## πŸ’° Financial Terms\n- **Payment Terms**: How and when to pay\n- **Fees & Costs**: Associated expenses\n- **Penalties**: Consequences of non-compliance\n- **Termination**: How to end the agreement\n\n## ⚠️ Risk Assessment\n- **Liability**: Who is responsible for what?\n- **Indemnification**: Protection clauses\n- **Force Majeure**: Unforeseen circumstances\n- **Dispute Resolution**: How conflicts are handled\n\n## πŸ’‘ Key Takeaways\n- **Critical Deadlines**: Important dates to remember\n- **Action Items**: What needs to be done\n- **Risks to Monitor**: Areas of concern\n- **Recommendations**: Suggested next steps",
101
+ "category": "legal"
102
  },
103
+
104
+ # Creative & Media
105
+ "creative_brief": {
106
+ "name": "🎨 Creative Brief Analysis",
107
+ "description": "Analyze creative briefs and marketing materials",
108
+ "template": "Analyze this creative brief/marketing document:\n\n## 🎯 Project Overview\n- **Objective**: What is the goal?\n- **Target Audience**: Who is this for?\n- **Brand Voice**: What tone should be used?\n- **Key Message**: What should people remember?\n\n## 🎨 Creative Direction\n- **Visual Style**: Design preferences\n- **Color Palette**: Brand colors\n- **Typography**: Font choices\n- **Imagery**: Photo/video style\n\n## πŸ“± Deliverables\n- **Format Requirements**: Sizes, specifications\n- **Platform Considerations**: Where will this be used?\n- **Technical Specs**: File formats, resolution\n- **Timeline**: Deadlines and milestones\n\n## πŸ” Success Metrics\n- **KPIs**: How will success be measured?\n- **Performance Goals**: Specific targets\n- **Testing Strategy**: How to validate effectiveness\n- **Reporting**: How to track results\n\n## πŸ’‘ Recommendations\n- **Optimization Opportunities**: How to improve\n- **Best Practices**: Industry standards\n- **Risk Mitigation**: Potential issues to avoid\n- **Next Steps**: Immediate actions needed",
109
+ "category": "creative"
110
  }
111
  }
112