
    ̞h@                        d Z ddlmZmZmZmZ ddlZ G d d      Z e       Zde	dee	   fdZ
d	e	de	fd
Zd	e	dee	   fdZedk(  r e       Z ed       ej!                  d      Zer1 eded            eded            eded            e        dZ ed        ede         edej'                  e               edej                  e              yy)z
Chicago Food Inspection Violation Code Lookup System
Based on FDA Food Code and Chicago Department of Public Health standards

This module provides comprehensive violation code explanations for
article generation and reader education.
    )DictOptionalListTupleNc                       e Zd ZdZd Zdeeef   fdZdeeef   fdZdeeef   fdZ	dede
e   fdZd	edee   fd
Zd	edefdZd	edeeef   fdZd	edee   fdZy)ViolationCodeLookupz
    Comprehensive violation code lookup system for Chicago food inspections.
    Based on FDA Food Code 2017/2022 and Chicago CDPH standards.
    c                     | j                         | _        | j                         | _        | j	                         | _        y )N)_build_violation_databaseviolation_codes_build_severity_mappingseverity_mapping_build_category_mappingcategory_mappingselfs    i/var/www/twin-digital-media/public_html/_sites/cleankitchens/production/scripts/violation_codes_lookup.py__init__zViolationCodeLookup.__init__   s5    #==? $ < < > $ < < >    returnc                     ddddddg ddd	d
dddddddgdd	ddddddddgdd	ddddddg ddd	d d!d"d#ddg d$d%d	d&d'd(d)ddg d*d+d	d,d-d.d/ddg d0d1d	d2d3d4d5ddg d6d7d	d8d9d:d;ddg d<d=d	d>	S )?zy
        Build comprehensive violation code database.
        Based on FDA Food Code and Chicago CDPH standards.
        z#Proper cooking time and temperaturezRFood must be cooked to safe minimum internal temperatures to kill harmful bacteriau   Bacteria are destroyed at high temperatures. Cook foods to these minimum internal temperatures: 165°F for poultry, 160°F for ground meat, 145°F for whole cuts of beef/pork.temperaturepriorityhigh)zInadequate cooking timeEquipment malfunctionzStaff training issueszEUse calibrated thermometers, train staff on proper cooking procedures)titledescriptiondetailscategoryseverityhealth_riskcommon_causes
preventionzApproved thawing methods usedz>Frozen foods must be thawed safely to prevent bacterial growthu   Safe thawing methods: refrigerator (41°F or below), cold running water, microwave, or as part of cooking process. Never thaw at room temperature.priority_foundationmediumzThawing at room temperaturezInadequate planningz<Plan ahead for safe thawing, train staff on approved methodszBUtensils, equipment and linens; properly stored, dried and handledzBClean equipment and utensils must be stored in sanitary conditionszClean equipment and utensils must be stored in clean, dry locations, protected from contamination. Handle by areas that don't contact food.	equipmentcorelowPoor storage practiceszContaminated storage areaszBImplement proper storage procedures, designate clean storage areaszUFood and non-food contact surfaces cleanable, properly designed, constructed and usedz;Equipment must be designed for easy cleaning and sanitationzFood contact surfaces must be smooth, non-absorbent, easily cleanable. Equipment must be properly maintained and used as designed.)zDamaged equipmentzImproper equipment designPoor maintenancez9Regular equipment maintenance, proper equipment selectionz@Warewashing facilities: installed, maintained, used; test stripszJDishwashing equipment must function properly with correct sanitizer levelszWarewashing equipment must maintain proper temperatures and sanitizer concentrations. Test strips must be available and used regularly.sanitization)r   z!Incorrect sanitizer concentrationzMissing test stripszJRegular equipment maintenance, monitor sanitizer levels, stock test stripsz5Adequate handwashing facilities supplied & accessiblez=Handwashing stations must be properly equipped and accessiblezHandwashing sinks must have hot and cold running water, soap, paper towels or air dryer. Must be accessible to employees at all times.
sanitation)zBlocked accesszMissing supplieszEquipment failurez;Regular supply checks, keep areas clear, maintain equipmentz+Plumbing installed; proper backflow devicesz8Plumbing systems must prevent contamination and backflowz|Plumbing must be installed to prevent cross-connections and backflow. Backflow prevention devices required where applicable.plumbing)zImproper installationzMissing backflow deviceszCross-connectionsz7Professional plumbing installation, regular inspectionsz$Refuse, recyclables properly removedz;Garbage and recyclables must be properly stored and removedzRefuse must be stored in leak-proof containers with tight-fitting lids, removed frequently enough to prevent pest attraction and odors.waste_management)zInfrequent removalzImproper containersr(   zARegular waste removal schedule, proper containers, staff trainingz1Physical facilities installed, maintained & cleanz<Building and facilities must be maintained in good conditionzFloors, walls, ceilings must be smooth, easily cleanable, and in good repair. Facilities must be kept clean and well-maintained.
facilities)r)   zDamaged surfaceszInadequate cleaningz?Regular maintenance schedule, prompt repairs, thorough cleaning)	183544474810515253 r   s    r   r
   z-ViolationCodeLookup._build_violation_database   sT    ?s M)&%!ne	 9_ p)1'"?AV!W\	 ^c i'"$":<X!Yb	 q\ `'1'!gY	 \k e*&%!vj	 Q^ d(&%!\[	 GY Z&1'!kW	 @\ e."$!ha	 M] ^("$!`_	{g
 g	
r   c                     ddddS )z=Map violation severity levels to human-readable descriptions.zECritical - Immediate health hazard that must be corrected immediatelyzSSerious - Potential health hazard that must be corrected within specified timeframez7Minor - Does not pose immediate threat to public healthr   r#   r&   r8   r   s    r   r   z+ViolationCodeLookup._build_severity_mapping   s     `#xM
 	
