Muqadas-13 commited on
Commit
5d5446b
Β·
verified Β·
1 Parent(s): 842eba1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -28
app.py CHANGED
@@ -3,33 +3,33 @@ import requests
3
  from PIL import Image
4
  from io import BytesIO
5
  import os
 
 
6
 
7
- # βœ… Load API key from environment
8
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
9
  GROQ_MODEL = "llama3-70b-8192"
10
 
11
- # πŸ”§ Simulated caption (replace later)
 
 
 
 
 
12
  def get_caption(image):
13
- return "This image shows a large crack in the wall extending diagonally."
 
 
 
 
 
14
 
15
- # πŸ’¬ Send prompt to Groq
16
  def generate_response(image, user_query=""):
17
  if GROQ_API_KEY is None:
18
- return "❌ API key not set. Please set GROQ_API_KEY using os.environ."
19
 
20
  caption = get_caption(image)
21
 
22
- prompt = f"""
23
- You are a construction damage analysis assistant. Based on the description: "{caption}", and user question: "{user_query}", provide the following:
24
- 1. Type of damage
25
- 2. Likely cause
26
- 3. Suggested repair solutions
27
- 4. Required tools
28
- 5. Estimated time and cost
29
-
30
- Respond in a helpful tone.
31
- """
32
-
33
  headers = {
34
  "Authorization": f"Bearer {GROQ_API_KEY}",
35
  "Content-Type": "application/json"
@@ -37,15 +37,23 @@ Respond in a helpful tone.
37
 
38
  data = {
39
  "model": GROQ_MODEL,
40
- "messages": [{"role": "user", "content": prompt}]
 
 
 
 
 
41
  }
42
 
43
- response = requests.post("https://api.groq.com/openai/v1/chat/completions", headers=headers, json=data)
44
-
45
- if response.status_code == 200:
46
- return response.json()['choices'][0]['message']['content']
47
- else:
48
- return f"❌ Error {response.status_code}: {response.text}"
 
 
 
49
 
50
  # ============================
51
  # 🌟 Gradio Modern UI
@@ -78,17 +86,17 @@ with gr.Blocks(css="""
78
  }
79
  """) as demo:
80
 
81
- gr.Markdown("<div id='title'>πŸ—οΈ BuildFix AI β€” Construction Damage Inspector</div>")
82
  gr.Markdown("<div id='subtitle'>Upload a construction damage image and get expert analysis with repair suggestions instantly.</div>")
83
 
84
  with gr.Row():
85
  with gr.Column(scale=1, elem_classes="card"):
86
- image_input = gr.Image(type="pil", label="πŸ“Έ Upload Image of Damage")
87
- user_query = gr.Textbox(label="πŸ’¬ Ask a follow-up question (optional)", placeholder="e.g., How expensive is this repair?", lines=2)
88
- submit_btn = gr.Button("πŸ” Analyze", variant="primary")
89
 
90
  with gr.Column(scale=1, elem_classes="card"):
91
- result_output = gr.Textbox(label="🧠 AI Report", lines=20)
92
 
93
  submit_btn.click(fn=generate_response, inputs=[image_input, user_query], outputs=result_output)
94
 
 
3
  from PIL import Image
4
  from io import BytesIO
5
  import os
6
+ import torch
7
+ from transformers import BlipProcessor, BlipForConditionalGeneration
8
 
9
+ # βœ… Load Groq API key from environment (add this in Hugging Face Secrets)
10
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
11
  GROQ_MODEL = "llama3-70b-8192"
12
 
13
+ # βœ… Load BLIP model for image captioning
14
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
15
+ blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
16
+
17
+ # πŸ“Έ Generate caption from image
18
+
19
  def get_caption(image):
20
+ inputs = processor(images=image, return_tensors="pt")
21
+ out = blip_model.generate(**inputs)
22
+ caption = processor.decode(out[0], skip_special_tokens=True)
23
+ return caption
24
+
25
+ # πŸ’¬ Communicate with Groq API
26
 
 
27
  def generate_response(image, user_query=""):
28
  if GROQ_API_KEY is None:
29
+ return "❌ API key not set. Please set GROQ_API_KEY using Hugging Face Secrets."
30
 
31
  caption = get_caption(image)
32
 
 
 
 
 
 
 
 
 
 
 
 
33
  headers = {
34
  "Authorization": f"Bearer {GROQ_API_KEY}",
35
  "Content-Type": "application/json"
 
37
 
38
  data = {
39
  "model": GROQ_MODEL,
40
+ "messages": [
41
+ {"role": "system", "content": "You are a helpful assistant that analyzes construction damage from image captions and gives expert repair advice."},
42
+ {"role": "user", "content": f"Image caption: {caption}"},
43
+ {"role": "user", "content": f"My question is: {user_query or 'No follow-up question.'}"},
44
+ {"role": "user", "content": "Please provide:\n1. Type of damage\n2. Likely cause\n3. Suggested repair solutions\n4. Required tools\n5. Estimated time and cost"}
45
+ ]
46
  }
47
 
48
+ try:
49
+ response = requests.post("https://api.groq.com/openai/v1/chat/completions", headers=headers, json=data, timeout=30)
50
+ if response.status_code == 200:
51
+ content = response.json()['choices'][0]['message']['content']
52
+ return content if content.strip() else "⚠️ No response received. Please try again."
53
+ else:
54
+ return f"❌ Error {response.status_code}: {response.text}"
55
+ except Exception as e:
56
+ return f"❌ Exception: {str(e)}"
57
 
58
  # ============================
59
  # 🌟 Gradio Modern UI
 
86
  }
87
  """) as demo:
88
 
89
+ gr.Markdown("<div id='title'>\ud83c\udfd7\ufe0f BuildFix AI β€” Construction Damage Inspector</div>")
90
  gr.Markdown("<div id='subtitle'>Upload a construction damage image and get expert analysis with repair suggestions instantly.</div>")
91
 
92
  with gr.Row():
93
  with gr.Column(scale=1, elem_classes="card"):
94
+ image_input = gr.Image(type="pil", label="\ud83d\udcf8 Upload Image of Damage")
95
+ user_query = gr.Textbox(label="\ud83d\udcac Ask a follow-up question (optional)", placeholder="e.g., How expensive is this repair?", lines=2)
96
+ submit_btn = gr.Button("\ud83d\udd0d Analyze", variant="primary")
97
 
98
  with gr.Column(scale=1, elem_classes="card"):
99
+ result_output = gr.Textbox(label="\ud83e\uddd0 AI Report", lines=20)
100
 
101
  submit_btn.click(fn=generate_response, inputs=[image_input, user_query], outputs=result_output)
102