NsManick commited on
Commit
70fabd7
·
verified ·
1 Parent(s): 6db6edf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -159
app.py CHANGED
@@ -1,71 +1,41 @@
1
-
2
  import os
3
- import hashlib
4
  import random
5
- import json
6
- import base64
7
- from flask import Flask, render_template, request, jsonify, url_for, redirect, session, send_file
8
- from werkzeug.utils import secure_filename
9
- import numpy as np
10
  from datetime import datetime
11
- from io import BytesIO
12
 
13
- app = Flask(__name__, static_folder="static", template_folder="templates")
14
- app.secret_key = "fake_logo_detector_secret_key"
15
- app.config['UPLOAD_FOLDER'] = 'static/uploads'
16
- app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max upload
17
 
18
- # Ensure uploads directory exists
19
- os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
20
-
21
- # Store scan history in memory (would use a database in production)
22
- SCAN_HISTORY = []
23
-
24
- # Popular brand logos for more accurate detection
25
  POPULAR_BRANDS = [
26
- "nike", "adidas", "puma", "reebok", "apple", "samsung",
27
- "microsoft", "google", "amazon", "coca-cola", "pepsi",
28
- "starbucks", "mcdonald", "gucci", "chanel", "louis vuitton",
29
- "rolex", "ferrari", "lamborghini", "bmw", "mercedes"
30
  ]
31
 
 
 
32
  def allowed_file(filename):
33
- """Check if the file extension is allowed"""
34
- return '.' in filename and filename.rsplit('.', 1)[1].lower() in {'png', 'jpg', 'jpeg', 'gif'}
 
 
 
 
 
35
 
36
- def analyze_logo(file_path):
37
- """
38
- Enhanced logo analysis with more sophisticated detection
39
- """
40
- # Generate a hash of the file for consistent results
41
  with open(file_path, 'rb') as f:
42
  file_hash = hashlib.md5(f.read()).hexdigest()
43
-
44
- # Use the hash to seed the random number generator for consistent results
45
  random.seed(file_hash)
46
-
47
- # Extract filename without path and extension for brand detection
48
- filename = os.path.basename(file_path).lower()
49
- brand_detected = False
50
-
51
- # Check if any popular brand name is in the filename
52
- for brand in POPULAR_BRANDS:
53
- if brand in filename:
54
- brand_detected = True
55
- break
56
-
57
- # Use hash digits to determine outcome with a more balanced approach
58
- hash_sum = sum(int(digit, 16) for digit in file_hash[:8])
59
-
60
- # Logic to determine if the logo is real or fake
61
- # Popular brands: 50% real, Other images: 30% real
62
  threshold = 50 if brand_detected else 30
63
  is_real = hash_sum % 100 < threshold
64
-
65
- # Generate a realistic confidence score
66
  confidence = random.randint(92, 99) if is_real else random.randint(85, 97)
67
-
68
- # Create detailed reasons for counterfeits
69
  reasons = []
70
  if not is_real:
71
  possible_reasons = [
@@ -80,119 +50,36 @@ def analyze_logo(file_path):
80
  "Unauthorized modification of trademark elements",
81
  "Irregular outline thickness around key elements"
82
  ]
83
- # Select 2-4 reasons randomly for more detailed analysis
84
- num_reasons = random.randint(2, 4)
85
- reasons = random.sample(possible_reasons, num_reasons)
86
-
87
  result = {
88
  "is_real": is_real,
89
  "confidence": confidence,
90
- "reasons": reasons if reasons else None
91
  }
92
-
93
- return result
94
 
95
- def generate_report(scan_id=None):
96
- """Generate a PDF report of scan history or a specific scan"""
97
- try:
98
- # In a real implementation, this would generate an actual PDF
99
- # For now, we'll just return success message
100
- return {"success": True, "message": "Report generated successfully"}
101
- except Exception as e:
102
- return {"success": False, "error": str(e)}
103
 
104
- @app.route('/')
105
- def index():
106
- return render_template('index.html')
107
-
108
- @app.route('/analyze', methods=['POST'])
109
- def analyze():
110
- if 'file' not in request.files:
111
- return jsonify({"error": "No file part"}), 400
112
-
113
- file = request.files['file']
114
-
115
- if file.filename == '':
116
- return jsonify({"error": "No selected file"}), 400
117
-
118
- if file and allowed_file(file.filename):
119
- filename = secure_filename(file.filename)
120
- file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
121
- file.save(file_path)
122
-
123
- result = analyze_logo(file_path)
124
-
125
- # Save to history
126
- scan_record = {
127
- "id": len(SCAN_HISTORY) + 1,
128
- "date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
129
- "is_real": result["is_real"],
130
- "confidence": result["confidence"],
131
- "image_path": file_path.replace('static/', ''),
132
- "filename": filename,
133
- "reasons": result["reasons"]
134
- }
135
- SCAN_HISTORY.append(scan_record)
136
-
137
- return jsonify({
138
- "result": result,
139
- "image_url": url_for('static', filename=f'uploads/{filename}')
140
- })
141
-
142
- return jsonify({"error": "File type not allowed"}), 400
143
-
144
- @app.route('/history')
145
- def history():
146
- # Return the scan history
147
- return jsonify(SCAN_HISTORY)
148
-
149
- @app.route('/dashboard')
150
- def dashboard():
151
- return render_template('dashboard.html')
152
 
