Spaces:
Sleeping
Sleeping
Download lambda-deployment/main.py from mousom/caltrans-pt: direct link, hf CLI and curl.
- Browser
- Download file 51.9 kB
-
https://huggingface.co/spaces/mousom/caltrans-pt/resolve/main/lambda-deployment/main.py
- Command line
-
hf download hf://spaces/mousom/caltrans-pt/lambda-deployment/main.py
-
curl -L -o main.py https://huggingface.co/spaces/mousom/caltrans-pt/resolve/main/lambda-deployment/main.py
51.9 kB
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from typing import Dict, List, Optional, Any
import requests
from bs4 import BeautifulSoup
import re
import time
import logging
from urllib.parse import urlparse
from datetime import datetime
import uvicorn
import os
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# FastAPI app initialization
app = FastAPI(
title="Caltrans Payment Tracking System",
description="API for retrieving contract payment history and detailed monthly estimates",
version="1.0.0"
)
# Pydantic Models
class PaymentRecord(BaseModel):
estimate_number: str = Field(..., description="Estimate number")
detail_link: Optional[str] = Field(None, description="Link to payment details")
voucher_link: Optional[str] = Field(None, description="Link to voucher")
type: str = Field(..., description="Payment type")
payment_type: str = Field(..., description="Payment classification")
release_date: str = Field(..., description="Payment release date")
held_amount: float = Field(..., description="Amount held")
disbursed_amount: float = Field(..., description="Amount disbursed")
class ContractDetails(BaseModel):
contract_number: str = Field(..., description="Contract number")
contractor_name: Optional[str] = Field(None, description="Contractor name")
last_updated: Optional[str] = Field(None, description="Last update date")
job_description: Optional[str] = Field(None, description="Job description")
contract_accepted: Optional[str] = Field(None, description="Contract acceptance date")
stop_notice_deadline: Optional[str] = Field(None, description="Stop notice deadline")
suit_filing_expiration: Optional[str] = Field(None, description="Suit filing expiration")
estimated_completion: Optional[str] = Field(None, description="Estimated completion date")
current_withhold: Optional[float] = Field(None, description="Current withhold amount")
currently_held: Optional[float] = Field(None, description="Currently held amount")
need_to_hold: Optional[float] = Field(None, description="Amount needed to hold")
class ContactInfo(BaseModel):
email: Optional[str] = Field(None, description="Contact email")
phone: Optional[str] = Field(None, description="Contact phone")
class PaymentSummary(BaseModel):
total_payments: int = Field(..., description="Total number of payments")
total_disbursed: float = Field(..., description="Total amount disbursed")
total_held: float = Field(..., description="Total amount held")
latest_payment_date: str = Field(..., description="Date of latest payment")
class Quantities(BaseModel):
original: float = Field(..., description="Original quantity")
this_period: float = Field(..., description="This period quantity")
percent_this_period: float = Field(..., description="Percentage this period")
job_to_date: float = Field(..., description="Job to date quantity")
percent_jtd: float = Field(..., description="Percentage job to date")
class Amounts(BaseModel):
original: float = Field(..., description="Original amount")
this_period: float = Field(..., description="This period amount")
job_to_date: float = Field(..., description="Job to date amount")
moh: float = Field(..., description="Materials on hand")
class LineItem(BaseModel):
item_number: str = Field(..., description="Item number")
revenue_code: str = Field(..., description="Revenue code")
description: str = Field(..., description="Work description")
sub_item: str = Field(..., description="Y=Subcontracted, N=Self-performed")
quantities: Quantities
units: str = Field(..., description="Unit of measurement")
unit_price: float = Field(..., description="Unit price")
amounts: Amounts
class DetailedPaymentRecord(BaseModel):
estimate_number: str = Field(..., description="Estimate number")
detail_link: Optional[str] = Field(None, description="Link to payment details")
voucher_link: Optional[str] = Field(None, description="Link to voucher")
type: str = Field(..., description="Payment type")
payment_type: str = Field(..., description="Payment classification")
release_date: str = Field(..., description="Payment release date")
held_amount: float = Field(..., description="Amount held")
disbursed_amount: float = Field(..., description="Amount disbursed")
detailed_estimate: Optional[Dict[str, Any]] = Field(None, description="Detailed CAS145 estimate data")
class MonthlyPaymentSummary(BaseModel):
month: str = Field(..., description="Month in YYYY-MM format")
payment_count: int = Field(..., description="Number of payments in month")
total_disbursed: float = Field(..., description="Total disbursed in month")
total_held: float = Field(..., description="Total held in month")
payments: List[DetailedPaymentRecord] = Field(..., description="Individual payments with detailed estimates")
class ContractResponse(BaseModel):
contract_details: ContractDetails
payment_history: List[PaymentRecord]
contact_info: ContactInfo
summary: PaymentSummary
monthly_breakdown: Dict[str, float] = Field(..., description="Monthly disbursement breakdown")
scraped_at: str = Field(..., description="Timestamp when data was scraped")
class CaltransPETSScraper:
"""
Powerful web scraper for California Department of Transportation (Caltrans)
Payment Estimation Tracking System (PETS)
"""
def __init__(self, base_url: str = "https://misc-external.dot.ca.gov/pets/",
delay: float = 1.0, timeout: int = 30):
"""
Initialize the scraper
Args:
base_url: Base URL for the PETS system
delay: Delay between requests (seconds)
timeout: Request timeout (seconds)
"""
self.base_url = base_url
self.delay = delay
self.timeout = timeout
self.session = requests.Session()
# Set up headers to mimic a real browser
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
})
# Set up logging
self.logger = logging.getLogger(__name__)
def _make_request(self, url: str, method: str = 'GET', **kwargs) -> Optional[requests.Response]:
"""Make a safe HTTP request with error handling"""
try:
self.logger.info(f"Making {method} request to: {url}")
if method.upper() == 'GET':
response = self.session.get(url, timeout=self.timeout, **kwargs)
else:
response = self.session.post(url, timeout=self.timeout, **kwargs)
response.raise_for_status()
time.sleep(self.delay) # Respect server
return response
except requests.exceptions.RequestException as e:
self.logger.error(f"Request failed for {url}: {str(e)}")
return None
def extract_contract_details(self, soup: BeautifulSoup) -> Dict[str, any]:
"""Extract contract details from a contract page"""
contract_info = {}
try:
# Extract contract number and contractor name from header
header = soup.find('h1', class_='rpt77tx')
if header:
header_text = header.get_text(strip=True)
# Extract contract number (format: 033F0704)
contract_match = re.search(r'Contract:\s*(\w+)', header_text)
if contract_match:
contract_info['contract_number'] = contract_match.group(1)
# Extract contractor name
lines = header_text.split('\n')
if len(lines) > 1:
contract_info['contractor_name'] = lines[1].strip()
# Extract date last updated
date_elem = soup.find('div', class_='rpt77b')
if date_elem and 'Date last updated:' in date_elem.get_text():
date_text = date_elem.get_text(strip=True)
date_match = re.search(r'Date last updated:\s*(\d{2}/\d{2}/\d{2})', date_text)
if date_match:
contract_info['last_updated'] = date_match.group(1)
# Extract contract details from the list
details_list = soup.find('ul', class_='rpt77')
if details_list:
for li in details_list.find_all('li'):
text = li.get_text(strip=True)
if 'Job Description:' in text:
# Extract job description from blockquote
blockquote = li.find('blockquote')
if blockquote:
contract_info['job_description'] = blockquote.get_text(strip=True)
elif 'Contract Accepted:' in text:
contract_info['contract_accepted'] = text.split(':', 1)[1].strip()
elif 'Stop Notice filing deadline:' in text:
contract_info['stop_notice_deadline'] = text.split(':', 1)[1].strip()
elif 'Expiration of Suit-filing period:' in text:
contract_info['suit_filing_expiration'] = text.split(':', 1)[1].strip()
elif 'Estimated Completion:' in text:
completion_text = text.split(':', 1)[1].strip()
contract_info['estimated_completion'] = completion_text
elif 'Current Withhold Obligations:' in text:
amount = re.search(r'\$([0-9,]+\.\d{2})', text)
if amount:
contract_info['current_withhold'] = float(amount.group(1).replace(',', ''))
elif 'Curently Held:' in text: # Note: typo in original
amount = re.search(r'\$([0-9,]+\.\d{2})', text)
if amount:
contract_info['currently_held'] = float(amount.group(1).replace(',', ''))
elif 'Need to Hold:' in text:
amount = re.search(r'\$([0-9,]+\.\d{2})', text)
if amount:
contract_info['need_to_hold'] = float(amount.group(1).replace(',', ''))
return contract_info
except Exception as e:
self.logger.error(f"Error extracting contract details: {str(e)}")
return contract_info
def extract_payment_history(self, soup: BeautifulSoup) -> List[Dict[str, any]]:
"""Extract payment history from the payment table"""
payments = []
try:
# Find the payment history table
payment_table = soup.find('table', class_='reporttablelft2')
if not payment_table:
self.logger.warning("Payment table not found")
return payments
# Find all data rows (skip header)
rows = payment_table.find_all('tr')[1:] # Skip header row
for row in rows:
cells = row.find_all('td')
if len(cells) >= 8: # Ensure we have enough columns
# Skip total row
if 'Total:' in cells[0].get_text(strip=True):
continue
payment = {}
# Extract estimate number
payment['estimate_number'] = cells[0].get_text(strip=True)
# Extract detail and voucher links (IMPORTANT!)
detail_link = cells[1].find('a')
if detail_link:
payment['detail_link'] = detail_link.get('href')
voucher_link = cells[2].find('a')
if voucher_link:
payment['voucher_link'] = voucher_link.get('href')
# Extract type
payment['type'] = cells[3].get_text(strip=True)
# Extract payment type
payment['payment_type'] = cells[4].get_text(strip=True)
# Extract release date
payment['release_date'] = cells[5].get_text(strip=True)
# Extract held amount
held_text = cells[6].get_text(strip=True).replace('$', '').replace(',', '')
try:
payment['held_amount'] = float(held_text) if held_text else 0.0
except ValueError:
payment['held_amount'] = 0.0
# Extract disbursed amount
disbursed_text = cells[7].get_text(strip=True).replace('$', '').replace(',', '')
try:
payment['disbursed_amount'] = float(disbursed_text) if disbursed_text else 0.0
except ValueError:
payment['disbursed_amount'] = 0.0
payments.append(payment)
return payments
except Exception as e:
self.logger.error(f"Error extracting payment history: {str(e)}")
return payments
def extract_contact_info(self, soup: BeautifulSoup) -> Dict[str, str]:
"""Extract contact information for payment inquiries"""
contact_info = {}
try:
# Look for contact information
contact_section = soup.find(text="Please direct Payment Inquiries to:")
if contact_section:
parent = contact_section.parent
if parent:
# Extract email
email_link = parent.find('a', href=re.compile(r'mailto:'))
if email_link:
contact_info['email'] = email_link.get('href').replace('mailto:', '').split('?')[0]
# Extract phone
phone_match = re.search(r'Phone:\s*\((\d{3})\)\s*(\d{3}-\d{4})', parent.get_text())
if phone_match:
contact_info['phone'] = f"({phone_match.group(1)}) {phone_match.group(2)}"
return contact_info
except Exception as e:
self.logger.error(f"Error extracting contact info: {str(e)}")
return contact_info
def parse_payment_date(self, date_str: str) -> datetime:
"""
Intelligently parse payment dates handling both 2-digit and 4-digit years
Args:
date_str: Date string in format "MM/DD/YY" or "MM/DD/YYYY"
Returns:
datetime object with correct year
Note:
For 2-digit years, assumes years 00-29 are 2000-2029 and years 30-99 are 1930-1999
This follows the "sliding window" approach used by many systems
"""
try:
# First try 4-digit year format
return datetime.strptime(date_str, '%m/%d/%Y')
except ValueError:
# If that fails, try 2-digit year format
try:
date_obj = datetime.strptime(date_str, '%m/%d/%y')
# Apply sliding window logic for 2-digit years
# Years 00-29 are interpreted as 2000-2029
# Years 30-99 are interpreted as 1930-1999
if date_obj.year < 2000:
# If year is less than 2000, it's likely from the 2000s
# Adjust based on current year context
current_year = datetime.now().year
if current_year >= 2020:
# We're in 2020s, so adjust accordingly
if date_obj.year < 30: # 00-29
date_obj = date_obj.replace(year=date_obj.year + 2000)
else: # 30-99
date_obj = date_obj.replace(year=date_obj.year + 1900)
else:
# We're in earlier years, use standard sliding window
if date_obj.year < 50: # 00-49
date_obj = date_obj.replace(year=date_obj.year + 2000)
else: # 50-99
date_obj = date_obj.replace(year=date_obj.year + 1900)
return date_obj
except ValueError:
raise ValueError(f"Unable to parse date: {date_str}. Expected format: MM/DD/YY or MM/DD/YYYY")
def scrape_contract(self, contract_number: str) -> Dict[str, any]:
"""Scrape complete contract information from a contract number"""
contract_url = f"{self.base_url}results.php?ctrnm={contract_number}"
response = self._make_request(contract_url)
if not response:
return {}
soup = BeautifulSoup(response.content, 'html.parser')
# Extract all information
contract_data = {
'url': contract_url,
'scraped_at': datetime.now().isoformat(),
'contract_details': self.extract_contract_details(soup),
'payment_history': self.extract_payment_history(soup),
'contact_info': self.extract_contact_info(soup)
}
# Calculate summary statistics
if contract_data['payment_history']:
total_disbursed = sum(p['disbursed_amount'] for p in contract_data['payment_history'])
total_held = sum(p['held_amount'] for p in contract_data['payment_history'])
contract_data['summary'] = {
'total_payments': len(contract_data['payment_history']),
'total_disbursed': total_disbursed,
'total_held': total_held,
'latest_payment_date': max((p['release_date'] for p in contract_data['payment_history'] if p['release_date']), default='N/A')
}
# Calculate monthly breakdown
monthly_breakdown = {}
for payment in contract_data['payment_history']:
if payment['release_date'] and payment['release_date'] != 'N/A':
try:
# Parse date and extract month - handle both 2-digit and 4-digit years intelligently
date_obj = self.parse_payment_date(payment['release_date'])
month_key = date_obj.strftime('%Y-%m')
if month_key not in monthly_breakdown:
monthly_breakdown[month_key] = 0.0
monthly_breakdown[month_key] += payment['disbursed_amount']
except ValueError:
continue
contract_data['monthly_breakdown'] = monthly_breakdown
return contract_data
class CAS145Parser:
"""
Parser for California DOT CAS145 Progress Estimate Reports
Converts CAS145 text format to GC Pay JSON format with proper calculations
"""
def __init__(self):
self.data = {
"prime_contract": {"items": [], "total": {}},
"change_orders": {"items": [], "total": {}},
"deductions": [],
"extra_work_totals": {
'total_this_estimate': 0.0,
'total_previous_estimate': 0.0,
'total_to_date': 0.0
}
}
self.main_estimate_no = None
def fetch_from_url(self, url: str) -> str:
"""Fetch content from URL"""
try:
response = requests.get(url, timeout=30)
response.raise_for_status()
return response.text
except requests.RequestException as e:
raise Exception(f"Failed to fetch URL: {e}")
def parse_content(self, content: str) -> Dict:
"""Parse CAS145 content"""
sections = self.split_sections(content)
self.parse_extra_work(sections.get('extra_work', ''))
self.parse_deductions(sections.get('deductions', ''))
self.parse_project_items(sections.get('items', ''))
self.calculate_totals()
return self.data
def split_sections(self, content: str) -> Dict[str, str]:
"""Split content into major sections"""
sections = {}
# Find section boundaries
extra_work_start = content.find('S C H E D U L E O F E X T R A W O R K')
deductions_start = content.find('S C H E D U L E O F D E D U C T I O N S')
items_start = content.find('P R O J E C T R E C O R D - E S T I M A T E')
# Extract sections
if extra_work_start > 0 and deductions_start > 0:
sections['extra_work'] = content[extra_work_start:deductions_start]
if deductions_start > 0 and items_start > 0:
sections['deductions'] = content[deductions_start:items_start]
if items_start > 0:
items_content = content[items_start:]
sections['items'] = items_content
return sections
def set_estimate_number(self, estimate_no: str):
"""Set estimate number from URL filename"""
self.main_estimate_no = estimate_no
def parse_extra_work(self, section: str):
"""Parse Schedule of Extra Work section with improved flexibility for various formats"""
if not section:
return
lines = section.split('\n')
parsed_count = 0
# Initialize totals tracking
self.data['extra_work_totals'] = {
'total_this_estimate': 0.0,
'total_previous_estimate': 0.0,
'total_to_date': 0.0
}
logger.info(f"Parsing extra work section with {len(lines)} lines")
for i, line in enumerate(lines):
# Skip empty lines
if not line.strip():
continue
# Extract totals for reference (but don't parse as line items)
line_lower = line.lower()
if 'total this estimate' in line_lower:
amount_match = re.search(r'([\d,]+\.\d{2})', line)
if amount_match:
self.data['extra_work_totals']['total_this_estimate'] = self.parse_currency(amount_match.group(1))
logger.debug(f"Extracted total this estimate: {self.data['extra_work_totals']['total_this_estimate']}")
continue
elif 'total previous estimate' in line_lower:
amount_match = re.search(r'([\d,]+\.\d{2})', line)
if amount_match:
self.data['extra_work_totals']['total_previous_estimate'] = self.parse_currency(amount_match.group(1))
logger.debug(f"Extracted total previous estimate: {self.data['extra_work_totals']['total_previous_estimate']}")
continue
elif 'total to date' in line_lower:
amount_match = re.search(r'([\d,]+\.\d{2})', line)
if amount_match:
self.data['extra_work_totals']['total_to_date'] = self.parse_currency(amount_match.group(1))
logger.debug(f"Extracted total to date: {self.data['extra_work_totals']['total_to_date']}")
continue
# Skip other total and summary lines
if any(total_indicator in line_lower for total_indicator in [
'total:',
'total ',
'subtotal',
'grand total'
]):
logger.debug(f"Skipping total line {i+1}: {line.strip()}")
continue
logger.debug(f"Processing line {i+1}: {line.strip()}")
# Try to parse the line using our helper method
parsed_item = self.parse_extra_work_line(line)
if parsed_item:
self.data['change_orders']['items'].append(parsed_item)
parsed_count += 1
logger.debug(f"Successfully parsed line {i+1} as {parsed_item['change_order_no']}: {parsed_item['description']}")
continue
# If the helper method didn't parse it, try some additional fallback patterns
# Look for lines that might contain extra work information but don't fit standard patterns
# Pattern: Lines with amounts and dates that might be extra work
amount_date_match = re.search(r'([\d,]+\.\d{2})\s+(\d{2}/\d{2}/\d{2})', line)
if amount_date_match and ('E.W.' in line or 'EXTRA' in line.upper()):
amount = self.parse_currency(amount_date_match.group(1))
date = amount_date_match.group(2)
# Extract any other meaningful information
identifier = self.extract_identifier_from_line(line)
cco_item = {
"change_order_no": "EW_DATE",
"revenue_code": "",
"description": f"Extra Work by Date: {date} - {identifier}",
"sub_item": "",
"original_qty": 0,
"this_period_qty": 0,
"job_to_date_qty": 0,
"units": "LS",
"unit_price": amount,
"original_amt": 0,
"this_period_amt": amount,
"job_to_date_amt": amount
}
self.data['change_orders']['items'].append(cco_item)
parsed_count += 1
logger.debug(f"Parsed line {i+1} as EW_DATE: {cco_item['description']}")
continue
# Pattern: Lines that just have amounts and might be extra work
# This is a very permissive fallback for lines that contain amounts
if 'E.W.' in line or 'EXTRA' in line.upper():
amount_match = re.search(r'([\d,]+\.\d{2})', line)
if amount_match:
amount = self.parse_currency(amount_match.group(1))
identifier = self.extract_identifier_from_line(line)
cco_item = {
"change_order_no": "EW_FALLBACK",
"revenue_code": "",
"description": f"Extra Work (Fallback): {identifier}",
"sub_item": "",
"original_qty": 0,
"this_period_qty": 0,
"job_to_date_qty": 0,
"units": "LS",
"unit_price": amount,
"original_amt": 0,
"this_period_amt": amount,
"job_to_date_amt": amount
}
self.data['change_orders']['items'].append(cco_item)
parsed_count += 1
logger.debug(f"Parsed line {i+1} as EW_FALLBACK: {cco_item['description']}")
continue
logger.info(f"Successfully parsed {parsed_count} extra work items out of {len(lines)} lines")
logger.info(f"Extra work totals: This estimate: {self.data['extra_work_totals']['total_this_estimate']}, "
f"Previous: {self.data['extra_work_totals']['total_previous_estimate']}, "
f"To date: {self.data['extra_work_totals']['total_to_date']}")
def parse_extra_work_line(self, line: str) -> Optional[Dict]:
"""
Helper method to parse individual extra work lines with various formats
Args:
line: The line to parse
Returns:
Parsed change order item or None if not a valid extra work line
"""
line = line.strip()
if not line:
return None
logger.debug(f"Attempting to parse line: {line}")
# Try different patterns to extract information
patterns = [
# Pattern 1: Standard CCO format
(r'(\d{3})\s+(\d{4})\s+([\d,]+\.\d{2})\s+E\.W\.\s+@\s+F\.A\.', 'CCO'),
# Pattern 2: Continuation line
(r'^\s+(\d{4})\s+([\d,]+\.\d{2})', 'CONT'),
# Pattern 3: Extra work with amount
(r'([\d,]+\.\d{2})\s+E\.W\.', 'EW'),
# Pattern 4: Generic amount line
(r'([\d,]+\.\d{2})', 'GENERIC')
]
for pattern, cco_type in patterns:
match = re.search(pattern, line)
if match:
logger.debug(f"Matched pattern {cco_type} for line: {line}")
if cco_type == 'CCO':
amount = self.parse_currency(match.group(3))
return {
"change_order_no": f"{match.group(2)[0]}",
"revenue_code": "",
"description": f"CCO {match.group(1)}-{match.group(2)}: E.W. @",
"sub_item": "",
"original_qty": 0,
"this_period_qty": 0,
"job_to_date_qty": 0,
"units": "LS",
"unit_price": amount,
"original_amt": 0,
"this_period_amt": amount,
"job_to_date_amt": amount
}
elif cco_type == 'CONT':
amount = self.parse_currency(match.group(2))
return {
"change_order_no": "CONT",
"revenue_code": "",
"description": f"Extra Work Continuation: {match.group(1)}",
"sub_item": "",
"original_qty": 0,
"this_period_qty": 0,
"job_to_date_qty": 0,
"units": "LS",
"unit_price": amount,
"original_amt": 0,
"this_period_amt": amount,
"job_to_date_amt": amount
}
elif cco_type in ['EW', 'GENERIC']:
amount = self.parse_currency(match.group(1))
# Extract identifier
identifier = self.extract_identifier_from_line(line)
return {
"change_order_no": cco_type,
"revenue_code": "",
"description": f"Extra Work: {identifier}",
"sub_item": "",
"original_qty": 0,
"this_period_qty": 0,
"job_to_date_qty": 0,
"units": "LS",
"unit_price": amount,
"original_amt": 0,
"this_period_amt": amount,
"job_to_date_amt": amount
}
logger.debug(f"No patterns matched for line: {line}")
return None
def extract_identifier_from_line(self, line: str) -> str:
"""
Extract meaningful identifier from a line
Args:
line: The line to extract identifier from
Returns:
Extracted identifier or "Unknown"
"""
line_parts = line.strip().split()
for part in line_parts:
# Look for 4-digit numbers (likely dates or report numbers)
if re.match(r'^\d{4}$', part):
return part
# Look for 3-digit numbers (likely CCO numbers)
elif re.match(r'^\d{3}$', part):
return part
# Look for alphanumeric codes
elif re.match(r'^[A-Z0-9]+$', part):
return part
return "Unknown"
def parse_deductions(self, section: str):
"""Parse Schedule of Deductions section"""
if not section:
return
lines = section.split('\n')
current_category = ""
deductions_list = []
for line in lines:
# Identify category
if 'ADMINISTRATIVE' in line:
current_category = "Administrative"
elif 'LABOR COMPLIANCE' in line:
current_category = "Labor Compliance"
elif 'LIQUIDATED DAMAGES' in line:
current_category = "Liquidated Damages"
elif 'OVERBID ITEMS' in line:
current_category = "Overbid Items"
# Skip total lines
if 'TOTAL DEDUCTIONS' in line:
break
# Parse deduction lines
if current_category and re.search(r'[-\d,]+\.\d{2}', line):
# Pattern to match deduction lines
pattern = r'([A-Z][A-Z0-9\s/\-\.]+?)\s+([-\d,]+\.\d{2})\s+(\d{3})'
match = re.search(pattern, line)
if match:
description = match.group(1).strip()
amount = self.parse_currency(match.group(2))
est_no = match.group(3)
deduction = {
"estimate_no": est_no,
"revenue_code": "",
"description": f"{current_category}: {description}",
"original": 0,
"this_period": amount,
"job_to_date": amount
}
deductions_list.append(deduction)
self.data['deductions'] = [d for d in deductions_list if 'TOTAL DEDUCTIONS' not in d['description']]
def parse_project_items(self, section: str):
"""Parse Project Record items table"""
if not section:
return
lines = section.split('\n')
current_item = None
items = []
for i, line in enumerate(lines):
# Skip header lines
if 'ITEM' in line and 'DESCRIPTION' in line:
continue
if '---' in line:
continue
if not line.strip():
continue
# Check if line starts with item number (3 digits)
if re.match(r'^\d{3}\s', line):
# Save previous item if exists
if current_item:
items.append(current_item)
# Start new item
current_item = self.parse_item_line(line)
# Check for (F) marker on current or next line
elif current_item:
if '(F)' in line and len(line) < 10:
current_item['sub_item'] = 'Y'
# Add last item
if current_item:
items.append(current_item)
self.data['prime_contract']['items'] = items
def parse_item_line(self, line: str) -> Dict:
"""Parse a single item line from the project record"""
item = {
"item_number": "",
"revenue_code": "",
"description": "",
"sub_item": "N",
"quantities": {
"original": 0.0,
"this_period": 0.0,
"percent_this_period": 0.0,
"job_to_date": 0.0,
"percent_jtd": 0.0
},
"units": "",
"unit_price": 0.0,
"amounts": {
"original": 0.0,
"this_period": 0.0,
"job_to_date": 0.0,
"moh": 0.0
}
}
# Parse by column positions (approximate)
try:
# Item number
item['item_number'] = line[:3].strip().zfill(3)
# Description
desc_end = 45
for unit in ['LS', 'EA', 'LF', 'SF', 'SY', 'CY', 'TON', 'TN', 'LB', 'HR', 'SQFT', 'SQYD', 'CF', 'ACRE']:
unit_pos = line[40:52].find(unit)
if unit_pos > -1:
desc_end = 40 + unit_pos
break
description = line[4:desc_end].strip()
# Check for (F) marker - indicates subcontracted work
if '(F)' in description:
item['sub_item'] = 'Y'
description = description.replace('(F)', '').strip()
elif '(F)' in line:
item['sub_item'] = 'Y'
item['description'] = description
# Find unit and parse numeric values
remaining = line[desc_end:].strip()
parts = remaining.split()
if parts:
# Unit
item['units'] = parts[0] if parts[0] in ['LS', 'EA', 'LF', 'SF', 'SY', 'CY', 'TON', 'TN', 'LB', 'HR', 'SQFT', 'SQYD', 'CF', 'ACRE'] else ''
# Parse numeric values
nums = []
for part in parts[1:]:
if re.match(r'^[\d,.-]+\.?\d*$', part):
nums.append(self.parse_number(part))
# Assign values based on position
if len(nums) > 0:
item['unit_price'] = nums[0]
if len(nums) > 1:
item['amounts']['original'] = nums[1]
# For LS items, original quantity is typically 1
if item['units'] == 'LS':
item['quantities']['original'] = 1.0
else:
# Back-calculate original quantity from amount and unit price
if item['unit_price'] > 0:
item['quantities']['original'] = item['amounts']['original'] / item['unit_price']
if len(nums) > 2:
item['quantities']['this_period'] = nums[2]
if len(nums) > 3:
item['amounts']['this_period'] = nums[3]
if len(nums) > 4:
item['quantities']['job_to_date'] = nums[4]
if len(nums) > 5:
item['amounts']['job_to_date'] = nums[5]
# Calculate percentages
if item['quantities']['original'] > 0:
if item['quantities']['this_period'] > 0:
item['quantities']['percent_this_period'] = round(
(item['quantities']['this_period'] / item['quantities']['original']) * 100, 2
)
if item['quantities']['job_to_date'] > 0:
item['quantities']['percent_jtd'] = round(
(item['quantities']['job_to_date'] / item['quantities']['original']) * 100, 2
)
except Exception as e:
# Return item with defaults if parsing fails
pass
return item
def parse_currency(self, value_str: str) -> float:
"""Parse currency string to float"""
if not value_str:
return 0.0
try:
clean = value_str.replace(',', '').replace('$', '').strip()
if clean.startswith('(') and clean.endswith(')'):
clean = '-' + clean[1:-1]
return float(clean)
except:
return 0.0
def parse_number(self, value_str: str) -> float:
"""Parse numeric string to float"""
if not value_str:
return 0.0
try:
clean = value_str.replace(',', '').strip()
return float(clean)
except:
return 0.0
def calculate_totals(self):
"""Calculate all totals from the parsed items"""
# Prime contract totals
prime_total = {
"original": sum(item['amounts']['original'] for item in self.data['prime_contract']['items']),
"this_period": sum(item['amounts']['this_period'] for item in self.data['prime_contract']['items']),
"job_to_date": sum(item['amounts']['job_to_date'] for item in self.data['prime_contract']['items']),
"moh": 0.0
}
self.data['prime_contract']['total'] = prime_total
# Change order totals
co_total = {
"original": 0,
"this_period": sum(item['this_period_amt'] for item in self.data['change_orders']['items']),
"job_to_date": sum(item['job_to_date_amt'] for item in self.data['change_orders']['items'])
}
self.data['change_orders']['total'] = co_total
# Calculate overall project totals including extra work
overall_total = {
"original": prime_total["original"],
"this_period": prime_total["this_period"] + co_total["this_period"],
"job_to_date": prime_total["job_to_date"] + co_total["job_to_date"],
"extra_work_this_estimate": self.data.get('extra_work_totals', {}).get('total_this_estimate', 0.0),
"extra_work_previous": self.data.get('extra_work_totals', {}).get('total_previous_estimate', 0.0),
"extra_work_to_date": self.data.get('extra_work_totals', {}).get('total_to_date', 0.0)
}
self.data['overall_totals'] = overall_total
# Store estimate number in data
self.data['main_estimate_no'] = self.main_estimate_no
# Log summary information
logger.info(f"Calculated totals for estimate {self.main_estimate_no}:")
logger.info(f" Prime contract: ${overall_total['original']:,.2f} original, ${overall_total['job_to_date']:,.2f} to date")
logger.info(f" Change orders: ${co_total['this_period']:,.2f} this period, ${co_total['job_to_date']:,.2f} to date")
logger.info(f" Extra work: ${overall_total['extra_work_this_estimate']:,.2f} this estimate, ${overall_total['extra_work_to_date']:,.2f} to date")
logger.info(f" Overall: ${overall_total['job_to_date']:,.2f} total to date")
def parse_from_url(self, url: str) -> Dict:
"""Parse a CAS145 file from URL"""
try:
# Extract estimate number from URL
url_parts = urlparse(url)
filename = os.path.basename(url_parts.path)
if filename.endswith('.txt'):
base_name = filename.replace('.txt', '')
match = re.search(r'(\d{3})$', base_name)
if match:
estimate_no = match.group(1)
self.set_estimate_number(estimate_no)
# Fetch and parse content
content = self.fetch_from_url(url)
return self.parse_content(content)
except Exception as e:
logger.error(f"Error parsing CAS145 from URL {url}: {str(e)}")
return {}
# Initialize scrapers
pets_scraper = CaltransPETSScraper()
cas145_parser = CAS145Parser()
# API Endpoints
@app.get("/")
async def root():
"""Root endpoint with API information"""
return {
"message": "Caltrans Payment Tracking API",
"version": "1.0.0",
"endpoints": {
"get_contract_payments": "/contracts/{contract_number}/payments",
"get_monthly_payments_with_details": "/contracts/{contract_number}/payments/monthly/{month}",
"health_check": "/health"
},
"workflow": {
"basic_payments": "Scrapes PETS system for payment history",
"monthly_details": "Scrapes PETS + follows detail_link to get CAS145 estimate details"
}
}
@app.get("/health")
async def health_check():
"""Health check endpoint"""
return {"status": "healthy", "timestamp": datetime.now().isoformat()}
@app.get("/contracts/{contract_number}/payments", response_model=ContractResponse)
async def get_contract_payments(contract_number: str):
"""
Retrieve complete payment history for a contract (basic PETS data only)
Args:
contract_number: The contract number to search for (e.g., '033F0704')
Returns:
Complete contract information including payment history from PETS system
"""
try:
logger.info(f"Fetching payment data for contract: {contract_number}")
contract_data = pets_scraper.scrape_contract(contract_number)
if not contract_data or not contract_data.get('contract_details'):
raise HTTPException(
status_code=404,
detail=f"Contract {contract_number} not found or no data available"
)
contract_details = contract_data.get('contract_details', {})
if not contract_details.get('contract_number'):
contract_details['contract_number'] = contract_number
payment_history = contract_data.get('payment_history', [])
contact_info = contract_data.get('contact_info', {})
summary = contract_data.get('summary', {
'total_payments': 0,
'total_disbursed': 0.0,
'total_held': 0.0,
'latest_payment_date': 'N/A'
})
monthly_breakdown = contract_data.get('monthly_breakdown', {})
return ContractResponse(
contract_details=ContractDetails(**contract_details),
payment_history=[PaymentRecord(**payment) for payment in payment_history],
contact_info=ContactInfo(**contact_info),
summary=PaymentSummary(**summary),
monthly_breakdown=monthly_breakdown,
scraped_at=contract_data.get('scraped_at', datetime.now().isoformat())
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Error processing contract {contract_number}: {str(e)}")
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
@app.get("/contracts/{contract_number}/payments/monthly/{month}", response_model=MonthlyPaymentSummary)
async def get_monthly_payments(contract_number: str, month: str):
"""
Retrieve detailed payment information for a specific month
This endpoint:
1. Scrapes PETS system to get payment history
2. Filters payments for the specified month
3. For each payment in that month, follows the detail_link
4. Parses the detailed CAS145 estimate information using main.py parser
Args:
contract_number: The contract number to search for
month: Month in YYYY-MM format (e.g., '2024-12' for December 2024)
Note:
Handles both 2-digit and 4-digit year formats in payment dates (e.g., "12/06/24" or "12/06/2024")
Returns:
Monthly payment summary with detailed CAS145 estimate data for each payment
"""
try:
# Validate month format
try:
datetime.strptime(month, '%Y-%m')
except ValueError:
raise HTTPException(
status_code=400,
detail="Month must be in YYYY-MM format (e.g., '2024-12')"
)
logger.info(f"Fetching detailed monthly payment data for contract: {contract_number}, month: {month}")
contract_data = pets_scraper.scrape_contract(contract_number)
if not contract_data or not contract_data.get('payment_history'):
raise HTTPException(
status_code=404,
detail=f"Contract {contract_number} not found or no payment history available"
)
monthly_payments = []
total_disbursed = 0.0
total_held = 0.0
for payment in contract_data['payment_history']:
if payment['release_date'] and payment['release_date'] != 'N/A':
try:
date_obj = pets_scraper.parse_payment_date(payment['release_date'])
payment_month = date_obj.strftime('%Y-%m')
if payment_month == month:
monthly_payments.append(payment)
total_disbursed += payment['disbursed_amount']
total_held += payment['held_amount']
except ValueError:
continue
if not monthly_payments:
raise HTTPException(
status_code=404,
detail=f"No payments found for contract {contract_number} in month {month}"
)
detailed_monthly_payments = []
for payment in monthly_payments:
detailed_payment = payment.copy()
if payment.get('detail_link'):
try:
logger.info(f"Fetching detailed estimate for payment {payment['estimate_number']} from {payment['detail_link']}")
parser = CAS145Parser()
detailed_estimate = parser.parse_from_url(payment['detail_link'])
if detailed_estimate:
detailed_payment['detailed_estimate'] = detailed_estimate
logger.info(f"Successfully parsed detailed estimate for payment {payment['estimate_number']}")
else:
logger.warning(f"No detailed estimate data found for payment {payment['estimate_number']}")
detailed_payment['detailed_estimate'] = None
except Exception as e:
logger.error(f"Error fetching detailed estimate for payment {payment['estimate_number']}: {str(e)}")
detailed_payment['detailed_estimate'] = None
else:
logger.warning(f"No detail_link found for payment {payment['estimate_number']}")
detailed_payment['detailed_estimate'] = None
detailed_monthly_payments.append(detailed_payment)
return MonthlyPaymentSummary(
month=month,
payment_count=len(detailed_monthly_payments),
total_disbursed=total_disbursed,
total_held=total_held,
payments=[DetailedPaymentRecord(**payment) for payment in detailed_monthly_payments]
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Error processing monthly data for contract {contract_number}, month {month}: {str(e)}")
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
if __name__ == "__main__":
uvicorn.run(
"main:app",
host="0.0.0.0",
port=8000,
reload=True,
log_level="info"
)
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from typing import Dict, List, Optional, Any
import requests
from bs4 import BeautifulSoup
import re
import time
import logging
from urllib.parse import urlparse
from datetime import datetime
import uvicorn
import os
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# FastAPI app initialization
app = FastAPI(
title="Caltrans Payment Tracking System",
description="API for retrieving contract payment history and detailed monthly estimates",
version="1.0.0"
)
# Pydantic Models
class PaymentRecord(BaseModel):
estimate_number: str = Field(..., description="Estimate number")
detail_link: Optional[str] = Field(None, description="Link to payment details")
voucher_link: Optional[str] = Field(None, description="Link to voucher")
type: str = Field(..., description="Payment type")
payment_type: str = Field(..., description="Payment classification")
release_date: str = Field(..., description="Payment release date")
held_amount: float = Field(..., description="Amount held")
disbursed_amount: float = Field(..., description="Amount disbursed")
class ContractDetails(BaseModel):
contract_number: str = Field(..., description="Contract number")
contractor_name: Optional[str] = Field(None, description="Contractor name")
last_updated: Optional[str] = Field(None, description="Last update date")
job_description: Optional[str] = Field(None, description="Job description")
contract_accepted: Optional[str] = Field(None, description="Contract acceptance date")
stop_notice_deadline: Optional[str] = Field(None, description="Stop notice deadline")
suit_filing_expiration: Optional[str] = Field(None, description="Suit filing expiration")
estimated_completion: Optional[str] = Field(None, description="Estimated completion date")
current_withhold: Optional[float] = Field(None, description="Current withhold amount")
currently_held: Optional[float] = Field(None, description="Currently held amount")
need_to_hold: Optional[float] = Field(None, description="Amount needed to hold")
class ContactInfo(BaseModel):
email: Optional[str] = Field(None, description="Contact email")
phone: Optional[str] = Field(None, description="Contact phone")
class PaymentSummary(BaseModel):
total_payments: int = Field(..., description="Total number of payments")
total_disbursed: float = Field(..., description="Total amount disbursed")
total_held: float = Field(..., description="Total amount held")
latest_payment_date: str = Field(..., description="Date of latest payment")
class Quantities(BaseModel):
original: float = Field(..., description="Original quantity")
this_period: float = Field(..., description="This period quantity")
percent_this_period: float = Field(..., description="Percentage this period")
job_to_date: float = Field(..., description="Job to date quantity")
percent_jtd: float = Field(..., description="Percentage job to date")
class Amounts(BaseModel):
original: float = Field(..., description="Original amount")
this_period: float = Field(..., description="This period amount")
job_to_date: float = Field(..., description="Job to date amount")
moh: float = Field(..., description="Materials on hand")
class LineItem(BaseModel):
item_number: str = Field(..., description="Item number")
revenue_code: str = Field(..., description="Revenue code")
description: str = Field(..., description="Work description")
sub_item: str = Field(..., description="Y=Subcontracted, N=Self-performed")
quantities: Quantities
units: str = Field(..., description="Unit of measurement")
unit_price: float = Field(..., description="Unit price")
amounts: Amounts
class DetailedPaymentRecord(BaseModel):
estimate_number: str = Field(..., description="Estimate number")
detail_link: Optional[str] = Field(None, description="Link to payment details")
voucher_link: Optional[str] = Field(None, description="Link to voucher")
type: str = Field(..., description="Payment type")
payment_type: str = Field(..., description="Payment classification")
release_date: str = Field(..., description="Payment release date")
held_amount: float = Field(..., description="Amount held")
disbursed_amount: float = Field(..., description="Amount disbursed")
detailed_estimate: Optional[Dict[str, Any]] = Field(None, description="Detailed CAS145 estimate data")
class MonthlyPaymentSummary(BaseModel):
month: str = Field(..., description="Month in YYYY-MM format")
payment_count: int = Field(..., description="Number of payments in month")
total_disbursed: float = Field(..., description="Total disbursed in month")
total_held: float = Field(..., description="Total held in month")
payments: List[DetailedPaymentRecord] = Field(..., description="Individual payments with detailed estimates")