engrharis's picture
Create app.py
9d55965 verified
raw
history blame
3.82 kB
import streamlit as st
from huggingface_hub import HfApi, create_repo, upload_file
from groq import Groq
import os
# Set up API keys
hf_api_key = st.secrets["hf_token"]
groq_api_key = st.secrets["devassistapi"]
# Initialize Groq client
client = Groq(api_key=groq_api_key)
# App title
st.title("HF DevAssist - Create and Manage Hugging Face Spaces")
# Authenticate Hugging Face token
st.subheader("Authenticate with Hugging Face")
if not hf_api_key:
st.error("Hugging Face API key is missing. Add it to secrets.")
st.stop()
api = HfApi()
try:
user_info = api.whoami(token=hf_api_key)
st.success(f"Authenticated as {user_info['name']}")
except Exception as e:
st.error(f"Authentication failed: {e}")
st.stop()
# User Input for Space creation
st.subheader("Describe Your App")
space_name = st.text_input("Enter the name for the new or existing Hugging Face Space:")
app_description = st.text_area("Describe the app you want to create:", height=150)
if st.button("Generate and Deploy App"):
if not space_name.strip():
st.error("Space name cannot be empty.")
elif not app_description.strip():
st.error("App description cannot be empty.")
else:
try:
# Generate app code using Groq
st.info("Generating app code using Groq API...")
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": (
f"Generate a Streamlit app based on this description: "
f"'{app_description}'"
),
}
],
model="llama-3.3-70b-versatile",
)
generated_code = chat_completion.choices[0].message.content
# Split generated code into `app.py` and `requirements.txt`
app_code = generated_code.split("### requirements.txt")[0].strip()
req_code = generated_code.split("### requirements.txt")[1].strip()
# Create or update Hugging Face Space
space_full_name = f"{user_info['name']}/{space_name}"
try:
st.info(f"Checking if Space '{space_full_name}' exists...")
api.repo_info(repo_id=space_full_name, repo_type="space", token=hf_api_key)
st.success(f"Space '{space_full_name}' exists. Updating files...")
except:
st.info(f"Space '{space_full_name}' does not exist. Creating new Space...")
create_repo(repo_id=space_name, repo_type="space", space_sdk="streamlit", token=hf_api_key)
# Upload `app.py`
with open("app.py", "w") as app_file:
app_file.write(app_code)
upload_file(
path_or_fileobj="app.py",
path_in_repo="app.py",
repo_id=space_full_name,
repo_type="space",
token=hf_api_key,
)
# Upload `requirements.txt`
with open("requirements.txt", "w") as req_file:
req_file.write(req_code)
upload_file(
path_or_fileobj="requirements.txt",
path_in_repo="requirements.txt",
repo_id=space_full_name,
repo_type="space",
token=hf_api_key,
)
st.success(f"App successfully deployed in Space '{space_full_name}'!")
except Exception as e:
st.error(f"An error occurred: {e}")
finally:
# Clean up temporary files
if os.path.exists("app.py"):
os.remove("app.py")
if os.path.exists("requirements.txt"):
os.remove("requirements.txt")