-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
89 lines (76 loc) · 4.13 KB
/
app.py
File metadata and controls
89 lines (76 loc) · 4.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from flask import Flask, request, jsonify, render_template
import os
from dotenv import load_dotenv
import groq as Groq
import re
import logging
# Load environment variables
load_dotenv()
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
# Initialize Flask app
app = Flask(__name__)
# Initialize Groq client
groq_client = Groq.Client(api_key=GROQ_API_KEY)
# Extract DOT definition
def extract_dot_definition(groq_response):
"""Extract DOT definition using regex."""
pattern = r"(digraph\s+\w+\s*{.*?})"
match = re.search(pattern, groq_response, re.DOTALL)
if match:
return match.group(1)
return None
# Validate DOT definition
def validate_dot_definition(dot_definition):
"""Validate that the DOT definition follows the basic syntax."""
return dot_definition.strip().startswith("digraph")
# Generalized Groq Prompt
def generate_flowchart(description):
prompt = (
f"Create a detailed and visually distinct flowchart in Graphviz DOT language that represents the following process: {description}. "
"The flowchart should be well-structured and clearly defined, with each step represented as a node. "
"Use the following color scheme and formatting guidelines to ensure clarity and visual appeal: \n\n"
"- **Start and End Nodes**: Use a soft, light **blue** color to signify the beginning and the end of the process. Make the nodes round to indicate their special significance.\n"
"- **Process Nodes**: Use a **green** color for process steps, representing actions or tasks that move the process forward. These should be rectangular with slightly rounded corners.\n"
"- **Decision Nodes**: Use a **red** color for decision points, where the flow branches based on conditions. These nodes should be diamond-shaped to visually indicate a decision.\n"
"- **Connecting Edges**: Use a **blue** color for edges to represent the flow between the nodes. The edges should have arrows pointing in the direction of the flow to maintain a logical sequence.\n"
"- **Node Labels**: Ensure that each node is labeled clearly with a short, descriptive text explaining its role in the process.\n"
"- **Clarity**: Avoid unnecessary details and keep the flowchart simple to ensure readability. Ensure that there is no ambiguity in the transitions between nodes.\n"
"- **Layout**: The flow should be organized vertically or horizontally to ensure the layout is easy to follow. Avoid crossing lines as much as possible.\n"
"The flowchart should be easy to follow, visually distinct, and well-organized with clear labels for each step."
)
try:
response = groq_client.chat.completions.create(
messages=[{"role": "user", "content": prompt}],
model="llama3-8b-8192",
)
raw_response = response.choices[0].message.content.strip()
logging.debug(f"Groq API raw response: {raw_response}")
dot_definition = extract_dot_definition(raw_response)
if dot_definition and validate_dot_definition(dot_definition):
return dot_definition
logging.error(f"Invalid DOT definition extracted: {raw_response}")
return None
except Exception as e:
logging.error(f"Groq API Error: {e}")
return None
@app.route('/')
def index():
return render_template('index.html')
@app.route('/generate_flowchart', methods=['POST'])
def generate():
try:
data = request.json
description = data.get('description', '')
if not description:
return jsonify({"error": "No description provided"}), 400
dot_definition = generate_flowchart(description)
if not dot_definition:
return jsonify({"error": "Failed to generate flowchart"}), 500
return jsonify({"dot_definition": dot_definition})
except Exception as e:
logging.error(f"Error in /generate_flowchart endpoint: {e}")
return jsonify({"error": "Internal Server Error"}), 500
if __name__ == '__main__':
# Use the PORT environment variable for deployment (default to 5000 for local dev)
port = int(os.environ.get("PORT", 10000))
app.run(debug=False, host="0.0.0.0", port=port)