Ahmad-01 commited on
Commit
04fba85
·
verified ·
1 Parent(s): b34712f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -19
app.py CHANGED
@@ -3,20 +3,26 @@ import base64
3
  import requests
4
  import os
5
 
6
- # === STEP 1: Get Groq API Key from HF Space Secret ===
7
- GROQ_API_KEY = os.getenv("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") # Define this in your Space settings!
 
8
  GROQ_MODEL = "llama3-70b-8192"
9
  GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
10
 
11
 
12
- # === STEP 2: Convert image to base64 ===
 
13
  def image_to_base64(image_path):
14
- with open(image_path, "rb") as image_file:
15
- image_bytes = image_file.read()
16
- return base64.b64encode(image_bytes).decode("utf-8")
 
 
 
 
17
 
 
18
 
19
- # === STEP 3: Build the LLM Prompt ===
20
  def build_prompt(image_b64: str) -> str:
21
  return f"""
22
  You are an expert in Non-Destructive Testing (NDT) and industrial defect analysis.
@@ -35,8 +41,12 @@ Analyze the defect and provide structured output with the following format:
35
  """
36
 
37
 
38
- # === STEP 4: Call Groq API ===
 
39
  def query_groq(prompt: str) -> str:
 
 
 
40
  headers = {
41
  "Authorization": f"Bearer {GROQ_API_KEY}",
42
  "Content-Type": "application/json"
@@ -52,34 +62,42 @@ def query_groq(prompt: str) -> str:
52
  "max_tokens": 800
53
  }
54
 
55
- response = requests.post(GROQ_API_URL, headers=headers, json=payload)
 
 
 
 
 
56
 
57
- if response.status_code == 200:
58
  return response.json()["choices"][0]["message"]["content"]
59
- else:
60
- return f"Error {response.status_code}: {response.text}"
61
 
 
 
 
 
 
62
 
63
- # === STEP 5: Main Function for Gradio ===
64
  def analyze_defect(image_path):
65
- if image_path is None:
66
  return "Please upload an image."
67
 
68
  image_b64 = image_to_base64(image_path)
 
 
 
69
  prompt = build_prompt(image_b64)
70
- response = query_groq(prompt)
71
- return response
72
 
 
73
 
74
- # === STEP 6: Gradio UI ===
75
  demo = gr.Interface(
76
  fn=analyze_defect,
77
  inputs=gr.Image(type="filepath", label="Upload Defective Component Image"),
78
  outputs=gr.Textbox(label="Defect Analysis Report"),
79
  title="🛠️ NDT Defect Analyzer",
80
- description="Upload an image of a damaged industrial component. The AI will identify the defect, recommend NDT methods, suggest fixes, tools, and future prevention."
81
  )
82
 
83
- # === STEP 7: Launch for Hugging Face Spaces ===
84
  if __name__ == "__main__":
85
  demo.launch()
 
3
  import requests
4
  import os
5
 
6
+ # === CONFIGURATION ===
7
+
8
+ GROQ_API_KEY = os.getenv("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")
9
  GROQ_MODEL = "llama3-70b-8192"
10
  GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
11
 
12
 
13
+ # === IMAGE TO BASE64 ===
14
+
15
  def image_to_base64(image_path):
16
+ try:
17
+ with open(image_path, "rb") as image_file:
18
+ image_bytes = image_file.read()
19
+ return base64.b64encode(image_bytes).decode("utf-8")
20
+ except Exception as e:
21
+ return None
22
+
23
 
24
+ # === PROMPT BUILDER ===
25
 
 
26
  def build_prompt(image_b64: str) -> str:
27
  return f"""
28
  You are an expert in Non-Destructive Testing (NDT) and industrial defect analysis.
 
41
  """
42
 
43
 
44
+ # === GROQ API CALL ===
45
+
46
  def query_groq(prompt: str) -> str:
47
+ if not GROQ_API_KEY or not GROQ_API_KEY.startswith("gsk_"):
48
+ return "❌ Error: Invalid or missing Groq API key. Please check Space secrets."
49
+
50
  headers = {
51
  "Authorization": f"Bearer {GROQ_API_KEY}",
52
  "Content-Type": "application/json"
 
62
  "max_tokens": 800
63
  }
64
 
65
+ try:
66
+ response = requests.post(GROQ_API_URL, headers=headers, json=payload)
67
+ if response.status_code == 401:
68
+ return "❌ Error 401: Invalid API Key. Please check your GROQ_API_KEY in Space secrets."
69
+ elif response.status_code != 200:
70
+ return f"❌ Error {response.status_code}: {response.text}"
71
 
 
72
  return response.json()["choices"][0]["message"]["content"]
 
 
73
 
74
+ except Exception as e:
75
+ return f"❌ Exception while calling Groq API: {str(e)}"
76
+
77
+
78
+ # === MAIN ANALYSIS FUNCTION ===
79
 
 
80
  def analyze_defect(image_path):
81
+ if not image_path:
82
  return "Please upload an image."
83
 
84
  image_b64 = image_to_base64(image_path)
85
+ if not image_b64:
86
+ return "❌ Error reading image. Please try a different file."
87
+
88
  prompt = build_prompt(image_b64)
89
+ return query_groq(prompt)
90
+
91
 
92
+ # === GRADIO UI ===
93
 
 
94
  demo = gr.Interface(
95
  fn=analyze_defect,
96
  inputs=gr.Image(type="filepath", label="Upload Defective Component Image"),
97
  outputs=gr.Textbox(label="Defect Analysis Report"),
98
  title="🛠️ NDT Defect Analyzer",
99
+ description="Upload an image of a damaged industrial component. The AI identifies the defect, recommends NDT method, and suggests solutions and preventive measures."
100
  )
101
 
 
102
  if __name__ == "__main__":
103
  demo.launch()