lazarusking commited on
Commit
a75af1e
1 Parent(s): fa71b98

fixed global state issue

Browse files
Files changed (5) hide show
  1. .gitignore +2 -1
  2. app.py +21 -30
  3. functions.py +260 -111
  4. new_mappings.json +68 -0
  5. requirements.txt → req.txt +0 -0
.gitignore CHANGED
@@ -1,4 +1,5 @@
1
  __pycache__/
2
  *.pyc
3
  flagged/
4
- .venv
 
 
1
  __pycache__/
2
  *.pyc
3
  flagged/
4
+ .venv
5
+ requirements.txt
app.py CHANGED
@@ -1,6 +1,4 @@
1
- import json
2
  import logging
3
- import os
4
  import subprocess
5
  from pprint import pprint
6
  from tempfile import _TemporaryFileWrapper
@@ -9,12 +7,9 @@ from ffmpy import FFmpeg
9
 
10
  import gradio as gr
11
  from functions import (Clear, CommandBuilder, audio_channels, audio_codecs,
12
- audio_containers, audio_quality, audio_sample_rates,
13
- change_clipbox, containers, customBitrate, filters,
14
- mediaChange, presets, profiles, speeds,
15
- supported_codecs, supported_presets, updateOutput,
16
- video_aspect_ratio, video_codecs, video_containers,
17
- video_scaling, videoChange,vf)
18
 
19
  logging.basicConfig(level=logging.INFO)
20
 
@@ -43,24 +38,16 @@ def convert(file: _TemporaryFileWrapper, options: str):
43
  stdout, stderr=ffmpeg.run(stderr=subprocess.PIPE)
44
  logging.info(f"{stdout} {stderr}")
45
  output=f"{ffmpeg.cmd}"
46
- video=gr.update(label=output_file,value=output_file)
47
 
48
  except Exception as e:
49
  stderr=e
50
  output=f"{ffmpeg.cmd} {stderr}"
 
51
 
52
- return [output_file,output_file,video,output]
53
 
54
 
55
-
56
- """Helper Functions for Processing """
57
-
58
-
59
-
60
- def get_component_instance(inputs: gr.Blocks) -> list:
61
- return [gr.components.get_component_instance(i, render=True) for i in inputs.children if not hasattr(i,"children")]
62
-
63
- # names=[{x:i} for x in ["audioChannels","audioQualities"] for i in [[i.get("name") for i in data[x]]]]
64
  with gr.Blocks(css="./styles.css") as dm:
65
  with gr.Tabs():
66
  with gr.TabItem("Format"):
@@ -70,14 +57,14 @@ with gr.Blocks(css="./styles.css") as dm:
70
  file_input = gr.File()
71
  options = gr.Radio(
72
  label="options", choices=containers,value=containers[0])
73
-
74
- with gr.Row() as inputs_clip:
75
  clip = gr.Dropdown(
76
  choices=["None", "Enabled"], label="Clip:", value="None")
77
- start_time = gr.Textbox(
78
- label="Start Time:", placeholder="00:00", visible=False)
79
- stop_time = gr.Textbox(
80
- label="Stop Time:", placeholder="00:00", visible=False)
 
81
  with gr.Row().style(mobile_collapse=False):
82
  clearBtn = gr.Button("Clear")
83
  convertBtn = gr.Button("Convert", variant="primary")
@@ -92,7 +79,8 @@ with gr.Blocks(css="./styles.css") as dm:
92
  media_output_audio = gr.Audio(label="Output",visible=True,interactive=False,source="filepath")
93
  media_output_video = gr.Video(label="Output",visible=False,format="mp4")
94
  media_output_file = gr.File(label="Output",visible=False)
95
- output_textbox = gr.Textbox(elem_id="outputtext")
 
96
 
97
  resetFormat=Clear(inputs,inputs_clip)
98
  clearBtn.click(resetFormat.clear, inputs=resetFormat(), outputs=resetFormat())
@@ -132,7 +120,7 @@ with gr.Blocks(css="./styles.css") as dm:
132
 
133
  with gr.TabItem("Filters") as filter_inputs:
134
  gr.Markdown("## Video")
135
- with gr.Row().style(equal_height=True,mobile_collapse=False) as filter_inputs:
136
  for i in vf:
137
  # print(i.values())
138
  # values = list(i.values())
@@ -152,8 +140,10 @@ with gr.Blocks(css="./styles.css") as dm:
152
 
153
  """ Format Tab change functions"""
154
  ffmpeg_commands=CommandBuilder(inputs_clip,video_inputs,audio_inputs,filter_inputs,filter_inputs_1)
155
- ffmpeg_commands.do()
 
156
  pprint(ffmpeg_commands.commands)
 
157
  ffmpeg_commands.update(output_textbox)
158
  # file_input.change(fn=updateOutput,inputs=file_input,outputs=output_textbox)
