shivrajkarewar commited on
Commit
413f976
·
verified ·
1 Parent(s): dec32d6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -38
app.py CHANGED
@@ -1,36 +1,55 @@
1
  import os
2
  import requests
3
  import gradio as gr
 
 
 
 
 
 
 
4
 
5
- # Retrieve the API key from the environment variable
6
  groq_api_key = os.getenv("GROQ_API_KEY")
7
-
8
  if not groq_api_key:
9
- raise ValueError("GROQ_API_KEY is missing! Set it in the Hugging Face Spaces 'Secrets'.")
10
 
11
- # Define the API endpoint and headers
12
  url = "https://api.groq.com/openai/v1/chat/completions"
13
  headers = {"Authorization": f"Bearer {groq_api_key}"}
14
 
15
- # Function to interact with Groq API
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def chat_with_groq(user_input):
17
- # Check if question is related to materials science
18
- keywords = [
19
- "material", "materials", "alloy", "composite", "polymer", "ceramic",
20
- "application", "mechanical properties", "thermal properties", "corrosion",
21
- "creep", "fatigue", "strength", "tensile", "impact", "fracture", "modulus"
22
- ]
23
-
24
  if not any(word in user_input.lower() for word in keywords):
25
- return "⚠️ I am an expert in Materials Science, ask me anything about it and I will try my best to answer. Anything outside, feel free to use ChatGPT! 🙂"
26
 
27
  system_prompt = (
28
- "You are an expert materials scientist. When a user asks about the best materials for a specific application, "
29
- "provide the top 3 material choices. First, list the key properties required for that application. Then show a clean, "
30
- "side-by-side comparison in markdown table format of the three materials, with the properties as rows and materials as columns. "
31
- "Include their relevant mechanical, thermal, and chemical properties. Conclude with a brief summary of which might be best depending on the scenario."
 
32
  )
33
-
34
  body = {
35
  "model": "llama-3.1-8b-instant",
36
  "messages": [
@@ -38,16 +57,44 @@ def chat_with_groq(user_input):
38
  {"role": "user", "content": user_input}
39
  ]
40
  }
41
-
42
  response = requests.post(url, headers=headers, json=body)
43
-
44
  if response.status_code == 200:
45
- return response.json()['choices'][0]['message']['content']
 
 
46
  else:
47
  return f"Error: {response.json()}"
48
 
49
- # Build Gradio interface with better layout and custom styling
50
- with gr.Blocks(title="Materials Science Expert Chatbot", css="""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  #orange-btn {
52
  background-color: #f97316 !important;
53
  color: white !important;
@@ -55,32 +102,56 @@ with gr.Blocks(title="Materials Science Expert Chatbot", css="""
55
  font-weight: bold;
56
  }
57
  """) as demo:
58
-
59
- gr.Markdown("## 🧪 Materials Science Expert\nAsk about the best materials for any engineering or industrial application.")
60
 
61
  with gr.Row():
62
  with gr.Column(scale=3):
63
  user_input = gr.Textbox(
 
 
64
  lines=2,
65
- placeholder="e.g. Best materials for high-temperature turbine blades...",
66
- label="Ask your question"
67
  )
 
68
  with gr.Column(scale=1, min_width=100):
69
- submit_btn = gr.Button("Submit", variant="primary", elem_id="orange-btn")
70
 
 
71
  gr.Markdown("#### 📌 Popular Materials Science related questions")
72
- gr.Markdown("""
73
- - What are the best corrosion-resistant materials for marine environments (e.g., desalination)?
74
- - Which materials are ideal for solar panel coatings and desert heat management?
75
- - What materials are used for aerospace structures in extreme climates?
76
- - Best high-strength materials for construction in the Gulf region?
77
- - What advanced materials are used in electric vehicles and batteries in the UAE?
78
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
- output = gr.Markdown()
 
 
 
 
81
 
82
- submit_btn.click(chat_with_groq, inputs=user_input, outputs=output)
 
83
 
84
- # Launch the app
85
  if __name__ == "__main__":
86
  demo.launch()
 
1
  import os
2
  import requests
3
  import gradio as gr
4
+ import pandas as pd
5
+ import markdown
6
+ import tempfile
7
+ from fpdf import FPDF
8
+ from io import BytesIO
9
+ import nglview as nv
10
+ import ipywidgets
11
 
12
+ # API setup
13
  groq_api_key = os.getenv("GROQ_API_KEY")
 
14
  if not groq_api_key:
15
+ raise ValueError("GROQ_API_KEY is missing!")
16
 
 
17
  url = "https://api.groq.com/openai/v1/chat/completions"
18
  headers = {"Authorization": f"Bearer {groq_api_key}"}
19
 
20
+ # Globals to hold table for export
21
+ comparison_table = None
22
+
23
+ # Function to extract markdown table and convert to dataframe
24
+ def extract_table(md):
25
+ global comparison_table
26
+ lines = [line.strip() for line in md.splitlines() if "|" in line and "---" not in line]
27
+ headers = [x.strip() for x in lines[0].split("|")[1:-1]]
28
+ data = []
29
+ for row in lines[1:]:
30
+ values = [x.strip() for x in row.split("|")[1:-1]]
31
+ data.append(values)
32
+ df = pd.DataFrame(data, columns=headers)
33
+ comparison_table = df
34
+ return df
35
+
36
+ # Main chatbot function
37
  def chat_with_groq(user_input):
