Komal133 commited on
Commit
3b94c91
·
verified ·
1 Parent(s): 7c231af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -70
app.py CHANGED
@@ -1,86 +1,68 @@
1
  import os
2
- import numpy as np
3
- from flask import Flask, request, jsonify, render_template
 
 
4
  from PIL import Image, ImageDraw
5
- from transformers import pipeline
6
- import cv2
7
- import torch
8
 
9
- # Initialize Flask app
10
  app = Flask(__name__)
11
-
12
- # Load the fine-tuned YOLOv8 or Faster R-CNN model
13
- # You can replace 'username/defect-detection-model' with your Hugging Face model path
14
- model = pipeline('object-detection', model='username/defect-detection-model', device=0)
15
-
16
- # Create an upload folder
17
  UPLOAD_FOLDER = 'uploads'
 
18
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
19
 
20
- # Max image size (10MB)
21
- app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024
22
 
23
- # Route for uploading images
24
  @app.route('/')
25
  def index():
26
  return render_template('index.html')
27
 
28
- # Route to handle image upload and detection
29
  @app.route('/upload', methods=['POST'])
30
- def upload_file():
31
- if 'file' not in request.files:
32
- return jsonify({"error": "No file part"})
33
- file = request.files['file']
34
- if file.filename == '':
35
- return jsonify({"error": "No selected file"})
36
-
37
- # Save file
38
- filepath = os.path.join(UPLOAD_FOLDER, file.filename)
39
- file.save(filepath)
40
-
41
- # Open the image using PIL
42
- image = Image.open(filepath)
43
-
44
- # Run detection
45
- results = model(filepath)
46
-
47
- # Draw bounding boxes on the image
48
- draw = ImageDraw.Draw(image)
49
- for result in results:
50
- label = result['label']
51
- score = result['score']
52
- box = result['box']
53
- draw.rectangle([box[0], box[1], box[2], box[3]], outline="red", width=2)
54
- draw.text((box[0], box[1] - 10), f'{label} ({score:.2f})', fill="red")
55
-
56
- # Save result image
57
- output_path = os.path.join(UPLOAD_FOLDER, 'result_' + file.filename)
58
- image.save(output_path)
59
-
60
- # Generate Fault Map and Repair Suggestion Report (simplified example)
61
- fault_map = [{"label": result['label'], "confidence": result['score'], "box": result['box']} for result in results]
62
- repair_suggestions = generate_repair_suggestions(fault_map)
63
-
64
- return jsonify({
65
- "message": "Detection completed successfully",
66
- "fault_map": fault_map,
67
- "repair_suggestions": repair_suggestions,
68
- "result_image": output_path
69
- })
70
-
71
- # Function to generate repair suggestions (simplified example)
72
- def generate_repair_suggestions(fault_map):
73
- suggestions = []
74
- for fault in fault_map:
75
- if fault['label'] == 'crack':
76
- suggestions.append("Crack repair with resin")
77
- elif fault['label'] == 'rust':
78
- suggestions.append("Rust removal and painting")
79
- elif fault['label'] == 'spalling':
80
- suggestions.append("Concrete spalling repair")
81
- else:
82
- suggestions.append("General maintenance required")
83
- return suggestions
84
 
85
  if __name__ == '__main__':
86
  app.run(debug=True)
 
1
  import os
2
+ import uuid
3
+ import requests
4
+ from flask import Flask, request, render_template, redirect, url_for, send_file
5
+ from werkzeug.utils import secure_filename
6
  from PIL import Image, ImageDraw
7
+ from io import BytesIO
 
 
8
 
9
+ # Flask config
10
  app = Flask(__name__)
 
 
 
 
 
 
11
  UPLOAD_FOLDER = 'uploads'
12
+ RESULT_FOLDER = 'results'
13
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
14
+ os.makedirs(RESULT_FOLDER, exist_ok=True)
15
+ app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
16
+
17
+ # Replace with your actual Hugging Face Inference Endpoint
18
+ HUGGINGFACE_API_URL = "https://your-model-url.huggingface.co"
19
+ API_TOKEN = "your_huggingface_token"
20
+
21
+ HEADERS = {
22
+ "Authorization": f"Bearer {API_TOKEN}"
23
+ }
24
 
 
 
25
 
 
26
  @app.route('/')
27
  def index():
28
  return render_template('index.html')
29
 
30
+
31
  @app.route('/upload', methods=['POST'])
32
+ def upload_files():
33
+ files = request.files.getlist('images')
34
+ result_images = []
35
+
36
+ for file in files:
37
+ filename = secure_filename(file.filename)
38
+ file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
39
+ file.save(file_path)
40
+
41
+ with open(file_path, "rb") as f:
42
+ response = requests.post(HUGGINGFACE_API_URL, headers=HEADERS, files={"file": f})
43
+
44
+ if response.status_code == 200:
45
+ data = response.json()
46
+ image = Image.open(file_path).convert("RGB")
47
+ draw = ImageDraw.Draw(image)
48
+
49
+ for detection in data.get("predictions", []):
50
+ bbox = detection["bbox"] # [x1, y1, x2, y2]
51
+ label = f"{detection['label']} ({detection['severity']})"
52
+ draw.rectangle(bbox, outline="red", width=3)
53
+ draw.text((bbox[0], bbox[1] - 10), label, fill="red")
54
+
55
+ result_path = os.path.join(RESULT_FOLDER, f"result_{uuid.uuid4().hex}.jpg")
56
+ image.save(result_path)
57
+ result_images.append(result_path)
58
+
59
+ return render_template('results.html', result_images=result_images)
60
+
61
+
62
+ @app.route('/results/<filename>')
63
+ def result_file(filename):
64
+ return send_file(os.path.join(RESULT_FOLDER, filename), mimetype='image/jpeg')
65
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  if __name__ == '__main__':
68
  app.run(debug=True)