159
  clip.change(fn=change_clipbox, inputs=clip,
@@ -170,5 +160,6 @@ with gr.Blocks(css="./styles.css") as dm:
170
  video_options.change(supported_presets,[video_options],[preset_options])
171
  """Audio Tab change functions"""
172
  audio_bitrate.change(customBitrate,[audio_bitrate],[custom_bitrate])
173
-
174
- dm.launch()
 
 
 
1
  import logging
 
2
  import subprocess
3
  from pprint import pprint
4
  from tempfile import _TemporaryFileWrapper
 
7
 
8
  import gradio as gr
9
  from functions import (Clear, CommandBuilder, audio_channels, audio_codecs,
10
+ audio_quality, audio_sample_rates,
11
+ change_clipbox, containers, customBitrate, mediaChange, presets, supported_codecs, supported_presets, video_codecs, video_containers,
12
+ vf)
 
 
 
13
 
14
  logging.basicConfig(level=logging.INFO)
15
 
 
38
  stdout, stderr=ffmpeg.run(stderr=subprocess.PIPE)
39
  logging.info(f"{stdout} {stderr}")
40
  output=f"{ffmpeg.cmd}"
41
+ # video=gr.update(label=output_file,value=output_file)
42
 
43
  except Exception as e:
44
  stderr=e
45
  output=f"{ffmpeg.cmd} {stderr}"
46
+ return [None,None,None,output]
47
 
48
+ return [output_file,output_file,output_file,output]
49
 
50
 
 
 
 
 
 
 
 
 
 
51
  with gr.Blocks(css="./styles.css") as dm:
52
  with gr.Tabs():
53
  with gr.TabItem("Format"):
 
57
  file_input = gr.File()
58
  options = gr.Radio(
59
  label="options", choices=containers,value=containers[0])
60
+ with gr.Row():
 
61
  clip = gr.Dropdown(
62
  choices=["None", "Enabled"], label="Clip:", value="None")
63
+ with gr.Row() as inputs_clip:
64
+ start_time = gr.Textbox(
65
+ label="Start Time:", placeholder="00:00", visible=False)
66
+ stop_time = gr.Textbox(
67
+ label="Stop Time:", placeholder="00:00", visible=False)
68
  with gr.Row().style(mobile_collapse=False):
69
  clearBtn = gr.Button("Clear")
70
  convertBtn = gr.Button("Convert", variant="primary")
 
79
  media_output_audio = gr.Audio(label="Output",visible=True,interactive=False,source="filepath")
80
  media_output_video = gr.Video(label="Output",visible=False,format="mp4")
81
  media_output_file = gr.File(label="Output",visible=False)
82
+ with gr.Row() as command_output:
83
+ output_textbox = gr.JSON(elem_id="outputtext")
84
 
85
  resetFormat=Clear(inputs,inputs_clip)
86
  clearBtn.click(resetFormat.clear, inputs=resetFormat(), outputs=resetFormat())
 
120
 
121
  with gr.TabItem("Filters") as filter_inputs:
122
  gr.Markdown("## Video")
123
+ with gr.Row().style(equal_height=True) as filter_inputs:
124
  for i in vf:
125
  # print(i.values())
126
  # values = list(i.values())
 
140
 
141
  """ Format Tab change functions"""
142
  ffmpeg_commands=CommandBuilder(inputs_clip,video_inputs,audio_inputs,filter_inputs,filter_inputs_1)
143
+ # ffmpeg_commands.do()
144
+ dm.load(fn=ffmpeg_commands.reset,inputs=[],outputs=[])
145
  pprint(ffmpeg_commands.commands)
146
+ state=gr.Variable()
147
  ffmpeg_commands.update(output_textbox)
148
  # file_input.change(fn=updateOutput,inputs=file_input,outputs=output_textbox)
149
  clip.change(fn=change_clipbox, inputs=clip,
 
160
  video_options.change(supported_presets,[video_options],[preset_options])
161
  """Audio Tab change functions"""
162
  audio_bitrate.change(customBitrate,[audio_bitrate],[custom_bitrate])
163
+
164
+ if __name__=='__main__':
165
+ dm.launch()
functions.py CHANGED
@@ -1,9 +1,13 @@
 
 
 
1
  import json
2
  from pprint import pprint
3
  from tempfile import _TemporaryFileWrapper
 
4
 
5
  import gradio as gr
6
-
7
 
8
  def parse(param: json) -> dict:
9
  with open(param) as file:
@@ -14,14 +18,15 @@ data = parse("./data.json")
14
  codecs = parse("./codecs.json")
15
 
16
  """Video"""
17
- containers=[j.get("name") for i in data["containers"] for j in data["containers"][i]]
 
18
  video_containers = [i.get("name") for i in data["containers"]["video"]]
19
- video_codecs = [i.get("name") for i in data["codecs"]["video"]]
20
  video_aspect_ratio = [i.get("name") for i in data["aspects"]]
21
  video_scaling = [i.get("name") for i in data["scalings"]]
22
  """ Audio """
23
  audio_containers = [i.get("name") for i in data["containers"]["audio"]]
24
- audio_codecs = [i.get("name") for i in data["codecs"]["audio"]]
25
  audio_channels = [i.get("name") for i in data["audioChannels"]]
26
  audio_quality = [i.get("name") for i in data["audioQualities"]]
27
  audio_sample_rates = [i.get("name") for i in data["sampleRates"]]
@@ -44,27 +49,42 @@ speeds = [i.get("name") for i in data["speeds"]]
44
 
45
 
46
  outputMap = parse("./mappings.json")
 
47
  """Output Mappings of commands to value
48
  audioQuality -b:a 128k
49
  """
50
 
51
 
52
  class CommandBuilder():
 
 
 
 
53
  def __call__(self, *args, **kwds):
54
  return [i.value for i in self._component]
55
 
56
  def do(self, *inputs, **kwds):
57
  for comp in self._component:
58
  if comp.label is not None:
59
- self.startfunc(comp,"",comp.value)
 
 
 
 
 
60
 
61
  def __init__(self, *inputs: gr.Blocks) -> None:
62
- self.outputDict = {}
 
 
 
 
 
63
  self.formatOutputDict = {"vf": {}, "af": {}}
64
  # state=gr.Variable()
65
  # state2=gr.Variable()
66
 
67
- self._component: list[gr.components.Changeable] = []
68
  self.vf, self.af, self.extra = ([] for _ in range(3))
69
  self.commands = ""
70
  if inputs is None:
@@ -80,29 +100,107 @@ class CommandBuilder():
80
  comp.change(fn=self.changefunc, inputs=[
81
  state, state2, comp], outputs=[])
82
 
 
 
 
 
 
 
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
- def update(self, Component: gr.components.IOComponent):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  for comp in self._component:
87
  comp.change(lambda: gr.update(
88
- value=self.commands), [], [Component])
89
-
90
- def _get_component_instance(self, inputs: gr.Blocks) -> "list[gr.components.Component]":
 
 
 
 
 
91
  return [gr.components.get_component_instance(i, render=True) for i in inputs.children if not hasattr(i, "children")]
92
 
93
  def setVideoFilters(self, options):
94
  value = self.outputDict.get(options, "-")
95
- filters = outputMap.get(options, None)
96
  arg = ""
97
  if options in ["deinterlace", "denoise"]:
98
  value = "_".join(value.lower().split())
99
  arg = filters.get(value, None)
100
  # self.vf.append(arg)
101
- self.formatOutputDict["vf"].update({options: arg})
102
  return True
103
  if options in ["deband", "deflicker", "deshake", "dejudder"]:
104
  arg = filters
105
- self.formatOutputDict["vf"].update({options: arg})
106
  return True
107
 
108
  return
@@ -113,28 +211,28 @@ class CommandBuilder():
113
  value = int(value)/100
114
  arg = f"{options}={value}"
115
 
116
- self.formatOutputDict["af"].update({options: arg})
117
  return True
118
  return
119
 
120
  def setFormat(self, options):
121
  value = self.outputDict.get(options, "-")
122
- filters = outputMap.get(options, None)
123
  if options in ["video", "audio"]:
124
  value = "".join([i.get("value", "None") for i in data.get(
125
  "codecs").get(options) if i.get("name", None) == value])
126
  arg = f"{filters} {value}"
127
- self.formatOutputDict.update({options: arg})
128
  return True
129
  elif data.get(options) == None:
130
  arg = f"{filters} {value}"
131
- self.formatOutputDict.update({options: arg})
132
  return True
133
  elif options != "clip":
134
  value = "".join([i.get("value", "None") for i in data.get(
135
  options) if i.get("name", None) == value])
136
  arg = f"{filters} {value}"
137
- self.formatOutputDict.update({options: arg})
138
 
139
  def build(self):
140
  for i in self.outputDict:
@@ -145,15 +243,15 @@ class CommandBuilder():
145
  else:
146
  self.setFormat(i)
147
  lst_extra, vf, af = ([] for _ in range(3))
148
- for val in self.formatOutputDict:
149
  if val == "vf":
150
- vf = self.formatOutputDict.get(val).values()
151
  vf = ",".join(list(vf))
152
  elif val == "af":
153
- af = self.formatOutputDict.get(val).values()
154
  af = ",".join(list(af))
155
  else:
156
- lst_extra.append(self.formatOutputDict.get(val))
157
  # print(lst_extra, "temp x")
158
  # if vf:self.vf=f"-vf '{vf}'"
159
  # if af:self.af=f"-af '{af}'"
@@ -162,50 +260,39 @@ class CommandBuilder():
162
  self.extra = " ".join(lst_extra)
163
  self.commands = f"{self.vf} {self.af} {self.extra}"
164
 
165
- def changefunc(self, input: gr.components.IOComponent, c_label="", newValue=""):
166
- label, *_ = input.label.strip(": ").lower().split(
167
- ) if type(input.label) != list else "".join(input.label).strip(": ").lower().split()
168
- label += "".join(_).title()
169
- if newValue not in [None, "Source", "Auto", "", "None",0]:
170
- self.outputDict.update({label: newValue})
171
- else:
172
- self.outputDict.pop(label, "No Key Exists")
173
- self.formatOutputDict["vf"].pop(label, "Key is None or similar")
174
- self.formatOutputDict["af"].pop(label, "Key is None or similar")
175
- self.formatOutputDict.pop(label, "Key is None or similar")
176
- self.build()
177
- print(self.commands," self.commands")
178
- print(self.vf, self.af, self.extra)
179
  def startfunc(self, input: gr.components.IOComponent, c_label="", newValue=""):
180
  label, *_ = input.label.strip(": ").lower().split(
181
  ) if type(input.label) != list else "".join(input.label).strip(": ").lower().split()
182
  label += "".join(_).title()
183
- if newValue not in [None, "Source", "Auto", "", "None",0]:
 
 
184
  self.outputDict.update({label: newValue})
185
  else:
186
  self.outputDict.pop(label, "No Key Exists")
187
- self.formatOutputDict["vf"].pop(label, "Key is None or similar")
188
- self.formatOutputDict["af"].pop(label, "Key is None or similar")
189
- self.formatOutputDict.pop(label, "Key is None or similar")
 
 
 
190
  self.build()
191
 
192
 
193
-
194
-
195
- def somefunc(input: gr.components.IOComponent, c_label=""):
196
- label = ""
197
- output={}
198
- print(input, c_label)
199
- label, *_ = input.label.strip(": ").lower().split(
200
- ) if type(input.label) != list else "".join(input.label).strip(": ").lower().split()
201
- label += "".join(_).title()
202
- print(outputMap.get(label), label, c_label)
203
- if c_label not in [None, "Source", "Auto", ""]:
204
- print(input.value)
205
- output.update({label: c_label})
206
- else:
207
- output.pop(label, "No Key Exists")
208
- pprint(output)
209
 
210
  # def mediaChange(option):
211
  # no_=gr.update(visible=False)
@@ -218,19 +305,29 @@ def somefunc(input: gr.components.IOComponent, c_label=""):
218
  # else:
219
  # output=gr.update(visible=False)
220
  # return [no_,no_]
221
- def mediaChange(option):
222
- no_=gr.update(visible=False)
223
- output=gr.update(visible=True)
224
- ops={"Audio":gr.update(visible=True)}
225
- ops2={"Video":gr.update(visible=True)}
226
- ops3={"File":gr.update(visible=True,interactive=False)}
227
- # if option.lower()!="mp4" and option in video_containers:
228
- # option="mp4"
229
- chosen=lambda x:x.get(option,gr.update(visible=False))
230
- print(chosen(ops2),ops2.get(option,no_))
231
- return [chosen(ops),chosen(ops2),chosen(ops3)]
232
- def videoChange(value):
233
- print(value.name)
 
 
 
 
 
 
 
 
 
 
234
 
235
  # if option in video_containers:
236
  # output=gr.update(visible=True)
@@ -243,67 +340,112 @@ def videoChange(value):
243
  # return [no_,no_]
244
 
245
 
246
- def customBitrate(choice):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  if choice == "Custom":
248
- return gr.update(visible=True, value=None)
249
  else:
250
- return gr.update(visible=False, value=None)
 
251
 
 
 
 
 
252
 
253
- def supported_codecs(format: str, a=data):
254
- # lst=[i for i in a["codecs"]["audio"]
255
- # if i.get("supported")==None or "ogg" in i["supported"]]
 
 
 
256
  if format:
257
  format = format.lower()
258
- video_lst = [val.get("name") for val in a["codecs"]["video"]
259
  if val.get("supported") == None or format in val["supported"]]
260
- audio_lst = [val.get("name") for val in a["codecs"]["audio"]
261
  if val.get("supported") == None or format in val["supported"]]
262
  return [gr.update(choices=video_lst), gr.update(choices=audio_lst)]
263
 
264
 
265
- def supported_presets(format: str, a=data):
 
 
 
 
 
 
 
 
 
266
  if format:
267
  format = format.lower()
268
- video_lst = [val.get("name") for val in a["presets"]
269
  if val.get("supported") == None or format in val["supported"]]
270
- print(format, video_lst)
271
  return gr.update(choices=video_lst)
272
 
273
 
274
- """Helper Functions for Processing """
275
-
276
-
277
- def clear(*input):
278
- print(input, " clear_func")
279
- # for i in [inp for i in input for inp in i]:
280
- # print(i, hasattr(i,"cleared_value"),type(i))
281
- # a=default_clear(input_components)
282
- def clear_func(x): return [component.cleared_value if hasattr(
283
- component, "cleared_value") else None for component in x]
284
- print(clear_func(input))
285
- return clear_func(input)
286
 
287
-
288
- def change_clipbox(choice):
289
- print(gr.Dropdown().postprocess("clip test"))
290
  if choice == "Enabled":
291
  return [gr.update(visible=True, value="00:00"), gr.update(visible=True, value="00:10")]
292
  else:
293
  return [gr.update(visible=False, value=""), gr.update(visible=False, value="")]
294
 
295
 
296
- def updateOutput(file: _TemporaryFileWrapper):
297
  if file:
298
  print(file.name)
299
  return gr.update(value=file.name)
300
 
301
 
302
- def get_component_instance(inputs: gr.Blocks) -> list:
 
 
 
 
 
 
 
 
303
  return [gr.components.get_component_instance(i, render=True) for i in inputs.children]
304
 
305
 
306
  class Clear(CommandBuilder):
 
 
 
307
  def __call__(self, *args, **kwds):
308
  return self._component
309
 
@@ -314,32 +456,39 @@ class Clear(CommandBuilder):
314
  return self._component
315
 
316
  def __init__(self, *input_component: gr.Blocks()) -> None:
 
 
 
 
317
  self._component = []
318
  if input_component is not None:
319
  for i in input_component:
320
  self._component += super()._get_component_instance(i)
321
 
322
- def __get_component_instance(self, inputs: gr.Blocks) -> list:
323
- # print(inputs, " class instance")
324
- # res=[]
325
- # for i in inputs.children:
326
- # print(hasattr(i,"children"))
327
- # if not (hasattr(i,"children")):
328
- # res.append(gr.components.get_component_instance(i,render=True))
329
- # print(i)
330
- # elif hasattr(i,"children"):
331
- # continue
332
- # return res
333
- return [gr.components.get_component_instance(i, render=True) for i in inputs.children if not hasattr(i, "children")]
334
 
335
  def add(self, *args):
336
  print(args, type(args))
337
  if args is not None:
338
  for i in args:
339
- self._component += self.__get_component_instance(i)
340
  return self._component
341
 
342
  def clear(self, *args):
 
 
 
343
  def clear_func(x): return [component.cleared_value if hasattr(
344
  component, "cleared_value") else component.value for component in x]
345
  return clear_func(self._component)
 
1
+ """
2
+ util functions and classes
3
+ """
4
  import json
5
  from pprint import pprint
6
  from tempfile import _TemporaryFileWrapper
7
+ from typing import List
8
 
9
  import gradio as gr
10
+ from gradio.components import Component
11
 
12
  def parse(param: json) -> dict:
13
  with open(param) as file:
 
18
  codecs = parse("./codecs.json")
19
 
20
  """Video"""
21
+ containers = [j.get("name") for i in data["containers"]
22
+ for j in data["containers"][i]]
23
  video_containers = [i.get("name") for i in data["containers"]["video"]]
24
+ video_codecs = [i.get("value") for i in data["codecs"]["video"]]
25
  video_aspect_ratio = [i.get("name") for i in data["aspects"]]
26
  video_scaling = [i.get("name") for i in data["scalings"]]
27
  """ Audio """
28
  audio_containers = [i.get("name") for i in data["containers"]["audio"]]
29
+ audio_codecs = [i.get("value") for i in data["codecs"]["audio"]]
30
  audio_channels = [i.get("name") for i in data["audioChannels"]]
31
  audio_quality = [i.get("name") for i in data["audioQualities"]]
32
  audio_sample_rates = [i.get("name") for i in data["sampleRates"]]
 
49
 
50
 
51
  outputMap = parse("./mappings.json")
52
+ newoutputMap = parse("./new_mappings.json")
53
  """Output Mappings of commands to value
54
  audioQuality -b:a 128k
55
  """
56
 
57
 
58
  class CommandBuilder():
59
+ """Takes a collection of gradio layout elements and attaches
60
+ a function to each component in the context
61
+ to build an array of ffmpeg commands"""
62
+
63
  def __call__(self, *args, **kwds):
64
  return [i.value for i in self._component]
65
 
66
  def do(self, *inputs, **kwds):
67
  for comp in self._component:
68
  if comp.label is not None:
69
+ self.changefunc(comp, "", comp.value)
70
+
71
+ def reset(self):
72
+ self.outputDict = {"vf": {}, "af": {}}
73
+ self.commands=""
74
+ self.vf, self.af, self.extra = ([] for _ in range(3))
75
 
76
  def __init__(self, *inputs: gr.Blocks) -> None:
77
+ """
78
+ Parameters:
79
+ *inputs: A tuple of layout blocks containing components(Textbox,Button...).
80
+ """
81
+
82
+ self.outputDict = {"vf": {}, "af": {}}
83
  self.formatOutputDict = {"vf": {}, "af": {}}
84
  # state=gr.Variable()
85
  # state2=gr.Variable()
86
 
87
+ self._component: List[Component] = []
88
  self.vf, self.af, self.extra = ([] for _ in range(3))
89
  self.commands = ""
90
  if inputs is None:
 
100
  comp.change(fn=self.changefunc, inputs=[
101
  state, state2, comp], outputs=[])
102
 
103
+ def changefunc(self, input: gr.components.IOComponent, c_label="", newValue=""):
104
+ label, *_ = input.label.strip(": \n").lower().split(
105
+ ) if type(input.label) != list else "".join(input.label).strip(": ").lower().split()
106
+ label += "".join(_).title()
107
+ key = newoutputMap.get(label)
108
+ lst_extra, vf, af = ([] for _ in range(3))
109
 
110
+ if newValue not in [None, "Source", "Auto", "", "None", "none", 0]:
111
+ self.setVf(label, newValue)
112
+ self.setAf(label, newValue)
113
+ self.setF(label, newValue)
114
+ for val in self.outputDict:
115
+ if val == "vf":
116
+ vf = self.outputDict.get(val).values()
117
+ vf = ",".join(list(vf))
118
+ elif val == "af":
119
+ af = self.outputDict.get(val).values()
120
+ af = ",".join(list(af))
121
+ pass
122
+ else:
123
+ lst_extra.extend([val, self.outputDict.get(val)])
124
 
125
+ else:
126
+ self.outputDict.pop(key, "No Key Exists")
127
+ self.outputDict["vf"].pop(label, "No Key Exists")
128
+ self.outputDict["af"].pop(label, "No Key Exists")
129
+ self.vf = f"-vf '{vf}'" if vf else ""
130
+ self.af = f"-af '{af}'" if af else ""
131
+ self.extra = " ".join(lst_extra)
132
+ self.commands = f"{self.vf} {self.af} {self.extra}"
133
+
134
+ print(self.vf, self.af, self.extra)
135
+
136
+ def setVf(self, label:str, newValue:"str| int"):
137
+ """Sets Video filters
138
+
139
+ Args:
140
+ label : label of components
141
+ newValue : value of component
142
+ """
143
+ if newoutputMap["vf"].get(label):
144
+ key = newoutputMap["vf"].get(label)
145
+ if label in ["deinterlace", "denoise"]:
146
+ value = "_".join(newValue.lower().split())
147
+ arg = key.get(value, None)
148
+ self.outputDict["vf"].update({label: arg})
149
+ else:
150
+ self.outputDict["vf"].update({key: key})
151
+
152
+ def setF(self, label, newValue):
153
+ """ Sets Extra filters
154
+ Args:
155
+ label : label of components
156
+ newValue : value of component
157
+ """
158
+ if newoutputMap.get(label):
159
+ key = newoutputMap.get(label)
160
+ if label in ["video", "audio", "startTime", "stopTime"]:
161
+ self.outputDict.update({key: newValue})
162
+ else:
163
+ value = "".join([i.get("value", "None") for i in data.get(
164
+ label) if i.get("name", None) == newValue])
165
+ self.outputDict.update({key: value})
166
+
167
+ def setAf(self, label:str, newValue:"str|int"):
168
+ """ Sets Extra filters
169
+ Args:
170
+ label : label of components
171
+ newValue : value of component
172
+ """
173
+ if newoutputMap["af"].get(label):
174
+ value = int(newValue)/100
175
+ arg = f"{label}={value}"
176
+ self.outputDict["af"].update({label: arg})
177
+
178
+ def update(self, Component: Component):
179
  for comp in self._component:
180
  comp.change(lambda: gr.update(
181
+ value=self.outputDict), [], [Component])
182
+
183
+ def _get_component_instance(self, inputs: gr.Blocks) -> List[Component]:
184
+ """
185
+ returns components present in a layout block
186
+ Parameters:
187
+ inputs: layout block
188
+ """
189
  return [gr.components.get_component_instance(i, render=True) for i in inputs.children if not hasattr(i, "children")]
190
 
191
  def setVideoFilters(self, options):
192
  value = self.outputDict.get(options, "-")
193
+ filters = newoutputMap.get(options, None)
194
  arg = ""
195
  if options in ["deinterlace", "denoise"]:
196
  value = "_".join(value.lower().split())
197
  arg = filters.get(value, None)
198
  # self.vf.append(arg)
199
+ self.outputDict["vf"].update({options: arg})
200
  return True
201
  if options in ["deband", "deflicker", "deshake", "dejudder"]:
202
  arg = filters
203
+ self.outputDict["vf"].update({options: arg})
204
  return True
205
 
206
  return
 
211
  value = int(value)/100
212
  arg = f"{options}={value}"
213
 
214
+ self.outputDict["af"].update({options: arg})
215
  return True
216
  return
217
 
218
  def setFormat(self, options):
219
  value = self.outputDict.get(options, "-")
220
+ filters = newoutputMap.get(options, None)
221
  if options in ["video", "audio"]:
222
  value = "".join([i.get("value", "None") for i in data.get(
223
  "codecs").get(options) if i.get("name", None) == value])
224
  arg = f"{filters} {value}"
225
+ self.outputDict.update({options: arg})
226
  return True
227
  elif data.get(options) == None:
228
  arg = f"{filters} {value}"
229
+ self.outputDict.update({options: arg})
230
  return True
231
  elif options != "clip":
232
  value = "".join([i.get("value", "None") for i in data.get(
233
  options) if i.get("name", None) == value])
234
  arg = f"{filters} {value}"
235
+ self.outputDict.update({options: arg})
236
 
237
  def build(self):
238
  for i in self.outputDict:
 
243
  else:
244
  self.setFormat(i)
245
  lst_extra, vf, af = ([] for _ in range(3))
246
+ for val in self.outputDict:
247
  if val == "vf":
248
+ vf = self.outputDict.get(val).values()
249
  vf = ",".join(list(vf))
250
  elif val == "af":
251
+ af = self.outputDict.get(val).values()
252
  af = ",".join(list(af))
253
  else:
254
+ lst_extra.append(self.outputDict.get(val))
255
  # print(lst_extra, "temp x")
256
  # if vf:self.vf=f"-vf '{vf}'"
257
  # if af:self.af=f"-af '{af}'"
 
260
  self.extra = " ".join(lst_extra)
261
  self.commands = f"{self.vf} {self.af} {self.extra}"
262
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263
  def startfunc(self, input: gr.components.IOComponent, c_label="", newValue=""):
264
  label, *_ = input.label.strip(": ").lower().split(
265
  ) if type(input.label) != list else "".join(input.label).strip(": ").lower().split()
266
  label += "".join(_).title()
267
+ if newValue not in [None, "Source", "Auto", "", "None", 0]:
268
+ self.outputDict["vf"].update({label: newValue})
269
+ self.outputDict["af"].update({label: newValue})
270
  self.outputDict.update({label: newValue})
271
  else:
272
  self.outputDict.pop(label, "No Key Exists")
273
+ self.outputDict["vf"].pop(label, "No Key Exists")
274
+ self.outputDict["af"].pop(label, "No Key Exists")
275
+ # self.formatOutputDict["vf"].pop(label, "Key is None or similar")
276
+ # self.formatOutputDict["af"].pop(label, "Key is None or similar")
277
+ # self.formatOutputDict.pop(label, "Key is None or similar")
278
+ print(self.outputDict)
279
  self.build()
280
 
281
 
282
+ # def somefunc(input: gr.components.IOComponent, c_label=""):
283
+ # label = ""
284
+ # output = {}
285
+ # print(input, c_label)
286
+ # label, *_ = input.label.strip(": ").lower().split(
287
+ # ) if type(input.label) != list else "".join(input.label).strip(": ").lower().split()
288
+ # label += "".join(_).title()
289
+ # print(newoutputMap.get(label), label, c_label)
290
+ # if c_label not in [None, "Source", "Auto", ""]:
291
+ # print(input.value)
292
+ # output.update({label: c_label})
293
+ # else:
294
+ # output.pop(label, "No Key Exists")
295
+ # pprint(output)
 
 
296
 
297
  # def mediaChange(option):
298
  # no_=gr.update(visible=False)
 
305
  # else:
306
  # output=gr.update(visible=False)
307
  # return [no_,no_]
308
+
309
+
310
+ def mediaChange(option:str)-> List[Component]:
311
+ """
312
+ Allows playing the media in various options,
313
+ Video, Audio or File
314
+
315
+ Args:
316
+ option : Clicked buttons value
317
+
318
+ Returns:
319
+ List[Component]: list of toggled output components to display
320
+ """
321
+ ops = {"Audio": gr.update(visible=True)}
322
+ ops2 = {"Video": gr.update(visible=True)}
323
+ ops3 = {"File": gr.update(visible=True, interactive=False)}
324
+
325
+ def chosen(x): return x.get(option, gr.update(visible=False))
326
+ return [chosen(ops), chosen(ops2), chosen(ops3)]
327
+
328
+
329
+ # def videoChange(value):
330
+ # print(value.name)
331
 
332
  # if option in video_containers:
333
  # output=gr.update(visible=True)
 
340
  # return [no_,no_]
341
 
342
 
343
+
344
+
345
+ """Helper Functions for Processing """
346
+
347
+
348
+ # def clear(*input):
349
+ # print(input, " clear_func")
350
+ # # for i in [inp for i in input for inp in i]:
351
+ # # print(i, hasattr(i,"cleared_value"),type(i))
352
+ # # a=default_clear(input_components)
353
+ # def clear_func(x): return [component.cleared_value if hasattr(
354
+ # component, "cleared_value") else None for component in x]
355
+ # print(clear_func(input))
356
+ # return clear_func(input)
357
+
358
+ def customBitrate(choice:int)-> Component:
359
+ """
360
+ Toggle acomponent for custom Audio Quality
361
+ visible/none
362
+ Args:
363
+ choice : Custom audio quality
364
+
365
+ Returns:
366
+ Component: component toggle state
367
+ """
368
  if choice == "Custom":
369
+ return gr.update(visible=True)
370
  else:
371
+ return gr.update(visible=False, value=0)
372
+
373
 
374
+ def supported_codecs(format: str)-> List[Component]:
375
+ """
376
+ Changes video and audio components with appropriate
377
+ options according to passed format
378
 
379
+ Args:
380
+ format: passed media codec (x264,x265)
381
+
382
+ Returns:
383
+ List[Component]: list of components with updated choices
384
+ """
385
  if format:
386
  format = format.lower()
387
+ video_lst = [val.get("value") for val in data["codecs"]["video"]
388
  if val.get("supported") == None or format in val["supported"]]
389
+ audio_lst = [val.get("value") for val in data["codecs"]["audio"]
390
  if val.get("supported") == None or format in val["supported"]]
391
  return [gr.update(choices=video_lst), gr.update(choices=audio_lst)]
392
 
393
 
394
+ def supported_presets(format: str)-> Component:
395
+ """
396
+ Changes presets component with appropriate
397
+ options according to passed format
398
+ Args:
399
+ format: passed media codec (x264,x265)
400
+
401
+ Returns:
402
+ Component: component with updated choice list (video codecs)
403
+ """
404
  if format:
405
  format = format.lower()
406
+ video_lst = [val.get("name") for val in data["presets"]
407
  if val.get("supported") == None or format in val["supported"]]
 
408
  return gr.update(choices=video_lst)
409
 
410
 
411
+ def change_clipbox(choice:str)-> List[Component]:
412
+ """
413
+ Toggles the clipping Textbox
414
+
415
+ Args:
416
+ choice: Enabled/None
 
 
 
 
 
 
417
 
418
+ Returns:
419
+ List[Component]: list of components with visible state of the clip components
420
+ """
421
  if choice == "Enabled":
422
  return [gr.update(visible=True, value="00:00"), gr.update(visible=True, value="00:10")]
423
  else:
424
  return [gr.update(visible=False, value=""), gr.update(visible=False, value="")]
425
 
426
 
427
+ def updateOutput(file: _TemporaryFileWrapper)-> Component:
428
  if file:
429
  print(file.name)
430
  return gr.update(value=file.name)
431
 
432
 
433
+ def get_component_instance(inputs: gr.Blocks)-> List[Component]:
434
+ """ returns only components
435
+
436
+ Args:
437
+ inputs: layout elements
438
+
439
+ Returns:
440
+ List[Component]: components
441
+ """
442
  return [gr.components.get_component_instance(i, render=True) for i in inputs.children]
443
 
444
 
445
  class Clear(CommandBuilder):
446
+ """ Class for clearing components in layouts
447
+ """
448
+
449
  def __call__(self, *args, **kwds):
450
  return self._component
451
 
 
456
  return self._component
457
 
458
  def __init__(self, *input_component: gr.Blocks()) -> None:
459
+ """
460
+ Parameters:
461
+ *input_component: A tuple of layout blocks containing components
462
+ """
463
  self._component = []
464
  if input_component is not None:
465
  for i in input_component:
466
  self._component += super()._get_component_instance(i)
467
 
468
+ # def __get_component_instance(self, inputs: gr.Blocks) -> list:
469
+ # # print(inputs, " class instance")
470
+ # # res=[]
471
+ # # for i in inputs.children:
472
+ # # print(hasattr(i,"children"))
473
+ # # if not (hasattr(i,"children")):
474
+ # # res.append(gr.components.get_component_instance(i,render=True))
475
+ # # print(i)
476
+ # # elif hasattr(i,"children"):
477
+ # # continue
478
+ # # return res
479
+ # return [gr.components.get_component_instance(i, render=True) for i in inputs.children if not hasattr(i, "children")]
480
 
481
  def add(self, *args):
482
  print(args, type(args))
483
  if args is not None:
484
  for i in args:
485
+ self._component += super().__get_component_instance(i)
486
  return self._component
487
 
488
  def clear(self, *args):
489
+ """
490
+ Function to clear components from a Block in the class instance
491
+ """
492
  def clear_func(x): return [component.cleared_value if hasattr(
493
  component, "cleared_value") else component.value for component in x]
494
  return clear_func(self._component)
new_mappings.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "vf": {
3
+ "deband": "deband",
4
+ "deshake": "deshake",
5
+ "deflicker": "deflicker",
6
+ "dejudder": "dejudder",
7
+ "denoise": {
8
+ "light": "removegrain=22",
9
+ "medium": "vaguedenoiser=threshold=3:method=soft:nsteps=5",
10
+ "heavy": "vaguedenoiser=threshold=6:method=soft:nsteps=5",
11
+ "default": "removegrain=0"
12
+ },
13
+ "deinterlace": {
14
+ "frame": "yadif=0:-1:0",
15
+ "field": "yadif=1:-1:0",
16
+ "frame_nospatial": "yadif=2:-1:0",
17
+ "field_nospatial": "yadif=3:-1:0"
18
+ }
19
+ },
20
+ "af": {
21
+ "acontrast": 0
22
+ },
23
+ "protocols": "",
24
+ "startTime": "-ss",
25
+ "stopTime": "-to",
26
+
27
+ "video": "-c:v",
28
+ "audio": "-c:a",
29
+ "bitrate": "-b:v",
30
+ "minrate": "-minrate",
31
+ "maxrate": "-maxrate",
32
+ "bufsize": "-bufsize",
33
+ "gopsize": "-g",
34
+ "pixelFormat": "-pix_fmt",
35
+
36
+ "containers": {
37
+ "video": "-c:v",
38
+ "audio": "-c:a"
39
+ },
40
+ "clipping": {
41
+ "startTime": "-ss",
42
+ "stopTime": "-to"
43
+ },
44
+ "codecs": "",
45
+ "presets": "-preset",
46
+ "passOptions": "-pass",
47
+ "pixelformats": "",
48
+ "frameRates": "-r",
49
+ "speeds": "",
50
+ "tunes": "-tune",
51
+ "profiles": "-profile:v",
52
+ "levels": "",
53
+ "fastStart": "-movflags",
54
+ "sizes": "",
55
+ "formats": "",
56
+ "aspects": "-aspect",
57
+ "scalings": "",
58
+
59
+
60
+ "audioStreams": "",
61
+ "audioChannels": "-ac",
62
+ "audioQualities": "-b:a",
63
+ "sampleRates": "-ar",
64
+
65
+
66
+ "extraOptions": "",
67
+ "logLevels": ""
68
+ }
requirements.txt → req.txt RENAMED
File without changes