Spaces:
Sleeping
Sleeping
| from flask import Flask, request, render_template | |
| import google.generativeai as genai | |
| import base64 | |
| import os | |
| # Initialize Flask app | |
| app = Flask(__name__) | |
| # Gemini API Configuration | |
| genai.configure(api_key="AIzaSyCtEVix5c3pv3wtt7JLUA0CWpmOCt2gBMw") | |
| model = genai.GenerativeModel("gemini-1.5-flash") | |
| def process_certificates(image_paths, certificates): | |
| """Process all certificates and generate a response in structured HTML.""" | |
| encoded_images = [] | |
| for image_path in image_paths: | |
| with open(image_path, "rb") as image_file: | |
| encoded_images.append(base64.b64encode(image_file.read()).decode("utf-8")) | |
| # Prompt to generate structured output | |
| # Prompt to generate structured output | |
| prompt = ( | |
| "Note Current date is 12 /12/2024 last month of 2024 (12 decemeebr 2024 is current date). Process the following certificates:\n" | |
| + "\n".join([f"- {cert_name}: (image attached)" for cert_name in certificates]) | |
| + "\n\nFor all certificates:\n" | |
| "1. Check the expiry date. If the expiry date is past as compared to current date, mark the certificate as Invalid❌. " | |
| "If the expiry date is a future date as compared current date, mark the certificate as Valid✅, ok clear simple check expiry data you are ai ai alteast you should be eligilbw ot check past and fuuture data with repsect to 12 decemeber 2024 (that is all dates byond 12 like 13 dec...2024...2025 and beyond are futuure dates and 10 dec 2024..2023...2022 are past dates) , pst ones a re invalida nd future ones are valid." | |
| "If expriy date on certiificate is not found, but right marks, government seals, or signatures found, mark the certificate as Valid✅.\n" | |
| "3. If both criteria are inconclusive (marks & expiry not present) , use semantic analysis of the content to decide Valid✅ or Invalid❌.\n" | |
| "Return the results in a single table with the following columns, please i reuqest you i want porper retival of table in pper format with borders content all on html webpage so please rneder it properly under markpu tag '''html opening and '''html closinga(no text outisde markup) not speicla in markup tag okay please: and check with current date 11 dec 2024 for expry date past or future ei wnat correct results.\n" | |
| "- Certificate Name\n" | |
| "- Status (Valid✅/Invalid❌)\n" | |
| "- Reason (short description).\n" | |
| "also in status not jsut right wrong sign but comlete Valid✅/Invalid❌ should,be printed (ex : not just ✅ but valid✅) and also calcuate percentage of dcoument vriified(✅) from table (just ex : 47.8 round off 48 then print bvelow table in medium bold cnetral alglin text Document Verification Marks : 48/100) whatever got and above tbale heading Document Valdiation reuslt central allgin and spaing bewtwen heading and table (dont print certificate validaty status 11 dec dont include) Structure the table with proper formatting, borders, colors, and suitable styles for rendering on an HTML webpage." | |
| ) | |
| response = model.generate_content([ | |
| {'mime_type': 'image/jpeg', 'data': image} for image in encoded_images | |
| ] + [prompt]) | |
| return response.text | |
| def extract_certificate_summary(image_path, cert_name): | |
| """Extract key points from individual certificates.""" | |
| with open(image_path, "rb") as image_file: | |
| encoded_image = base64.b64encode(image_file.read()).decode("utf-8") | |
| prompt = ( | |
| f"Extract key points from the certificate named '{cert_name}'. " | |
| f"Provide a summarized text with the following information:\n" | |
| "1. Issuing authority\n" | |
| "2. Validity period or expiry date\n" | |
| "3. Seal or signature presence\n" | |
| "4. Any special notes or conditions.\n" | |
| "Return the information as structured bullet points in HTML format. (within markup tag)." | |
| ) | |
| response = model.generate_content([ | |
| {'mime_type': 'image/jpeg', 'data': encoded_image}, prompt | |
| ]) | |
| return response.text | |
| def home(): | |
| if request.method == "POST": | |
| certificates = [ | |
| "Affiliation Certificate", | |
| "Approval Certificate", | |
| "Accreditation Certificate", | |
| "ISO Certificate", | |
| "Fire Safety Certificate", | |
| "Land Certificate", | |
| "Government Lab Quality Certificate", | |
| "Financial Audit Report", | |
| "No Objection Certificate", | |
| "Affidavit Certificate", | |
| "Anti Ragging Certificate", | |
| "Environmental Clearance Certificate", | |
| "Occupancy Certificate", | |
| "Trust Certificate", | |
| "MOU with Industry Certificate", | |
| "Food Safety Certificate" | |
| ] | |
| image_paths = [] | |
| summaries = [] | |
| for cert_name in certificates: | |
| file = request.files.get(cert_name) | |
| if file and file.filename: # Check if a file was uploaded | |
| os.makedirs("static/uploads", exist_ok=True) | |
| image_path = os.path.join("static/uploads", file.filename) | |
| file.save(image_path) | |
| image_paths.append((image_path, cert_name)) | |
| # Check if no certificates were uploaded | |
| if not image_paths: | |
| return render_template( | |
| "index.html", error="Please upload at least one certificate." | |
| ) | |
| # Process certificates collectively | |
| gemini_output = process_certificates([p[0] for p in image_paths], certificates) | |
| # Add summaries for individual certificates | |
| for image_path, cert_name in image_paths: | |
| summary = extract_certificate_summary(image_path, cert_name) # Generate summary | |
| summaries.append({ | |
| "name": cert_name, | |
| "image_path": image_path, | |
| "summary": summary | |
| }) | |
| return render_template("index.html", gemini_output=gemini_output, summaries=summaries) | |
| return render_template("index.html") | |
| if __name__ == "__main__": | |
| app.run(debug=True) | |