File size: 6,961 Bytes
bc28484
d4c6f47
af709bf
 
 
 
5a35ca5
af709bf
 
bc28484
af709bf
5a35ca5
af709bf
 
 
 
 
d4c6f47
af709bf
d4c6f47
11fadc8
 
d4c6f47
11fadc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4c6f47
11fadc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4c6f47
 
 
b8b59e0
af709bf
 
 
d4c6f47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af709bf
 
 
 
 
 
d4c6f47
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from utils import fetch_active_tenders, fetch_tender_details, get_ppra_resources, chunk_text
from model_config import get_model

st.set_page_config(page_title="PPRA Co-Pilot", layout="wide")
st.title("πŸ“„ PPRA Co-Pilot – Understand Government Tenders Easily")

# Load model
llm = get_model()

tab1, tab2, tab3 = st.tabs(["πŸ“€ Upload Tender", "πŸ“Œ View Active Tenders", "πŸ“š PPRA Resources"])

# Upload Tender Tab
with tab1:
    st.subheader("Upload a Tender Document (PDF or Text)")
    uploaded_file = st.file_uploader("Choose a file", type=["pdf", "txt"])
    user_name = st.text_input("Enter your name")
    
    if uploaded_file and user_name:
        try:
            # Process different file types
            file_extension = uploaded_file.name.split('.')[-1].lower()
            
            if file_extension == 'pdf':
                # Handle PDF files
                try:
                    import pdfplumber
                    pdf = pdfplumber.open(uploaded_file)
                    file_text = ""
                    # Extract text from first few pages
                    for i in range(min(5, len(pdf.pages))):
                        page_text = pdf.pages[i].extract_text() or ""
                        file_text += page_text + "\n\n"
                    pdf.close()
                except Exception as e:
                    st.error(f"Error processing PDF: {str(e)}")
                    file_text = "Error extracting PDF content"
            else:
                # Handle text files
                file_content = uploaded_file.read()
                try:
                    file_text = file_content.decode("utf-8", errors="ignore")
                except:
                    file_text = str(file_content)
            
            # Show a preview of the document (first 500 chars)
            with st.expander("Document Preview"):
                st.text(file_text[:500] + "..." if len(file_text) > 500 else file_text)
            
            # Process the document if we have content
            if file_text:
                # Create direct prompt with the document content
                with st.spinner("Analyzing the tender document..."):
                    # Chunk the text if needed
                    chunks = chunk_text(file_text, max_tokens=3000)
                    
                    if not chunks:
                        st.error("Unable to process document - no valid content found")
                    else:
                        # Direct analysis of first chunk
                        analysis_prompt = f"""
                        The following is a government tender document:
                        
                        {chunks[0]}
                        
                        Please analyze this tender document and provide a clear, simple explanation for {user_name}:
                        
                        1. What is this tender for? (explain the purpose clearly)
                        2. What are the key requirements to apply?
                        3. Who is eligible to apply for this tender?
                        4. What are the important deadlines?
                        5. What documents or qualifications are needed?
                        
                        Address {user_name} directly in your response. Make it personal.
                        """
                        
                        detailed_analysis = llm(analysis_prompt)
                        
                st.success("Tender Summary:")
                st.write(detailed_analysis)
            else:
                st.error("Could not extract text from the uploaded file")
        except Exception as e:
            st.error(f"Error processing file: {str(e)}")
            st.info("Try uploading a smaller file or a text extract of the most important sections.")

# View Active Tenders Tab
with tab2:
    st.subheader("πŸ” Active Government Tenders")
    
    # Add a refresh button
    if st.button("πŸ”„ Refresh Tenders"):
        st.experimental_rerun()
    
    try:
        with st.spinner("Fetching active tenders..."):
            tenders = fetch_active_tenders()
        
        if not tenders or len(tenders) == 0:
            st.warning("No active tenders found or there was an issue fetching the tenders.")
        else:
            tender_titles = [t["title"] for t in tenders]
            selected = st.selectbox("Select a tender to understand", tender_titles)
            
            if selected:
                tender = next((t for t in tenders if t["title"] == selected), None)
                if tender:
                    st.markdown(f"### πŸ“Œ {tender['title']}")
                    st.markdown(f"**Department:** {tender['department']}")
                    st.markdown(f"**Closing Date:** {tender['closing_date']}")
                    st.markdown(f"[View Tender Detail]({tender['link']})")
                    
                    if st.button("🧠 Summarize and Explain This Tender"):
                        with st.spinner("Fetching tender details..."):
                            content = fetch_tender_details(tender['link'])
                        
                        if content:
                            prompt = f"This is a government tender document from {tender['department']}. The title is: {tender['title']}.\n\nHere's some content from the tender:\n\n{content}\n\nExplain this tender for a Pakistani citizen. What are the key requirements? Keep your response brief and focus on practical information."
                            
                            with st.spinner("Generating explanation..."):
                                summary = llm(prompt)
                            
                            st.write(summary)
                        else:
                            st.warning("Unable to fetch tender details. The document might be in PDF format or require login.")
    except Exception as e:
        st.error(f"Error displaying active tenders: {str(e)}")
        st.info("Try refreshing the page or check your internet connection.")

# PPRA Resources Tab
with tab3:
    st.header("πŸ“š PPRA Official Resources")
    st.markdown("Below are official links to all relevant PPRA documentation and tender policies.")
    resources = get_ppra_resources()
    
    # Group resources by category for better organization
    categories = {
        "Main Links": ["Home", "Active Tenders"],
        "Guidelines & Documents": ["Procurement Guidelines (PDF)", "PPRA Ordinance", "Rules"],
        "Regulations": [k for k in resources.keys() if "Regulation" in k or "SRO" in k],
        "Other Resources": ["Board Info", "Blacklisting & Debarment Regulations 2024"]
    }
    
    for category, resource_keys in categories.items():
        st.subheader(category)
        for key in resource_keys:
            if key in resources:
                st.markdown(f"- [{key}]({resources[key]})")