<commit_before>#***************************************************************************
#*                                                                         *
#*   Copyright (c) 2017 - <NAME> <<EMAIL>>            *
#*                                                                         *
#*   This program is free software; you can redistribute it and/or modify  *
#*   it under the terms of the GNU Lesser General Public License (LGPL)    *
#*   as published by the Free Software Foundation; either version 2 of     *
#*   the License, or (at your option) any later version.                   *
#*   for detail see the LICENCE text file.                                 *
#*                                                                         *
#*   This program is distributed in the hope that it will be useful,       *
#*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
#*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
#*   GNU Library General Public License for more details.                  *
#*                                                                         *
#*   You should have received a copy of the GNU Library General Public     *
#*   License along with this program; if not, write to the Free Software   *
#*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
#*   USA                                                                   *
#*                                                                         *
#***************************************************************************

from __future__ import print_function

__title__ = "Sketchfab uploader"
__author__ = "<NAME>"
__url__ = "http://www.freecadweb.org"

import FreeCAD, FreeCADGui, WebGui, os, zipfile, requests, tempfile, json, time, re
from PySide import QtCore, QtGui

# \cond
try:
    def translate(context, text, disambig=None):
        return QtGui.QApplication.translate(context, text, disambig, QtGui.QApplication.UnicodeUTF8)
except AttributeError:
    def translate(context, text, disambig=None):
        return QtGui.QApplication.translate(context, text, disambig)
# \endcond

SKETCHFAB_UPLOAD_URL = "https://api.sketchfab.com/v3/models"
SKETCHFAB_TOKEN_URL = "https://sketchfab.com/settings/password"
SKETCHFAB_MODEL_URL = "https://sketchfab.com/show/"


