noxo8888 commited on
Commit
2f9659d
Β·
verified Β·
1 Parent(s): 4ee40b2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -116
app.py CHANGED
@@ -1,126 +1,138 @@
1
  import gradio as gr
2
- import torch
3
- import gc
4
- from diffusers import StableDiffusionInpaintPipeline
5
- from PIL import Image
6
- import numpy as np
7
- from transformers import SegformerImageProcessor, SegformerForSemanticSegmentation
8
- import cv2
9
- import traceback
10
  import os
11
 
12
- # Set environment variables to prevent warnings and errors
13
- os.environ['TOKENIZERS_PARALLELISM'] = 'false'
14
- os.environ['TORCH_HOME'] = '/tmp/torch'
15
- os.environ['HF_HOME'] = '/tmp/huggingface'
16
-
17
- class RafayyVirtualTryOn:
18
  def __init__(self):
19
- try:
20
- # Clear CUDA cache
21
- if torch.cuda.is_available():
22
- torch.cuda.empty_cache()
23
- gc.collect()
24
-
25
- # Use smaller model for stability
26
- model_id = "runwayml/stable-diffusion-inpainting"
27
- self.inpaint_model = StableDiffusionInpaintPipeline.from_pretrained(
28
- model_id,
29
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
30
- safety_checker=None,
31
- cache_dir='/tmp/models'
32
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- if torch.cuda.is_available():
35
- self.inpaint_model.to("cuda")
36
- self.inpaint_model.enable_attention_slicing()
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
- # Initialize segmentation with error handling
39
- try:
40
- self.segmenter = SegformerForSemanticSegmentation.from_pretrained(
41
- "mattmdjaga/segformer_b2_clothes",
42
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
43
- cache_dir='/tmp/models'
44
- )
45
- self.processor = SegformerImageProcessor.from_pretrained(
46
- "mattmdjaga/segformer_b2_clothes",
47
- cache_dir='/tmp/models'
48
- )
49
- except Exception as e:
50
- print(f"Segmentation model loading error: {str(e)}")
51
- raise
52
-
53
- except Exception as e:
54
- print(f"Initialization error: {str(e)}")
55
- raise
56
-
57
- # ... (rest of the code remains the same)
58
-
59
- # Initialize model with error handling and retry mechanism
60
- def initialize_model(max_retries=3):
61
- for attempt in range(max_retries):
62
- try:
63
- return RafayyVirtualTryOn()
64
- except Exception as e:
65
- if attempt == max_retries - 1:
66
- print(f"Failed to initialize model after {max_retries} attempts: {str(e)}")
67
- raise
68
- print(f"Attempt {attempt + 1} failed, retrying...")
69
- torch.cuda.empty_cache()
70
- gc.collect()
71
-
72
- try:
73
- model = initialize_model()
74
- except Exception as e:
75
- print(f"Model initialization failed: {str(e)}")
76
- raise
77
-
78
- # Create Gradio interface with error handling
79
  demo = gr.Interface(
80
- fn=model.try_on,
81
- inputs=[
82
- gr.Image(label="πŸ“Έ Upload Your Photo", type="numpy"),
83
- gr.Textbox(
84
- label="🎨 Describe New Clothing",
85
- placeholder="e.g., 'elegant black suit', 'red dress'",
86
- lines=2
87
- ),
88
- gr.Slider(
89
- label="Style Strength",
90
- minimum=0.1,
91
- maximum=1.0,
92
- value=0.7,
93
- step=0.1
94
- )
95
- ],
96
- outputs=gr.Image(label="✨ Result", type="pil"),
97
- title="🌟 Rafayy's Virtual Try-On Studio 🌟",
98
- description="""
99
- <div style="text-align: center;">
100
- <h3>Transform Your Style with AI</h3>
101
- <p>Upload a photo and describe the new clothing you want to try on!</p>
102
- </div>
103
- """,
104
- examples=[
105
- ["example1.jpg", "black suit", 0.7],
106
- ["example2.jpg", "white dress", 0.7]
107
- ],
108
- allow_flagging="never",
109
- cache_examples=True
110
  )
111
 
112
- # Launch with error handling and retry mechanism
113
  if __name__ == "__main__":
114
- try:
115
- demo.launch(
116
- share=False,
117
- server_name="0.0.0.0",
118
- server_port=7860,
119
- show_error=True,
120
- enable_queue=True,
121
- cache_examples=True,
122
- max_threads=4
123
- )
124
- except Exception as e:
125
- print(f"Launch failed: {str(e)}")
126
- raise
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
2
  import os
3
 
4
+ class RafayyAIAssistant:
 
 
 
 
 
5
  def __init__(self):
6
+ self.responses = {
7
+ "greeting": """πŸ‘‹ Welcome to Rafayy's Virtual Try-On Studio! How can I help you today?
8
+
9
+ β€’ Type 'features' to learn about our services
10
+ β€’ Type 'pricing' for subscription plans
11
+ β€’ Type 'help' for usage tips
12
+ β€’ Type 'contact' for support""",
13
+
14
+ "features": """✨ Our AI-Powered Features:
15
+
16
+ 1. Virtual Clothing Try-On
17
+ β€’ Upload your photo
18
+ β€’ Describe any clothing
19
+ β€’ Get instant visualization
20
+
21
+ 2. Professional Quality
22
+ β€’ High-resolution output
23
+ β€’ Realistic clothing rendering
24
+ β€’ Advanced style controls
25
+
26
+ 3. Easy to Use
27
+ β€’ Simple interface
28
+ β€’ Quick processing
29
+ β€’ Multiple style options""",
30
+
31
+ "pricing": """πŸ’Ž Subscription Plans:
32
+
33
+ 1. Basic Plan - $9.99/month
34
+ β€’ 100 try-ons per month
35
+ β€’ Standard resolution
36
+ β€’ Basic support
37
+
38
+ 2. Pro Plan - $29.99/month
39
+ β€’ 500 try-ons per month
40
+ β€’ HD resolution
41
+ β€’ Priority support
42
+
43
+ 3. Enterprise Plan - Custom pricing
44
+ β€’ Unlimited try-ons
45
+ β€’ Ultra HD resolution
46
+ β€’ Dedicated support""",
47
 
48
+ "help": """πŸ” Quick Tips:
49
+
50
+ 1. For Best Results:
51
+ β€’ Use clear, front-facing photos
52
+ β€’ Ensure good lighting
53
+ β€’ Wear fitted clothing
54
+
55
+ 2. When Describing Clothes:
56
+ β€’ Be specific about style
57
+ β€’ Mention colors clearly
58
+ β€’ Include design details
59
+
60
+ 3. Troubleshooting:
61
+ β€’ Retry if result isn't perfect
62
+ β€’ Adjust style strength
63
+ β€’ Check example prompts""",
64
 
65
+ "contact": """πŸ“§ Contact & Support:
66
+
67
+ β€’ Email: support@rafayy.ai
68
+ β€’ Hours: 24/7
69
+ β€’ Response time: Within 24 hours
70
+
71
+ For immediate help, try our FAQ section or usage tips."""
72
+ }
73
+
74
+ def get_response(self, message):
75
+ """Generate response based on user input"""
76
+ message = message.lower().strip()
77
+
78
+ # Check for keywords and return appropriate response
79
+ if message in ['hi', 'hello', 'hey', 'start']:
80
+ return self.responses["greeting"]
81
+
82
+ elif 'feature' in message or 'can' in message or 'what' in message:
83
+ return self.responses["features"]
84
+
85
+ elif 'price' in message or 'cost' in message or 'plan' in message:
86
+ return self.responses["pricing"]
87
+
88
+ elif 'help' in message or 'how' in message or 'tip' in message:
89
+ return self.responses["help"]
90
+
91
+ elif 'contact' in message or 'support' in message or 'email' in message:
92
+ return self.responses["contact"]
93
+
94
+ else:
95
+ return self.responses["greeting"]
96
+
97
+ # Initialize the chatbot
98
+ chatbot = RafayyAIAssistant()
99
+
100
+ # Create the Gradio interface
 
 
 
 
 
101
  demo = gr.Interface(
102
+ fn=chatbot.get_response,
103
+ inputs=gr.Textbox(
104
+ placeholder="Ask me anything about Rafayy's Virtual Try-On Studio...",
105
+ label="Your Message"
106
+ ),
107
+ outputs=gr.Textbox(
108
+ label="AI Assistant",
109
+ lines=10
110
+ ),
111
+ title="πŸ€– Rafayy AI Assistant",
112
+ description="""Welcome to Rafayy's Virtual Try-On Studio Support!
113
+ I'm here to help you with features, pricing, and usage tips.""",
114
+ theme="soft",
115
+ css="""
116
+ .gradio-container {
117
+ font-family: 'Arial', sans-serif;
118
+ }
119
+ .gr-button {
120
+ background: linear-gradient(45deg, #2193b0, #6dd5ed) !important;
121
+ border: none !important;
122
+ }
123
+ .gr-button:hover {
124
+ background: linear-gradient(45deg, #6dd5ed, #2193b0) !important;
125
+ transform: translateY(-2px);
126
+ transition: all 0.3s ease;
127
+ }
128
+ """
 
 
 
129
  )
130
 
131
+ # Launch the interface
132
  if __name__ == "__main__":
133
+ demo.launch(
134
+ server_name="0.0.0.0",
135
+ server_port=7860,
136
+ share=False,
137
+ show_error=True
138
+ )