File size: 14,858 Bytes
ad1a399
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import mimetypes
import time
import logging
import pandas as pd
import requests
import google.generativeai as genai
import pypdf
from tabulate import tabulate

gemini_api_key = "AIzaSyDC5D6SFk4SRlPzBGmXGwQZBtFd5jXr384" ###Use own API key

# Configure logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")

# Altered project path structure
# Assuming the script is located in the project root:
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
DATA_DIR = os.path.join(BASE_DIR, "data")
RESULTS_DIR = os.path.join(BASE_DIR, "results")
CSV_PATH = os.path.join(DATA_DIR, "output_new.csv")

def extract_text_from_proper_pdf(pdf_path):
    """

    Extracts text from a proper (digitally generated) PDF using pypdf.

    """
    logging.info(f"Extracting text from proper PDF: {pdf_path}")
    try:
        with open(pdf_path, "rb") as f:
            reader = pypdf.PdfReader(f)
            text = ""
            for page in reader.pages:
                page_text = page.extract_text()
                if page_text:
                    text += page_text
            if not text:
                logging.warning(f"No text found in proper PDF: {pdf_path}")
            return text
    except Exception as e:
        logging.error(f"Error extracting text from proper PDF {pdf_path}: {e}")
        return ""

def extract_text_with_gemini_ocr(pdf_path, gemini_api_key):
    """

    Extracts text from a scanned image PDF using Gemini multimodal OCR capabilities.

    """
    logging.info(f"Attempting OCR extraction for scanned PDF: {pdf_path}")
    try:
        genai.configure(api_key=gemini_api_key)
        mime_type, _ = mimetypes.guess_type(pdf_path)
        if mime_type is None:
            mime_type = "application/pdf"
            logging.warning(f"Could not guess MIME type for {pdf_path}, assuming {mime_type}")

        logging.info(f"Uploading file {pdf_path} with MIME type {mime_type}...")
        pdf_file = genai.upload_file(path=pdf_path, mime_type=mime_type)
        logging.info(f"File uploaded successfully: {pdf_file.name}")

        model = genai.GenerativeModel('gemini-1.5-flash-latest')
        max_attempts = 30
        attempts = 0
        while pdf_file.state.name == "PROCESSING" and attempts < max_attempts:
            print('.', end='', flush=True)
            time.sleep(10)
            pdf_file = genai.get_file(pdf_file.name)
            attempts += 1

        if attempts == max_attempts:
            logging.error("Error: File processing timed out.")
            return ""
        if pdf_file.state.name == "FAILED":
            logging.error(f"Error: File processing failed for {pdf_path}")
            return ""

        logging.info("\nFile processed. Sending prompt to Gemini for OCR text extraction...")
        prompt = "Extract all the text content from the provided document. Preserve formatting like paragraphs and tables as best as possible."
        response = model.generate_content([prompt, pdf_file])
        if response.parts:
            extracted_text = response.text
            logging.info(f"OCR text extraction successful (length: {len(extracted_text)} chars).")
            return extracted_text
        else:
            logging.warning("Gemini response contained no parts for text extraction.")
            logging.debug(f"Full Response: {response}")
            return ""
    except Exception as e:
        logging.error(f"An error occurred during Gemini OCR for {pdf_path}: {e}")
        return ""

