File size: 3,815 Bytes
9d55965
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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")