File size: 4,786 Bytes
9d55965
 
 
fd64baa
 
9d55965
fd64baa
 
 
9d55965
 
 
 
b2155f4
 
 
 
9d55965
b2155f4
 
 
 
 
 
 
 
 
 
9d55965
 
b2155f4
 
 
9d55965
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd64baa
 
 
 
9d55965
fd64baa
9d55965
fd64baa
 
 
 
9d55965
fd64baa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import streamlit as st
from huggingface_hub import HfApi, create_repo, upload_file
import os
import requests
import json

# Set up Google API key
google_api_key = st.secrets["googleapi"]
google_api_url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={google_api_key}"

# App title
st.title("HF DevAssist - Create and Manage Hugging Face Spaces")

# Input for Hugging Face token
if "hf_token" not in st.session_state:
    st.session_state["hf_token"] = None

st.subheader("Authenticate with Hugging Face")
if st.session_state["hf_token"] is None:
    token_input = st.text_input("Enter your Hugging Face Access Token:", type="password")
    if token_input:
        st.session_state["hf_token"] = token_input
        st.success("Token saved.")
else:
    st.write("Token already saved.")

if st.session_state["hf_token"] is None:
    st.error("Please provide a valid Hugging Face token to proceed.")
    st.stop()

hf_api_key = st.session_state["hf_token"]

# Authenticate Hugging Face API
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 Google API
            st.info("Generating app code using Google API...")
            payload = {
                "contents": [
                    {
                        "parts": [{"text": f"Generate a Streamlit app with the following description: {app_description}. Include the app code followed by '### requirements.txt' and the dependencies required."}]
                    }
                ]
            }
            headers = {"Content-Type": "application/json"}
            response = requests.post(google_api_url, headers=headers, json=payload)

            if response.status_code != 200:
                st.error(f"Google API request failed with status code {response.status_code}: {response.text}")
                st.stop()

            generated_code = response.json()["contents"][0]["parts"][0]["text"]
            st.text_area("Debug: Google API Response", generated_code, height=150)

            # Split generated code
            try:
                app_code, req_code = generated_code.split("### requirements.txt")
                app_code = app_code.strip()
                req_code = req_code.strip()
            except ValueError:
                st.error("The Google API response did not contain the expected sections. Please try again.")
                st.stop()

            # 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")