RushiMane2003 commited on
Commit
1a55e09
·
verified ·
1 Parent(s): bc29354

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -0
app.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, jsonify
2
+ from google import genai
3
+ from google.genai import types
4
+ import google.generativeai as genai
5
+ from PIL import Image
6
+ import io
7
+ import fitz
8
+ import re
9
+ import base64
10
+ import json
11
+ from dotenv import load_dotenv
12
+ import os
13
+
14
+ load_dotenv() # Loads environment variables from .env file
15
+ gemini_api_key = "AIzaSyBtXV2xJbrWVV57B5RWy_meKXOA59HFMeY"
16
+ if not gemini_api_key:
17
+ raise ValueError("GEMINI_API_KEY not set in environment variables.")
18
+ genai.configure(api_key=gemini_api_key)
19
+
20
+ app = Flask(__name__)
21
+ app.secret_key = "supersecretkey"
22
+
23
+
24
+ def process_file(file):
25
+ """Process file into an appropriate format for Gemini."""
26
+ if file.content_type == 'application/pdf':
27
+ try:
28
+ pdf_bytes = file.read()
29
+ pdf_document = fitz.open(stream=pdf_bytes, filetype="pdf")
30
+ first_page = pdf_document[0]
31
+ pix = first_page.get_pixmap()
32
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
33
+ return img, file.filename
34
+ except Exception as e:
35
+ raise Exception(f"Error processing PDF {file.filename}: {str(e)}")
36
+ else:
37
+ try:
38
+ image_bytes = file.read()
39
+ image = Image.open(io.BytesIO(image_bytes))
40
+ return image, file.filename
41
+ except Exception as e:
42
+ raise Exception(f"Error processing image {file.filename}: {str(e)}")
43
+
44
+
45
+ @app.route("/", methods=["GET", "POST"])
46
+ def index():
47
+ if request.method == "POST":
48
+ if "files" not in request.files:
49
+ return jsonify({"error": "No files uploaded"})
50
+ files = request.files.getlist("files")
51
+ if not files or files[0].filename == "":
52
+ return jsonify({"error": "No files selected"})
53
+
54
+ # Retrieve the selected language from the form
55
+ language = request.form.get("language", "English")
56
+
57
+ try:
58
+ processed_files = []
59
+ for file in files:
60
+ processed_content, filename = process_file(file)
61
+ processed_files.append((processed_content, filename))
62
+ filenames = [f[1] for f in processed_files]
63
+ files_list = "\n".join([f"- {fname}" for fname in filenames])
64
+ content_parts = []
65
+ for img, _ in processed_files:
66
+ content_parts.append(img)
67
+ # Updated prompt: include the language instruction and refined content details
68
+ content_parts.append(f"""
69
+ Please analyze all {len(files)} soil reports and generate a comprehensive soil analysis report in JSON format, entirely in {language}.
70
+ The JSON should include exactly five keys: "Overview", "Soil Composition", "Nutrient Levels", "pH Balance & Moisture Content", and "Recommendations & Actionable Steps".
71
+ Each key should have a string value containing the respective analysis.
72
+ Reports being analyzed:
73
+ {files_list}
74
+ """)
75
+ model = genai.GenerativeModel("gemini-1.5-flash")
76
+ response = model.generate_content(content_parts)
77
+
78
+ if response and response.text:
79
+ summary = response.text.strip()
80
+ if summary.lower().startswith("please provide"):
81
+ return jsonify({"error": "Could not analyze the documents"})
82
+
83
+ # Optionally, attempt to load a JSON object from the response
84
+ try:
85
+ analysis_json = json.loads(summary)
86
+ except Exception:
87
+ # If the response is not a valid JSON, return it as a simple text field.
88
+ analysis_json = {"analysis": summary}
89
+
90
+ return jsonify(analysis_json)
91
+ else:
92
+ return jsonify({"error": "No analysis could be generated"})
93
+ except Exception as e:
94
+ return jsonify({"error": f"Error processing files: {str(e)}"})
95
+ return render_template("index.html")
96
+
97
+
98
+ if __name__ == "__main__":
99
+ port = int(os.environ.get("PORT", 7860))
100
+ app.run(host='0.0.0.0', port=port)