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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -31
app.py CHANGED
@@ -3,21 +3,19 @@ import base64
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:
@@ -25,25 +23,20 @@ def image_to_base64(image_path):
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):
39
- 3. Explanation of Defect Cause:
40
- 4. Proposed Solution/Fix:
41
- 5. Estimated Time to Repair:
42
- 6. Tools Required:
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."
@@ -68,40 +61,39 @@ def query_groq(prompt: str) -> str:
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()
 
 
3
  import requests
4
  import os
5
 
6
+ # βœ… LOAD API KEY from Space Secret
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
  def debug_env():
12
  if GROQ_API_KEY is None:
13
+ return "❌ GROQ_API_KEY is NOT found. Did you set the Space Secret and restart the Space?"
14
  elif not GROQ_API_KEY.startswith("gsk_"):
15
+ return f"⚠️ GROQ_API_KEY is loaded but seems malformed: {GROQ_API_KEY[:6]}..."
16
  else:
17
+ return f"βœ… GROQ_API_KEY loaded: {GROQ_API_KEY[:6]}..."
18
 
 
19
  def image_to_base64(image_path):
20
  try:
21
  with open(image_path, "rb") as image_file:
 
23
  except Exception:
24
  return None
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
+ A user has uploaded an image of a defected component. Here's the base64 representation (partial): {image_b64[:300]}...
30
+ Analyze and return the following:
31
+ 1. Defect Type
32
+ 2. Recommended NDT Technique(s)
33
+ 3. Explanation of Defect Cause
34
+ 4. Solution/Fix
35
+ 5. Time to Repair
36
+ 6. Tools Required
37
+ 7. Preventive Measures
 
 
 
38
  """
39
 
 
40
  def query_groq(prompt: str) -> str:
41
  if not GROQ_API_KEY:
42
  return "❌ Error: GROQ_API_KEY is missing. Check Space secrets."
 
61
  try:
62
  response = requests.post(GROQ_API_URL, headers=headers, json=payload)
63
  if response.status_code == 401:
64
+ return "❌ Error 401: Invalid API Key."
65
  elif response.status_code != 200:
66
  return f"❌ Error {response.status_code}: {response.text}"
67
  return response.json()["choices"][0]["message"]["content"]
68
  except Exception as e:
69
  return f"❌ Exception: {str(e)}"
70
 
 
71
  def analyze_defect(image_path):
72
  if not image_path:
73
  return "⚠️ Please upload an image."
74
 
75
  image_b64 = image_to_base64(image_path)
76
  if not image_b64:
77
+ return "❌ Failed to read the image. Try again."
78
 
79
  prompt = build_prompt(image_b64)
80
  return query_groq(prompt)
81
 
82
+ # ==== GRADIO UI ====
83
  with gr.Blocks() as demo:
84
+ gr.Markdown("# πŸ” NDT Defect Analyzer")
85
 
86
  with gr.Tab("Analyze Image"):
87
+ image_input = gr.Image(type="filepath", label="Upload Image")
88
+ output_box = gr.Textbox(label="Analysis Output")
89
  analyze_btn = gr.Button("Analyze")
90
  analyze_btn.click(analyze_defect, inputs=image_input, outputs=output_box)
91
 
92
+ with gr.Tab("Debug API Key"):
93
+ debug_output = gr.Textbox(label="API Key Debug")
94
+ debug_btn = gr.Button("Check")
95
  debug_btn.click(fn=debug_env, inputs=[], outputs=debug_output)
96
 
 
97
  if __name__ == "__main__":
98
  demo.launch()
99
+