chitraGPT / app.py
VishalMysore's picture
Update app.py
d28532e verified
import requests
import subprocess
import tarfile
import os
import shutil
# Try to find the path of the Graphviz executable
graphviz_path = shutil.which("dot")
if graphviz_path:
print("Graphviz executable found at:", graphviz_path)
else:
print("Graphviz executable not found. Please make sure Graphviz is installed and added to your system's PATH.")
def download_and_extract_java_tarball(url, destination):
try:
# Download the tarball
response = requests.get(url, stream=True)
response.raise_for_status()
# Create the destination directory if it doesn't exist
os.makedirs(os.path.dirname(destination), exist_ok=True)
# Write the tarball content to the file
with open(destination, 'wb') as file:
for chunk in response.iter_content(chunk_size=8192):
file.write(chunk)
print(f"Downloaded {url} to {destination}")
# Extract the tarball
with tarfile.open(destination, 'r:gz') as tar:
tar.extractall(os.path.dirname(destination))
extracted_dir = '/tmp/jdk-21.0.2'
print(f"Extracted {destination}")
os.environ["JAVA_HOME"] = extracted_dir
print(f"Contents of tmp: {os.listdir('/tmp')}")
print(f"Set JAVA_HOME to {extracted_dir}")
print(f"Contents of {extracted_dir}: {os.listdir(extracted_dir)}")
except requests.exceptions.RequestException as e:
print(f"Error downloading {url}: {e}")
except tarfile.TarError as e:
print(f"Error extracting {destination}: {e}")
# Example usage
url = "https://download.java.net/java/GA/jdk21.0.2/f2283984656d49d69e91c558476027ac/13/GPL/openjdk-21.0.2_linux-x64_bin.tar.gz"
destination = "/tmp/openjdk-21.0.2_linux-x64_bin.tar.gz"
download_and_extract_java_tarball(url, destination)
def run_java_version():
try:
subprocess.run(['java', '-version'], check=True)
except subprocess.CalledProcessError as e:
print(f"Error occurred: {e}")
def install_openjdk_tmp():
try:
temp_directory = '/tmp'
subprocess.run(['apt-get', 'install', '--download-only', '--yes', '--reinstall', 'openjdk-8-jdk-headless'], check=True, cwd=temp_directory)
subprocess.run(['dpkg', '--install', 'openjdk-8-jdk-headless*.deb'], check=True, cwd=temp_directory)
print("Installation completed successfully.")
except subprocess.CalledProcessError as e:
print(f"Error occurred: {e}")
def install_openjdk():
try:
subprocess.run(['apt-get', 'install', '-y', 'openjdk-8-jdk-headless', '-qq'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
print("Installation completed successfully.")
except subprocess.CalledProcessError as e:
print(f"Error occurred: {e}")
def apt_update():
try:
subprocess.run(['apt', 'update'], check=True)
print("apt update completed successfully.")
except subprocess.CalledProcessError as e:
print(f"Error occurred: {e}")
def download_file(url, destination):
try:
response = requests.get(url)
with open(destination, 'wb') as file:
file.write(response.content)
print(f"Download successful. File saved at: {destination}")
except Exception as e:
print(f"Error downloading file: {e}")
url = "https://github.com/plantuml/plantuml/releases/download/v1.2023.13/plantuml-1.2023.13.jar"
destination = "plantuml-1.2023.13.jar"
download_file(url, destination)
import os #importing os to set environment variable
def install_java():
#apt_update()
install_openjdk_tmp()
os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64" #set environment variable
run_java_version() #check java version
#install_java()
from openai import OpenAI
import os
import random
os.environ["OPENAI_API_KEY"]=os.environ['API_TOKEN']
client = OpenAI()
def generate_example(query,temperature=.5):
print(query)
messages=[
{"role" : "system", "content": "you are an expert in plantuml and will provide the uml for query by user" },
{"role" : "user", "content": query },
]
response = client.chat.completions.create(
model="gpt-3.5-turbo-1106",
response_format={ "type": "text" },
messages=messages,
temperature=temperature,
max_tokens=1000,
)
return response.choices[0].message.content
def generate_image(query):
example = generate_example(query)
print(example)
matches = re.search(r'(@startuml.*?@enduml)', example, re.DOTALL)
if matches:
extracted_content = matches.group(1).strip()
print('extracted content start ')
print(extracted_content)
print('extracted content end')
else:
print("No match found.")
file_path = "/tmp/diagram"
with open(file_path, "w") as file:
file.write(extracted_content)
print(f"generted {file_path}")
run_java_command(file_path)
return {im:gr.Image(file_path+".png",height=500, width=500),outBox:extracted_content}
import gradio as gr
import re
def read_html_file(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
html_content = file.read()
html_content = html_content.encode('ascii', 'ignore').decode('ascii')
html_content= html_content.replace("\n","")
html_content=re.sub( ">\s+<", "><" , html_content)
return html_content
except FileNotFoundError:
print(f"File not found: {file_path}")
return None
except Exception as e:
print(f"An error occurred: {str(e)}")
return None
def run_java_command(file_path):
try:
command = ['/tmp/jdk-21.0.2/bin/java', '-jar', 'plantuml-1.2023.13.jar' ,file_path]
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if process.returncode == 0:
print("Java command executed successfully.")
print("Output:", stdout.decode())
else:
print("Java command failed.")
print("Error:", stderr.decode())
except Exception as e:
print("An error occurred:", str(e))
import gradio as gr
html_content = read_html_file("cookgpt.html")
with gr.Blocks() as demo:
with gr.Tab("ChitraGPT"):
gr.Markdown("Welcome to <b>ChitraGPT</b>, Create Activity, Sequence, Component diagram with just plain english commands. It uses <a href=\'https://plantuml.com/\'> PlantUML</a> and LLM to generate diagrams <br> scroll down below for more examples <br><br> For other interesting AI related work click <a href=\'https://www.linkedin.com/in/vishalrow/\'> here</a> <br><br> ")
diagramQuery = gr.Textbox("create an activity diagram for making tea",label="Diagram Query",info="Write query in plain English")
findbtn = gr.Button(value="Create Diagram")
im = gr.Image("ChitraGPT.gif",type="pil", height=200, width=200)
outBox = gr.Textbox(label="UML Code",info="UML code will appear here")
findbtn.click(generate_image, inputs=[diagramQuery],outputs=[im,outBox])
examples = gr.Examples(examples=[["Create Activity Diagram for making tea."],['Create an activity diagram for the onboarding process of a new employee in a company'],['Create a component diagram outlining the coponents of a system for user checking out a book from the library.'],['create an activity diagram for KYC process of the user in bank'], ["Create Sequence Diagram of user adding a recipe and then modirying it."],["I have 5 microservices, recipe fetch microservice, llm fine tuning microservice, database microservice and add receipe microservice. Create a component diagram for this"],["users can create new recipe and send request via rest call , they can also get new recipe via rest call. the recipes created can be saved to database. Create sequence diagram for it"],["My streaming application has these components , API Gateway service component, Application component , cache component and streaming component. Application component has 3 subcomponents namely Signup, Discovery, Play. Create a component Diagram for it"],["This microservices application orchestrates the seamless delivery of recipes to customers, comprising eight distinct components. The core functionalities include a Recipe Management service responsible for curating and organizing recipes, a Customer Management service ensuring personalized interactions, and an Order Processing service overseeing the handling of customer requests. Additionally, the application incorporates a Shipping service for efficient logistics, a Payment Gateway service to manage transactions securely, and a Notification service for real-time updates. Authentication and Authorization components enhance security, while a centralized Configuration service ensures adaptability. The entire system is orchestrated through containerization, fostering scalability and resilience, making this microservices architecture a robust solution for the streamlined delivery of culinary experiences to customers."]],
inputs=[diagramQuery])
gr.HTML(html_content)
with gr.Tab("AI App Development"):
gr.Markdown("<a href=\'https://www.linkedin.com/pulse/ai-generated-full-stack-application-vishal-mysore-vhagc%3FtrackingId=%252F6fPbpE%252BRFmYtHYi%252BBP5Rg%253D%253D/?trackingId=%2F6fPbpE%2BRFmYtHYi%2BBP5Rg%3D%3D\'> Click here Learn about AI application Development</a>")
gr.HTML(html_content)
with gr.Tab("Intellij Plugin"):
gr.Markdown("<a href=\'https://www.linkedin.com/pulse/ai-generated-full-stack-application-vishal-mysore-vhagc%3FtrackingId=%252F6fPbpE%252BRFmYtHYi%252BBP5Rg%253D%253D/?trackingId=%2F6fPbpE%2BRFmYtHYi%2BBP5Rg%3D%3D\'> Click here Learn about AI application Development</a>")
gr.HTML(html_content)
with gr.Tab("Upload Requirement Document"):
gr.Markdown("Will be able to create entire diagrams from the requirement document <a href=\'https://www.linkedin.com/pulse/ai-generated-full-stack-application-vishal-mysore-vhagc%3FtrackingId=%252F6fPbpE%252BRFmYtHYi%252BBP5Rg%253D%253D/?trackingId=%2F6fPbpE%2BRFmYtHYi%2BBP5Rg%3D%3D\'> Click here Learn about AI application Development</a>")
gr.HTML(html_content)
demo.launch()