Mahrukhh commited on
Commit
baee0d1
Β·
verified Β·
1 Parent(s): 7d40784

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -0
app.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 here (or use HF Secrets)
9
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY") or "PASTE_YOUR_GROQ_API_KEY_HERE"
10
+
11
+ # βœ… Supported model from Groq
12
+ GROQ_MODEL = "llama-3.3-70b-versatile"
13
+ GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
14
+
15
+ # Store history per session
16
+ history = []
17
+
18
+ def analyze_image_with_prompt(image, user_prompt):
19
+ global history
20
+
21
+ # Convert image to base64
22
+ buffered = BytesIO()
23
+ image.save(buffered, format="JPEG")
24
+ img_base64 = base64.b64encode(buffered.getvalue()).decode()
25
+
26
+ # System prompt on first message
27
+ if len(history) == 0:
28
+ system_msg = {
29
+ "role": "system",
30
+ "content": (
31
+ "You are a helpful construction engineer bot. "
32
+ "Given an image of a construction issue and a prompt, identify:\n"
33
+ "- Type of damage\n"
34
+ "- Possible causes\n"
35
+ "- Recommended tools and materials\n"
36
+ "- Estimated repair time.\n"
37
+ "Then answer follow-up questions."
38
+ )
39
+ }
40
+ history.append(system_msg)
41
+ user_msg = {
42
+ "role": "user",
43
+ "content": f"Image base64: {img_base64}\nPrompt: {user_prompt}"
44
+ }
45
+ history.append(user_msg)
46
+ else:
47
+ history.append({"role": "user", "content": user_prompt})
48
+
49
+ headers = {
50
+ "Authorization": f"Bearer {GROQ_API_KEY}",
51
+ "Content-Type": "application/json"
52
+ }
53
+
54
+ payload = {
55
+ "model": GROQ_MODEL,
56
+ "messages": history,
57
+ "temperature": 0.7
58
+ }
59
+
60
+ response = requests.post(GROQ_URL, headers=headers, json=payload)
61
+
62
+ if response.status_code == 200:
63
+ reply = response.json()["choices"][0]["message"]["content"]
64
+ history.append({"role": "assistant", "content": reply})
65
+ return reply
66
+ else:
67
+ return f"❌ Error: {response.status_code}\n{response.text}"
68
+
69
+ # Gradio Interface
70
+ with gr.Blocks() as demo:
71
+ gr.Markdown("## πŸ—οΈ Construction Damage Identifier Chatbot")
72
+ with gr.Row():
73
+ img_input = gr.Image(type="pil", label="Upload Damage Image")
74
+ prompt_input = gr.Textbox(lines=2, label="Your Prompt / Question")
75
+ output = gr.Textbox(label="Bot Response", lines=10)
76
+ submit = gr.Button("Analyze / Ask")
77
+ submit.click(analyze_image_with_prompt, inputs=[img_input, prompt_input], outputs=[output])
78
+ gr.Markdown("πŸ’¬ You can continue asking questions about the uploaded image.")
79
+
80
+ demo.launch()