Mahrukhh commited on
Commit
78e66ed
Β·
verified Β·
1 Parent(s): 526573c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -82
app.py CHANGED
@@ -1,43 +1,37 @@
1
  import os
2
  import gradio as gr
3
- import base64
4
  import requests
 
5
  from PIL import Image
6
  from io import BytesIO
7
 
8
- # Set your Groq API Key
9
  GROQ_API_KEY = os.getenv("GROQ_API_KEY") or "PASTE_YOUR_GROQ_API_KEY_HERE"
10
- GROQ_MODEL = "llama3-8b-8192"
11
  GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
 
12
 
13
- history = []
14
-
15
- def analyze_image_with_prompt(image, user_prompt):
16
- global history
17
-
18
  if image is None or not user_prompt.strip():
19
- return "⚠️ Please upload an image and ask a question."
20
 
 
21
  buffered = BytesIO()
22
  image.save(buffered, format="JPEG")
23
  img_base64 = base64.b64encode(buffered.getvalue()).decode()
24
 
25
- if not history:
26
- history.append({
27
- "role": "system",
28
- "content": (
29
- "You are a professional construction assistant. Users upload images and describe damage. Based on the description, provide:\n"
30
- "- Type of construction damage\n"
31
- "- Possible causes\n"
32
- "- Recommended tools/materials\n"
33
- "- Estimated repair time"
34
- )
35
- })
36
 
37
- history.append({
38
- "role": "user",
39
- "content": f"Image uploaded. Description: {user_prompt}"
40
- })
41
 
