shivrajkarewar commited on
Commit
57ed11e
·
verified ·
1 Parent(s): bc42773

Update app.py

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