WahibR commited on
Commit
ef8692d
·
verified ·
1 Parent(s): 66788d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -63
app.py CHANGED
@@ -6,83 +6,95 @@ import gradio as gr
6
  from ultralytics import YOLO
7
  from openai import OpenAI
8
 
9
- # -------------------------------
10
- # Load YOLO Model (best.pt)
11
- # -------------------------------
12
- model = YOLO("best.pt")
13
-
14
- # -------------------------------
15
- # OpenAI Vision Function
16
- # -------------------------------
17
- def analyze_with_openai(image):
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  try:
19
- api_key = os.getenv("OPENAI_API_KEY")
20
- if api_key is None:
21
- return "❌ Missing OPENAI_API_KEY in HuggingFace Space Secrets."
 
 
22
 
23
- client = OpenAI(api_key=api_key)
24
 
25
- # Convert to base64 for OpenAI
 
 
 
 
 
 
 
 
 
26
  _, buffer = cv2.imencode(".jpg", image)
27
- img_b64 = base64.b64encode(buffer).decode("utf-8")
28
 
29
- prompt = (
30
- "Analyze this smartphone image. Identify all visible defects.\n"
31
- "- Classify: light scratches, deep scratches, dents, cracks, stains.\n"
32
- "- Ignore reflections and dust.\n"
33
- "- Provide clear bullet points."
34
- )
35
 
36
- response = client.chat.completions.create(
37
  model="gpt-4o-mini",
38
- messages=[
39
- {
40
- "role": "user",
41
- "content": [
42
- {"type": "text", "text": prompt},
43
- {"type": "image_url", "image_url": f"data:image/jpeg;base64,{img_b64}"}
44
- ],
45
- }
46
- ],
47
  )
48
 
49
- return response.choices[0].message["content"]
50
 
51
  except Exception as e:
52
  return f"OpenAI Vision Error: {str(e)}"
53
 
54
 
55
- # -------------------------------
56
- # YOLO + OpenAI Combined Pipeline
57
- # -------------------------------
58
- def detect_and_analyze(image):
59
- try:
60
- # YOLO detection
61
- results = model.predict(image, conf=0.25)
62
- yolo_annotated = results[0].plot()
63
 
64
- # OpenAI Vision analysis
65
- openai_text = analyze_with_openai(image)
66
 
67
- return yolo_annotated, openai_text
68
 
69
- except Exception as e:
70
- return image, f"❌ Processing Error: {str(e)}"
71
-
72
-
73
- # -------------------------------
74
- # Gradio UI
75
- # -------------------------------
76
- interface = gr.Interface(
77
- fn=detect_and_analyze,
78
- inputs=gr.Image(type="numpy", label="Upload a Phone Image"),
79
- outputs=[
80
- gr.Image(type="numpy", label="YOLO Detection Output"),
81
- gr.Textbox(label="OpenAI Vision Analysis", lines=8)
82
- ],
83
- title="📱 Phone Damage Detector (YOLO + OpenAI Vision)",
84
- description="Upload a smartphone image. This tool highlights scratches using YOLO and provides detailed AI analysis using OpenAI Vision.",
85
- allow_flagging="never"
86
- )
87
-
88
- interface.launch()
 
6
  from ultralytics import YOLO
7
  from openai import OpenAI
8
 
9
+ # -----------------------
10
+ # Load YOLO model
11
+ # -----------------------
12
+ try:
13
+ yolo_model = YOLO("best.pt")
14
+ yolo_loaded = True
15
+ except Exception as e:
16
+ print("YOLO Load Error:", e)
17
+ yolo_loaded = False
18
+
19
+ # -----------------------
20
+ # OpenAI client (auto reads OPENAI_API_KEY)
21
+ # -----------------------
22
+ client = OpenAI() # DO NOT add api_key or proxies here
23
+
24
+ # -----------------------
25
+ # YOLO Detection
26
+ # -----------------------
27
+ def run_yolo(image):
28
+ if not yolo_loaded:
29
+ return None, "⚠ YOLO model failed to load."
30
+
31
  try:
32
+ results = yolo_model.predict(image, conf=0.25)
33
+ annotated = results[0].plot()
34
+ return annotated, None
35
+ except Exception as e:
36
+ return None, f"YOLO error: {str(e)}"
37
 
 
38
 
39
+ # -----------------------
40
+ # OpenAI Vision Detection
41
+ # -----------------------
42
+ def run_openai_vision(image):
43
+ # Ensure API Key exists
44
+ if os.getenv("OPENAI_API_KEY") is None:
45
+ return "⚠ Missing OPENAI_API_KEY in Space Secrets!"
46
+
47
+ try:
48
+ # Convert image → base64
49
  _, buffer = cv2.imencode(".jpg", image)
50
+ b64 = base64.b64encode(buffer).decode()
51
 
52
+ prompt = """
53
+ Analyze this phone screen for scratches, cracks, dents, or defects.
54
+ Respond only with a detailed defect description.
55
+ """
 
 
56
 
57
+ response = client.responses.create(
58
  model="gpt-4o-mini",
59
+ input=[
60
+ {"role": "user", "content": prompt},
61
+ {"role": "user", "content": {"image": b64}}
62
+ ]
 
 
 
 
 
63
  )
64
 
65
+ return response.output_text
66
 
67
  except Exception as e:
68
  return f"OpenAI Vision Error: {str(e)}"
69
 
70
 
71
+ # -----------------------
72
+ # Master pipeline
73
+ # -----------------------
74
+ def master_detector(image):
75
+ # 1️⃣ Try YOLO first
76
+ yolo_result, yolo_error = run_yolo(image)
 
 
77
 
78
+ # 2️⃣ Also run OpenAI Vision
79
+ vision_result = run_openai_vision(image)
80
 
81
+ return yolo_result, vision_result, yolo_error
82
 
83
+
84
+ # -----------------------
85
+ # GRADIO UI
86
+ # -----------------------
87
+ with gr.Blocks(title="Phone Scratch Detector - YOLO + AI Vision") as app:
88
+ gr.Markdown("## 📱 Phone Screen Defect Detector (YOLO + OpenAI Vision)")
89
+
90
+ inp = gr.Image(type="numpy", label="Upload Phone Image")
91
+
92
+ yolo_out = gr.Image(type="numpy", label="YOLO Detection (Bounding Boxes)")
93
+ vision_out = gr.Textbox(label="OpenAI Vision Report")
94
+ error_out = gr.Textbox(label="Internal Errors")
95
+
96
+ btn = gr.Button("Analyze Image")
97
+
98
+ btn.click(master_detector, inputs=inp, outputs=[yolo_out, vision_out, error_out])
99
+
100
+ app.launch()