def extract_tender_info(extracted_text, gemini_api_key):
    """

    Extracts structured tender information using Gemini API.

    """
    genai.configure(api_key=gemini_api_key)
    model = genai.GenerativeModel('gemini-1.5-flash-latest')
    prompt = f"""

Okay, here are prompt templates designed to extract the specified data points from State Transport Corporation (STC) tender documents. Each template includes a standardized name, a definition, and a prompt for extraction.

________________________________________Basic Tender Information

1.	Name: TenderBasic_Id

   Prompt: Extract the unique Tender ID.

2.	Name: TenderBasic_Title

   Prompt: Extract the complete Tender Title.

3.	Name: TenderBasic_IssuingStu

   Prompt: Extract the issuing State Transport Undertaking (STU) name.

4.	Name: TenderBasic_IssuingDepartment

   Prompt: Extract the Issuing Department name, if mentioned.

5.	Name: TenderBasic_State

   Prompt: Extract the State of operation.

6.	Name: TenderBasic_Type

   Prompt: Extract the Tender Type.

7.	Name: TenderBasic_Category

   Prompt: Extract the Tender Category.

8.	Name: TenderBasic_ProcurementMethod

   Prompt: Extract the Procurement Method and any bid conditions.

________________________________________Product/Service Details

9.	Name: Product_ItemCategory

   Prompt: Extract the main Item Category.

10.	Name: Product_ItemSubcategory

   Prompt: Extract the Item Subcategory, if specified.

11.	Name: Product_ItemCode

   Prompt: Extract the Item Code(s) or Part Number(s), if available.

12.	Name: Product_ItemDescription

   Prompt: Extract the detailed description for each required item.

13.	Name: Product_QuantityRequired

   Prompt: Extract the Quantity Required for each item.

14.	Name: Product_UnitOfMeasurement

   Prompt: Extract the Unit of Measurement.

15.	Name: Product_QualityStandards

   Prompt: Extract the Quality Standards or Certifications.

16.	Name: Product_WarrantyRequirements

   Prompt: Extract the details of the Warranty Period and Coverage.

17.	Name: Product_DeliveryLocation

   Prompt: Extract the Delivery Location(s).

18.	Name: Product_InstallationRequirements

   Prompt: Extract the installation requirements.

________________________________________Timeline Information

19.	Name: Timeline_PublicationDate

   Prompt: Extract the Tender Publication Date.

20.	Name: Timeline_BidSubmissionStartDate

   Prompt: Extract the Bid Submission Start Date and Time.

21.	Name: Timeline_BidSubmissionEndDate

   Prompt: Extract the Bid Submission End Date and Time.

22.	Name: Timeline_BidOpeningDate

   Prompt: Extract the Bid Opening Date and Time.

23.	Name: Timeline_DocDownloadStartDate

   Prompt: Extract the Document Download Start Date and Time.

24.	Name: Timeline_DocDownloadEndDate

   Prompt: Extract the Document Download End Date and Time.

25.	Name: Timeline_PreBidMeetingDate

   Prompt: Extract the Pre-Bid Meeting Date, Time, and Venue.

26.	Name: Timeline_ClarificationDeadline

   Prompt: Extract the Clarification Submission Deadline.

27.	Name: Timeline_ContractAwardDate

   Prompt: Extract the Contract Award Date, if mentioned.

28.	Name: Timeline_DeliveryPeriod

   Prompt: Extract the Delivery Timeline or Period.

________________________________________Financial Information

29.	Name: Financial_EstimatedValue

   Prompt: Extract the Estimated Contract Value or Cost.

30.	Name: Financial_EmdAmount

   Prompt: Extract the EMD Amount.

31.	Name: Financial_EmdExemption

   Prompt: Extract details about EMD Exemption eligibility.

32.	Name: Financial_TenderFee

   Prompt: Extract the Tender Fee amount and payment method.

33.	Name: Financial_TenderFeeExemption

   Prompt: Extract details about Tender Fee Exemption.

34.	Name: Financial_PerformanceSecurity

   Prompt: Extract the Performance Security details.

35.	Name: Financial_PaymentTerms

   Prompt: Extract the Payment Terms.

36.	Name: Financial_PriceRevisionTerms

   Prompt: Extract the Price Revision Terms.

________________________________________Documentation Requirements

37.	Name: Docs_RequiredGeneral

   Prompt: Extract the list of general technical and financial documents.

38.	Name: Docs_RequiredLegal

   Prompt: Extract the list of legal documents.

39.	Name: Docs_RequiredCompliance

   Prompt: Extract the list of compliance documents.

40.	Name: Docs_SubmissionFormat

   Prompt: Extract the required Format and Method of Submission.

________________________________________Contract Terms

41.	Name: Contract_Duration

   Prompt: Extract the Contract Duration.

42.	Name: Contract_ExtensionProvisions

   Prompt: Extract the Contract Extension provisions.

43.	Name: Contract_PenaltyClauses

   Prompt: Extract the Penalty Clauses.

44.	Name: Contract_DisputeResolution

   Prompt: Extract the Dispute Resolution mechanism.

45.	Name: Contract_ForceMajeure

   Prompt: Extract the Force Majeure conditions.

46.	Name: Contract_TerminationConditions

   Prompt: Extract the Termination Conditions.

47.	Name: Contract_ContinuingObligations

   Prompt: Extract any Continuing Obligations.

________________________________________Contact Information

48.	Name: Contact_PersonName

   Prompt: Extract the Contact Person's name.

49.	Name: Contact_PersonDesignation

   Prompt: Extract the Contact Person's designation.

50.	Name: Contact_PhoneNumber

   Prompt: Extract the Contact Phone Number(s).

51.	Name: Contact_Email

   Prompt: Extract the Contact Email Address(es).

52.	Name: Contact_OfficeAddress

   Prompt: Extract the Tender Office Address.

________________________________________Eligibility and Qualification Criteria

53.	Name: Eligibility_BidderNationality

   Prompt: Extract the required Bidder Nationality.

54.	Name: Eligibility_MinAnnualTurnover

   Prompt: Extract the Minimum Annual Turnover.

55.	Name: Eligibility_MinYearsExperience

   Prompt: Extract the Minimum Years of Experience.

56.	Name: Eligibility_SimilarWorkExperience

   Prompt: Extract the Similar Work Experience requirements.

57.	Name: Eligibility_IsoCertification

   Prompt: Extract any required ISO Certifications.

58.	Name: Eligibility_ManufacturingCapacity

   Prompt: Extract the Manufacturing Capacity requirements.

59.	Name: Eligibility_TechnicalCapability

   Prompt: Extract the required Technical Capabilities.

60.	Name: Eligibility_FinancialRatios

   Prompt: Extract any Financial Ratios requirements.

61.	Name: Eligibility_RegistrationRequirements

   Prompt: Extract the required Registration Requirements.

________________________________________

Tender Document Text:

{extracted_text}

Provide ONLY the extracted information in valid JSON format, without any introductory text, explanations, or markdown formatting.

    """
    try:
        response = model.generate_content(prompt)
        cleaned_text = response.text.strip()
        if cleaned_text.startswith("```json"):
            cleaned_text = cleaned_text[7:]
        if cleaned_text.endswith("```"):
            cleaned_text = cleaned_text[:-3]
        cleaned_text = cleaned_text.strip()
        extracted_data = json.loads(cleaned_text)
        return extracted_data
    except json.JSONDecodeError as e:
        logging.error(f"Error decoding JSON from Gemini response: {e}")
        logging.debug(f"--- Raw Response Text ---:\n{response.text}\n-------------------------")
        return {}
    except Exception as e:
        logging.error(f"An unexpected error occurred during Gemini processing: {e}")
        if 'response' in locals() and hasattr(response, 'text'):
            logging.debug(f"--- Raw Response Text ---:\n{response.text}\n-------------------------")
        return {}

