denisenkom / pytwain

TWAIN library using ctypes bindings
Other
46 stars 23 forks source link

GET ERROR #40

Open Dhruv00710 opened 11 months ago

Dhruv00710 commented 11 months ago

res. sir below is my code and also show "SELECT SOURCE" but when i press scan button its get error like

INFO:twain:user selected source with id 21102
INFO:twain:opening data source with id 21102
INFO:twain:closing data source with id 21102
INFO:__main__:Creating source manager
INFO:twain:attempting to load dll: C:\Windows\twain_32.dll
INFO:twain:DSM initialized
INFO:__main__:Opening source
INFO:twain:opening data source with id 0
INFO:__main__:Request acquire
**ERROR:__main__:Error: File transfer is not supported**
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QTextEdit, QVBoxLayout, QWidget, QLabel
from PyQt5.QtCore import Qt
import sys
import os
import logging
import twain
import connection
class Ui_Form(QMainWindow):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 300)
        self.checkBox = QtWidgets.QCheckBox(Form)
        self.checkBox.setGeometry(QtCore.QRect(130, 50, 141, 17))
        self.checkBox.setObjectName("checkBox")
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(140, 90, 100, 23))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(Form)
        self.pushButton_2.setGeometry(QtCore.QRect(149, 130, 75, 23))
        self.pushButton_2.setObjectName("pushButton_2")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.checkBox.setText(_translate("Form", "Select Advance Scanner"))
        self.pushButton.setText(_translate("Form", "Select Scanner"))
        self.pushButton_2.setText(_translate("Form", "Scan"))
        self.logger = logging.getLogger(__name__)
        logging.basicConfig(level=logging.INFO)
        self.pushButton_2.clicked.connect(self.scan)
        self.pushButton.clicked.connect(self.selectscanner)
        self.loadscanner()
    def loadscanner(self):
        global scanner
        cursor = connection.con.cursor()
        query = "SELECT scanner_name FROM scanner ORDER BY id ASC"
        cursor.execute(query)
        fetch_load_scanner = cursor.fetchone()
        scanner=''.join(fetch_load_scanner)
    def selectscanner(self):
        parent_window_handle = int(self.winId())
        global ss
        global sm
        sm=twain.SourceManager(parent_window=parent_window_handle)
        ss=sm.open_source()
        if ss:
            scanner_name=ss.GetSourceName()
            mycursor=connection.con.cursor()
            query="UPDATE scanner SET scanner_name = %s WHERE id=1"
            value=(scanner_name,)
            mycursor.execute(query, value)
            connection.con.commit()
            self.loadscanner()
        sm.close()
    def scan(self):
        parent_window_handle = int(self.winId())
        self.logger.info('Creating source manager')
        try:
            def counter():
                for i in range(1000):
                    yield i+1
            count = counter()
            before = lambda file: 'd:/omr/output/multi%s.jpg' % (next(count))
            sm = twain.SourceManager(parent_window=parent_window_handle)
            self.logger.info('Opening source')
            ss = sm.open_source(scanner)
            if not ss:
                self.logger.error('Failed to open a scanner source')
                return None
            self.logger.info('Request acquire')
            if self.checkBox.isChecked():
                ss.acquire_file(before=before,
                                after=lambda file: print(file),
                                show_ui=True,
                                modal=True
                                )
                ss.close()
            else:
                ss.acquire_file(before=before,
                                after=lambda file: print(file),
                                show_ui=False,
                                modal=False
                                )
                ss.close()
        except Exception as e:
            self.logger.error(f'Error: {str(e)}')
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())
![Untitled](https://github.com/denisenkom/pytwain/assets/71647436/9c3a7f77-6910-4a25-8ec9-6fdea6429c1e)
denisenkom commented 11 months ago

This error means that source does not support file transfer, therefore you need to use native transfer instead via acquire_natively function.

Dhruv00710 commented 11 months ago

sir i write this function and i scan more then one document def scan(self):
parent_window_handle = int(self.winId()) self.logger.info('Creating source manager') try: def counter(): for i in range(1000): yield i

        count = counter()

        # before = lambda file: 'd:/%s.jpg' % (next(count))
        after = lambda file: 'd:/%s.jpg' % (next(count))
        sm = twain.SourceManager(parent_window=parent_window_handle)

        first_available = None

        # with twain.SourceManager(parent_window=parent_window_handle) as sm:
        self.logger.info('Opening source')
        ss = sm.open_source(scanner)
        if not ss:
            self.logger.error('Failed to open a scanner source')
            return None
        self.logger.info('Request acquire')
        ss.acquire_natively(before=lambda file: print(file),
                            after=after,
                            show_ui=True,
                            modal=True,
                            )

except Exception as e: self.logger.error(f'Error: {str(e)}') but i got error like Exception ignored in: <function _Image.del at 0x0362A848> Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python311-32\Lib\site-packages\twain__init.py", line 112, in del self.close() File "C:\Users\DELL\AppData\Local\Programs\Python\Python311-32\Lib\site-packages\twain\init__.py", line 116, in close self._free(self._handle) ^^^^^^^^^^ AttributeError: '_Image' object has no attribute '_free'

sir in above code if any changes then please tell me.

denisenkom commented 11 months ago

That is a bug in pytwain. You can try fixing it. First you need to add close, lock, unlock parameters to _Image class constructor and save them in _close, _lock, _unlock attributes https://github.com/denisenkom/pytwain/blob/4ce4712a3af35e056370bb97ce6cd1763dde18b2/src/twain/__init__.py#L128. Then change code that creates _Image instance here https://github.com/denisenkom/pytwain/blob/4ce4712a3af35e056370bb97ce6cd1763dde18b2/src/twain/__init__.py#L907 to pass values of respective _close, _lock, _unlock attributes of the Source class to _Image constructor. That should fix the error that you are getting. If that works please open a pull request.

Dhruv00710 commented 10 months ago

sir i tried as you say above. but i not success. if you try and success then please tell me.

denisenkom commented 10 months ago

I made a fix https://github.com/denisenkom/pytwain/commit/6eb7c5861c10159d6424d53f1ff2be4159d2ca5e, it should fix the below error:

AttributeError: '_Image' object has no attribute '_free'

Try it.

Dhruv00710 commented 10 months ago

i upgrade pytwain version 2.2.2 and my code is below

def scans(self): parent_window_handle = int(self.winId()) self.logger.info('Creating source manager') try: def counter(): for i in range(1000): yield i+1 count = counter() before = lambda file: 'd:/omr/output/multi%s.jpg' % (next(count)) sm = twain.SourceManager(parent_window=parent_window_handle) self.logger.info('Opening source') ss = sm.open_source(scanner) if not ss: self.logger.error('Failed to open a scanner source') return None self.logger.info('Request acquire') result = ss.acquire_natively(before=before, after=lambda file: print(file), show_ui=True, modal=True ) ss.close()

    except Exception as e:
        self.logger.error(f'Error: {str(e)}')

using above code i got also error Exception ignored in: <function _Image.del at 0x03C5AA28> Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python311-32\Lib\site-packages\twain__init.py", line 114, in del self.close() File "C:\Users\DELL\AppData\Local\Programs\Python\Python311-32\Lib\site-packages\twain\init.py", line 118, in close self._free(self._handle) ^^^^^^^^^^ AttributeError: '_Image' object has no attribute '_free' ERROR:main__:Error: name 'CancelAll' is not defined