本文整理汇总了Python中classes.query.File类的典型用法代码示例。如果您正苦于以下问题:Python File类的具体用法?Python File怎么用?Python File使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了File类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_filter_File
def test_filter_File(self):
""" Test the File.filter method """
# Import additional classes that need the app defined first
from classes.query import File
# Find all Files named file1
files = File.filter(id=TestQueryClass.file_ids[0])
self.assertTrue(files)
# Do not find a File
files = File.filter(id="invalidID")
self.assertEqual(len(files), 0)
示例2: test_get_File
def test_get_File(self):
""" Test the File.get method """
# Import additional classes that need the app defined first
from classes.query import File
# Find a File named file1
file = File.get(id=TestQueryClass.file_ids[1])
self.assertTrue(file)
# Do not find a File
file = File.get(id="invalidID")
self.assertEqual(file, None)
示例3: value_updated
def value_updated(self, item):
""" Name or tags updated """
# Get translation method
_ = get_app()._tr
# Determine what was changed
file_id = self.files_model.model.item(item.row(), 5).text()
name = self.files_model.model.item(item.row(), 1).text()
tags = self.files_model.model.item(item.row(), 2).text()
# Get file object and update friendly name and tags attribute
f = File.get(id=file_id)
if name != f.data["path"]:
f.data["name"] = name
else:
f.data["name"] = ""
if "tags" in f.data.keys():
if tags != f.data["tags"]:
f.data["tags"] = tags
elif tags:
f.data["tags"] = tags
# Tell file model to ignore updates (since this treeview will already be updated)
self.files_model.ignore_update_signal = True
# Save File
f.save()
# Re-enable updates
self.files_model.ignore_update_signal = False
示例4: contextMenuEvent
def contextMenuEvent(self, event):
# Update selection
self.updateSelection()
# Set context menu mode
app = get_app()
app.context_menu_object = "files"
menu = QMenu(self)
menu.addAction(self.win.actionImportFiles)
menu.addAction(self.win.actionDetailsView)
if self.selected:
# If file selected, show file related options
menu.addSeparator()
# Add edit title option (if svg file)
selected_file_id = self.win.selected_files[0]
file = File.get(id=selected_file_id)
if file and file.data.get("path").endswith(".svg"):
menu.addAction(self.win.actionEditTitle)
menu.addAction(self.win.actionDuplicateTitle)
menu.addSeparator()
menu.addAction(self.win.actionPreview_File)
menu.addAction(self.win.actionSplitClip)
menu.addAction(self.win.actionAdd_to_Timeline)
menu.addAction(self.win.actionFile_Properties)
menu.addSeparator()
menu.addAction(self.win.actionRemove_from_Project)
menu.addSeparator()
# Show menu
menu.exec_(QCursor.pos())
示例5: add_file
def add_file(self, filepath):
path, filename = os.path.split(filepath)
# Add file into project
app = get_app()
_ = get_app()._tr
# Check for this path in our existing project data
file = File.get(path=filepath)
# If this file is already found, exit
if file:
return
# Load filepath in libopenshot clip object (which will try multiple readers to open it)
clip = openshot.Clip(filepath)
# Get the JSON for the clip's internal reader
try:
reader = clip.Reader()
file_data = json.loads(reader.Json())
# Determine media type
if file_data["has_video"] and not self.is_image(file_data):
file_data["media_type"] = "video"
elif file_data["has_video"] and self.is_image(file_data):
file_data["media_type"] = "image"
elif file_data["has_audio"] and not file_data["has_video"]:
file_data["media_type"] = "audio"
# Save new file to the project data
file = File()
file.data = file_data
file.save()
return True
except:
# Handle exception
msg = QMessageBox()
msg.setText(_("{} is not a valid video, audio, or image file.".format(filename)))
msg.exec_()
return False
示例6: test_update_File
def test_update_File(self):
""" Test the File.save method """
# Import additional classes that need the app defined first
from classes.query import File
# Find a File named file1
update_id = TestQueryClass.file_ids[0]
file = File.get(id=update_id)
self.assertTrue(file)
# Update File
file.data["height"] = 1080
file.data["width"] = 1920
file.save()
# Verify updated data
# Get File again
file = File.get(id=update_id)
self.assertEqual(file.data["height"], 1080)
self.assertEqual(file.data["width"], 1920)
示例7: add_file
def add_file(self, filepath):
""" Add an animation to the project file tree """
path, filename = os.path.split(filepath)
# Add file into project
app = get_app()
_ = get_app()._tr
# Check for this path in our existing project data
file = File.get(path=filepath)
# If this file is already found, exit
if file:
return
# Get the JSON for the clip's internal reader
try:
# Open image sequence in FFmpegReader
reader = openshot.FFmpegReader(filepath)
reader.Open()
# Serialize JSON for the reader
file_data = json.loads(reader.Json())
# Set media type
file_data["media_type"] = "video"
# Save new file to the project data
file = File()
file.data = file_data
file.save()
return True
except:
# Handle exception
msg = QMessageBox()
msg.setText(_("{} is not a valid video, audio, or image file.".format(filename)))
msg.exec_()
return False
示例8: setUpClass
def setUpClass(TestQueryClass):
""" Init unit test data """
# Create Qt application
TestQueryClass.app = OpenShotApp(sys.argv, mode="unittest")
TestQueryClass.clip_ids = []
TestQueryClass.file_ids = []
TestQueryClass.transition_ids = []
# Import additional classes that need the app defined first
from classes.query import Clip, File, Transition
# Insert some clips into the project data
for num in range(5):
# Create clip
c = openshot.Clip(os.path.join(info.IMAGES_PATH, "AboutLogo.png"))
# Parse JSON
clip_data = json.loads(c.Json())
# Insert into project data
query_clip = Clip()
query_clip.data = clip_data
query_clip.save()
# Keep track of the ids
TestQueryClass.clip_ids.append(query_clip.id)
# Insert some files into the project data
for num in range(5):
# Create file
r = openshot.DummyReader(openshot.Fraction(24, 1), 640, 480, 44100, 2, 30.0)
# Parse JSON
file_data = json.loads(r.Json())
# Insert into project data
query_file = File()
query_file.data = file_data
query_file.data["path"] = os.path.join(info.IMAGES_PATH, "AboutLogo.png")
query_file.data["media_type"] = "image"
query_file.save()
# Keep track of the ids
TestQueryClass.file_ids.append(query_file.id)
# Insert some transitions into the project data
for num in range(5):
# Create mask object
transition_object = openshot.Mask()
transitions_data = json.loads(transition_object.Json())
# Insert into project data
query_transition = Transition()
query_transition.data = transitions_data
query_transition.save()
# Keep track of the ids
TestQueryClass.transition_ids.append(query_transition.id)
示例9: test_delete_File
def test_delete_File(self):
""" Test the File.delete method """
# Import additional classes that need the app defined first
from classes.query import File
# Find a File named file1
delete_id = TestQueryClass.file_ids[4]
file = File.get(id=delete_id)
self.assertTrue(file)
# Delete File
file.delete()
# Verify deleted data
deleted_file = File.get(id=delete_id)
self.assertFalse(deleted_file)
# Delete File again (should do nothing
file.delete()
# Verify deleted data
deleted_file = File.get(id=delete_id)
self.assertFalse(deleted_file)
示例10: actionPreview_File_trigger
def actionPreview_File_trigger(self, event):
""" Preview the selected media file """
log.info('actionPreview_File_trigger')
if self.selected_files:
# Find matching file
f = File.get(id=self.selected_files[0])
if f:
# Get file path
previewPath = f.data["path"]
# Load file into player
self.preview_thread.LoadFile(previewPath)
# Trigger play button
self.actionPlay.setChecked(False)
self.actionPlay.trigger()
示例11: actionRemove_from_Project_trigger
def actionRemove_from_Project_trigger(self, event):
log.info("actionRemove_from_Project_trigger")
# Loop through selected files
for file_id in self.selected_files:
# Find matching file
f = File.get(id=file_id)
if f:
# Remove file
f.delete()
# Find matching clips (if any)
clips = Clip.filter(file_id=file_id)
for c in clips:
# Remove clip
c.delete()
# Clear selected files
self.selected_files = []
示例12: add_file
def add_file(self, filepath):
path, filename = os.path.split(filepath)
# Add file into project
app = get_app()
_ = get_app()._tr
# Check for this path in our existing project data
file = File.get(path=filepath)
# If this file is already found, exit
if file:
return
# Load filepath in libopenshot clip object (which will try multiple readers to open it)
clip = openshot.Clip(filepath)
# Get the JSON for the clip's internal reader
try:
reader = clip.Reader()
file_data = json.loads(reader.Json())
# Determine media type
if file_data["has_video"] and not self.is_image(file_data):
file_data["media_type"] = "video"
elif file_data["has_video"] and self.is_image(file_data):
file_data["media_type"] = "image"
elif file_data["has_audio"] and not file_data["has_video"]:
file_data["media_type"] = "audio"
# Save new file to the project data
file = File()
file.data = file_data
# Is this file an image sequence / animation?
image_seq_details = self.get_image_sequence_details(filepath)
if image_seq_details:
# Update file with correct path
folder_path = image_seq_details["folder_path"]
file_name = image_seq_details["file_path"]
base_name = image_seq_details["base_name"]
fixlen = image_seq_details["fixlen"]
digits = image_seq_details["digits"]
extension = image_seq_details["extension"]
if not fixlen:
zero_pattern = "%d"
else:
zero_pattern = "%%0%sd" % digits
# Generate the regex pattern for this image sequence
pattern = "%s%s.%s" % (base_name, zero_pattern, extension)
# Split folder name
(parentPath, folderName) = os.path.split(folder_path)
if not base_name:
# Give alternate name
file.data["name"] = "%s (%s)" % (folderName, pattern)
# Load image sequence (to determine duration and video_length)
image_seq = openshot.Clip(os.path.join(folder_path, pattern))
# Update file details
file.data["path"] = os.path.join(folder_path, pattern)
file.data["media_type"] = "video"
file.data["duration"] = image_seq.Reader().info.duration
file.data["video_length"] = image_seq.Reader().info.video_length
# Save file
file.save()
return True
except:
# Handle exception
msg = QMessageBox()
msg.setText(_("{} is not a valid video, audio, or image file.".format(filename)))
msg.exec_()
return False
示例13: currentChanged
def currentChanged(self, selected, deselected):
# Get selected item
self.selected = selected
self.deselected = deselected
# Get translation object
_ = self.app._tr
# Clear existing settings
self.win.clear_effect_controls()
# Get animation details
animation = self.get_animation_details()
self.selected_template = animation["service"]
# Assign a new unique id for each template selected
self.generateUniqueFolder()
# Loop through params
for param in animation["params"]:
log.info(param["title"])
# Is Hidden Param?
if param["name"] == "start_frame" or param["name"] == "end_frame":
# add value to dictionary
self.params[param["name"]] = int(param["default"])
# skip to next param without rendering the controls
continue
# Create Label
widget = None
label = QLabel()
label.setText(_(param["title"]))
label.setToolTip(_(param["title"]))
if param["type"] == "spinner":
# add value to dictionary
self.params[param["name"]] = float(param["default"])
# create spinner
widget = QDoubleSpinBox()
widget.setMinimum(float(param["min"]))
widget.setMaximum(float(param["max"]))
widget.setValue(float(param["default"]))
widget.setSingleStep(0.01)
widget.setToolTip(param["title"])
widget.valueChanged.connect(functools.partial(self.spinner_value_changed, param))
elif param["type"] == "text":
# add value to dictionary
self.params[param["name"]] = _(param["default"])
# create spinner
widget = QLineEdit()
widget.setText(_(param["default"]))
widget.textChanged.connect(functools.partial(self.text_value_changed, widget, param))
elif param["type"] == "multiline":
# add value to dictionary
self.params[param["name"]] = _(param["default"])
# create spinner
widget = QTextEdit()
widget.setText(_(param["default"]))
widget.textChanged.connect(functools.partial(self.text_value_changed, widget, param))
elif param["type"] == "dropdown":
# add value to dictionary
self.params[param["name"]] = param["default"]
# create spinner
widget = QComboBox()
widget.currentIndexChanged.connect(functools.partial(self.dropdown_index_changed, widget, param))
# Add values to dropdown
if "project_files" in param["name"]:
# override files dropdown
param["values"] = {}
for file in File.filter():
if file.data["media_type"] in ("image", "video"):
(dirName, fileName) = os.path.split(file.data["path"])
(fileBaseName, fileExtension) = os.path.splitext(fileName)
if fileExtension.lower() not in (".svg"):
param["values"][fileName] = "|".join((file.data["path"], str(file.data["height"]),
str(file.data["width"]), file.data["media_type"],
str(file.data["fps"]["num"] / file.data["fps"][
"den"])))
# Add normal values
box_index = 0
for k, v in sorted(param["values"].items()):
# add dropdown item
widget.addItem(_(k), v)
# select dropdown (if default)
if v == param["default"]:
widget.setCurrentIndex(box_index)
box_index = box_index + 1
#.........这里部分代码省略.........
示例14: update_model
def update_model(self, clear=True):
log.info("updating files model.")
app = get_app()
# Get window to check filters
win = app.window
_ = app._tr
# Skip updates (if needed)
if self.ignore_update_signal:
return
# Clear all items
if clear:
self.model_ids = {}
self.model.clear()
# Add Headers
self.model.setHorizontalHeaderLabels([_("Thumb"), _("Name"), _("Tags"), "", "", ""])
# Get list of files in project
files = File.filter() # get all files
# add item for each file
for file in files:
path, filename = os.path.split(file.data["path"])
tags = ""
if "tags" in file.data.keys():
tags = file.data["tags"]
name = filename
if "name" in file.data.keys():
name = file.data["name"]
if not win.actionFilesShowAll.isChecked():
if win.actionFilesShowVideo.isChecked():
if not file.data["media_type"] == "video":
continue # to next file, didn't match filter
elif win.actionFilesShowAudio.isChecked():
if not file.data["media_type"] == "audio":
continue # to next file, didn't match filter
elif win.actionFilesShowImage.isChecked():
if not file.data["media_type"] == "image":
continue # to next file, didn't match filter
if win.filesFilter.text() != "":
if not win.filesFilter.text().lower() in filename.lower() \
and not win.filesFilter.text().lower() in tags.lower() \
and not win.filesFilter.text().lower() in name.lower():
continue
# Generate thumbnail for file (if needed)
if (file.data["media_type"] == "video" or file.data["media_type"] == "image"):
# Determine thumb path
thumb_path = os.path.join(info.THUMBNAIL_PATH, "{}.png".format(file.id))
# Check if thumb exists
if not os.path.exists(thumb_path):
try:
# Convert path to the correct relative path (based on this folder)
file_path = file.absolute_path()
# Reload this reader
clip = openshot.Clip(file_path)
reader = clip.Reader()
# Open reader
reader.Open()
# Determine if video overlay should be applied to thumbnail
overlay_path = ""
if file.data["media_type"] == "video":
overlay_path = os.path.join(info.IMAGES_PATH, "overlay.png")
# Check for start and end attributes (optional)
thumbnail_frame = 1
if 'start' in file.data.keys():
fps = file.data["fps"]
fps_float = float(fps["num"]) / float(fps["den"])
thumbnail_frame = round(float(file.data['start']) * fps_float) + 1
# Save thumbnail
reader.GetFrame(thumbnail_frame).Thumbnail(thumb_path, 98, 64, os.path.join(info.IMAGES_PATH, "mask.png"),
overlay_path, "#000", False)
reader.Close()
clip.Close()
except:
# Handle exception
msg = QMessageBox()
msg.setText(_("{} is not a valid video, audio, or image file.".format(filename)))
msg.exec_()
continue
else:
# Audio file
thumb_path = os.path.join(info.PATH, "images", "AudioThumbnail.png")
#.........这里部分代码省略.........
示例15: read_legacy_project_file
def read_legacy_project_file(self, file_path):
"""Attempt to read a legacy version 1.x openshot project file"""
import sys, pickle
from classes.query import File, Track, Clip, Transition
from classes.app import get_app
import openshot
try:
import json
except ImportError:
import simplejson as json
# Get translation method
_ = get_app()._tr
# Append version info
v = openshot.GetVersion()
project_data = {}
project_data["version"] = {"openshot-qt" : info.VERSION,
"libopenshot" : v.ToString()}
# Get FPS from project
from classes.app import get_app
fps = get_app().project.get(["fps"])
fps_float = float(fps["num"]) / float(fps["den"])
# Import legacy openshot classes (from version 1.X)
from classes.legacy.openshot import classes as legacy_classes
from classes.legacy.openshot.classes import project as legacy_project
from classes.legacy.openshot.classes import sequences as legacy_sequences
from classes.legacy.openshot.classes import track as legacy_track
from classes.legacy.openshot.classes import clip as legacy_clip
from classes.legacy.openshot.classes import keyframe as legacy_keyframe
from classes.legacy.openshot.classes import files as legacy_files
from classes.legacy.openshot.classes import transition as legacy_transition
from classes.legacy.openshot.classes import effect as legacy_effect
from classes.legacy.openshot.classes import marker as legacy_marker
sys.modules['openshot.classes'] = legacy_classes
sys.modules['classes.project'] = legacy_project
sys.modules['classes.sequences'] = legacy_sequences
sys.modules['classes.track'] = legacy_track
sys.modules['classes.clip'] = legacy_clip
sys.modules['classes.keyframe'] = legacy_keyframe
sys.modules['classes.files'] = legacy_files
sys.modules['classes.transition'] = legacy_transition
sys.modules['classes.effect'] = legacy_effect
sys.modules['classes.marker'] = legacy_marker
# Keep track of files that failed to load
failed_files = []
with open(file_path.encode('UTF-8'), 'rb') as f:
try:
# Unpickle legacy openshot project file
v1_data = pickle.load(f, fix_imports=True, encoding="UTF-8")
file_lookup = {}
# Loop through files
for item in v1_data.project_folder.items:
# Is this item a File (i.e. ignore folders)
if isinstance(item, legacy_files.OpenShotFile):
# Create file
try:
clip = openshot.Clip(item.name)
reader = clip.Reader()
file_data = json.loads(reader.Json(), strict=False)
# Determine media type
if file_data["has_video"] and not self.is_image(file_data):
file_data["media_type"] = "video"
elif file_data["has_video"] and self.is_image(file_data):
file_data["media_type"] = "image"
elif file_data["has_audio"] and not file_data["has_video"]:
file_data["media_type"] = "audio"
# Save new file to the project data
file = File()
file.data = file_data
file.save()
# Keep track of new ids and old ids
file_lookup[item.unique_id] = file
except:
# Handle exception quietly
msg = ("%s is not a valid video, audio, or image file." % item.name)
log.error(msg)
failed_files.append(item.name)
# Delete all tracks
track_list = copy.deepcopy(Track.filter())
for track in track_list:
track.delete()
# Create new tracks
track_counter = 0
for legacy_t in reversed(v1_data.sequences[0].tracks):
t = Track()
t.data = {"number": track_counter, "y": 0, "label": legacy_t.name}
t.save()
#.........这里部分代码省略.........