shivrajkarewar commited on
Commit
3a7bfe7
·
verified ·
1 Parent(s): 860dbf0

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -170
app.py DELETED
@@ -1,170 +0,0 @@
1
- import os
2
- import requests
3
- import gradio as gr
4
- import json # For handling JSON responses
5
- from pymatgen.core import Structure, Lattice
6
- from pymatgen.io.cif import CifWriter
7
- from pymatgen.io.xyz import XYZ
8
-
9
- # Retrieve the API key from the environment variable
10
- groq_api_key = os.getenv("GROQ_API_KEY")
11
- if not groq_api_key:
12
- raise ValueError("GROQ_API_KEY is missing! Set it in the Hugging Face Spaces 'Secrets'.")
13
-
14
- # Define the API endpoint and headers
15
- url = "https://api.groq.com/openai/v1/chat/completions"
16
- headers = {"Authorization": f"Bearer {groq_api_key}"}
17
-
18
- # Function to interact with Groq API
19
- def get_material_info(user_input):
20
- json_format = """
21
- ```json
22
- {
23
- "materials": [
24
- {
25
- "Material Name": "...",
26
- "Key Properties": {
27
- "Property 1": "value unit",
28
- "Property 2": "value unit",
29
- "...": "..."
30
- },
31
- "Suitability Explanation": "...",
32
- "Atomic Structure": "..."
33
- },
34
- {
35
- "Material Name": "...",
36
- "Key Properties": {
37
- "Property 1": "value unit",
38
- "Property 2": "value unit",
39
- "...": "..."
40
- },
41
- "Suitability Explanation": "...",
42
- "Atomic Structure": "..."
43
- },
44
- {
45
- "Material Name": "...",
46
- "Key Properties": {
47
- "Property 1": "value unit",
48
- "Property 2": "value unit",
49
- "...": "..."
50
- },
51
- "Suitability Explanation": "...",
52
- "Atomic Structure": "..."
53
- }
54
- ]
55
- }
56
- ```
57
- """
58
- prompt = f"""You are a materials science expert. A user is asking for applications of materials.
59
- Based on the user's request: "{user_input}", identify the 3 best materials for this application.
60
- For each material, provide:
61
- - Material Name:
62
- - Key Properties relevant to the application: (e.g., strength, conductivity, melting point) with values if possible.
63
- - A brief explanation of why this material is suitable for the application.
64
- - A simplified representation of its atomic structure (if readily available and can be described textually, e.g., "FCC lattice", "HCP lattice", or a simple chemical formula with a basic structural description).
65
-
66
- Format your response as a JSON object with the following structure:
67
- {json_format}
68
- """
69
- body = {
70
- "model": "llama-3.1-8b-instant",
71
- "messages": [{"role": "user", "content": prompt}]
72
- }
73
-
74
- response = requests.post(url, headers=headers, json=body)
75
-
76
- if response.status_code == 200:
77
- try:
78
- return json.loads(response.json()['choices'][0]['message']['content'])
79
- except json.JSONDecodeError:
80
- return f"Error decoding JSON: {response.text}"
81
- else:
82
- return f"Error: {response.json()}"
83
-
84
- def create_structure_file(material_info, file_format="xyz"):
85
- if not isinstance(material_info, dict) or "materials" not in material_info or not material_info["materials"]:
86
- return "No material information found to create structure file.", None
87
-
88
- # Choose the first material for structure generation (can be modified to let user choose)
89
- first_material = material_info["materials"][0]
90
- structure_description = first_material.get("Atomic Structure", "")
91
- material_name = first_material.get("Material Name", "unknown")
92
-
93
- if not structure_description:
94
- return f"No atomic structure information available for {material_name}.", None
95
-
96
- # Attempt to create a basic structure based on the description
97
- try:
98
- if "FCC lattice" in structure_description.lower():
99
- lattice = Lattice.cubic(4.0) # Example lattice parameter
100
- structure = Structure(lattice, ["A", "A", "A", "A"], [[0, 0, 0], [0.5, 0.5, 0], [0.5, 0, 0.5], [0, 0.5, 0.5]])
101
- elif "HCP lattice" in structure_description.lower():
102
- lattice = Lattice.hexagonal(3.0, 5.0) # Example lattice parameters
103
- structure = Structure(lattice, ["A", "A"], [[0, 0, 0], [1/3, 2/3, 1/2]])
104
- elif structure_description and len(structure_description.split()) == 2: # Attempt simple diatomic
105
- formula, struct = structure_description.split()
106
- if len(formula) == 2 and len(struct.lower()) == 3 and "unit" in struct.lower():
107
- lattice = Lattice.cubic(3.5) # Another example
108
- structure = Structure(lattice, [formula[0], formula[1]], [[0, 0, 0], [0.5, 0.5, 0.5]])
109
- else:
110
- return f"Could not interpret the atomic structure description for {material_name}.", None
111
-
112
- # Limit to 20 atoms if the generated structure has more
113
- if structure.num_sites > 20:
114
- structure = structure[:20]
115
-
116
- if file_format == "xyz":
117
- filepath = f"{material_name.replace(' ', '_')}_20atoms.xyz"
118
- XYZ(structure).write_file(filepath)
119
- elif file_format == "cif":
120
- filepath = f"{material_name.replace(' ', '_')}_20atoms.cif"
121
- CifWriter(structure, symprec=1e-5).write_file(filepath)
122
- else:
123
- return f"Unsupported file format: {file_format}", None
124
-
125
- with open(filepath, 'r') as f:
126
- file_content = f.read()
127
- os.remove(filepath) # Clean up the temporary file
128
- return f"Successfully created {file_format} file for {material_name} (first 20 atoms).", file_content
129
-
130
- except Exception as e:
131
- return f"Error creating structure file for {material_name}: {e}", None
132
-
133
- def chat_and_generate(user_input, file_format):
134
- material_info = get_material_info(user_input)
135
- structure_message, file_content = create_structure_file(material_info, file_format)
136
-
137
- output_text = ""
138
- if isinstance(material_info, dict) and "materials" in material_info:
139
- for i, material in enumerate(material_info["materials"]):
140
- output_text += f"**Material {i+1}: {material['Material Name']}**\n"
141
- output_text += f"Key Properties: {', '.join([f'{k}: {v}' for k, v in material['Key Properties'].items()])}\n"
142
- output_text += f"Suitability: {material['Suitability Explanation']}\n"
143
- output_text += f"Atomic Structure: {material['Atomic Structure']}\n\n"
144
- else:
145
- output_text = str(material_info)
146
-
147
- return output_text, structure_message, file_content
148
-
149
- # Create Gradio interface
150
- inputs = [
151
- gr.Textbox(lines=2, placeholder="Ask for material applications (e.g., 'materials for high-temperature superconductors')."),
152
- gr.Radio(["xyz", "cif"], label="Generate Structure File (first material)", value="xyz")
153
- ]
154
- outputs = [
155
- gr.Markdown(),
156
- gr.Textbox(label="Structure Generation Status"),
157
- gr.Code(label="Generated Structure File Content")
158
- ]
159
-
160
- interface = gr.Interface(
161
- fn=chat_and_generate,
162
- inputs=inputs,
163
- outputs=outputs,
164
- title="Materials Science Expert AI",
165
- description="Ask about applications of materials and get information on the top 3 candidates with their properties and a generated atomic structure file (first 20 atoms).",
166
- )
167
-
168
- # Launch Gradio app
169
- if __name__ == "__main__":
170
- interface.launch()