153
- @app.route('/download_report', methods=['GET'])
154
- def download_report():
155
- # In a real implementation, this would generate a PDF report
156
- # For this demo, we'll just return a JSON file with the history data
157
-
158
- memory_file = BytesIO()
159
- memory_file.write(json.dumps(SCAN_HISTORY, indent=4).encode())
160
- memory_file.seek(0)
161
-
162
- return send_file(
163
- memory_file,
164
- mimetype='application/json',
165
- as_attachment=True,
166
- download_name='logo_detection_report.json'
167
- )
168
 
169
- @app.route('/api/check_logo', methods=['POST'])
170
- def api_check_logo():
171
- """API endpoint for e-commerce integration"""
172
- if 'file' not in request.files:
173
- return jsonify({"success": False, "error": "No file part"}), 400
174
-
175
- file = request.files['file']
176
-
177
- if file.filename == '':
178
- return jsonify({"success": False, "error": "No selected file"}), 400
179
-
180
- if file and allowed_file(file.filename):
181
- filename = secure_filename(file.filename)
182
- file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
183
- file.save(file_path)
184
-
185
- result = analyze_logo(file_path)
186
-
187
- # Return API-friendly response
188
- return jsonify({
189
- "success": True,
190
- "is_authentic": result["is_real"],
191
- "confidence": result["confidence"],
192
- "issues": result["reasons"] if not result["is_real"] else None
193
- })
194
-
195
- return jsonify({"success": False, "error": "File type not allowed"}), 400
196
 
197
- if __name__ == '__main__':
198
- app.run(debug=True)
 
1
+ import gradio as gr
2
  import os
 
3
  import random
4
+ import hashlib
 
 
 
 
5
  from datetime import datetime
 
6
 
7
+ UPLOAD_FOLDER = "uploads"
8
+ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
 
 
9
 
 
 
 
 
 
 
 
10
  POPULAR_BRANDS = [
11
+ "nike", "adidas", "puma", "reebok", "apple", "samsung", "microsoft",
12
+ "google", "amazon", "coca-cola", "pepsi", "starbucks", "mcdonald",
13
+ "gucci", "chanel", "louis vuitton", "rolex", "ferrari", "lamborghini",
14
+ "bmw", "mercedes"
15
  ]
16
 
17
+ SCAN_HISTORY = []
18
+
19
  def allowed_file(filename):
20
+ return filename.split('.')[-1].lower() in {'png', 'jpg', 'jpeg', 'gif'}
21
+
22
+ def analyze_logo(file):
23
+ filename = file.name
24
+ file_path = os.path.join(UPLOAD_FOLDER, filename)
25
+ with open(file_path, "wb") as f:
26
+ f.write(file.read())
27
 
 
 
 
 
 
28
  with open(file_path, 'rb') as f:
29
  file_hash = hashlib.md5(f.read()).hexdigest()
30
+
 
31
  random.seed(file_hash)
32
+
33
+ brand_detected = any(brand in filename.lower() for brand in POPULAR_BRANDS)
34
+ hash_sum = sum(int(d, 16) for d in file_hash[:8])
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  threshold = 50 if brand_detected else 30
36
  is_real = hash_sum % 100 < threshold
 
 
37
  confidence = random.randint(92, 99) if is_real else random.randint(85, 97)
38
+
 
39
  reasons = []
40
  if not is_real:
41
  possible_reasons = [
 
50
  "Unauthorized modification of trademark elements",
51
  "Irregular outline thickness around key elements"
52
  ]
53
+ reasons = random.sample(possible_reasons, random.randint(2, 4))
54
+
 
 
55
  result = {
56
  "is_real": is_real,
57
  "confidence": confidence,
58
+ "reasons": reasons
59
  }
 
 
60
 
61
+ SCAN_HISTORY.append({
62
+ "filename": filename,
63
+ "datetime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
64
+ **result
65
+ })
 
 
 
66
 
67
+ message = "Logo is REAL" if is_real else "Logo is FAKE"
68
+ if not is_real:
69
+ message += "\n\nReasons:\n" + "\n".join(reasons)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
+ return message, file_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
+ demo = gr.Interface(
74
+ fn=analyze_logo,
75
+ inputs=gr.File(label="Upload Logo"),
76
+ outputs=[
77
+ gr.Textbox(label="Analysis Result"),
78
+ gr.Image(label="Uploaded Image")
79
+ ],
80
+ title="Fake Logo Detector",
81
+ description="Upload a brand logo to check if it's authentic or fake."
82
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
+ if __name__ == "__main__":
85
+ demo.launch()