r   c           	          ddddddddd	S )
z)Map violation categories to descriptions.zTemperature ControlzEquipment & UtensilszSanitation & HygienezPlumbing & Water SystemszWaste ManagementzPhysical FacilitieszFood Handling & StoragezEmployee Health & Hygiene)r   r%   r+   r,   r-   r.   food_handlingemployee_healthr8   r   s    r   r   z+ViolationCodeLookup._build_category_mapping   s&     1/02 2/6:	
 		
r   codec                 0   t        j                  ddt        |            }|| j                  v rh| j                  |   j	                         }||d<   | j
                  j                  |d   d      |d<   | j                  j                  |d   d      |d	<   |S y
)a  
        Look up violation code and return comprehensive information.
        
        Args:
            code: Violation code (e.g., "52", "18", "44")
            
        Returns:
            Dictionary with violation information or None if not found
        z[^\d] r>   r   Unknownseverity_descriptionr   Othercategory_descriptionN)resubstrr   copyr   getr   )r   r>   
clean_code	violations       r   lookup_violationz$ViolationCodeLookup.lookup_violation   s     VVHb#d)4
---,,Z8==?I *If040E0E0I0I)T^J_aj0kI,-040E0E0I0I)T^J_ah0iI,-r   violations_textc                     |r|j                         dk(  rg S g }d}t        j                  ||      }|D ]'  }| j                  |      }|s|j	                  |       ) |S )a  
        Parse violations text from Chicago inspection data and return violation details.
        
        Args:
            violations_text: Raw violations text from inspection record
            
        Returns:
            List of violation dictionaries with explanations
        r@   z\b(\d{1,3})\b)striprE   findallrL   append)r   rM   
violationscode_patterncodesr>   violation_infos          r   parse_violations_textz)ViolationCodeLookup.parse_violations_text   sp     /"7"7"9R"?I
 (

<9 	2D!2248N!!.1	2
 r   c           	         | j                  |      }|syg }|D ]]  }ddddj                  |d   d      }| d|d    d	|d
    d|d    }|d   dk(  r|dz  }n|d   dk(  r|dz  }|j                  |       _ dj                  |      S )a  
        Generate reader-friendly explanation of violations for article content.
        
        Args:
            violations_text: Raw violations text from inspection record
            
        Returns:
            Formatted explanation suitable for article content
        z>No specific violations were detailed in the inspection report.u   🚨u   ⚠️u   📋r:   r   z **r   z	** (Code r>   z): r   r    r   zS This is considered a high-risk violation that could pose immediate health dangers.r$   z@ This violation creates potential health risks if not addressed.z

)rV   rI   rQ   join)r   rM   rR   explanationsrK   severity_emojiexplanations          r   explain_violations_for_articlez2ViolationCodeLookup.explain_violations_for_article   s     //@
S# 	-I"'/ c)J'0	  ,,C	'0B/C9YW]M^L__bclmzc{b|}K'61tt=)X5aa,	-  {{<((r   c                    | j                  |      }|s
dddddg ddS t        |      t        |D cg c]  }|d   dk(  s| c}      t        |D cg c]  }|d   dk(  s| c}      t        |D cg c]  }|d   dk(  s| c}      t        |D cg c]  }|d   d	k(  s| c}      t        t        |D cg c]  }|d
   	 c}            dd}|d   dkD  rd|d<   |S |d   dkD  rd|d<   |S c c}w c c}w c c}w c c}w c c}w )a  
        Get summary statistics about violations for article metadata.
        
        Args:
            violations_text: Raw violations text from inspection record
            
        Returns:
            Dictionary with violation summary statistics
        r   none)total_violationspriority_countpriority_foundation_count
