File size: 8,361 Bytes
922c3ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
#!/usr/bin/env python3
"""

Hugging Face Spaces Deployment Script

=====================================



This script automates the deployment of the Legal Dashboard OCR system to Hugging Face Spaces.

"""

import os
import sys
import subprocess
import shutil
import json
from pathlib import Path
import logging

# Configure logging
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


class HFDeployment:
    def __init__(self, space_name, username, hf_token):
        self.space_name = space_name
        self.username = username
        self.hf_token = hf_token
        self.project_root = Path(__file__).parent
        self.hf_space_dir = self.project_root / "huggingface_space"

    def validate_structure(self):
        """Validate the project structure before deployment"""
        logger.info("Validating project structure...")

        required_files = [
            "huggingface_space/app.py",
            "huggingface_space/Spacefile",
            "huggingface_space/README.md",
            "requirements.txt",
            "app/services/ocr_service.py",
            "app/services/ai_service.py",
            "app/services/database_service.py"
        ]

        missing_files = []
        for file_path in required_files:
            if not (self.project_root / file_path).exists():
                missing_files.append(file_path)

        if missing_files:
            logger.error(f"Missing required files: {missing_files}")
            return False

        logger.info("βœ… Project structure validation passed")
        return True

    def prepare_deployment_files(self):
        """Prepare files for Hugging Face Space deployment"""
        logger.info("Preparing deployment files...")

        # Copy required files to HF space directory
        files_to_copy = [
            ("requirements.txt", "requirements.txt"),
            ("app/", "app/"),
            ("data/", "data/"),
            ("tests/", "tests/")
        ]

        for src, dst in files_to_copy:
            src_path = self.project_root / src
            dst_path = self.hf_space_dir / dst

            if src_path.exists():
                if src_path.is_dir():
                    if dst_path.exists():
                        shutil.rmtree(dst_path)
                    shutil.copytree(src_path, dst_path)
                else:
                    shutil.copy2(src_path, dst_path)
                logger.info(f"βœ… Copied {src} to {dst}")

        # Create .gitignore for HF space
        gitignore_content = """

# Python

__pycache__/

*.py[cod]

*$py.class

*.so

.Python

build/

develop-eggs/

dist/

downloads/

eggs/

.eggs/

lib/

lib64/

parts/

sdist/

var/

wheels/

*.egg-info/

.installed.cfg

*.egg



# Virtual environments

venv/

env/

ENV/



# IDE

.vscode/

.idea/

*.swp

*.swo



# OS

.DS_Store

Thumbs.db



# Logs

*.log



# Database

*.db

*.sqlite



# Environment variables

.env



# Temporary files

*.tmp

*.temp

"""

        gitignore_path = self.hf_space_dir / ".gitignore"
        with open(gitignore_path, 'w') as f:
            f.write(gitignore_content.strip())

        logger.info("βœ… Deployment files prepared")
        return True

    def create_space(self):
        """Create a new Hugging Face Space"""
        logger.info(
            f"Creating Hugging Face Space: {self.username}/{self.space_name}")

        # This would typically be done via Hugging Face API or web interface
        # For now, we'll provide instructions
        logger.info("""

πŸ“‹ Manual Space Creation Required:



1. Go to https://huggingface.co/spaces

2. Click "Create new Space"

3. Fill in the details:

   - Owner: {username}

   - Space name: {space_name}

   - SDK: Gradio

   - License: MIT

   - Visibility: Public

4. Click "Create Space"



The Space will be created at: https://huggingface.co/spaces/{username}/{space_name}

        """.format(username=self.username, space_name=self.space_name))

        return True

    def setup_git_repository(self):
        """Set up Git repository for the Space"""
        logger.info("Setting up Git repository...")

        # Change to HF space directory
        os.chdir(self.hf_space_dir)

        # Initialize git repository
        subprocess.run(["git", "init"], check=True)

        # Add remote origin
        remote_url = f"https://{self.username}:{self.hf_token}@huggingface.co/spaces/{self.username}/{self.space_name}"
        subprocess.run(
            ["git", "remote", "add", "origin", remote_url], check=True)

        logger.info("βœ… Git repository initialized")
        return True

    def commit_and_push(self):
        """Commit and push changes to Hugging Face Space"""
        logger.info("Committing and pushing changes...")

        try:
            # Add all files
            subprocess.run(["git", "add", "."], check=True)

            # Commit changes
            subprocess.run(
                ["git", "commit", "-m", "Initial deployment of Legal Dashboard OCR"], check=True)

            # Push to main branch
            subprocess.run(["git", "push", "-u", "origin", "main"], check=True)

            logger.info("βœ… Changes pushed successfully")
            return True

        except subprocess.CalledProcessError as e:
            logger.error(f"❌ Git operation failed: {e}")
            return False

    def verify_deployment(self):
        """Verify the deployment was successful"""
        logger.info("Verifying deployment...")

        space_url = f"https://huggingface.co/spaces/{self.username}/{self.space_name}"
        logger.info(f"🌐 Space URL: {space_url}")

        logger.info("""

πŸ“‹ Deployment Verification Checklist:



βœ… Project structure validated

βœ… Deployment files prepared  

βœ… Git repository initialized

βœ… Changes committed and pushed

βœ… Space created on Hugging Face



Next Steps:

1. Visit the Space URL to verify it's building correctly

2. Test the OCR functionality with sample documents

3. Check the logs for any errors

4. Verify all features are working as expected



Space URL: {space_url}

        """.format(space_url=space_url))

        return True

    def deploy(self):
        """Main deployment method"""
        logger.info("πŸš€ Starting Hugging Face Spaces deployment...")

        try:
            # Step 1: Validate structure
            if not self.validate_structure():
                return False

            # Step 2: Prepare deployment files
            if not self.prepare_deployment_files():
                return False

            # Step 3: Create space (manual step)
            self.create_space()

            # Step 4: Setup git repository
            if not self.setup_git_repository():
                return False

            # Step 5: Commit and push
            if not self.commit_and_push():
                return False

            # Step 6: Verify deployment
            self.verify_deployment()

            logger.info("πŸŽ‰ Deployment completed successfully!")
            return True

        except Exception as e:
            logger.error(f"❌ Deployment failed: {e}")
            return False


def main():
    """Main function"""
    print("πŸš€ Legal Dashboard OCR - Hugging Face Spaces Deployment")
    print("=" * 60)

    # Get deployment parameters
    space_name = input(
        "Enter Space name (e.g., legal-dashboard-ocr): ").strip()
    username = input("Enter your Hugging Face username: ").strip()
    hf_token = input("Enter your Hugging Face token: ").strip()

    if not all([space_name, username, hf_token]):
        print("❌ All parameters are required")
        return

    # Create deployment instance
    deployment = HFDeployment(space_name, username, hf_token)

    # Run deployment
    success = deployment.deploy()

    if success:
        print(f"\nπŸŽ‰ Deployment successful!")
        print(
            f"🌐 Visit your Space at: https://huggingface.co/spaces/{username}/{space_name}")
    else:
        print("\n❌ Deployment failed. Please check the logs above.")


if __name__ == "__main__":
    main()