class SketchfabTaskPanel:
    
    '''The TaskPanel for Sketchfab upload'''
    
    def __init__(self):
        
        self.url = None
        self.form = FreeCADGui.PySideUic.loadUi(":/ui/TaskDlgSketchfab.ui")
        self.form.ProgressBar.hide()
        self.form.Button_View.hide()
        QtCore.QObject.connect(self.form.Button_Token,QtCore.SIGNAL("pressed()"),self.getToken)
        QtCore.QObject.connect(self.form.Button_Upload,QtCore.SIGNAL("pressed()"),self.upload)
        QtCore.QObject.connect(self.form.Button_View,QtCore.SIGNAL("pressed()"),self.viewModel)
        self.form.Text_Name.setText(FreeCAD.ActiveDocument.Label)
        self.form.Text_Token.setText(FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Web").GetString("SketchfabToken",""))

    def isAllowedAlterSelection(self):
        
        return True

    def isAllowedAlterView(self):
        
        return True

    def getStandardButtons(self):
        
        return int(QtGui.QDialogButtonBox.Close)

    def accept(self):
        
        FreeCADGui.ActiveDocument.resetEdit()
        return True

    def getToken(self):
        
        QtGui.QDesktopServices.openUrl(SKETCHFAB_TOKEN_URL)
        
    def get_request_payload(self, token, data={}, files={}, json_payload=False):
        
        """Helper method that returns the authentication token and proper content
        type depending on whether or not we use JSON payload."""
        headers = {'Authorization': 'Token {}'.format(token)}
        if json_payload:
            headers.update({'Content-Type': 'application/json'})
            data = json.dumps(data)
        return {'data': data, 'files': files, 'headers': headers}
        
    def saveFile(self):
        
        import FreeCADGui
        if self.form.Radio_Selection.isChecked():
            objects = FreeCADGui.Selection.getSelection()
        else:
            objects = [obj for obj in FreeCAD.ActiveDocument.Objects if obj.ViewObject.isVisible()]
        if not objects:
            QtGui.QMessageBox.critical(None,translate("Web","Nothing to upload"),translate("The selection of the document contains no object to upload"))
            return None
        filename = os.path.join(tempfile._get_default_tempdir(),next(tempfile._get_candidate_names()))
        filetype = self.form.Combo_Filetype.currentIndex()
        # 0 = obj + mtl, 1 = obj, 2 = dae, 3 = stl, 4 = IGES, 5 = iv (currently not working)
        if filetype == 0: # OBJ + MTL
            import importOBJ
            importOBJ.export(objects,filename+".obj")
            return self.packFiles(filename,[filename+".obj",filename+".mtl"])
        elif filetype == 1: # OBJ (mesh exporter)
            import Mesh
            Mesh.export(objects,filename+".obj")
            return self.packFiles(filename,[filename+".obj"])
        elif filetype == 2: # DAE
            import importDAE
            importDAE.export(objects,filename+".dae")
            return self.packFiles(filename,[filename+".dae"])
        elif filetype == 3: # STL
            import Mesh
            Mesh.export(objects,filename+".stl")
            return self.packFiles(filename,[filename+".stl"])
        elif filetype == 4: # IGES
            import Part
            Part.export(objects,filename+".iges")
            return self.packFiles(filename,[filename+".iges"])
        elif filetype == 5: # IV
            import FreeCADGui
            FreeCADGui.export(objects,filename+".iv")
            # removing FreeCAD-specific nodes
            f = open(filename+".iv","rb")
            s = f.read()
            f.close()
            s = s.replace("SoBrepEdgeSet","SoIndexedLineSet")
            s = s.replace("SoBrepFaceSet","SoIndexedFaceSet")
            s = s.replace("\n","--endl--")
            s = re.sub("highlightIndex .*?\]"," ",s)
            s = re.sub("partIndex .*?\]"," ",s)
            s = s.replace("--endl--","\n")
            f = open(filename+".iv","wb")
            f.write(s)
            f.close()
            return self.packFiles(filename,[filename+".iv"])

    def packFiles(self,filename,fileslist):
        
        for f in fileslist:
            if not os.path.exists(f):
                return None
        z = zipfile.ZipFile(filename+".zip","w")
        for f in fileslist:
            z.write(f)
        z.close()
        for f in fileslist:
            os.remove(f)
        s = os.path.getsize(filename+".zip")
        if s > 1048576:
            size = str(s >> 20)+" MB"
        else:
            size = str(s >> 10)+" KB"
        return (filename+".zip",size)

    def upload(self):<commit_msg>Web: Add freecad version in iv files exported by the sketchfab exporter<commit_after>#***************************************************************************
#*                                                                         *
#*   Copyright (c) 2017 - <NAME> <<EMAIL>>            *
#*                                                                         *
#*   This program is free software; you can redistribute it and/or modify  *
#*   it under the terms of the GNU Lesser General Public License (LGPL)    *
#*   as published by the Free Software Foundation; either version 2 of     *
#*   the License, or (at your option) any later version.                   *
#*   for detail see the LICENCE text file.                                 *
#*                                                                         *
#*   This program is distributed in the hope that it will be useful,       *
#*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
#*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
#*   GNU Library General Public License for more details.                  *
#*                                                                         *
#*   You should have received a copy of the GNU Library General Public     *
#*   License along with this program; if not, write to the Free Software   *
#*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
#*   USA                                                                   *
#*                                                                         *
#***************************************************************************

from __future__ import print_function

__title__ = "Sketchfab uploader"
__author__ = "<NAME>"
__url__ = "http://www.freecadweb.org"

import FreeCAD, FreeCADGui, WebGui, os, zipfile, requests, tempfile, json, time, re
from PySide import QtCore, QtGui

# \cond
try:
    def translate(context, text, disambig=None):
        return QtGui.QApplication.translate(context, text, disambig, QtGui.QApplication.UnicodeUTF8)
except AttributeError:
    def translate(context, text, disambig=None):
        return QtGui.QApplication.translate(context, text, disambig)
# \endcond

SKETCHFAB_UPLOAD_URL = "https://api.sketchfab.com/v3/models"
SKETCHFAB_TOKEN_URL = "https://sketchfab.com/settings/password"
SKETCHFAB_MODEL_URL = "https://sketchfab.com/show/"


class SketchfabTaskPanel:
    
    '''The TaskPanel for Sketchfab upload'''
    
    def __init__(self):
        
        self.url = None
        self.form = FreeCADGui.PySideUic.loadUi(":/ui/TaskDlgSketchfab.ui")
        self.form.ProgressBar.hide()
        self.form.Button_View.hide()
        QtCore.QObject.connect(self.form.Button_Token,QtCore.SIGNAL("pressed()"),self.getToken)
        QtCore.QObject.connect(self.form.Button_Upload,QtCore.SIGNAL("pressed()"),self.upload)
        QtCore.QObject.connect(self.form.Button_View,QtCore.SIGNAL("pressed()"),self.viewModel)
        self.form.Text_Name.setText(FreeCAD.ActiveDocument.Label)
        self.form.Text_Token.setText(FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Web").GetString("SketchfabToken",""))

    def isAllowedAlterSelection(self):
        
        return True

    def isAllowedAlterView(self):
        
        return True

    def getStandardButtons(self):
        
        return int(QtGui.QDialogButtonBox.Close)

    def accept(self):
        
        FreeCADGui.ActiveDocument.resetEdit()
        return True

    def getToken(self):
        
        QtGui.QDesktopServices.openUrl(SKETCHFAB_TOKEN_URL)
        
    def get_request_payload(self, token, data={}, files={}, json_payload=False):
        
        """Helper method that returns the authentication token and proper content
        type depending on whether or not we use JSON payload."""
        headers = {'Authorization': 'Token {}'.format(token)}
        if json_payload:
            headers.update({'Content-Type': 'application/json'})
            data = json.dumps(data)
        return {'data': data, 'files': files, 'headers': headers}
        
    def saveFile(self):
        
        import FreeCADGui
        if self.form.Radio_Selection.isChecked():
            objects = FreeCADGui.Selection.getSelection()
        else:
            objects = [obj for obj in FreeCAD.ActiveDocument.Objects if obj.ViewObject.isVisible()]
        if not objects:
            QtGui.QMessageBox.critical(None,translate("Web","Nothing to upload"),translate("The selection of the document contains no object to upload"))
            return None
        filename = os.path.join(tempfile._get_default_tempdir(),next(tempfile._get_candidate_names()))
        filetype = self.form.Combo_Filetype.currentIndex()
        # 0 = obj + mtl, 1 = obj, 2 = dae, 3 = stl, 4 = IGES, 5 = iv (currently not working)
        if filetype == 0: # OBJ + MTL
            import importOBJ
            importOBJ.export(objects,filename+".obj")
            return self.packFiles(filename,[filename+".obj",filename+".mtl"])
        elif filetype == 1: # OBJ (mesh exporter)
            import Mesh
            Mesh.export(objects,filename+".obj")
            return self.packFiles(filename,[filename+".obj"])
        elif filetype == 2: # DAE
            import importDAE
            importDAE.export(objects,filename+".dae")
            return self.packFiles(filename,[filename+".dae"])
        elif filetype == 3: # STL
            import Mesh
            Mesh.export(objects,filename+".stl")
            return self.packFiles(filename,[filename+".stl"])
        elif filetype == 4: # IGES
            import Part
            Part.export(objects,filename+".iges")
            return self.packFiles(filename,[filename+".iges"])
        elif filetype == 5: # IV
            import FreeCADGui
            FreeCADGui.export(objects,filename+".iv")
            # removing FreeCAD-specific nodes
            f = open(filename+".iv","rb")
            s = f.read()
            f.close()
            ver = FreeCAD.Version()
            vinfo = "# Exported by FreeCAD v" + ver[0] + "." + ver[1] + " build" + ver[2] + "\n"
            vinfo += "# http://www.freecadweb.org\n"
            s = s.replace("#Inventor V2.1 ascii","#Inventor V2.1 ascii\n"+vinfo)
            s = s.replace("SoBrepEdgeSet","SoIndexedLineSet")
            s = s.replace("SoBrepFaceSet","SoIndexedFaceSet")
            s = s.replace("\n","--endl--")
            s = re.sub("highlightIndex .*?\]"," ",s)
            s = re.sub("partIndex .*?\]"," ",s)
            s = s.replace("--endl--","\n")
            f = open(filename+".iv","wb")
            f.write(s)
            f.close()
            return self.packFiles(filename,[filename+".iv"])

    def packFiles(self,filename,fileslist):
        
        for f in fileslist:
            if not os.path.exists(f):
                return None
        z = zipfile.ZipFile(filename+".zip","w")
        for f in fileslist:
            z.write(f)
        z.close()
        for f in fileslist:
            os.remove(f)
        s = os.path.getsize(filename+".zip")
        if s > 1048576:
            size = str(s >> 20)+" MB"
        else:
            size = str(s >> 10)+" KB"
        return (filename+".zip",size)

    def upload(self):
{'fraction_non_alphanumeric': 0.1346950235137222, 'fraction_numerical': 0.0066680704709763455, 'mean_word_length': 1.9857502095557418, 'pattern_counts': {'":': 2, '<': 11, '<?xml version=': 0, '>': 21, 'https://': 6, 'lorem ipsum': 0, 'www.': 3, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 36, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1669557', 'n_tokens_mistral': 4014, 'n_tokens_neox': 3854, 'n_words': 926}