core_counthigh_risk_count
categoriesworst_severityr   r   r#   r&   r    r   r   r`   re   ra   )rV   lenlistset)r   rM   rR   vsummarys        r   get_violation_summaryz)ViolationCodeLookup.get_violation_summary   s4    //@
$%"#-.#$ "(  !$J!j"XAjMZ<W1"XY),-nAq}XmGma-n)o*PQ*8OqPQ"z#X!Q}=MQW=WA#XYs:#FaAjM#FGH$
 #$q((2G$%  01A5(=G$% #Y-nP#X#Fs4   C2
C2
C7 C73C<C<D"D:Dc                    | j                  |      }g }|s|S t        |D cg c]  }|d   	 c}      }|D ]a  }| j                  j                  ||      }|j	                  d|        |j	                  |j                         j                  dd             c t        d |D              r|j                  ddg       n%t        d |D              r|j                  d	d
g       |D ]M  }|d   dv r|j	                  d       |d   dv r|j	                  d       5|d   dv s=|j	                  d       O t        t        |            S c c}w )z
        Generate tags for auto-tagging system based on violations.
        
        Args:
            violations_text: Raw violations text from inspection record
            
        Returns:
            List of tags for article auto-tagging
        r   z
violation- -c              3   ,   K   | ]  }|d    dk(    yw)r   r   Nr8   .0ri   s     r   	<genexpr>z9ViolationCodeLookup.get_violation_tags.<locals>.<genexpr>0  s     ?qq}
*?   zcritical-violationszimmediate-closure-riskc              3   ,   K   | ]  }|d    dk(    yw)r   r#   Nr8   rp   s     r   rr   z9ViolationCodeLookup.get_violation_tags.<locals>.<genexpr>2  s     LA:"77Lrs   zserious-violationszhealth-riskr>   )r/   r0   ztemperature-violations)r1   r2   r3   zequipment-violations)r4   zsanitation-violations)
rV   rh   r   rI   rQ   lowerreplaceanyextendrg   )	r   rM   rR   tagsri   rd   r   category_namerK   s	            r   get_violation_tagsz&ViolationCodeLookup.get_violation_tags  sR    //@
K <A!J-<=
" 	AH 1155hIMKK*XJ/0KK++-55c3?@	A ?J??KK.0HIJLLLKK-}=> $ 	5I L0456"&88236"f,34	5 CI+ =s   EN)__name__
__module____qualname____doc__r   r   rG   r
   r   r   r   rL   r   rV   r\   rw   rk   r{   r8   r   r   r   r      s    
?
l
4T	? l
\
c3h 

c3h 
S Xd^ ,S T$Z 6!)c !)c !)F'S 'T#s(^ 'R&# &$s) &r   r   r>   r   c                 >    t         j                  |       }|r|d   S dS )z#Quick violation explanation lookup.r   N)violation_lookuprL   )r>   rK   s     r   explain_violationr   D  s$     11$7I'09]#:d:r   rM   c                 ,    t         j                  |       S )z"Quick violations text explanation.)r   r\   rM   s    r   explain_violations_textr   I  s    ::?KKr   c                 ,    t         j                  |       S )z Quick violation tags generation.)r   r{   r   s    r   r{   r{   M  s    ..??r   __main__zTesting violation code 52:r6   zTitle: r   zDescription: r   z
Severity: rB   zP52. REFUSE, RECYCLABLES PROPERLY REMOVED | Comments: Observed dumpster lids openz Testing violations text parsing:zInput: zExplanation: zTags: )r   typingr   r   r   r   rE   r   r   rG   r   r   r{   r|   lookupprintrL   rK   sample_textr\   r8   r   r   <module>r      sD   / . 	q qh	 '( ;C ;HSM ;
LS LS L@ @S	 @ z "F 

&'''-I	'*+,-i6789
9%;<=>? eK	
,-	GK=
!"	M&??LM
NO	F6,,[9:
;<% r   