42
  headers = {
43
  "Authorization": f"Bearer {GROQ_API_KEY}",
@@ -46,67 +40,53 @@ def analyze_image_with_prompt(image, user_prompt):
46
 
47
  payload = {
48
  "model": GROQ_MODEL,
49
- "messages": history,
50
  "temperature": 0.7
51
  }
52
 
53
- response = requests.post(GROQ_URL, headers=headers, json=payload)
54
-
55
- if response.status_code == 200:
56
  reply = response.json()["choices"][0]["message"]["content"]
57
- history.append({"role": "assistant", "content": reply})
58
  return reply
59
- else:
60
- return f"\u274c Error: {response.status_code}\n{response.text}"
61
-
62
- def reset_session():
63
- global history
64
- history = []
65
- return "βœ… Session reset. Please upload a new image and ask a question."
66
-
67
- # UI Design
68
- with gr.Blocks(theme=gr.themes.Base(), css="""
69
- #main-box {background-color: #f4f4f9; border-radius: 20px; padding: 2rem; box-shadow: 0 4px 12px rgba(0,0,0,0.1);}
70
- h1, h2, h3 {color: #2c3e50;}
71
- .gr-button {border-radius: 10px !important; font-weight: bold; font-size: 1rem;}
72
- .gr-textbox textarea {font-size: 1rem;}
73
- .gr-textbox label {font-weight: bold; color: #34495e;}
74
- .gr-image label {font-weight: bold; color: #34495e;}
75
- """) as demo:
76
-
77
- with gr.Column(elem_id="main-box"):
78
- gr.Markdown("""
79
- # πŸ—οΈ Construction Damage Assistant
80
- Upload a picture and describe the issue to get detailed construction repair guidance.
81
- """)
82
-
83
- with gr.Row():
84
- with gr.Column(scale=1):
85
- img_input = gr.Image(
86
- type="pil",
87
- label="πŸ“€ Upload Picture of Damage",
88
- height=300
89
- )
90
-
91
- prompt_input = gr.Textbox(
92
- lines=4,
93
- label="πŸ“ Ask Your Question or Describe the Problem",
94
- placeholder="e.g., What caused this crack? How to fix it?"
95
- )
96
-
97
- with gr.Row():
98
- submit_btn = gr.Button("πŸ” Analyze Issue", variant="primary")
99
- reset_btn = gr.Button("πŸ” Start New Session")
100
-
101
- with gr.Column(scale=1):
102
- output = gr.Textbox(
103
- label="🧠 AI Assistant's Response",
104
- lines=20,
105
- show_copy_button=True
106
- )
107
-
108
- submit_btn.click(analyze_image_with_prompt, inputs=[img_input, prompt_input], outputs=[output])
109
- reset_btn.click(reset_session, outputs=[output])
110
-
111
- # Launch the app
112
  demo.launch()
 
1
  import os
2
  import gradio as gr
 
3
  import requests
4
+ import base64
5
  from PIL import Image
6
  from io import BytesIO
7
 
8
+ # Set your Groq API key
9
  GROQ_API_KEY = os.getenv("GROQ_API_KEY") or "PASTE_YOUR_GROQ_API_KEY_HERE"
 
10
  GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
11
+ GROQ_MODEL = "llama3-70b-8192"
12
 
13
+ def analyze_damage(image, user_prompt):
 
 
 
 
14
  if image is None or not user_prompt.strip():
15
+ return "⚠️ Please upload an image and enter a question or description."
16
 
17
+ # Convert image to base64 for potential future use
18
  buffered = BytesIO()
19
  image.save(buffered, format="JPEG")
20
  img_base64 = base64.b64encode(buffered.getvalue()).decode()
21
 
22
+ system_prompt = (
23
+ "You are a helpful construction engineer. The user has uploaded an image of some construction damage "
24
+ "and has asked a question. Based on the image and their description or question, identify:\n"
25
+ "- Type of damage\n"
26
+ "- Possible causes\n"
27
+ "- Recommended repair materials/tools\n"
28
+ "- Estimated repair time"
29
+ )
 
 
 
30
 
31
+ messages = [
32
+ {"role": "system", "content": system_prompt},
33
+ {"role": "user", "content": f"Image uploaded.\nQuestion: {user_prompt}"}
34
+ ]
35
 
36
  headers = {
37
  "Authorization": f"Bearer {GROQ_API_KEY}",
 
40
 
41
  payload = {
42
  "model": GROQ_MODEL,
43
+ "messages": messages,
44
  "temperature": 0.7
45
  }
46
 
47
+ try:
48
+ response = requests.post(GROQ_URL, headers=headers, json=payload)
49
+ response.raise_for_status()
50
  reply = response.json()["choices"][0]["message"]["content"]
 
51
  return reply
52
+ except Exception as e:
53
+ return f"❌ Error: {str(e)}"
54
+
55
+ # Gradio UI
56
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange")) as demo:
57
+ gr.Markdown("# πŸ—οΈ Construction Damage Assistant")
58
+
59
+ gr.Markdown("""
60
+ Upload an image of the damage and ask a question like:<br>
61
+ πŸ”Ή *What type of crack is this?*<br>
62
+ οΏ½οΏ½οΏ½ *What material should I use to fix it?*<br><br>
63
+ The assistant will analyze your question and give expert suggestions.
64
+ """, elem_classes="description-box")
65
+
66
+ with gr.Row():
67
+ with gr.Column(scale=1):
68
+ image_input = gr.Image(label="πŸ“Έ Upload Damage Photo", type="pil", height=280)
69
+
70
+ question_input = gr.Textbox(
71
+ label="🧾 Ask a Question or Describe the Problem",
72
+ placeholder="e.g., What caused this crack? How do I fix it?",
73
+ lines=3
74
+ )
75
+
76
+ submit_btn = gr.Button("πŸ” Analyze", variant="primary")
77
+ clear_btn = gr.Button("🧹 Clear Inputs")
78
+
79
+ with gr.Column(scale=1.5):
80
+ output = gr.Textbox(
81
+ label="πŸ’‘ AI Response",
82
+ lines=18,
83
+ show_copy_button=True
84
+ )
85
+
86
+ submit_btn.click(fn=analyze_damage, inputs=[image_input, question_input], outputs=output)
87
+ clear_btn.click(lambda: (None, "", ""), outputs=[image_input, question_input, output])
88
+
89
+ gr.Markdown("___")
90
+ gr.Markdown("πŸ”§ Powered by **Groq LLaMA3** | Built with ❀️ using **Gradio**")
91
+
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  demo.launch()