MySafeCode commited on
Commit
48a8766
·
verified ·
1 Parent(s): e699ed3

Create chatgpt.py

Browse files
Files changed (1) hide show
  1. chatgpt.py +183 -0
chatgpt.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import gradio as gr
4
+ from byteplussdkarkruntime import Ark
5
+ import requests
6
+ from datetime import datetime
7
+
8
+ # Get API key from Hugging Face secret "Key" and CLEAN it
9
+ API_KEY = os.environ.get("Key", "").strip()
10
+ print(f"✅ Key loaded, length: {len(API_KEY)}")
11
+
12
+ # Initialize client with proxy
13
+ client = Ark(
14
+ base_url="https://1hit.no/proxy/proxy.php",
15
+ api_key=API_KEY,
16
+ timeout=30.0,
17
+ max_retries=3,
18
+ )
19
+
20
+ # In-memory upload queue
21
+ upload_queue = []
22
+
23
+ # ---------------- MANUAL POLLING ----------------
24
+ def manual_poll(task_id):
25
+ if not task_id:
26
+ return "❌ Please enter a task ID"
27
+
28
+ try:
29
+ url = f"https://1hit.no/proxy/proxy.php?task_id={task_id}"
30
+ headers = {"Authorization": f"Bearer {API_KEY}"}
31
+ requests.get(url, headers=headers)
32
+
33
+ io_response = requests.get("https://1hit.no/proxy/io.json")
34
+ io_data = io_response.json()
35
+
36
+ if task_id in io_data:
37
+ status = io_data[task_id].get('status')
38
+ video_url = io_data[task_id].get('video_url')
39
+ result = f"✅ Task {task_id}\nStatus: {status}\n"
40
+ if video_url:
41
+ result += f"Video URL: {video_url}\n"
42
+ if 'response' in io_data[task_id]:
43
+ result += f"Full response: {io_data[task_id]['response']}\n"
44
+ return result
45
+ else:
46
+ return f"❌ Task {task_id} not found in io.json"
47
+ except Exception as e:
48
+ return f"❌ Error: {str(e)}"
49
+
50
+ def get_raw_json():
51
+ try:
52
+ r = requests.get("https://1hit.no/proxy/io.json")
53
+ return r.json()
54
+ except:
55
+ return {"error": "Could not fetch io.json"}
56
+
57
+ # ---------------- WATCH & DOWNLOAD ----------------
58
+ def get_task_list():
59
+ try:
60
+ r = requests.get("https://1hit.no/proxy/io.json")
61
+ data = r.json()
62
+ tasks = []
63
+ for task_id, task_data in data.items():
64
+ status = task_data.get('status', 'unknown')
65
+ created = task_data.get('created', 0)
66
+ time_str = datetime.fromtimestamp(created).strftime('%Y-%m-%d %H:%M:%S')
67
+ prompt = task_data.get('request', {}).get('content', [{}])[0].get('text', 'No prompt')
68
+ prompt_preview = prompt[:50] + '...' if len(prompt) > 50 else prompt
69
+ tasks.append({
70
+ "id": task_id,
71
+ "status": status,
72
+ "created": time_str,
73
+ "created_ts": created,
74
+ "video_url": task_data.get('video_url', ''),
75
+ "prompt": prompt_preview
76
+ })
77
+ tasks.sort(key=lambda x: x['created_ts'], reverse=True)
78
+ return tasks
79
+ except Exception as e:
80
+ print(f"Error getting task list: {e}")
81
+ return []
82
+
83
+ def refresh_task_list():
84
+ tasks = get_task_list()
85
+ choices = [f"{t['id']} | {t['status']} | {t['created']}" for t in tasks]
86
+ return gr.Dropdown.update(choices=choices, value=choices[0] if choices else None)
87
+
88
+ def load_task(selection):
89
+ if not selection:
90
+ return "No task selected", None, None
91
+
92
+ task_id = selection.split(' | ')[0]
93
+ try:
94
+ r = requests.get("https://1hit.no/proxy/io.json")
95
+ data = r.json()
96
+ task = data.get(task_id, {})
97
+ video_url = task.get('video_url', '')
98
+ status = task.get('status', 'unknown')
99
+ prompt = task.get('request', {}).get('content', [{}])[0].get('text', 'No prompt')
100
+ created = task.get('created', 0)
101
+ created_str = datetime.fromtimestamp(created).strftime('%Y-%m-%d %H:%M:%S')
102
+ response = task.get('response', {})
103
+
104
+ info = f"### Task Details\n\n**Task ID:** `{task_id}`\n**Status:** `{status}`\n**Created:** {created_str}\n**Prompt:** {prompt}\n\n"
105
+ if status == 'succeeded' and video_url:
106
+ info += f"✅ **Video ready!**\n**Download:** [Click here]({video_url})\n"
107
+ elif status == 'failed':
108
+ error = task.get('response', {}).get('error', 'Unknown error')
109
+ info += f"❌ **Failed:** {error}\n"
110
+
111
+ return info, video_url, video_url
112
+ except Exception as e:
113
+ return f"Error loading task: {e}", None, None
114
+
115
+ # ---------------- UPLOAD QUEUE ----------------
116
+ def add_to_queue(file_path, queue_state):
117
+ if file_path:
118
+ queue_state = queue_state or []
119
+ if file_path not in queue_state:
120
+ queue_state.append(file_path)
121
+ return [[q] for q in queue_state], queue_state
122
+
123
+ def clear_queue():
124
+ return [], []
125
+
126
+ # ---------------- GRADIO APP ----------------
127
+ with gr.Blocks(title="BytePlus Video Gallery", theme=gr.themes.Soft()) as demo:
128
+
129
+ # ---------------- Manual Polling Tab ----------------
130
+ with gr.TabItem("🔧 Manual Polling"):
131
+ gr.Markdown("### 🔧 Manual Polling & Debug")
132
+ with gr.Row():
133
+ with gr.Column():
134
+ gr.Markdown("#### Poll Specific Task")
135
+ task_id_input = gr.Textbox(label="Task ID", placeholder="Enter task ID (cgt-...)")
136
+ poll_btn = gr.Button("🔄 Poll Now", variant="primary")
137
+ poll_result = gr.Textbox(label="Poll Result", lines=10)
138
+ poll_btn.click(fn=manual_poll, inputs=task_id_input, outputs=poll_result)
139
+ with gr.Column():
140
+ gr.Markdown("#### Current io.json")
141
+ refresh_btn = gr.Button("🔄 Refresh io.json", variant="secondary")
142
+ raw_json = gr.JSON(label="io.json Contents")
143
+ refresh_btn.click(fn=get_raw_json, outputs=raw_json)
144
+ gr.Markdown("""
145
+ ### 📝 Instructions
146
+ 1. Copy a task ID from above (like `cgt-20260217072358-hszt9`)
147
+ 2. Paste it in the Task ID field
148
+ 3. Click "Poll Now" to force an update
149
+ 4. Check io.json to see if status changed
150
+ """)
151
+
152
+ # ---------------- Watch & Download Tab ----------------
153
+ with gr.TabItem("📺 Watch & Download"):
154
+ gr.Markdown("### 📺 Browse and Download Generated Videos")
155
+
156
+ with gr.Row():
157
+ with gr.Column(scale=1):
158
+ refresh_list_btn = gr.Button("🔄 Refresh Task List", variant="primary")
159
+ task_list = gr.Dropdown(label="Select Task", choices=[], interactive=True)
160
+ with gr.Column(scale=2):
161
+ task_info = gr.Markdown("Select a task to view details")
162
+
163
+ with gr.Row():
164
+ with gr.Column():
165
+ video_player = gr.Video(label="Video Player")
166
+ download_link = gr.File(label="Download Video")
167
+ put_queue_btn = gr.Button("📥 Put in Upload Queue")
168
+ queue_display = gr.Dataframe(
169
+ headers=["Upload Queue"], value=[], interactive=False, max_rows=10
170
+ )
171
+ clear_queue_btn = gr.Button("🗑️ Clear Queue")
172
+
173
+ # Button connections
174
+ refresh_list_btn.click(fn=refresh_task_list, outputs=task_list)
175
+ task_list.change(fn=load_task, inputs=task_list, outputs=[task_info, video_player, download_link])
176
+ put_queue_btn.click(fn=add_to_queue, inputs=[download_link, gr.State(upload_queue)], outputs=[queue_display, gr.State(upload_queue)])
177
+ clear_queue_btn.click(fn=clear_queue, outputs=[queue_display])
178
+
179
+ # Auto-load task list when tab is opened
180
+ demo.load(fn=refresh_task_list, outputs=task_list)
181
+
182
+ if __name__ == "__main__":
183
+ demo.launch(server_name="0.0.0.0")