38
+ keywords = ["material", "materials", "alloy", "composite", "polymer", "ceramic",
39
+ "application", "mechanical", "thermal", "corrosion", "creep", "fatigue",
40
+ "strength", "tensile", "impact", "fracture", "modulus", "AI", "ML", "machine learning"]
41
+
 
 
 
42
  if not any(word in user_input.lower() for word in keywords):
43
+ return "⚠️ I am an expert in Materials Science. Ask me anything about it and I’ll try my best. For other topics, try ChatGPT! 🙂"
44
 
45
  system_prompt = (
46
+ "You are a materials science expert. When a user asks about materials for an application, provide:\n"
47
+ "1. Required properties.\n"
48
+ "2. A markdown table comparing the top 3 materials (rows: properties, columns: materials).\n"
49
+ "3. A short summary of use cases.\n"
50
+ "Only reply with markdown content."
51
  )
52
+
53
  body = {
54
  "model": "llama-3.1-8b-instant",
55
  "messages": [
 
57
  {"role": "user", "content": user_input}
58
  ]
59
  }
60
+
61
  response = requests.post(url, headers=headers, json=body)
62
+
63
  if response.status_code == 200:
64
+ content = response.json()['choices'][0]['message']['content']
65
+ extract_table(content)
66
+ return content
67
  else:
68
  return f"Error: {response.json()}"
69
 
70
+ # File export functions
71
+ def download_csv():
72
+ if comparison_table is not None:
73
+ return comparison_table.to_csv(index=False).encode('utf-8')
74
+ return None
75
+
76
+ def download_pdf():
77
+ if comparison_table is None:
78
+ return None
79
+ pdf = FPDF()
80
+ pdf.add_page()
81
+ pdf.set_font("Arial", size=10)
82
+ col_width = pdf.w / (len(comparison_table.columns) + 1)
83
+ row_height = 8
84
+ for col in comparison_table.columns:
85
+ pdf.cell(col_width, row_height, col, border=1)
86
+ pdf.ln()
87
+ for i in range(len(comparison_table)):
88
+ for item in comparison_table.iloc[i]:
89
+ pdf.cell(col_width, row_height, str(item), border=1)
90
+ pdf.ln()
91
+ output = BytesIO()
92
+ pdf.output(output)
93
+ output.seek(0)
94
+ return output.read()
95
+
96
+ # Build UI
97
+ with gr.Blocks(title="Materials Science Chatbot", css="""
98
  #orange-btn {
99
  background-color: #f97316 !important;
100
  color: white !important;
 
102
  font-weight: bold;
103
  }
104
  """) as demo:
105
+ gr.Markdown("## 🧪 Materials Science Expert\nAsk about materials for any application or property requirements.")
 
106
 
107
  with gr.Row():
108
  with gr.Column(scale=3):
109
  user_input = gr.Textbox(
110
+ label="Ask your question",
111
+ placeholder="e.g. Best materials for heat shields...",
112
  lines=2,
113
+ elem_id="question_box"
 
114
  )
115
+ gr.Markdown("💡 *Hit Enter to submit your query*")
116
  with gr.Column(scale=1, min_width=100):
117
+ submit_btn = gr.Button("Submit", elem_id="orange-btn")
118
 
119
+ # Popular questions section
120
  gr.Markdown("#### 📌 Popular Materials Science related questions")
121
+ popular_questions = [
122
+ "What are the best corrosion-resistant materials for marine environments (e.g., desalination)?",
123
+ "Which materials are ideal for solar panel coatings and desert heat management?",
124
+ "What materials are used for aerospace structures in extreme climates?",
125
+ "Best high-strength materials for construction in the Gulf region?",
126
+ "What advanced materials are used in electric vehicles and batteries in the UAE?",
127
+ "How can one leverage AI/ML techniques in Materials Science?",
128
+ "I’m a recent high school graduate interested in science. How can I explore Materials Science with AI/ML?"
129
+ ]
130
+
131
+ def autofill(question):
132
+ return gr.Textbox.update(value=question)
133
+
134
+ with gr.Row():
135
+ for q in popular_questions:
136
+ gr.Button(q, size="sm").click(autofill, inputs=[], outputs=user_input)
137
+
138
+ # Output
139
+ output_md = gr.Markdown()
140
+
141
+ with gr.Row():
142
+ with gr.Column():
143
+ csv_btn = gr.File(label="Download CSV", visible=False)
144
+ pdf_btn = gr.File(label="Download PDF", visible=False)
145
 
146
+ def submit_and_prepare(user_input):
147
+ response = chat_with_groq(user_input)
148
+ csv_data = download_csv()
149
+ pdf_data = download_pdf()
150
+ return response, gr.File.update(value=("materials.csv", csv_data), visible=True), gr.File.update(value=("materials.pdf", pdf_data), visible=True)
151
 
152
+ submit_btn.click(submit_and_prepare, inputs=user_input, outputs=[output_md, csv_btn, pdf_btn])
153
+ user_input.submit(submit_and_prepare, inputs=user_input, outputs=[output_md, csv_btn, pdf_btn])
154
 
155
+ # Launch
156
  if __name__ == "__main__":
157
  demo.launch()