def process_tender_documents():
    """

    Main function to process tender documents. It reads a CSV file that contains

    the file path and PDF type (e.g., 'Proper' for digital PDFs or 'Scanned' for image PDFs),

    extracts text using the appropriate method, and then extracts structured tender information.

    """
    gemini_api_key = input("Enter your Gemini API key: ").strip()
    os.makedirs(RESULTS_DIR, exist_ok=True)
    
    try:
        df_paths = pd.read_csv(CSV_PATH)
        # Ensure that a "PDF Type" column exists; if not, default all to "Scanned"
        if "PDF Type" not in df_paths.columns:
            df_paths["PDF Type"] = "Scanned Image PDF"
        file_info = df_paths[["Local PDF File", "PDF Type"]].dropna()
        file_info = file_info.iloc[:]  # Process only the first 10 files
    except Exception as e:
        logging.error(f"Error reading CSV file: {e}")
        return

    results = []
    for index, row in file_info.iterrows():
        # Assuming PDF paths in the CSV are relative to the data directory
        pdf_path = os.path.join(DATA_DIR, os.path.normpath(row["Local PDF File"]))
        pdf_type = str(row["PDF Type"]).strip().lower()
        if not os.path.exists(pdf_path):
            logging.warning(f"File not found: {pdf_path}. Skipping...")
            continue

        filename = os.path.basename(pdf_path)
        logging.info(f"Processing {filename} with PDF type: {pdf_type}...")

        # Choose extraction method based on PDF type
        if pdf_type in ["Proper PDF", ""]:
            extracted_text = extract_text_from_proper_pdf(pdf_path)
        else:
            extracted_text = extract_text_with_gemini_ocr(pdf_path, gemini_api_key)
        
        # Save extracted text to a .txt file
        text_filename = os.path.join(RESULTS_DIR, f"{os.path.splitext(filename)[0]}.txt")
        try:
            with open(text_filename, 'w', encoding='utf-8') as f:
                f.write(extracted_text)
            logging.info(f"Text extracted and saved to {text_filename}")
        except Exception as e:
            logging.error(f"Error saving extracted text for {filename}: {e}")

        # Extract structured tender information
        logging.info("Extracting tender information using Gemini...")
        tender_info_dict = extract_tender_info(extracted_text, gemini_api_key)
        if isinstance(tender_info_dict, dict) and tender_info_dict:
            tender_info_dict['filename'] = filename
            results.append(tender_info_dict)
            logging.info(f"Successfully extracted data for {filename}.")
        else:
            logging.warning(f"Could not extract structured data or received empty data for {filename}.")

    if results:
        df = pd.DataFrame(results)
        cols = df.columns.tolist()
        if 'filename' in cols:
            cols.remove('filename')
            cols = ['filename'] + cols
            df = df[cols]
        csv_output_path = os.path.join(RESULTS_DIR, "tender_results.csv")
        try:
            df.to_csv(csv_output_path, index=False)
            logging.info(f"Results saved to {csv_output_path}")
        except Exception as e:
            logging.error(f"Error saving results to CSV: {e}")
        print("\nExtracted Tender Information:")
        print(tabulate(df, headers='keys', tablefmt='grid'))
    else:
        logging.info("No results to display.")

def main():
    process_tender_documents()

if __name__ == "__main__":
    main()