shivrajkarewar commited on
Commit
9a08316
·
verified ·
1 Parent(s): 77e7f70

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -81
app.py CHANGED
@@ -1,10 +1,10 @@
1
  import os
2
  import requests
3
  import gradio as gr
4
- import matplotlib.pyplot as plt
5
- from ase.build import bulk
6
- from ase.visualize.plot import plot_atoms
7
- from io import BytesIO
8
 
9
  # Retrieve the API key from the environment variable
10
  groq_api_key = os.getenv("GROQ_API_KEY")
@@ -16,90 +16,73 @@ if not groq_api_key:
16
  url = "https://api.groq.com/openai/v1/chat/completions"
17
  headers = {"Authorization": f"Bearer {groq_api_key}"}
18
 
19
- # Helper function to generate structure visualization
20
- def visualize_structure(material: str):
21
- """
22
- Generate an atomic structure visualization for a given material.
23
-
24
- Parameters:
25
- - material (str): Chemical symbol of the material (e.g., 'Fe' for iron).
26
-
27
- Returns:
28
- - BytesIO object containing the image data if successful, None otherwise.
29
- """
30
- try:
31
- # Create a bulk structure; adjust 'crystalstructure' as needed
32
- atoms = bulk(material, crystalstructure='fcc') # Default to face-centered cubic
33
- except Exception as e:
34
- print(f"Error creating structure for {material}: {e}")
35
- return None
36
-
37
- # Plot the atomic structure
38
- fig, ax = plt.subplots(figsize=(4, 4))
39
- plot_atoms(atoms, ax, radii=0.3, rotation=('45x,45y,0z'), show_unit_cell=2)
40
- buf = BytesIO()
41
- plt.tight_layout()
42
- plt.savefig(buf, format="png")
43
- buf.seek(0)
44
- return buf
45
-
46
- # Function to interact with Groq API and return 3 best materials with visuals
47
- def recommend_materials(user_input):
48
- """
49
- Recommend three materials for a given application and provide their visualizations.
50
-
51
- Parameters:
52
- - user_input (str): Description of the application.
53
-
54
- Returns:
55
- - Tuple containing:
56
- - Recommendations and properties as a string.
57
- - List of BytesIO objects containing images of the atomic structures.
58
- """
59
- prompt = f"You are a materials science expert. Recommend the 3 best materials for the following application: '{user_input}'. " \
60
- f"For each material, list key properties (e.g., mechanical, thermal, chemical)."
61
-
62
  body = {
63
  "model": "llama-3.1-8b-instant",
64
- "messages": [{"role": "user", "content": prompt}]
65
  }
66
-
67
  response = requests.post(url, headers=headers, json=body)
68
-
69
- if response.status_code != 200:
70
- return f"Error: {response.json()}", [None, None, None]
71
-
72
- reply = response.json()['choices'][0]['message']['content']
73
-
74
- # Extract material names from the response
75
- lines = reply.splitlines()
76
- materials = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  for line in lines:
78
- if line.strip().startswith(("1.", "2.", "3.")):
79
- words = line.split()
80
- if len(words) > 1:
81
- material = words[1].strip(",.")
82
- materials.append(material)
83
- if len(materials) == 3:
84
- break
85
-
86
- # Generate visualizations for each material
87
- images = [visualize_structure(mat) for mat in materials]
88
-
89
- return reply, images
90
-
91
- # Gradio Interface
 
 
 
 
 
 
 
 
 
92
  interface = gr.Interface(
93
- fn=recommend_materials,
94
- inputs=gr.Textbox(lines=2, placeholder="e.g., High strength lightweight material for aerospace"),
95
- outputs=[
96
- gr.Textbox(label="Recommended Materials & Properties"),
97
- gr.Image(label="Atomic Structure of Material 1"),
98
- gr.Image(label="Atomic Structure of Material 2"),
99
- gr.Image(label="Atomic Structure of Material 3")
100
- ],
101
  title="Materials Science Expert",
102
- description="Ask for the best materials for your application. Get 3 top recommendations with key properties and atomic structure visualizations."
103
  )
104
 
105
  # Launch Gradio app
 
1
  import os
2
  import requests
3
  import gradio as gr
4
+ from pymatgen.core import Structure, Lattice
5
+ from pymatgen.io.cif import CifWriter
6
+ import tempfile
7
+ import shutil
8
 
9
  # Retrieve the API key from the environment variable
10
  groq_api_key = os.getenv("GROQ_API_KEY")
 
16
  url = "https://api.groq.com/openai/v1/chat/completions"
17
  headers = {"Authorization": f"Bearer {groq_api_key}"}
18
 
19
+ # Function to get material recommendations from Groq API
20
+ def get_material_recommendations(application):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  body = {
22
  "model": "llama-3.1-8b-instant",
23
+ "messages": [{"role": "user", "content": f"Recommend three best materials for {application} with their key properties."}]
24
  }
25
+
26
  response = requests.post(url, headers=headers, json=body)
27
+
28
+ if response.status_code == 200:
29
+ return response.json()['choices'][0]['message']['content']
30
+ else:
31
+ return f"Error: {response.json()}"
32
+
33
+ # Function to create dummy structures for visualization
34
+ def create_dummy_structure(material_name):
35
+ # This function creates a simple cubic structure as a placeholder
36
+ lattice = Lattice.cubic(3.5)
37
+ structure = Structure(
38
+ lattice,
39
+ ["Si"],
40
+ [[0, 0, 0]]
41
+ )
42
+ return structure
43
+
44
+ # Function to generate CIF files and visualize structures
45
+ def generate_and_visualize(application):
46
+ # Get material recommendations
47
+ recommendations = get_material_recommendations(application)
48
+
49
+ # Parse the recommendations to extract material names
50
+ # For simplicity, we'll assume the material names are listed as:
51
+ # 1. Material A
52
+ # 2. Material B
53
+ # 3. Material C
54
+ lines = recommendations.split('\n')
55
+ material_names = []
56
  for line in lines:
57
+ if line.strip().startswith(('1.', '2.', '3.')):
58
+ parts = line.split('.')
59
+ if len(parts) > 1:
60
+ material_name = parts[1].strip().split(' ')[0]
61
+ material_names.append(material_name)
62
+
63
+ # Create temporary directory to store CIF files
64
+ temp_dir = tempfile.mkdtemp()
65
+ cif_file_paths = []
66
+ for name in material_names:
67
+ structure = create_dummy_structure(name)
68
+ cif_path = os.path.join(temp_dir, f"{name}.cif")
69
+ writer = CifWriter(structure)
70
+ writer.write_file(cif_path)
71
+ cif_file_paths.append(cif_path)
72
+
73
+ # Display the recommendations and provide CIF files for download
74
+ output_text = recommendations
75
+ download_links = [gr.File(cif_path, label=os.path.basename(cif_path)) for cif_path in cif_file_paths]
76
+
77
+ return output_text, download_links
78
+
79
+ # Create Gradio interface
80
  interface = gr.Interface(
81
+ fn=generate_and_visualize,
82
+ inputs=gr.Textbox(lines=2, placeholder="Enter application (e.g., aerospace structural component)"),
83
+ outputs=[gr.Textbox(label="Material Recommendations"), gr.File(label="Download CIF Files")],
 
 
 
 
 
84
  title="Materials Science Expert",
85
+ description="Enter a specific application to get the top 3 material recommendations with their properties and download their CIF files."
86
  )
87
 
88
  # Launch Gradio app