sushantvyz commited on
Commit
e3b6b7d
Β·
verified Β·
1 Parent(s): e9fb849

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -142
app.py CHANGED
@@ -1,176 +1,125 @@
1
  import gradio as gr
2
  import os
3
- import requests
4
 
5
- # Try multiple ways to get the token
6
- HF_TOKEN = os.getenv("HF_TOKEN") or os.getenv("HF_API_TOKEN") or os.getenv("HUGGING_FACE_HUB_TOKEN")
7
 
8
- # Debug: Check if token exists (don't print the actual token!)
9
- TOKEN_STATUS = "βœ… Token found" if HF_TOKEN else "❌ No token found"
10
-
11
- def generate_output(project_name, user_input, file_path=None):
12
- """Generates specialized output using the LLM based on the project context."""
13
 
14
- if not user_input and project_name != "VYZENVO":
15
- return "Please provide text input for the AI to process."
16
-
17
- # Define the specialized system prompt for context
18
- if project_name == "VYZVERSE":
19
- system_prompt = (
20
- "You are Commander Zylos, the lead narrative designer for the VYZVERSE animation project. "
21
- "Generate high-quality, creative dialogue, lore, or scene synopses. "
22
- "Maintain a dramatic, sci-fi tone. Keep your response focused on narrative elements."
23
- )
24
- max_tokens = 400
25
 
26
- elif project_name == "ReVYZGen":
27
- system_prompt = (
28
- "You are a senior game code debugger and architect specializing in Python and C#. Analyze the "
29
- "provided code and bug description. Suggest the most efficient fix or generate the requested starter function. "
30
- "Always output the resulting code or fix inside a clear code block."
31
- )
32
- max_tokens = 512
33
-
34
- elif project_name == "VYZENVO":
35
- # Simulate RAG by including the document content in the prompt
36
- document_content = ""
37
- if file_path and os.path.exists(file_path):
38
- with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
39
- document_content = f.read(2000)
40
-
41
- system_prompt = (
42
- f"You are an Environmental Analyst for VYZENVO. Analyze the document provided below "
43
- f"and answer the user's question by citing information only from the document context. "
44
- f"If the answer is not in the document, state that clearly. The document extract is:\n\n---\n{document_content}\n---"
45
- )
46
- user_input = f"Question: {user_input}" if user_input else "Summarize the key findings of the document."
47
- else:
48
- system_prompt = "You are a general-purpose analyst. Answer the user question."
49
-
50
- max_tokens = 600
51
-
52
- else:
53
- system_prompt = "You are a general-purpose AI assistant. Respond helpfully."
54
- max_tokens = 250
55
-
56
- # Call the HF Inference API using requests
57
  try:
58
  API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
59
 
60
- headers = {"Content-Type": "application/json"}
61
- if HF_TOKEN:
62
- headers["Authorization"] = f"Bearer {HF_TOKEN}"
63
- else:
64
- return "❌ ERROR: No HF_TOKEN found!\n\nPlease add your Hugging Face token:\n1. Go to Space Settings\n2. Click 'Variables and secrets'\n3. Add new secret: Name='HF_TOKEN', Value=your token from https://huggingface.co/settings/tokens"
65
 
66
- # Format the prompt for Mistral
67
- prompt = f"<s>[INST] {system_prompt}\n\n{user_input} [/INST]"
68
 
69
  payload = {
70
  "inputs": prompt,
71
  "parameters": {
72
- "max_new_tokens": max_tokens,
73
- "temperature": 0.7,
74
- "top_p": 0.9,
75
- "return_full_text": False
76
  }
77
  }
78
 
79
- response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
 
 
 
 
 
 
80
 
81
  if response.status_code == 200:
82
  result = response.json()
 
 
 
83
  if isinstance(result, list) and len(result) > 0:
84
- generated_text = result[0].get('generated_text', '').strip()
85
- return generated_text if generated_text else "Error: Empty response from model"
86
- else:
87
- return f"Error: Unexpected response format: {result}"
 
88
  elif response.status_code == 503:
89
- return "⏳ Model is loading... This can take 20-60 seconds on first use. Please try again in a moment."
 
90
  elif response.status_code == 401 or response.status_code == 403:
91
- return f"⚠️ Authentication Error (Code {response.status_code}): Your HF_TOKEN is invalid or expired.\n\n1. Get a new token from https://huggingface.co/settings/tokens\n2. Make sure to select 'Read' permission\n3. Update the HF_TOKEN secret in Space Settings"
 
92
  else:
93
- return f"⚠️ API Error (Code {response.status_code}):\n{response.text[:500]}"
94
-
95
  except requests.exceptions.Timeout:
96
- return "⏳ Request timed out. The model might be loading. Please try again in 30 seconds."
 
 
 
 
97
  except Exception as e:
98
- return f"ERROR: {str(e)}"
 
99
 
100
 
101
- # Build the Gradio Interface
102
- with gr.Blocks(title="VYZ Interstellar Multi-Tool AI", theme=gr.themes.Soft()) as demo:
103
- gr.Markdown("# πŸš€ VYZ Interstellar AI Assistant")
104
- gr.Markdown("A specialized, multi-tool assistant for VYZVERSE, ReVYZGen, and VYZENVO projects. **(Powered by Mistral 7B via HF Inference API)**")
105
 
106
- # Show token status
107
- gr.Markdown(f"**Status:** {TOKEN_STATUS}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
- if not HF_TOKEN:
110
- gr.Markdown("""
111
- ### ⚠️ Setup Required:
112
- 1. Go to https://huggingface.co/settings/tokens
113
- 2. Create a new token with 'Read' permission
114
- 3. Go to your Space Settings β†’ Variables and secrets
115
- 4. Add new secret: Name = `HF_TOKEN`, Value = your token
116
- 5. Restart the Space
117
- """)
118
-
119
- with gr.Tabs() as tabs:
120
- # TAB 1: VYZVERSE (Animation/Lore Generation)
121
- with gr.TabItem("VYZVERSE: Script & Lore", id="vyzverse_tab"):
122
- gr.Markdown("### Generate Dialogue, Descriptions, or Scene Synopses.")
123
- vyzverse_input = gr.Textbox(
124
- lines=5,
125
- label="Input Prompt / Plot Outline",
126
- placeholder="e.g., Write a tense dialogue between Commander Zylos and the Regulator about planet-side energy drain."
127
- )
128
- vyzverse_output = gr.Textbox(label="VYZVERSE Generation", lines=10, interactive=False)
129
- vyzverse_btn = gr.Button("Generate VYZVERSE Content", variant="primary")
130
-
131
- vyzverse_btn.click(
132
- fn=lambda x: generate_output("VYZVERSE", x, None),
133
- inputs=vyzverse_input,
134
- outputs=vyzverse_output
135
- )
136
-
137
- # TAB 2: ReVYZGen (Game Code Assistant)
138
- with gr.TabItem("ReVYZGen: Code Helper", id="revyzgen_tab"):
139
- gr.Markdown("### Debug Code Snippets or Generate Starter Functions.")
140
- revyzgen_input = gr.Code(
141
- label="Paste Code (Python/C#)",
142
- language="python",
143
- lines=8,
144
- value="# Paste your game code snippet and bug description here..."
145
- )
146
- revyzgen_output = gr.Code(label="Corrected Code / Suggestion", language="python", lines=10, interactive=False)
147
- revyzgen_btn = gr.Button("Analyze ReVYZGen Code", variant="primary")
148
-
149
- revyzgen_btn.click(
150
- fn=lambda x: generate_output("ReVYZGen", x, None),
151
- inputs=revyzgen_input,
152
- outputs=revyzgen_output
153
- )
154
-
155
- # TAB 3: VYZENVO (Document Analysis/RAG Simulator)
156
- with gr.TabItem("VYZENVO: Environmental Analysis", id="vyzenvo_tab"):
157
- gr.Markdown("### Analyze Private Documents (Simulated RAG). Upload a document and ask a specific question.")
158
- vyzenvo_file = gr.File(label="Upload VYZENVO Document (TXT)", file_types=[".txt"])
159
- vyzenvo_question = gr.Textbox(
160
- label="Question about the Document",
161
- placeholder="e.g., What are the safety parameters for the 'Auror-1' power core?"
162
- )
163
- vyzenvo_output = gr.Textbox(label="Analysis Output", lines=10, interactive=False)
164
- vyzenvo_btn = gr.Button("Analyze VYZENVO Data", variant="primary")
165
-
166
- vyzenvo_btn.click(
167
- fn=lambda f, q: generate_output("VYZENVO", q, f.name if f else None),
168
- inputs=[vyzenvo_file, vyzenvo_question],
169
- outputs=vyzenvo_output
170
- )
171
-
172
  gr.Markdown("---")
173
- gr.Markdown("*Built by VYZ Interstellar | Powered by Hugging Face Inference API*")
 
 
 
 
174
 
175
  if __name__ == "__main__":
176
  demo.launch()
 
1
  import gradio as gr
2
  import os
 
3
 
4
+ # Get token
5
+ HF_TOKEN = os.getenv("HF_TOKEN")
6
 
7
+ def simple_test(user_text):
8
+ """Super simple test function with detailed debugging"""
 
 
 
9
 
10
+ # Step 1: Check if we got input
11
+ if not user_text or user_text.strip() == "":
12
+ return "❌ No input provided"
 
 
 
 
 
 
 
 
13
 
14
+ # Step 2: Check token exists
15
+ if not HF_TOKEN:
16
+ return "❌ ERROR: HF_TOKEN not found in environment"
17
+
18
+ # Step 3: Show token prefix (first 10 chars only - safe to show)
19
+ token_preview = HF_TOKEN[:10] + "..." if len(HF_TOKEN) > 10 else "Token too short!"
20
+
21
+ # Step 4: Try importing requests
22
+ try:
23
+ import requests
24
+ except ImportError:
25
+ return "❌ ERROR: 'requests' library not installed"
26
+
27
+ # Step 5: Try calling the API
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  try:
29
  API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
30
 
31
+ headers = {
32
+ "Authorization": f"Bearer {HF_TOKEN}",
33
+ "Content-Type": "application/json"
34
+ }
 
35
 
36
+ prompt = f"<s>[INST] Say hello in a friendly way. [/INST]"
 
37
 
38
  payload = {
39
  "inputs": prompt,
40
  "parameters": {
41
+ "max_new_tokens": 50,
42
+ "temperature": 0.7
 
 
43
  }
44
  }
45
 
46
+ # Show we're about to make the call
47
+ status_msg = f"βœ… Token found: {token_preview}\nβœ… Calling API...\n\n"
48
+
49
+ response = requests.post(API_URL, headers=headers, json=payload, timeout=30)
50
+
51
+ # Show response details
52
+ status_msg += f"Response Code: {response.status_code}\n\n"
53
 
54
  if response.status_code == 200:
55
  result = response.json()
56
+ status_msg += f"βœ… SUCCESS!\n\nAPI Response:\n{result}"
57
+
58
+ # Try to extract the generated text
59
  if isinstance(result, list) and len(result) > 0:
60
+ text = result[0].get('generated_text', 'No text found')
61
+ status_msg += f"\n\nGenerated Text:\n{text}"
62
+
63
+ return status_msg
64
+
65
  elif response.status_code == 503:
66
+ return status_msg + "⏳ Model is loading. Wait 30-60 seconds and try again."
67
+
68
  elif response.status_code == 401 or response.status_code == 403:
69
+ return status_msg + f"❌ Authentication failed!\n\nYour token might be invalid or expired.\n\nResponse:\n{response.text}"
70
+
71
  else:
72
+ return status_msg + f"❌ Unexpected error\n\nResponse:\n{response.text[:500]}"
73
+
74
  except requests.exceptions.Timeout:
75
+ return "⏳ Request timed out (took more than 30 seconds)"
76
+
77
+ except requests.exceptions.RequestException as e:
78
+ return f"❌ Network error:\n{str(e)}"
79
+
80
  except Exception as e:
81
+ import traceback
82
+ return f"❌ Unexpected error:\n{str(e)}\n\nFull traceback:\n{traceback.format_exc()}"
83
 
84
 
85
+ # Simple interface
86
+ with gr.Blocks(title="DEBUG MODE", theme=gr.themes.Soft()) as demo:
87
+ gr.Markdown("# πŸ”§ DEBUG MODE - VYZ Assistant")
88
+ gr.Markdown("## This version shows detailed diagnostic information")
89
 
90
+ if HF_TOKEN:
91
+ gr.Markdown(f"**Token Status:** βœ… Found (starts with `{HF_TOKEN[:7]}...`)")
92
+ else:
93
+ gr.Markdown("**Token Status:** ❌ NOT FOUND")
94
+
95
+ gr.Markdown("---")
96
+
97
+ input_box = gr.Textbox(
98
+ label="Type anything (like 'hello')",
99
+ placeholder="hello",
100
+ lines=2
101
+ )
102
+
103
+ output_box = gr.Textbox(
104
+ label="Detailed Debug Output",
105
+ lines=15,
106
+ interactive=False
107
+ )
108
+
109
+ test_btn = gr.Button("πŸ§ͺ Test API Call", variant="primary", size="lg")
110
+
111
+ test_btn.click(
112
+ fn=simple_test,
113
+ inputs=input_box,
114
+ outputs=output_box
115
+ )
116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  gr.Markdown("---")
118
+ gr.Markdown("### Instructions:")
119
+ gr.Markdown("1. Type 'hello' in the box above")
120
+ gr.Markdown("2. Click the 'Test API Call' button")
121
+ gr.Markdown("3. Wait for the output")
122
+ gr.Markdown("4. Copy the ENTIRE output and send it to me")
123
 
124
  if __name__ == "__main__":
125
  demo.launch()