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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -30
app.py CHANGED
@@ -3,33 +3,36 @@ import base64
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.
29
 
30
- A user has uploaded an image of a defected component. Here's the base64 representation of that image (partial for size): {image_b64[:300]}...
31
 
32
- Analyze the defect and provide structured output with the following format:
33
 
34
  1. Defect Type:
35
  2. Recommended NDT Technique(s):
@@ -40,12 +43,12 @@ Analyze the defect and provide structured output with the following format:
40
  7. Preventive Measures:
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}",
@@ -65,39 +68,40 @@ def query_groq(prompt: str) -> str:
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()
 
3
  import requests
4
  import os
5
 
6
+ # === GET API KEY FROM SECRETS ===
 
7
  GROQ_API_KEY = os.getenv("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")
8
  GROQ_MODEL = "llama3-70b-8192"
9
  GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
10
 
11
+ # === DEBUG OUTPUT TO GRADIO UI ===
12
+ def debug_env():
13
+ if GROQ_API_KEY is None:
14
+ return "❌ GROQ_API_KEY is NOT found in environment variables."
15
+ elif not GROQ_API_KEY.startswith("gsk_"):
16
+ return f"⚠️ GROQ_API_KEY is set, but seems invalid: {GROQ_API_KEY[:6]}..."
17
+ else:
18
+ return f"βœ… GROQ_API_KEY loaded and starts correctly: {GROQ_API_KEY[:6]}..."
19
 
20
  # === IMAGE TO BASE64 ===
 
21
  def image_to_base64(image_path):
22
  try:
23
  with open(image_path, "rb") as image_file:
24
+ return base64.b64encode(image_file.read()).decode("utf-8")
25
+ except Exception:
 
26
  return None
27
 
 
28
  # === PROMPT BUILDER ===
 
29
  def build_prompt(image_b64: str) -> str:
30
  return f"""
31
  You are an expert in Non-Destructive Testing (NDT) and industrial defect analysis.
32
 
33
+ A user has uploaded an image of a defected component. Here's the base64 representation of that image (partial): {image_b64[:300]}...
34
 
35
+ Analyze the defect and provide structured output:
36
 
37
  1. Defect Type:
38
  2. Recommended NDT Technique(s):
 
43
  7. Preventive Measures:
44
  """
45
 
 
46
  # === GROQ API CALL ===
 
47
  def query_groq(prompt: str) -> str:
48
+ if not GROQ_API_KEY:
49
+ return "❌ Error: GROQ_API_KEY is missing. Check Space secrets."
50
+ if not GROQ_API_KEY.startswith("gsk_"):
51
+ return "❌ Error: GROQ_API_KEY seems invalid. Should start with 'gsk_'."
52
 
53
  headers = {
54
  "Authorization": f"Bearer {GROQ_API_KEY}",
 
68
  try:
69
  response = requests.post(GROQ_API_URL, headers=headers, json=payload)
70
  if response.status_code == 401:
71
+ return "❌ Error 401: Invalid API Key. Check your Space secret."
72
  elif response.status_code != 200:
73
  return f"❌ Error {response.status_code}: {response.text}"
 
74
  return response.json()["choices"][0]["message"]["content"]
 
75
  except Exception as e:
76
+ return f"❌ Exception: {str(e)}"
 
77
 
78
  # === MAIN ANALYSIS FUNCTION ===
 
79
  def analyze_defect(image_path):
80
  if not image_path:
81
+ return "⚠️ Please upload an image."
82
 
83
  image_b64 = image_to_base64(image_path)
84
  if not image_b64:
85
+ return "❌ Failed to read the image. Try a different file."
86
 
87
  prompt = build_prompt(image_b64)
88
  return query_groq(prompt)
89
 
90
+ # === GRADIO UI WITH DEBUG TAB ===
91
+ with gr.Blocks() as demo:
92
+ gr.Markdown("# πŸ› οΈ NDT Defect Analyzer")
93
 
94
+ with gr.Tab("Analyze Image"):
95
+ image_input = gr.Image(type="filepath", label="Upload Defective Component Image")
96
+ output_box = gr.Textbox(label="Defect Analysis Report")
97
+ analyze_btn = gr.Button("Analyze")
98
+ analyze_btn.click(analyze_defect, inputs=image_input, outputs=output_box)
99
 
100
+ with gr.Tab("πŸ” Debug API Key"):
101
+ debug_output = gr.Textbox(label="Groq Key Status")
102
+ debug_btn = gr.Button("Check Key")
103
+ debug_btn.click(fn=debug_env, inputs=[], outputs=debug_output)
 
 
 
104
 
105
+ # Run app
106
  if __name__ == "__main__":
107
  demo.launch()