Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import google.generativeai as genai
|
4 |
+
import gradio as gr
|
5 |
+
|
6 |
+
# Configure the Gemini API
|
7 |
+
genai.configure(api_key=os.environ["GEMINI_API_KEY"])
|
8 |
+
|
9 |
+
# Generation configuration
|
10 |
+
generation_config = {
|
11 |
+
"temperature": 1,
|
12 |
+
"top_p": 0.95,
|
13 |
+
"top_k": 64,
|
14 |
+
"max_output_tokens": 8192,
|
15 |
+
"response_mime_type": "text/plain",
|
16 |
+
}
|
17 |
+
|
18 |
+
# Define the model
|
19 |
+
model = genai.GenerativeModel(
|
20 |
+
model_name="gemini-1.5-flash",
|
21 |
+
generation_config=generation_config,
|
22 |
+
)
|
23 |
+
|
24 |
+
# Function to generate substeps recursively
|
25 |
+
def generate_substeps(reactants, products):
|
26 |
+
prompt = f"Given reactants: {reactants} and products: {products}, break down the reaction mechanism into simple steps and provide in JSON format."
|
27 |
+
|
28 |
+
chat_session = model.start_chat(history=[])
|
29 |
+
response = chat_session.send_message(prompt)
|
30 |
+
|
31 |
+
# Extract the JSON output
|
32 |
+
try:
|
33 |
+
steps = json.loads(response.text)
|
34 |
+
except json.JSONDecodeError:
|
35 |
+
steps = {"error": "Failed to decode JSON from Gemini response."}
|
36 |
+
|
37 |
+
# Recursively break down each step if possible
|
38 |
+
for step in steps:
|
39 |
+
step_reactants = steps[step][0] # reactants in this step
|
40 |
+
step_products = steps[step][1] # products in this step
|
41 |
+
reason = steps[step][2] # reason in this step
|
42 |
+
|
43 |
+
if reason != "found through experiment":
|
44 |
+
substeps = generate_substeps(step_reactants, step_products)
|
45 |
+
steps[step].append({"substeps": substeps})
|
46 |
+
|
47 |
+
return steps
|
48 |
+
|
49 |
+
# Gradio interface
|
50 |
+
def process_reaction(reactants, products):
|
51 |
+
steps = generate_substeps(reactants, products)
|
52 |
+
return json.dumps(steps, indent=4)
|
53 |
+
|
54 |
+
# Create the Gradio interface
|
55 |
+
iface = gr.Interface(
|
56 |
+
fn=process_reaction,
|
57 |
+
inputs=[gr.Textbox(label="Reactants (comma-separated)"), gr.Textbox(label="Products (comma-separated)")],
|
58 |
+
outputs="json",
|
59 |
+
title="Chemistry Rationalizer",
|
60 |
+
description="Break down a reaction mechanism into recursive steps."
|
61 |
+
)
|
62 |
+
|
63 |
+
if __name__ == "__main__":
|
64 |
+
iface.launch()
|