1635844603
जानें कि पाइथन में प्री-ट्रेन्ड DialoGPT मॉडल के साथ संवादी प्रतिक्रियाएं उत्पन्न करने के लिए हगिंगफेस ट्रांसफॉर्मर लाइब्रेरी का उपयोग कैसे करें।
हाल के वर्षों में चैटबॉट्स ने बहुत लोकप्रियता हासिल की है, और जैसे-जैसे व्यवसाय के लिए चैटबॉट्स का उपयोग करने में रुचि बढ़ती है, शोधकर्ताओं ने संवादी एआई चैटबॉट्स को आगे बढ़ाने पर भी बहुत अच्छा काम किया है।
इस ट्यूटोरियल में, हम संवादी प्रतिक्रिया पीढ़ी के लिए पूर्व-प्रशिक्षित DialoGPT मॉडल को नियोजित करने के लिए हगिंगफेस ट्रांसफॉर्मर लाइब्रेरी का उपयोग करेंगे ।
DialoGPT एक बड़े पैमाने पर ट्यून करने योग्य तंत्रिका संवादी प्रतिक्रिया पीढ़ी मॉडल है जिसे रेडिट से निकाले गए 147M वार्तालापों पर प्रशिक्षित किया गया था, और अच्छी बात यह है कि आप स्क्रैच से प्रशिक्षण की तुलना में बेहतर प्रदर्शन प्राप्त करने के लिए इसे अपने डेटासेट के साथ ठीक कर सकते हैं।
आरंभ करने के लिए, आइए ट्रांसफॉर्मर स्थापित करें :
$ pip3 install transformers
एक नई पायथन फ़ाइल या नोटबुक खोलें और निम्न कार्य करें:
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
# model_name = "microsoft/DialoGPT-large"
model_name = "microsoft/DialoGPT-medium"
# model_name = "microsoft/DialoGPT-small"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
DialoGPT के तीन संस्करण हैं; छोटा, मध्यम और बड़ा। बेशक, जितना बड़ा बेहतर होगा, लेकिन अगर आप इसे अपनी मशीन पर चला रहे हैं, तो मुझे लगता है कि छोटा या मध्यम आपकी याददाश्त को बिना किसी समस्या के फिट करता है। बड़े वाले को आज़माने के लिए आप Google Colab का भी उपयोग कर सकते हैं।
इस खंड में, हम प्रतिक्रिया उत्पन्न करने के लिए लालची खोज एल्गोरिथ्म का उपयोग करेंगे । यही है, हम चैटबॉट प्रतिक्रिया का चयन करते हैं जिसमें प्रत्येक समय चरण पर चुने जाने की सबसे अधिक संभावना होती है।
आइए लालची खोज का उपयोग करके हमारे AI के साथ चैट करने के लिए कोड बनाएं:
# chatting 5 times with greedy search
for step in range(5):
# take user input
text = input(">> You:")
# encode the input and add end of string token
input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
# concatenate new user input with chat history (if there is)
bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
# generate a bot response
chat_history_ids = model.generate(
bot_input_ids,
max_length=1000,
pad_token_id=tokenizer.eos_token_id,
)
#print the output
output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
print(f"DialoGPT: {output}")
आइए इस कोड के मूल की व्याख्या करें:
input_ids
DialoGPT टोकननाइज़र का उपयोग करने के लिए टेक्स्ट को एन्कोड करते हैं , हम स्ट्रिंग टोकन के अंत को भी जोड़ते हैं और इसे पाइटोरच टेंसर के रूप में वापस करते हैं।input_ids
एक पीढ़ी के लिए सीधे अपने मॉडल को फीड करते हैं। अन्यथा, हम torch.cat()
मेथड की मदद से कॉन्सटेनेशन का उपयोग करके चैट हिस्ट्री को जोड़ देते हैं ।model.generate()
चैटबॉट प्रतिक्रिया उत्पन्न करने के लिए विधि का उपयोग करते हैं ।tokenizer.decode()
और यह सुनिश्चित skip_special_tokens
करने के True
लिए सेट करते हैं कि हमें कोई कष्टप्रद विशेष टोकन जैसे कि <|endoftext|>
. साथ ही, चूंकि मॉडल पूरे अनुक्रम को लौटाता है, हम पिछले चैट इतिहास को छोड़ देते हैं और केवल नए जेनरेट किए गए चैटबॉट उत्तर को प्रिंट करते हैं।नीचे बॉट के साथ एक नमूना चर्चा है:
>> You:How can you be rich so quickly?
DialoGPT: I'm not rich, I'm just a rich man.
>> You:Ok, you don't make sense, how old are you ?
DialoGPT: I'm not a rich man, I'm just a rich man.
>> You:How can you be happy ?
DialoGPT: I'm not happy, I'm just a rich man.
>> You:But they say money buys happiness!
DialoGPT: Money buys happiness, but not happiness itself.
>> You:You don't make sense again!
DialoGPT: I'm not happy, I'm just a rich man.
आप देखते हैं कि मॉडल बहुत सारी प्रतिक्रियाओं को दोहराता है, क्योंकि ये सबसे अधिक संभावना है और यह हर बार इसे चुन रहा है।
डिफ़ॉल्ट रूप से, model.generate()
लालची खोज एल्गोरिथ्म का उपयोग करता है जब कोई अन्य पैरामीटर सेट नहीं किया जाता है, अगले अनुभागों में, हम इस पद्धति में कुछ तर्क जोड़ेंगे कि क्या हम पीढ़ी में सुधार कर सकते हैं।
बीम खोज हमें num_beams
हर समय कदम पर परिकल्पना की सबसे अधिक संभावना रखते हुए उच्च संभावना अनुक्रमों के लापता होने के जोखिम को कम करने की अनुमति देता है और फिर उन अनुक्रमों को लेकर जिनकी समग्र उच्चतम संभावना है, नीचे दिए गए कोड बीम खोज के साथ चैटबॉट प्रतिक्रियाएं उत्पन्न करेंगे:
# chatting 5 times with beam search
for step in range(5):
# take user input
text = input(">> You:")
# encode the input and add end of string token
input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
# concatenate new user input with chat history (if there is)
bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
# generate a bot response
chat_history_ids = model.generate(
bot_input_ids,
max_length=1000,
num_beams=3,
early_stopping=True,
pad_token_id=tokenizer.eos_token_id
)
#print the output
output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
print(f"DialoGPT: {output}")
सेट करते समय num_beams
के लिए 3
में model.generate()
विधि है, तो हम हर बार कदम पर 3 शब्दों का चयन और अनुक्रम के उच्चतम समग्र संभावना खोजने के लिए उन्हें विकसित करने के लिए जा रहे हैं, की स्थापना num_beams
1 के लिए लालची खोज के समान है।
नीचे बीम खोज का उपयोग करके चैटबॉट के साथ एक नमूना चर्चा है:
>> You:How can I be rich?
DialoGPT: You can't.
>> You:Why not?
DialoGPT: Because you can't.
>> You:Then how am I supposed to live well?
DialoGPT: You can't.
>> You:So basically, you want me to be a poor guy?
DialoGPT: No, I want you to be a rich guy.
>> You:Ok how to be rich, then?
DialoGPT: I don't know.
पिछले अनुभागों में, हमने उच्चतम संभाव्यता अनुक्रम उत्पन्न करने के लिए बीम और लालची खोज का उपयोग किया था। अब यह मशीनी अनुवाद या टेक्स्ट सारांश जैसे कार्यों के लिए बहुत अच्छा है जहां आउटपुट अनुमानित है। हालाँकि, चैटबॉट्स की तरह ओपन-एंडेड पीढ़ी के लिए यह सबसे अच्छा विकल्प नहीं है।
एक बेहतर पीढ़ी के लिए, हमें कुछ यादृच्छिकता पेश करने की आवश्यकता है जहां हम संभावनाओं के आधार पर उम्मीदवार अनुक्रमों की एक विस्तृत श्रृंखला से नमूना लेते हैं:
# chatting 5 times with sampling
for step in range(5):
# take user input
text = input(">> You:")
# encode the input and add end of string token
input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
# concatenate new user input with chat history (if there is)
bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
# generate a bot response
chat_history_ids = model.generate(
bot_input_ids,
max_length=1000,
do_sample=True,
top_k=0,
pad_token_id=tokenizer.eos_token_id
)
#print the output
output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
print(f"DialoGPT: {output}")
इस बार, हमने नमूनाकरण के लिए सेट do_sample
किया True
है, और हम यह इंगित करने के top_k
लिए सेट हैं 0
कि हम सभी संभावित संभावनाओं का चयन कर रहे हैं, हम बाद में top_k
पैरामीटर पर चर्चा करेंगे ।
यहाँ इन मापदंडों के साथ बातचीत है:
>> You:Hello, how can I be rich?
DialoGPT: You can't
>> You:Really? then how others get rich?
DialoGPT: They work as money artists
>> You:How to be a money artist?
DialoGPT: I don't know, I don't have enough knowledge on artists
>> You:Alright, thank you!
DialoGPT: No problem, if you need tips pm me.
>> You:Great, you're my savior!
DialoGPT: Thank you for helping a stranger out like me!
स्पष्ट रूप से कुछ सुधार हैं। हालांकि, कम संभावनाओं वाले अनुक्रमों की एक विस्तृत सूची पर नमूना लेने से यादृच्छिक पीढ़ी हो सकती है (जैसा कि आप अंतिम वाक्य में देखते हैं)।
इसे और बेहतर बनाने के लिए, हम यह कर सकते हैं:
temperature
, जिससे हमें कम संभावना वाले शब्दों को चुनने की संभावना कम करने में मदद मिलती है और उच्च संभावना वाले शब्दों को चुनने की संभावना बढ़ जाती है।# chatting 5 times with Top K sampling & tweaking temperature
for step in range(5):
# take user input
text = input(">> You:")
# encode the input and add end of string token
input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
# concatenate new user input with chat history (if there is)
bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
# generate a bot response
chat_history_ids = model.generate(
bot_input_ids,
max_length=1000,
do_sample=True,
top_k=100,
temperature=0.75,
pad_token_id=tokenizer.eos_token_id
)
#print the output
output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
print(f"DialoGPT: {output}")
अब, हम संभाव्यता द्वारा अवरोही क्रम में शीर्ष शब्दों से नमूना लेने के लिए सेट top_k
करते हैं । हम उच्च संभावना वाले शब्दों को चुनने का एक उच्च मौका देने के लिए (डिफ़ॉल्ट है ) पर भी सेट करते हैं , तापमान को लालची खोज के समान ही सेट करते हैं, इसे अनंत पर सेट करना पूरी तरह से यादृच्छिक के समान है।100100temperature0.751.00.0
यहाँ इन मापदंडों के साथ एक चर्चा है:
>> You:How can I get rich?
DialoGPT: I'd also like to know this.
>> You:So you don't know it?
DialoGPT: I know it, but it doesn't matter.
>> You:Really? money matters, man!
DialoGPT: Well, money is money and I gotta get my money.
>> You:Yeah how to get them?
DialoGPT: Well, that's a question. I'd like to know more, just for curiosity's sake, to know what other people have said about how I should get rich.
>> You:Some robots like you told me you have to buy gold, silver or stocks.
DialoGPT: I think my wallet is empty.
जैसा कि आप देख सकते हैं, यह अब बहुत बेहतर है, बेझिझक ट्विक करें temperature
और top_k
पैरामीटर देखें और देखें कि क्या यह इसमें सुधार कर सकता है।
न्यूक्लियस सैंपलिंग या टॉप-पी सैंपलिंग उन सबसे छोटे संभव शब्दों में से चुनता है जिनकी संचयी संभावना p
हमारे द्वारा निर्धारित पैरामीटर से अधिक होती है ।
टॉप-पी सैंपलिंग का उपयोग करते हुए एक उदाहरण नीचे दिया गया है:
# chatting 5 times with nucleus sampling & tweaking temperature
for step in range(5):
# take user input
text = input(">> You:")
# encode the input and add end of string token
input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
# concatenate new user input with chat history (if there is)
bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
# generate a bot response
chat_history_ids = model.generate(
bot_input_ids,
max_length=1000,
do_sample=True,
top_p=0.95,
top_k=0,
temperature=0.75,
pad_token_id=tokenizer.eos_token_id
)
#print the output
output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
print(f"DialoGPT: {output}")
हमने टॉप-के सैंपलिंग को अक्षम top_k
करने के 0
लिए सेट किया है, लेकिन आप दोनों विधियों का उपयोग कर सकते हैं जो बेहतर काम करती हैं। यहाँ एक चैट है:
>> You:How can I be rich fast?
DialoGPT: Inflation and free money
>> You:lol, but that takes time, I need fast money.
DialoGPT: Your post makes no sense. You just need a lot of money to be rich fast
>> You:Ok how to get a lot of money?
DialoGPT: Buy gold and then trade it for money.
>> You:Hmm, I got your point, thanks.
DialoGPT: No problem. You have to have money to buy gold, but its only good for trading it.
>> You:Yeah, I understand, thank you so much.
DialoGPT: Ok, let me know if you need help
अब चैटबॉट कई मामलों में स्पष्ट रूप से समझ में आता है।
अब एक से अधिक चैटबॉट प्रतिक्रिया उत्पन्न करने के लिए कुछ कोड जोड़ते हैं, और फिर हम चुनते हैं कि अगले इनपुट में किस प्रतिक्रिया को शामिल करना है:
# chatting 5 times with nucleus & top-k sampling & tweaking temperature & multiple
# sentences
for step in range(5):
# take user input
text = input(">> You:")
# encode the input and add end of string token
input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
# concatenate new user input with chat history (if there is)
bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
# generate a bot response
chat_history_ids_list = model.generate(
bot_input_ids,
max_length=1000,
do_sample=True,
top_p=0.95,
top_k=50,
temperature=0.75,
num_return_sequences=5,
pad_token_id=tokenizer.eos_token_id
)
#print the outputs
for i in range(len(chat_history_ids_list)):
output = tokenizer.decode(chat_history_ids_list[i][bot_input_ids.shape[-1]:], skip_special_tokens=True)
print(f"DialoGPT {i}: {output}")
choice_index = int(input("Choose the response you want for the next input: "))
chat_history_ids = torch.unsqueeze(chat_history_ids_list[choice_index], dim=0)
मैंने एक बार में 5 वाक्यों को वापस num_return_sequences
करने के 5
लिए निर्धारित किया है, हमें एक को चुनना होगा जिसे अगले अनुक्रम में शामिल किया जाएगा। यहां बताया गया है कि यह कैसे चला गया:
>> You:Hello, friend.
DialoGPT 0: Hey there!
DialoGPT 1: I am your friend, and I am also your friend.
DialoGPT 2: Hello. :
DialoGPT 3: Hiya! How are you?
DialoGPT 4: Hello. I like your username.
Choose the response you want for the next input: 3
>> You:Fine, thanks, what about you?
DialoGPT 0: Good. Not much to do.
DialoGPT 1: Not much, you?
DialoGPT 2: Fine, thanks.
DialoGPT 3: I'm okay, thank you for asking.
DialoGPT 4: I'm fine too.
Choose the response you want for the next input: 2
>> You:Can you tell me how can I get rich quickly?
DialoGPT 0: Yes, I can!
DialoGPT 1: Yes, just look up how to get rich on Google.
DialoGPT 2: Just keep doing your thing. You'll get rich.
DialoGPT 3: No, I can't.
DialoGPT 4: no, i have no money
Choose the response you want for the next input: 1
>> You:Yeah, but I thought you have an answer...
DialoGPT 0: I'm getting married in the morning.
DialoGPT 1: How do you get rich?
DialoGPT 2: I think there are many good answers, but I could send you one, if you want.
DialoGPT 3: I will, thanks!
DialoGPT 4: I thought you have an answer.
Choose the response you want for the next input: 2
>> You:Yes, please send me.
DialoGPT 0: You can send me link.
DialoGPT 1: I am very interested
DialoGPT 2: I sent you a PM
DialoGPT 3: I'll send you a PM
DialoGPT 4: I am always interested in new ideas.
Choose the response you want for the next input: 2
और आप वहां जाएं, मुझे आशा है कि इस ट्यूटोरियल ने आपको DialoGPT और इसी तरह के मॉडल पर टेक्स्ट जेनरेट करने में मदद की। टेक्स्ट जेनरेट करने के तरीके के बारे में अधिक जानकारी के लिए, मैं आपको ट्रांसफॉर्मर्स गाइड के साथ टेक्स्ट जेनरेट करने का तरीका पढ़ने की अत्यधिक सलाह देता हूं ।
यह देखने के लिए कि क्या आप बॉट को बेहतर प्रदर्शन कर सकते हैं, मैं आपको मापदंडों को बदलना छोड़ दूँगा।
साथ ही, आप इसे टेक्स्ट-टू-स्पीच और स्पीच-टू-टेक्स्ट ट्यूटोरियल्स के साथ जोड़कर एक वर्चुअल असिस्टेंट जैसे एलेक्सा , सिरी , कोरटाना आदि बना सकते हैं।
#python #chatbot #ai
1635844603
जानें कि पाइथन में प्री-ट्रेन्ड DialoGPT मॉडल के साथ संवादी प्रतिक्रियाएं उत्पन्न करने के लिए हगिंगफेस ट्रांसफॉर्मर लाइब्रेरी का उपयोग कैसे करें।
हाल के वर्षों में चैटबॉट्स ने बहुत लोकप्रियता हासिल की है, और जैसे-जैसे व्यवसाय के लिए चैटबॉट्स का उपयोग करने में रुचि बढ़ती है, शोधकर्ताओं ने संवादी एआई चैटबॉट्स को आगे बढ़ाने पर भी बहुत अच्छा काम किया है।
इस ट्यूटोरियल में, हम संवादी प्रतिक्रिया पीढ़ी के लिए पूर्व-प्रशिक्षित DialoGPT मॉडल को नियोजित करने के लिए हगिंगफेस ट्रांसफॉर्मर लाइब्रेरी का उपयोग करेंगे ।
DialoGPT एक बड़े पैमाने पर ट्यून करने योग्य तंत्रिका संवादी प्रतिक्रिया पीढ़ी मॉडल है जिसे रेडिट से निकाले गए 147M वार्तालापों पर प्रशिक्षित किया गया था, और अच्छी बात यह है कि आप स्क्रैच से प्रशिक्षण की तुलना में बेहतर प्रदर्शन प्राप्त करने के लिए इसे अपने डेटासेट के साथ ठीक कर सकते हैं।
आरंभ करने के लिए, आइए ट्रांसफॉर्मर स्थापित करें :
$ pip3 install transformers
एक नई पायथन फ़ाइल या नोटबुक खोलें और निम्न कार्य करें:
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
# model_name = "microsoft/DialoGPT-large"
model_name = "microsoft/DialoGPT-medium"
# model_name = "microsoft/DialoGPT-small"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
DialoGPT के तीन संस्करण हैं; छोटा, मध्यम और बड़ा। बेशक, जितना बड़ा बेहतर होगा, लेकिन अगर आप इसे अपनी मशीन पर चला रहे हैं, तो मुझे लगता है कि छोटा या मध्यम आपकी याददाश्त को बिना किसी समस्या के फिट करता है। बड़े वाले को आज़माने के लिए आप Google Colab का भी उपयोग कर सकते हैं।
इस खंड में, हम प्रतिक्रिया उत्पन्न करने के लिए लालची खोज एल्गोरिथ्म का उपयोग करेंगे । यही है, हम चैटबॉट प्रतिक्रिया का चयन करते हैं जिसमें प्रत्येक समय चरण पर चुने जाने की सबसे अधिक संभावना होती है।
आइए लालची खोज का उपयोग करके हमारे AI के साथ चैट करने के लिए कोड बनाएं:
# chatting 5 times with greedy search
for step in range(5):
# take user input
text = input(">> You:")
# encode the input and add end of string token
input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
# concatenate new user input with chat history (if there is)
bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
# generate a bot response
chat_history_ids = model.generate(
bot_input_ids,
max_length=1000,
pad_token_id=tokenizer.eos_token_id,
)
#print the output
output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
print(f"DialoGPT: {output}")
आइए इस कोड के मूल की व्याख्या करें:
input_ids
DialoGPT टोकननाइज़र का उपयोग करने के लिए टेक्स्ट को एन्कोड करते हैं , हम स्ट्रिंग टोकन के अंत को भी जोड़ते हैं और इसे पाइटोरच टेंसर के रूप में वापस करते हैं।input_ids
एक पीढ़ी के लिए सीधे अपने मॉडल को फीड करते हैं। अन्यथा, हम torch.cat()
मेथड की मदद से कॉन्सटेनेशन का उपयोग करके चैट हिस्ट्री को जोड़ देते हैं ।model.generate()
चैटबॉट प्रतिक्रिया उत्पन्न करने के लिए विधि का उपयोग करते हैं ।tokenizer.decode()
और यह सुनिश्चित skip_special_tokens
करने के True
लिए सेट करते हैं कि हमें कोई कष्टप्रद विशेष टोकन जैसे कि <|endoftext|>
. साथ ही, चूंकि मॉडल पूरे अनुक्रम को लौटाता है, हम पिछले चैट इतिहास को छोड़ देते हैं और केवल नए जेनरेट किए गए चैटबॉट उत्तर को प्रिंट करते हैं।नीचे बॉट के साथ एक नमूना चर्चा है:
>> You:How can you be rich so quickly?
DialoGPT: I'm not rich, I'm just a rich man.
>> You:Ok, you don't make sense, how old are you ?
DialoGPT: I'm not a rich man, I'm just a rich man.
>> You:How can you be happy ?
DialoGPT: I'm not happy, I'm just a rich man.
>> You:But they say money buys happiness!
DialoGPT: Money buys happiness, but not happiness itself.
>> You:You don't make sense again!
DialoGPT: I'm not happy, I'm just a rich man.
आप देखते हैं कि मॉडल बहुत सारी प्रतिक्रियाओं को दोहराता है, क्योंकि ये सबसे अधिक संभावना है और यह हर बार इसे चुन रहा है।
डिफ़ॉल्ट रूप से, model.generate()
लालची खोज एल्गोरिथ्म का उपयोग करता है जब कोई अन्य पैरामीटर सेट नहीं किया जाता है, अगले अनुभागों में, हम इस पद्धति में कुछ तर्क जोड़ेंगे कि क्या हम पीढ़ी में सुधार कर सकते हैं।
बीम खोज हमें num_beams
हर समय कदम पर परिकल्पना की सबसे अधिक संभावना रखते हुए उच्च संभावना अनुक्रमों के लापता होने के जोखिम को कम करने की अनुमति देता है और फिर उन अनुक्रमों को लेकर जिनकी समग्र उच्चतम संभावना है, नीचे दिए गए कोड बीम खोज के साथ चैटबॉट प्रतिक्रियाएं उत्पन्न करेंगे:
# chatting 5 times with beam search
for step in range(5):
# take user input
text = input(">> You:")
# encode the input and add end of string token
input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
# concatenate new user input with chat history (if there is)
bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
# generate a bot response
chat_history_ids = model.generate(
bot_input_ids,
max_length=1000,
num_beams=3,
early_stopping=True,
pad_token_id=tokenizer.eos_token_id
)
#print the output
output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
print(f"DialoGPT: {output}")
सेट करते समय num_beams
के लिए 3
में model.generate()
विधि है, तो हम हर बार कदम पर 3 शब्दों का चयन और अनुक्रम के उच्चतम समग्र संभावना खोजने के लिए उन्हें विकसित करने के लिए जा रहे हैं, की स्थापना num_beams
1 के लिए लालची खोज के समान है।
नीचे बीम खोज का उपयोग करके चैटबॉट के साथ एक नमूना चर्चा है:
>> You:How can I be rich?
DialoGPT: You can't.
>> You:Why not?
DialoGPT: Because you can't.
>> You:Then how am I supposed to live well?
DialoGPT: You can't.
>> You:So basically, you want me to be a poor guy?
DialoGPT: No, I want you to be a rich guy.
>> You:Ok how to be rich, then?
DialoGPT: I don't know.
पिछले अनुभागों में, हमने उच्चतम संभाव्यता अनुक्रम उत्पन्न करने के लिए बीम और लालची खोज का उपयोग किया था। अब यह मशीनी अनुवाद या टेक्स्ट सारांश जैसे कार्यों के लिए बहुत अच्छा है जहां आउटपुट अनुमानित है। हालाँकि, चैटबॉट्स की तरह ओपन-एंडेड पीढ़ी के लिए यह सबसे अच्छा विकल्प नहीं है।
एक बेहतर पीढ़ी के लिए, हमें कुछ यादृच्छिकता पेश करने की आवश्यकता है जहां हम संभावनाओं के आधार पर उम्मीदवार अनुक्रमों की एक विस्तृत श्रृंखला से नमूना लेते हैं:
# chatting 5 times with sampling
for step in range(5):
# take user input
text = input(">> You:")
# encode the input and add end of string token
input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
# concatenate new user input with chat history (if there is)
bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
# generate a bot response
chat_history_ids = model.generate(
bot_input_ids,
max_length=1000,
do_sample=True,
top_k=0,
pad_token_id=tokenizer.eos_token_id
)
#print the output
output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
print(f"DialoGPT: {output}")
इस बार, हमने नमूनाकरण के लिए सेट do_sample
किया True
है, और हम यह इंगित करने के top_k
लिए सेट हैं 0
कि हम सभी संभावित संभावनाओं का चयन कर रहे हैं, हम बाद में top_k
पैरामीटर पर चर्चा करेंगे ।
यहाँ इन मापदंडों के साथ बातचीत है:
>> You:Hello, how can I be rich?
DialoGPT: You can't
>> You:Really? then how others get rich?
DialoGPT: They work as money artists
>> You:How to be a money artist?
DialoGPT: I don't know, I don't have enough knowledge on artists
>> You:Alright, thank you!
DialoGPT: No problem, if you need tips pm me.
>> You:Great, you're my savior!
DialoGPT: Thank you for helping a stranger out like me!
स्पष्ट रूप से कुछ सुधार हैं। हालांकि, कम संभावनाओं वाले अनुक्रमों की एक विस्तृत सूची पर नमूना लेने से यादृच्छिक पीढ़ी हो सकती है (जैसा कि आप अंतिम वाक्य में देखते हैं)।
इसे और बेहतर बनाने के लिए, हम यह कर सकते हैं:
temperature
, जिससे हमें कम संभावना वाले शब्दों को चुनने की संभावना कम करने में मदद मिलती है और उच्च संभावना वाले शब्दों को चुनने की संभावना बढ़ जाती है।# chatting 5 times with Top K sampling & tweaking temperature
for step in range(5):
# take user input
text = input(">> You:")
# encode the input and add end of string token
input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
# concatenate new user input with chat history (if there is)
bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
# generate a bot response
chat_history_ids = model.generate(
bot_input_ids,
max_length=1000,
do_sample=True,
top_k=100,
temperature=0.75,
pad_token_id=tokenizer.eos_token_id
)
#print the output
output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
print(f"DialoGPT: {output}")
अब, हम संभाव्यता द्वारा अवरोही क्रम में शीर्ष शब्दों से नमूना लेने के लिए सेट top_k
करते हैं । हम उच्च संभावना वाले शब्दों को चुनने का एक उच्च मौका देने के लिए (डिफ़ॉल्ट है ) पर भी सेट करते हैं , तापमान को लालची खोज के समान ही सेट करते हैं, इसे अनंत पर सेट करना पूरी तरह से यादृच्छिक के समान है।100100temperature0.751.00.0
यहाँ इन मापदंडों के साथ एक चर्चा है:
>> You:How can I get rich?
DialoGPT: I'd also like to know this.
>> You:So you don't know it?
DialoGPT: I know it, but it doesn't matter.
>> You:Really? money matters, man!
DialoGPT: Well, money is money and I gotta get my money.
>> You:Yeah how to get them?
DialoGPT: Well, that's a question. I'd like to know more, just for curiosity's sake, to know what other people have said about how I should get rich.
>> You:Some robots like you told me you have to buy gold, silver or stocks.
DialoGPT: I think my wallet is empty.
जैसा कि आप देख सकते हैं, यह अब बहुत बेहतर है, बेझिझक ट्विक करें temperature
और top_k
पैरामीटर देखें और देखें कि क्या यह इसमें सुधार कर सकता है।
न्यूक्लियस सैंपलिंग या टॉप-पी सैंपलिंग उन सबसे छोटे संभव शब्दों में से चुनता है जिनकी संचयी संभावना p
हमारे द्वारा निर्धारित पैरामीटर से अधिक होती है ।
टॉप-पी सैंपलिंग का उपयोग करते हुए एक उदाहरण नीचे दिया गया है:
# chatting 5 times with nucleus sampling & tweaking temperature
for step in range(5):
# take user input
text = input(">> You:")
# encode the input and add end of string token
input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
# concatenate new user input with chat history (if there is)
bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
# generate a bot response
chat_history_ids = model.generate(
bot_input_ids,
max_length=1000,
do_sample=True,
top_p=0.95,
top_k=0,
temperature=0.75,
pad_token_id=tokenizer.eos_token_id
)
#print the output
output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
print(f"DialoGPT: {output}")
हमने टॉप-के सैंपलिंग को अक्षम top_k
करने के 0
लिए सेट किया है, लेकिन आप दोनों विधियों का उपयोग कर सकते हैं जो बेहतर काम करती हैं। यहाँ एक चैट है:
>> You:How can I be rich fast?
DialoGPT: Inflation and free money
>> You:lol, but that takes time, I need fast money.
DialoGPT: Your post makes no sense. You just need a lot of money to be rich fast
>> You:Ok how to get a lot of money?
DialoGPT: Buy gold and then trade it for money.
>> You:Hmm, I got your point, thanks.
DialoGPT: No problem. You have to have money to buy gold, but its only good for trading it.
>> You:Yeah, I understand, thank you so much.
DialoGPT: Ok, let me know if you need help
अब चैटबॉट कई मामलों में स्पष्ट रूप से समझ में आता है।
अब एक से अधिक चैटबॉट प्रतिक्रिया उत्पन्न करने के लिए कुछ कोड जोड़ते हैं, और फिर हम चुनते हैं कि अगले इनपुट में किस प्रतिक्रिया को शामिल करना है:
# chatting 5 times with nucleus & top-k sampling & tweaking temperature & multiple
# sentences
for step in range(5):
# take user input
text = input(">> You:")
# encode the input and add end of string token
input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
# concatenate new user input with chat history (if there is)
bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
# generate a bot response
chat_history_ids_list = model.generate(
bot_input_ids,
max_length=1000,
do_sample=True,
top_p=0.95,
top_k=50,
temperature=0.75,
num_return_sequences=5,
pad_token_id=tokenizer.eos_token_id
)
#print the outputs
for i in range(len(chat_history_ids_list)):
output = tokenizer.decode(chat_history_ids_list[i][bot_input_ids.shape[-1]:], skip_special_tokens=True)
print(f"DialoGPT {i}: {output}")
choice_index = int(input("Choose the response you want for the next input: "))
chat_history_ids = torch.unsqueeze(chat_history_ids_list[choice_index], dim=0)
मैंने एक बार में 5 वाक्यों को वापस num_return_sequences
करने के 5
लिए निर्धारित किया है, हमें एक को चुनना होगा जिसे अगले अनुक्रम में शामिल किया जाएगा। यहां बताया गया है कि यह कैसे चला गया:
>> You:Hello, friend.
DialoGPT 0: Hey there!
DialoGPT 1: I am your friend, and I am also your friend.
DialoGPT 2: Hello. :
DialoGPT 3: Hiya! How are you?
DialoGPT 4: Hello. I like your username.
Choose the response you want for the next input: 3
>> You:Fine, thanks, what about you?
DialoGPT 0: Good. Not much to do.
DialoGPT 1: Not much, you?
DialoGPT 2: Fine, thanks.
DialoGPT 3: I'm okay, thank you for asking.
DialoGPT 4: I'm fine too.
Choose the response you want for the next input: 2
>> You:Can you tell me how can I get rich quickly?
DialoGPT 0: Yes, I can!
DialoGPT 1: Yes, just look up how to get rich on Google.
DialoGPT 2: Just keep doing your thing. You'll get rich.
DialoGPT 3: No, I can't.
DialoGPT 4: no, i have no money
Choose the response you want for the next input: 1
>> You:Yeah, but I thought you have an answer...
DialoGPT 0: I'm getting married in the morning.
DialoGPT 1: How do you get rich?
DialoGPT 2: I think there are many good answers, but I could send you one, if you want.
DialoGPT 3: I will, thanks!
DialoGPT 4: I thought you have an answer.
Choose the response you want for the next input: 2
>> You:Yes, please send me.
DialoGPT 0: You can send me link.
DialoGPT 1: I am very interested
DialoGPT 2: I sent you a PM
DialoGPT 3: I'll send you a PM
DialoGPT 4: I am always interested in new ideas.
Choose the response you want for the next input: 2
और आप वहां जाएं, मुझे आशा है कि इस ट्यूटोरियल ने आपको DialoGPT और इसी तरह के मॉडल पर टेक्स्ट जेनरेट करने में मदद की। टेक्स्ट जेनरेट करने के तरीके के बारे में अधिक जानकारी के लिए, मैं आपको ट्रांसफॉर्मर्स गाइड के साथ टेक्स्ट जेनरेट करने का तरीका पढ़ने की अत्यधिक सलाह देता हूं ।
यह देखने के लिए कि क्या आप बॉट को बेहतर प्रदर्शन कर सकते हैं, मैं आपको मापदंडों को बदलना छोड़ दूँगा।
साथ ही, आप इसे टेक्स्ट-टू-स्पीच और स्पीच-टू-टेक्स्ट ट्यूटोरियल्स के साथ जोड़कर एक वर्चुअल असिस्टेंट जैसे एलेक्सा , सिरी , कोरटाना आदि बना सकते हैं।
#python #chatbot #ai
1634551440
पाइथन के साथ पीडीएफ फाइलों में छवियों से टेक्स्ट निकालने के लिए टेसरैक्ट, ओपनसीवी, पीईएमयूपीडीएफ और कई अन्य पुस्तकालयों का लाभ उठाने का तरीका जानें
आजकल, मध्यम और बड़े पैमाने की कंपनियों के पास दैनिक उपयोग में भारी मात्रा में मुद्रित दस्तावेज़ हैं। इनमें चालान, रसीदें, कॉर्पोरेट दस्तावेज़, रिपोर्ट और मीडिया रिलीज़ शामिल हैं।
उन कंपनियों के लिए, ओसीआर स्कैनर का उपयोग दक्षता और सटीकता में सुधार करते हुए काफी समय बचा सकता है।
ऑप्टिकल कैरेक्टर रिकग्निशन (ओसीआर) एल्गोरिदम कंप्यूटर को मुद्रित या हस्तलिखित दस्तावेजों का स्वचालित रूप से विश्लेषण करने की अनुमति देता है और कंप्यूटर के लिए उन्हें कुशलतापूर्वक संसाधित करने के लिए संपादन योग्य प्रारूपों में टेक्स्ट डेटा तैयार करता है। OCR सिस्टम टेक्स्ट की एक द्वि-आयामी छवि को रूपांतरित करता है जिसमें मशीन-मुद्रित या हस्तलिखित पाठ हो सकता है, जो इसके छवि प्रतिनिधित्व से मशीन-पठनीय पाठ में हो सकता है।
आम तौर पर, एक ओसीआर इंजन में ऑप्टिकल कैरेक्टर रिकग्निशन की मदद से कुशल समस्या-समाधान के लिए मशीन लर्निंग एल्गोरिदम को प्रशिक्षित करने के लिए आवश्यक कई कदम शामिल होते हैं ।
निम्नलिखित चरण जो एक इंजन से दूसरे इंजन में भिन्न हो सकते हैं, स्वचालित चरित्र पहचान के लिए मोटे तौर पर आवश्यक हैं: इस ट्यूटोरियल के भीतर, मैं आपको निम्नलिखित दिखाने जा रहा हूं:
आरंभ करने के लिए, हमें निम्नलिखित पुस्तकालयों का उपयोग करने की आवश्यकता है:
Tesseract OCR : एक ओपन-सोर्स टेक्स्ट रिकग्निशन इंजन है जो Apache 2.0 लाइसेंस के तहत उपलब्ध है और इसका विकास 2006 से Google द्वारा प्रायोजित किया गया है। वर्ष 2006 में, Tesseract को सबसे सटीक ओपन-सोर्स OCR इंजनों में से एक माना जाता था। आप इसे सीधे उपयोग कर सकते हैं या छवियों से मुद्रित पाठ निकालने के लिए एपीआई का उपयोग कर सकते हैं। सबसे अच्छी बात यह है कि यह विभिन्न प्रकार की भाषाओं का समर्थन करता है।
Tesseract इंजन को स्थापित करना इस लेख के दायरे से बाहर है। हालाँकि, आपको इसे अपने ऑपरेटिंग सिस्टम पर स्थापित करने के लिए Tesseract की आधिकारिक स्थापना मार्गदर्शिका का पालन करने की आवश्यकता है।
Tesseract सेटअप को मान्य करने के लिए, कृपया निम्न कमांड चलाएँ और उत्पन्न आउटपुट की जाँच करें:
Python-tesseract : Google के Tesseract-OCR Engine के लिए एक Python आवरण है। यह टेसरैक्ट के लिए एक स्टैंड-अलोन इनवोकेशन स्क्रिप्ट के रूप में भी उपयोगी है, क्योंकि यह पिल्लो और लेप्टोनिका इमेजिंग लाइब्रेरी द्वारा समर्थित सभी छवि प्रकारों को पढ़ सकता है, जिसमें jpeg, png, gif, bmp, tiff, और अन्य शामिल हैं।
OpenCV : कंप्यूटर विज़न, मशीन लर्निंग और इमेज प्रोसेसिंग के लिए एक पायथन ओपन-सोर्स लाइब्रेरी है। ओपनसीवी विभिन्न प्रकार की प्रोग्रामिंग भाषाओं जैसे पायथन, सी ++, जावा, आदि का समर्थन करता है। यह वस्तुओं, चेहरों या यहां तक कि मानव की लिखावट की पहचान करने के लिए छवियों और वीडियो को संसाधित कर सकता है।
PyMuPDF : MuPDF एक अत्यधिक बहुमुखी, अनुकूलन योग्य PDF, XPS और eBook दुभाषिया समाधान है जिसका उपयोग PDF रेंडरर, व्यूअर या टूलकिट के रूप में अनुप्रयोगों की एक विस्तृत श्रृंखला में किया जा सकता है। PyMuPDF, MuPDF के लिए एक पायथन बाइंडिंग है। यह हल्का PDF और XPS व्यूअर है।
Numpy: एक सामान्य-उद्देश्य वाला सरणी-प्रसंस्करण पैकेज है। यह इन सरणियों के साथ काम करने के लिए एक उच्च-प्रदर्शन बहुआयामी सरणी वस्तु और उपकरण प्रदान करता है। यह पायथन के साथ वैज्ञानिक कंप्यूटिंग के लिए मौलिक पैकेज है। इसके अलावा, Numpy को जेनेरिक डेटा के एक कुशल बहु-आयामी कंटेनर के रूप में भी इस्तेमाल किया जा सकता है।
पिलो: पीआईएल (पायथन इमेज लाइब्रेरी) के ऊपर बनाया गया है। यह पायथन में इमेज प्रोसेसिंग के लिए एक आवश्यक मॉड्यूल है।
पांडा: एक खुला स्रोत, बीएसडी-लाइसेंस प्राप्त पायथन पुस्तकालय है जो पायथन प्रोग्रामिंग भाषा के लिए उच्च-प्रदर्शन, उपयोग में आसान डेटा संरचना और डेटा विश्लेषण उपकरण प्रदान करता है।
Filetype: लघु और अनुमान फ़ाइल प्रकार और MIME प्रकार के लिए निर्भरता से मुक्त अजगर पैकेज।
इस ट्यूटोरियल का उद्देश्य एक छवि या स्कैन की गई पीडीएफ फाइल के भीतर या पीडीएफ फाइलों के संग्रह वाले फ़ोल्डर में शामिल टेक्स्ट को निकालने, संशोधित करने या हाइलाइट करने के लिए एक हल्की कमांड-लाइन-आधारित उपयोगिता विकसित करना है।
आरंभ करने के लिए, आइए आवश्यकताओं को स्थापित करें:
$ pip install Filetype==1.0.7 numpy==1.19.4 opencv-python==4.4.0.46 pandas==1.1.4 Pillow==8.0.1 PyMuPDF==1.18.9 pytesseract==0.3.7
आइए आवश्यक पुस्तकालयों को आयात करके शुरू करें:
import os
import re
import argparse
import pytesseract
from pytesseract import Output
import cv2
import numpy as np
import fitz
from io import BytesIO
from PIL import Image
import pandas as pd
import filetype
# Path Of The Tesseract OCR engine
TESSERACT_PATH = "C:\Program Files\Tesseract-OCR\tesseract.exe"
# Include tesseract executable
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH
TESSERACT_PATH
वह जगह है जहाँ Tesseract निष्पादन योग्य स्थित है। जाहिर है, आपको इसे अपने मामले के लिए बदलने की जरूरत है।
def pix2np(pix):
"""
Converts a pixmap buffer into a numpy array
"""
# pix.samples = sequence of bytes of the image pixels like RGBA
#pix.h = height in pixels
#pix.w = width in pixels
# pix.n = number of components per pixel (depends on the colorspace and alpha)
im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(
pix.h, pix.w, pix.n)
try:
im = np.ascontiguousarray(im[..., [2, 1, 0]]) # RGB To BGR
except IndexError:
# Convert Gray to RGB
im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
im = np.ascontiguousarray(im[..., [2, 1, 0]]) # RGB To BGR
return im
यह फ़ंक्शन एक पिक्समैप बफर को एक NumPy सरणी में PyMuPDF लाइब्रेरी का उपयोग करके लिए गए स्क्रीनशॉट का प्रतिनिधित्व करता है ।
Tesseract सटीकता में सुधार करने के लिए, आइए OpenCV का उपयोग करके कुछ प्रीप्रोसेसिंग फ़ंक्शन को परिभाषित करें:
# Image Pre-Processing Functions to improve output accurracy
# Convert to grayscale
def grayscale(img):
return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Remove noise
def remove_noise(img):
return cv2.medianBlur(img, 5)
# Thresholding
def threshold(img):
# return cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
return cv2.threshold(img, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
# dilation
def dilate(img):
kernel = np.ones((5, 5), np.uint8)
return cv2.dilate(img, kernel, iterations=1)
# erosion
def erode(img):
kernel = np.ones((5, 5), np.uint8)
return cv2.erode(img, kernel, iterations=1)
# opening -- erosion followed by a dilation
def opening(img):
kernel = np.ones((5, 5), np.uint8)
return cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
# canny edge detection
def canny(img):
return cv2.Canny(img, 100, 200)
# skew correction
def deskew(img):
coords = np.column_stack(np.where(img > 0))
angle = cv2.minAreaRect(coords)[-1]
if angle < -45:
angle = -(90 + angle)
else:
angle = -angle
(h, w) = img.shape[:2]
center = (w//2, h//2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(
img, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
return rotated
# template matching
def match_template(img, template):
return cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
def convert_img2bin(img):
"""
Pre-processes the image and generates a binary output
"""
# Convert the image into a grayscale image
output_img = grayscale(img)
# Invert the grayscale image by flipping pixel values.
# All pixels that are grater than 0 are set to 0 and all pixels that are = to 0 are set to 255
output_img = cv2.bitwise_not(output_img)
# Converting image to binary by Thresholding in order to show a clear separation between white and blacl pixels.
output_img = threshold(output_img)
return output_img
हमने कई प्रीप्रोसेसिंग कार्यों के लिए कार्यों को परिभाषित किया है, जिसमें छवियों को ग्रेस्केल में परिवर्तित करना, पिक्सेल मानों को फ़्लिप करना, सफेद और काले पिक्सेल को अलग करना, और बहुत कुछ शामिल है।
अगला, आइए एक छवि प्रदर्शित करने के लिए एक फ़ंक्शन को परिभाषित करें:
def display_img(title, img):
"""Displays an image on screen and maintains the output until the user presses a key"""
cv2.namedWindow('img', cv2.WINDOW_NORMAL)
cv2.setWindowTitle('img', title)
cv2.resizeWindow('img', 1200, 900)
# Display Image on screen
cv2.imshow('img', img)
# Mantain output until user presses a key
cv2.waitKey(0)
# Destroy windows when user presses a key
cv2.destroyAllWindows()
display_img()
ऑन-स्क्रीन समारोह को प्रदर्शित करता है एक छवि एक विंडो में करने के लिए एक शीर्षक सेट होने title
पैरामीटर और इस विंडो उपयोगकर्ता तक खुला रखता है कुंजीपटल पर एक कुंजी प्रेस।
def generate_ss_text(ss_details):
"""Loops through the captured text of an image and arranges this text line by line.
This function depends on the image layout."""
# Arrange the captured text after scanning the page
parse_text = []
word_list = []
last_word = ''
# Loop through the captured text of the entire page
for word in ss_details['text']:
# If the word captured is not empty
if word != '':
# Add it to the line word list
word_list.append(word)
last_word = word
if (last_word != '' and word == '') or (word == ss_details['text'][-1]):
parse_text.append(word_list)
word_list = []
return parse_text
उपरोक्त फ़ंक्शन किसी छवि के कैप्चर किए गए टेक्स्ट में पुनरावृति करता है और ग्रैब्ड टेक्स्ट लाइन को लाइन से व्यवस्थित करता है। यह छवि लेआउट पर निर्भर करता है और कुछ छवि प्रारूपों के लिए ट्विकिंग की आवश्यकता हो सकती है।
अगला, आइए रेगुलर एक्सप्रेशन का उपयोग करके टेक्स्ट खोजने के लिए एक फ़ंक्शन को परिभाषित करें :
def search_for_text(ss_details, search_str):
"""Search for the search string within the image content"""
# Find all matches within one page
results = re.findall(search_str, ss_details['text'], re.IGNORECASE)
# In case multiple matches within one page
for result in results:
yield result
हम इस फ़ंक्शन का उपयोग किसी छवि की पकड़ी गई सामग्री के भीतर विशिष्ट पाठ खोजने के लिए करेंगे। यह पाए गए मैचों का जनरेटर देता है।
def save_page_content(pdfContent, page_id, page_data):
"""Appends the content of a scanned page, line by line, to a pandas DataFrame."""
if page_data:
for idx, line in enumerate(page_data, 1):
line = ' '.join(line)
pdfContent = pdfContent.append(
{'page': page_id, 'line_id': idx, 'line': line}, ignore_index=True
)
return pdfContent
save_page_content()
फ़ंक्शन pdfContent
पांडा डेटाफ़्रेम पर स्कैन करने के बाद एक छवि लाइन की पकड़ी गई सामग्री को लाइन से जोड़ता है ।
अब परिणामी डेटाफ़्रेम को CSV फ़ाइल में सहेजने के लिए एक फ़ंक्शन बनाते हैं:
def save_file_content(pdfContent, input_file):
"""Outputs the content of the pandas DataFrame to a CSV file having the same path as the input_file
but with different extension (.csv)"""
content_file = os.path.join(os.path.dirname(input_file), os.path.splitext(
os.path.basename(input_file))[0] + ".csv")
pdfContent.to_csv(content_file, sep=',', index=False)
return content_file
इसके बाद, एक फ़ंक्शन लिखते हैं जो स्कैन की गई छवि से लिए गए टेक्स्ट के कॉन्फिडेंस स्कोर की गणना करता है:
def calculate_ss_confidence(ss_details: dict):
"""Calculate the confidence score of the text grabbed from the scanned image."""
# page_num --> Page number of the detected text or item
# block_num --> Block number of the detected text or item
# par_num --> Paragraph number of the detected text or item
# line_num --> Line number of the detected text or item
# Convert the dict to dataFrame
df = pd.DataFrame.from_dict(ss_details)
# Convert the field conf (confidence) to numeric
df['conf'] = pd.to_numeric(df['conf'], errors='coerce')
# Elliminate records with negative confidence
df = df[df.conf != -1]
# Calculate the mean confidence by page
conf = df.groupby(['page_num'])['conf'].mean().tolist()
return conf[0]
मुख्य समारोह में जा रहे हैं: छवि को स्कैन करना:
def ocr_img(
img: np.array, input_file: str, search_str: str,
highlight_readable_text: bool = False, action: str = 'Highlight',
show_comparison: bool = False, generate_output: bool = True):
"""Scans an image buffer or an image file.
Pre-processes the image.
Calls the Tesseract engine with pre-defined parameters.
Calculates the confidence score of the image grabbed content.
Draws a green rectangle around readable text items having a confidence score > 30.
Searches for a specific text.
Highlight or redact found matches of the searched text.
Displays a window showing readable text fields or the highlighted or redacted text.
Generates the text content of the image.
Prints a summary to the console."""
# If image source file is inputted as a parameter
if input_file:
# Reading image using opencv
img = cv2.imread(input_file)
# Preserve a copy of this image for comparison purposes
initial_img = img.copy()
highlighted_img = img.copy()
# Convert image to binary
bin_img = convert_img2bin(img)
# Calling Tesseract
# Tesseract Configuration parameters
# oem --> OCR engine mode = 3 >> Legacy + LSTM mode only (LSTM neutral net mode works the best)
# psm --> page segmentation mode = 6 >> Assume as single uniform block of text (How a page of text can be analyzed)
config_param = r'--oem 3 --psm 6'
# Feeding image to tesseract
details = pytesseract.image_to_data(
bin_img, output_type=Output.DICT, config=config_param, lang='eng')
# The details dictionary contains the information of the input image
# such as detected text, region, position, information, height, width, confidence score.
ss_confidence = calculate_ss_confidence(details)
boxed_img = None
# Total readable items
ss_readable_items = 0
# Total matches found
ss_matches = 0
for seq in range(len(details['text'])):
# Consider only text fields with confidence score > 30 (text is readable)
if float(details['conf'][seq]) > 30.0:
ss_readable_items += 1
# Draws a green rectangle around readable text items having a confidence score > 30
if highlight_readable_text:
(x, y, w, h) = (details['left'][seq], details['top']
[seq], details['width'][seq], details['height'][seq])
boxed_img = cv2.rectangle(
img, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Searches for the string
if search_str:
results = re.findall(
search_str, details['text'][seq], re.IGNORECASE)
for result in results:
ss_matches += 1
if action:
# Draw a red rectangle around the searchable text
(x, y, w, h) = (details['left'][seq], details['top']
[seq], details['width'][seq], details['height'][seq])
# Details of the rectangle
# Starting coordinate representing the top left corner of the rectangle
start_point = (x, y)
# Ending coordinate representing the botton right corner of the rectangle
end_point = (x + w, y + h)
#Color in BGR -- Blue, Green, Red
if action == "Highlight":
color = (0, 255, 255) # Yellow
elif action == "Redact":
color = (0, 0, 0) # Black
# Thickness in px (-1 will fill the entire shape)
thickness = -1
boxed_img = cv2.rectangle(
img, start_point, end_point, color, thickness)
if ss_readable_items > 0 and highlight_readable_text and not (ss_matches > 0 and action in ("Highlight", "Redact")):
highlighted_img = boxed_img.copy()
# Highlight found matches of the search string
if ss_matches > 0 and action == "Highlight":
cv2.addWeighted(boxed_img, 0.4, highlighted_img,
1 - 0.4, 0, highlighted_img)
# Redact found matches of the search string
elif ss_matches > 0 and action == "Redact":
highlighted_img = boxed_img.copy()
#cv2.addWeighted(boxed_img, 1, highlighted_img, 0, 0, highlighted_img)
# save the image
cv2.imwrite("highlighted-text-image.jpg", highlighted_img)
# Displays window showing readable text fields or the highlighted or redacted data
if show_comparison and (highlight_readable_text or action):
title = input_file if input_file else 'Compare'
conc_img = cv2.hconcat([initial_img, highlighted_img])
display_img(title, conc_img)
# Generates the text content of the image
output_data = None
if generate_output and details:
output_data = generate_ss_text(details)
# Prints a summary to the console
if input_file:
summary = {
"File": input_file, "Total readable words": ss_readable_items, "Total matches": ss_matches, "Confidence score": ss_confidence
}
# Printing Summary
print("## Summary ########################################################")
print("\n".join("{}:{}".format(i, j) for i, j in summary.items()))
print("###################################################################")
return highlighted_img, ss_readable_items, ss_matches, ss_confidence, output_data
# pass image into pytesseract module
# pytesseract is trained in many languages
#config_param = r'--oem 3 --psm 6'
#details = pytesseract.image_to_data(img,config=config_param,lang='eng')
# print(details)
# return details
उपरोक्त निम्नलिखित कार्य करता है:
def image_to_byte_array(image: Image):
"""
Converts an image into a byte array
"""
imgByteArr = BytesIO()
image.save(imgByteArr, format=image.format if image.format else 'JPEG')
imgByteArr = imgByteArr.getvalue()
return imgByteArr
def ocr_file(**kwargs):
"""Opens the input PDF File.
Opens a memory buffer for storing the output PDF file.
Creates a DataFrame for storing pages statistics
Iterates throughout the chosen pages of the input PDF file
Grabs a screen-shot of the selected PDF page.
Converts the screen-shot pix to a numpy array
Scans the grabbed screen-shot.
Collects the statistics of the screen-shot(page).
Saves the content of the screen-shot(page).
Adds the updated screen-shot (Highlighted, Redacted) to the output file.
Saves the whole content of the PDF file.
Saves the output PDF file if required.
Prints a summary to the console."""
input_file = kwargs.get('input_file')
output_file = kwargs.get('output_file')
search_str = kwargs.get('search_str')
pages = kwargs.get('pages')
highlight_readable_text = kwargs.get('highlight_readable_text')
action = kwargs.get('action')
show_comparison = kwargs.get('show_comparison')
generate_output = kwargs.get('generate_output')
# Opens the input PDF file
pdfIn = fitz.open(input_file)
# Opens a memory buffer for storing the output PDF file.
pdfOut = fitz.open()
# Creates an empty DataFrame for storing pages statistics
dfResult = pd.DataFrame(
columns=['page', 'page_readable_items', 'page_matches', 'page_total_confidence'])
# Creates an empty DataFrame for storing file content
if generate_output:
pdfContent = pd.DataFrame(columns=['page', 'line_id', 'line'])
# Iterate throughout the pages of the input file
for pg in range(pdfIn.pageCount):
if str(pages) != str(None):
if str(pg) not in str(pages):
continue
# Select a page
page = pdfIn[pg]
# Rotation angle
rotate = int(0)
# PDF Page is converted into a whole picture 1056*816 and then for each picture a screenshot is taken.
# zoom = 1.33333333 -----> Image size = 1056*816
# zoom = 2 ---> 2 * Default Resolution (text is clear, image text is hard to read) = filesize small / Image size = 1584*1224
# zoom = 4 ---> 4 * Default Resolution (text is clear, image text is barely readable) = filesize large
# zoom = 8 ---> 8 * Default Resolution (text is clear, image text is readable) = filesize large
zoom_x = 2
zoom_y = 2
# The zoom factor is equal to 2 in order to make text clear
# Pre-rotate is to rotate if needed.
mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
# To captue a specific part of the PDF page
# rect = page.rect #page size
# mp = rect.tl + (rect.bl - (0.75)/zoom_x) #rectangular area 56 = 75/1.3333
# clip = fitz.Rect(mp,rect.br) #The area to capture
# pix = page.getPixmap(matrix=mat, alpha=False,clip=clip)
# Get a screen-shot of the PDF page
# Colorspace -> represents the color space of the pixmap (csRGB, csGRAY, csCMYK)
# alpha -> Transparancy indicator
pix = page.getPixmap(matrix=mat, alpha=False, colorspace="csGRAY")
# convert the screen-shot pix to numpy array
img = pix2np(pix)
# Erode image to omit or thin the boundaries of the bright area of the image
# We apply Erosion on binary images.
#kernel = np.ones((2,2) , np.uint8)
#img = cv2.erode(img,kernel,iterations=1)
upd_np_array, pg_readable_items, pg_matches, pg_total_confidence, pg_output_data \
= ocr_img(img=img, input_file=None, search_str=search_str, highlight_readable_text=highlight_readable_text # False
, action=action # 'Redact'
, show_comparison=show_comparison # True
, generate_output=generate_output # False
)
# Collects the statistics of the page
dfResult = dfResult.append({'page': (pg+1), 'page_readable_items': pg_readable_items,
'page_matches': pg_matches, 'page_total_confidence': pg_total_confidence}, ignore_index=True)
if generate_output:
pdfContent = save_page_content(
pdfContent=pdfContent, page_id=(pg+1), page_data=pg_output_data)
# Convert the numpy array to image object with mode = RGB
#upd_img = Image.fromarray(np.uint8(upd_np_array)).convert('RGB')
upd_img = Image.fromarray(upd_np_array[..., ::-1])
# Convert the image to byte array
upd_array = image_to_byte_array(upd_img)
# Get Page Size
"""
#To check whether initial page is portrait or landscape
if page.rect.width > page.rect.height:
fmt = fitz.PaperRect("a4-1")
else:
fmt = fitz.PaperRect("a4")
#pno = -1 -> Insert after last page
pageo = pdfOut.newPage(pno = -1, width = fmt.width, height = fmt.height)
"""
pageo = pdfOut.newPage(
pno=-1, width=page.rect.width, height=page.rect.height)
pageo.insertImage(page.rect, stream=upd_array)
#pageo.insertImage(page.rect, stream=upd_img.tobytes())
#pageo.showPDFpage(pageo.rect, pdfDoc, page.number)
content_file = None
if generate_output:
content_file = save_file_content(
pdfContent=pdfContent, input_file=input_file)
summary = {
"File": input_file, "Total pages": pdfIn.pageCount,
"Processed pages": dfResult['page'].count(), "Total readable words": dfResult['page_readable_items'].sum(),
"Total matches": dfResult['page_matches'].sum(), "Confidence score": dfResult['page_total_confidence'].mean(),
"Output file": output_file, "Content file": content_file
}
# Printing Summary
print("## Summary ########################################################")
print("\n".join("{}:{}".format(i, j) for i, j in summary.items()))
print("\nPages Statistics:")
print(dfResult, sep='\n')
print("###################################################################")
pdfIn.close()
if output_file:
pdfOut.save(output_file)
pdfOut.close()
image_to_byte_array()
समारोह एक बाइट सरणी में एक छवि बदल देता है।
ocr_file()
समारोह निम्नलिखित है:
आइए एक फ़ोल्डर को संसाधित करने के लिए एक और फ़ंक्शन जोड़ें जिसमें एकाधिक पीडीएफ फाइलें हों:
def ocr_folder(**kwargs):
"""Scans all PDF Files within a specified path"""
input_folder = kwargs.get('input_folder')
# Run in recursive mode
recursive = kwargs.get('recursive')
search_str = kwargs.get('search_str')
pages = kwargs.get('pages')
action = kwargs.get('action')
generate_output = kwargs.get('generate_output')
# Loop though the files within the input folder.
for foldername, dirs, filenames in os.walk(input_folder):
for filename in filenames:
# Check if pdf file
if not filename.endswith('.pdf'):
continue
# PDF File found
inp_pdf_file = os.path.join(foldername, filename)
print("Processing file =", inp_pdf_file)
output_file = None
if search_str:
# Generate an output file
output_file = os.path.join(os.path.dirname(
inp_pdf_file), 'ocr_' + os.path.basename(inp_pdf_file))
ocr_file(
input_file=inp_pdf_file, output_file=output_file, search_str=search_str, pages=pages, highlight_readable_text=False, action=action, show_comparison=False, generate_output=generate_output
)
if not recursive:
break
इस फ़ंक्शन का उद्देश्य एक विशिष्ट फ़ोल्डर में शामिल पीडीएफ फाइलों को स्कैन करना है। यह निर्दिष्ट फ़ोल्डर की फ़ाइलों में या तो पुनरावर्ती रूप से लूप करता है या नहीं, यह पैरामीटर पुनरावर्ती के मान पर निर्भर करता है और इन फ़ाइलों को एक-एक करके संसाधित करता है।
यह निम्नलिखित मापदंडों को स्वीकार करता है:
input_folder
: प्रोसेस करने के लिए पीडीएफ फाइलों वाले फोल्डर का पाथ।search_str
: हेरफेर करने के लिए खोजने के लिए पाठ।recursive
: सबफ़ोल्डर में लूप करके इस प्रक्रिया को पुनरावर्ती रूप से चलाना है या नहीं।action
: निम्नलिखित में से करने के लिए क्रिया: हाइलाइट करें, सुधारें।pages
: विचार करने के लिए पृष्ठ।generate_output
: चुनें कि इनपुट पीडीएफ फाइल की सामग्री को CSV फाइल में सेव करना है या नहींसमाप्त करने से पहले, आइए कमांड-लाइन तर्कों को पार्स करने के लिए उपयोगी कार्यों को परिभाषित करें:
def is_valid_path(path):
"""Validates the path inputted and checks whether it is a file path or a folder path"""
if not path:
raise ValueError(f"Invalid Path")
if os.path.isfile(path):
return path
elif os.path.isdir(path):
return path
else:
raise ValueError(f"Invalid Path {path}")
def parse_args():
"""Get user command line parameters"""
parser = argparse.ArgumentParser(description="Available Options")
parser.add_argument('-i', '--input-path', type=is_valid_path,
required=True, help="Enter the path of the file or the folder to process")
parser.add_argument('-a', '--action', choices=[
'Highlight', 'Redact'], type=str, help="Choose to highlight or to redact")
parser.add_argument('-s', '--search-str', dest='search_str',
type=str, help="Enter a valid search string")
parser.add_argument('-p', '--pages', dest='pages', type=tuple,
help="Enter the pages to consider in the PDF file, e.g. (0,1)")
parser.add_argument("-g", "--generate-output", action="store_true", help="Generate text content in a CSV file")
path = parser.parse_known_args()[0].input_path
if os.path.isfile(path):
parser.add_argument('-o', '--output_file', dest='output_file',
type=str, help="Enter a valid output file")
parser.add_argument("-t", "--highlight-readable-text", action="store_true", help="Highlight readable text in the generated image")
parser.add_argument("-c", "--show-comparison", action="store_true", help="Show comparison between captured image and the generated image")
if os.path.isdir(path):
parser.add_argument("-r", "--recursive", action="store_true", help="Whether to process the directory recursively")
# To Porse The Command Line Arguments
args = vars(parser.parse_args())
# To Display The Command Line Arguments
print("## Command Arguments #################################################")
print("\n".join("{}:{}".format(i, j) for i, j in args.items()))
print("######################################################################")
return args
is_valid_path()
समारोह एक रास्ता एक पैरामीटर और चेक यह एक फ़ाइल पथ है कि क्या है या एक निर्देशिका पथ के रूप में inputted सत्यापित करता है।
parse_args()
समारोह परिभाषित करता है और सेट उचित बाधाओं उपयोगकर्ता के कमांड लाइन तर्क के लिए इस उपयोगिता सुनिश्चित करें।
नीचे सभी मापदंडों के लिए स्पष्टीकरण दिया गया है:
input_path
: फ़ाइल या फ़ोल्डर को संसाधित करने के पथ को इनपुट करने के लिए एक आवश्यक पैरामीटर, यह पैरामीटर is_valid_path()
पहले परिभाषित फ़ंक्शन से जुड़ा हुआ है।action
: किसी भी गलत चयन से बचने के लिए पूर्व-निर्धारित विकल्पों की सूची के बीच प्रदर्शन करने की क्रिया।search_str
: हेरफेर करने के लिए खोजने के लिए पाठ।pages
: PDF फ़ाइल को संसाधित करते समय विचार करने वाले पृष्ठ।generate_content
: निर्दिष्ट करता है कि इनपुट फ़ाइल की पकड़ी गई सामग्री को जनरेट करना है या नहीं, छवि या PDF CSV फ़ाइल के लिए है या नहीं।output_file
: आउटपुट फ़ाइल का पथ। इस तर्क को भरना एक फ़ाइल के इनपुट के रूप में चयन से बाधित है, निर्देशिका नहीं।highlight_readable_text
: 30 से अधिक कॉन्फिडेंस स्कोर वाले पठनीय टेक्स्ट फ़ील्ड के चारों ओर हरे रंग के आयत बनाने के लिए।show_comparison
: मूल छवि और संसाधित छवि के बीच तुलना दिखाते हुए एक विंडो प्रदर्शित करता है।recursive
: किसी फोल्डर को रिकर्सिवली प्रोसेस करना है या नहीं। इस तर्क को भरना एक निर्देशिका के चयन से विवश है।अंत में, आइए मुख्य कोड लिखें जो पहले परिभाषित कार्यों का उपयोग करता है:
if __name__ == '__main__':
# Parsing command line arguments entered by user
args = parse_args()
# If File Path
if os.path.isfile(args['input_path']):
# Process a file
if filetype.is_image(args['input_path']):
ocr_img(
# if 'search_str' in (args.keys()) else None
img=None, input_file=args['input_path'], search_str=args['search_str'], highlight_readable_text=args['highlight_readable_text'], action=args['action'], show_comparison=args['show_comparison'], generate_output=args['generate_output']
)
else:
ocr_file(
input_file=args['input_path'], output_file=args['output_file'], search_str=args['search_str'] if 'search_str' in (args.keys()) else None, pages=args['pages'], highlight_readable_text=args['highlight_readable_text'], action=args['action'], show_comparison=args['show_comparison'], generate_output=args['generate_output']
)
# If Folder Path
elif os.path.isdir(args['input_path']):
# Process a folder
ocr_folder(
input_folder=args['input_path'], recursive=args['recursive'], search_str=args['search_str'] if 'search_str' in (args.keys()) else None, pages=args['pages'], action=args['action'], generate_output=args['generate_output']
)
आइए हमारे कार्यक्रम का परीक्षण करें:
$ python pdf_ocr.py
आउटपुट:
usage: pdf_ocr.py [-h] -i INPUT_PATH [-a {Highlight,Redact}] [-s SEARCH_STR] [-p PAGES] [-g GENERATE_OUTPUT]
Available Options
optional arguments:
-h, --help show this help message and exit
-i INPUT_PATH, --input_path INPUT_PATH
Enter the path of the file or the folder to process
-a {Highlight,Redact}, --action {Highlight,Redact}
Choose to highlight or to redact
-s SEARCH_STR, --search_str SEARCH_STR
Enter a valid search string
-p PAGES, --pages PAGES
Enter the pages to consider e.g.: (0,1)
-g GENERATE_OUTPUT, --generate_output GENERATE_OUTPUT
Generate content in a CSV file
हमारे परीक्षण परिदृश्यों की खोज करने से पहले, निम्नलिखित से सावधान रहें:
PermissionError
त्रुटि का सामना करने से बचने के लिए , कृपया इस उपयोगिता को चलाने से पहले इनपुट फ़ाइल को बंद कर दें।सबसे पहले, आइए एक छवि इनपुट करने का प्रयास करें ( यदि आप समान आउटपुट प्राप्त करना चाहते हैं तो आप इसे यहां प्राप्त कर सकते हैं ), बिना किसी पीडीएफ फाइल को शामिल किए:
$ python pdf_ocr.py -s "BERT" -a Highlight -i example-image-containing-text.jpg
निम्नलिखित आउटपुट होगा:
## Command Arguments #################################################
input_path:example-image-containing-text.jpg
action:Highlight
search_str:BERT
pages:None
generate_output:False
output_file:None
highlight_readable_text:False
show_comparison:False
######################################################################
## Summary ########################################################
File:example-image-containing-text.jpg
Total readable words:192
Total matches:3
Confidence score:89.89337547979804
###################################################################
और वर्तमान निर्देशिका में एक नई छवि दिखाई दी है:
आप सभी खोजे गए टेक्स्ट को पास कर सकते हैं
-t
या --highlight-readable-text
हाइलाइट कर सकते हैं (एक अलग प्रारूप के साथ, ताकि खोज स्ट्रिंग को दूसरों से अलग किया जा सके)।
आप मूल छवि और संपादित छवि को एक ही विंडो में पास -c
या --show-comparison
प्रदर्शित करने के लिए भी कर सकते हैं।
अब यह छवियों के लिए काम कर रहा है, आइए पीडीएफ फाइलों के लिए प्रयास करें:
$ python pdf_ocr.py -s "BERT" -i image.pdf -o output.pdf --generate-output -a "Highlight"
image.pdf
पिछले उदाहरण में छवि वाली एक साधारण पीडीएफ फाइल है (फिर से, आप इसे यहां प्राप्त कर सकते हैं )।
इस बार हमने -i
तर्क के लिए एक पीडीएफ फाइल पास की है, और output.pdf
परिणामी पीडीएफ फाइल के रूप में (जहां सभी हाइलाइटिंग होती है)। उपरोक्त आदेश निम्न आउटपुट उत्पन्न करता है:
## Command Arguments #################################################
input_path:image.pdf
action:Highlight
search_str:BERT
pages:None
generate_output:True
output_file:output.pdf
highlight_readable_text:False
show_comparison:False
######################################################################
## Summary ########################################################
File:image.pdf
Total pages:1
Processed pages:1
Total readable words:192.0
Total matches:3.0
Confidence score:83.1775128855722
Output file:output.pdf
Content file:image.csv
Pages Statistics:
page page_readable_items page_matches page_total_confidence
0 1.0 192.0 3.0 83.177513
###################################################################
output.pdf
फ़ाइल निष्पादन, जहां यह एक ही मूल PDF लेकिन प्रकाश डाला पाठ के साथ शामिल करने के बाद उत्पादन किया जाता है। इसके अतिरिक्त, अब हमारे पास हमारी पीडीएफ फाइल के बारे में आंकड़े हैं, जहां कुल 192 शब्दों का पता चला है, और लगभग 83.2% के विश्वास के साथ हमारी खोज का उपयोग करके 3 का मिलान किया गया था।
एक CSV फ़ाइल भी तैयार की जाती है जिसमें प्रत्येक पंक्ति पर छवि से पता लगाया गया पाठ शामिल होता है।
ऐसे अन्य पैरामीटर हैं जिनका हमने अपने उदाहरणों में उपयोग नहीं किया है, उन्हें बेझिझक एक्सप्लोर करें। आप -i
पीडीएफ फाइलों के संग्रह को स्कैन करने के लिए तर्क के लिए एक संपूर्ण फ़ोल्डर भी पास कर सकते हैं ।
Tesseract स्वच्छ और स्पष्ट दस्तावेजों को स्कैन करने के लिए एकदम सही है। खराब गुणवत्ता वाला स्कैन ओसीआर में खराब परिणाम दे सकता है। आम तौर पर, यह आंशिक रोड़ा, विकृत परिप्रेक्ष्य और जटिल पृष्ठभूमि सहित कलाकृतियों से प्रभावित छवियों के सटीक परिणाम नहीं देता है।
#python
1633539240
पायथन में MoviePy लाइब्रेरी का उपयोग करके वीडियो फ़ाइल बनाने के लिए ऑडियो फ़ाइल में स्थिर फ़ोटो जोड़ने का तरीका जानें।
ऐसे कई मामले हैं जहां आप अपनी ऑडियो फ़ाइल को वीडियो में बदलना चाहते हैं, जैसे कि YouTube पर ऑडियो अपलोड करना या ऐसा ही कुछ। इस ट्यूटोरियल में, आप सीखेंगे कि मूवीपी लाइब्रेरी का उपयोग करके पायथन के साथ एक वीडियो फ़ाइल बनाने के लिए एक ऑडियो फ़ाइल में एक स्थिर छवि कैसे जोड़ें।
इससे पहले कि हम कोड के साथ शुरुआत करें, आइए MoviePy इंस्टॉल करें:
$ pip install moviepy
एक नई पायथन फ़ाइल खोलें और निम्नलिखित लिखें:
from moviepy.editor import AudioFileClip, ImageClip
def add_static_image_to_audio(image_path, audio_path, output_path):
"""Create and save a video file to `output_path` after
combining a static image that is located in `image_path`
with an audio file in `audio_path`"""
# create the audio clip object
audio_clip = AudioFileClip(audio_path)
# create the image clip object
image_clip = ImageClip(image_path)
# use set_audio method from image clip to combine the audio with the image
video_clip = image_clip.set_audio(audio_clip)
# specify the duration of the new clip to be the duration of the audio clip
video_clip.duration = audio_clip.duration
# set the FPS to 1
video_clip.fps = 1
# write the resuling video clip
video_clip.write_videofile(output_path)
add_static_image_to_audio()
समारोह सब कुछ है, यह छवि पथ, ऑडियो पथ, और आउटपुट वीडियो पथ, और फिर उम्मीद करता है:
AudioFileClip()
audio_path से उदाहरण बनाता है ।ImageClip()
image_path से इंस्टेंस भी बनाया ।set_audio()
विधि का उपयोग करके इमेजक्लिप इंस्टेंस में ऑडियो जोड़ते हैं जो एक नई क्लिप देता है।write_videofile()
परिणामी वीडियो फ़ाइल को सहेजने के लिए विधि का उपयोग करते हैं ।आइए अब कमांड-लाइन तर्कों को पार्स करने के लिए argparse मॉड्यूल का उपयोग करें :
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Simple Python script to add a static image to an audio to make a video")
parser.add_argument("image", help="The image path")
parser.add_argument("audio", help="The audio path")
parser.add_argument("output", help="The output video file path")
args = parser.parse_args()
add_static_image_to_audio(args.image, args.audio, args.output)
बहुत बढ़िया, आइए इसका परीक्षण करें:
$ python add_photo_to_audio.py --help
आउटपुट:
usage: add_photo_to_audio.py [-h] image audio output
Simple Python script to add a static image to an audio to make a video
positional arguments:
image The image path
audio The audio path
output The output video file path
optional arguments:
-h, --help show this help message and exit
बढ़िया, आइए इसे इस छवि और इस ऑडियो फ़ाइल के साथ आज़माएँ:
$ python add_photo_to_audio.py directed-by-robert-image.jpg "Directed-by-Robert-B.-Weide-theme.mp3" output.mp4
output.mp4
फ़ाइल वर्तमान निर्देशिका में दिखाई देगा:
ठीक है, यह ट्यूटोरियल के लिए है! चेक यहाँ पूर्ण कोड ।
#python
1652098200
उपयोगकर्ता इनपुट को सत्यापित करने के लिए PyInputPlus मॉड्यूल का उपयोग करके Python में एक साधारण गणित प्रश्नोत्तरी गेम बनाना सीखें।
इस ट्यूटोरियल में, हम कंसोल पर PyInputPlus मॉड्यूल के साथ एक साधारण गणित गेम बनाएंगे । इस सरल खेल की मुख्य विशेषताएं अंक जोड़ना (एक अंक की तरह), कई समीकरण प्रकार (जैसे जोड़, घटाव, गुणा और भाग), और खेल को रोकने की क्षमता है।
आरंभ करने के लिए, चूंकि PyInputPlus एक अंतर्निहित मॉड्यूल नहीं है, इसलिए हमें इसे स्थापित करना होगा:
$ pip install PyInputPlus
PyInputPlus और random आयात करना :
# Imports
import pyinputplus as pyip
from random import choice
हम बाद में उपयोग करने के लिए कुछ चर सेट करके जारी रखते हैं।
questionTypes
सूची में उन ऑपरेटरों को रखा गया है जिनका उपयोग समीकरणों में किया जा सकता है ; ध्यान रखें कि उन्हें वैध पायथन ऑपरेटर होना चाहिए। (%)
आप इन ऑपरेटरों को गेम में सक्षम करने के लिए मॉड्यूल या किसी अन्य वैध पायथन ऑपरेटर को सूची में जोड़ सकते हैं । इन्हें random.choice()
फ़ंक्शन के साथ यादृच्छिक रूप से चुना जाएगा।
इसके बाद, हम एक सूची को परिभाषित करते हैं जिसे कहा जाता है numberRange
जिसमें सभी संख्याएं होती हैं जो समीकरणों में प्रकट हो सकती हैं। हम इसे एक पंक्ति में कर सकते हैं।
अंतिम लेकिन कम से कम, हम एक अंक चर परिभाषित करते हैं, जो 0 से शुरू होता है।
# Variables
questionTypes = ['+', '-', '*', '/', '**']
numbersRange = [num for num in range(1, 20)]
points = 0
यह सुनिश्चित करने के लिए कि उपयोगकर्ता जानता है कि उसे क्या करना है, हम खेल के बारे में कुछ संकेत प्रिंट करते हैं।
बाद में हम हलों को गोल करेंगे क्योंकि समीकरणों 7 / 4
को लिखना असंभव है।
हम उपयोगकर्ता को प्रत्येक प्रश्न के बाद गेम को रोकने में भी सक्षम करेंगे। इसलिए हम यहां इसका जिक्र कर रहे हैं।
# Hints
print('Round down to one Number after the Comma.')
print('When asked to press enter to continue, type stop to stop.\n')
अब हम गेम लूप में प्रवेश करते हैं, जहां हम एक प्रश्न प्रकार पर निर्णय करके शुरू करते हैं। random.choice()
यह यादृच्छिक मॉड्यूल से विधि के साथ किया जाता है । यह आइटम में से एक को questionTypes
.
फिर हम उस समीकरण का निर्माण करते हैं जहां हम सूची random.choice()
से यादृच्छिक आइटम चुनने के लिए भी उपयोग करते हैं numbersRange
और उन्हें इस स्ट्रिंग में सम्मिलित करते हैं।
उसके बाद, हमने Python's great eval()
function का उपयोग किया। यह एक स्ट्रिंग लेता है और इसका मूल्यांकन करता है, और समाधान देता है। हम इसे समाधान चर में सहेजते हैं; हम बाद में इसका परीक्षण करते हैं कि उपयोगकर्ता ने क्या लिखा है।
# Game Loop
while True:
# Deciding and generating question
currenType = choice(questionTypes)
promptEquation = str(choice(numbersRange)) + ' ' + currenType + ' ' + str(choice(numbersRange))
solution = round(eval(promptEquation), 1)
अगला, हम inputNum()
PyInputPlus मॉड्यूल से विधि का उपयोग करते हैं। यह फ़ंक्शन परीक्षण करेगा कि क्या इनपुट एक संख्या थी, और यदि नहीं, तो यह फिर से पूछेगा। हम अपने प्रॉम्प्ट स्ट्रिंग के साथ इसके प्रॉम्प्ट पैरामीटर को भरते हैं; जोड़ने के लिए ध्यान रखें ' = '
ताकि यह उपयोगकर्ता के लिए समझ में आए। हम समारोह से पहले ऐसा नहीं कर सकते थे eval()
क्योंकि यह उस तरह से काम करेगा।
# Getting answer from User
answer = pyip.inputNum(prompt=promptEquation + ' = ')
उपयोगकर्ता इनपुट प्राप्त करने के बाद, हम eval()
फ़ंक्शन द्वारा दिए गए समाधान के विरुद्ध इसका परीक्षण करते हैं। यदि वे मेल खाते हैं, तो हम एक-एक करके अंक बढ़ाते हैं और एक अच्छी टिप्पणी और नई बिंदु संख्या का प्रिंट आउट लेते हैं।
यदि यह गलत है, तो हम एक-एक करके अंक कम करते हैं और सही समाधान का प्रिंट आउट लेते हैं।
# Feedback and Points
if answer == solution:
points += 1
print('Correct!\nPoints: ',points)
else:
points -= 1
print('Wrong!\nSolution: '+str(solution)+'\nPoints: ',points)
अंतिम लेकिन कम से कम, हम प्रत्येक प्रश्न के बाद खेल को रोक देते हैं। यदि उपयोगकर्ता एंटर दबाता है, तो यह जारी रहता है। उसके लिए काम करने के लिए, हमें सेट blank
करना होगा True
लेकिन यदि उपयोगकर्ता टाइप stop
करता है, तो गेम बंद हो जाएगा।
# Stopping the Game
if pyip.inputStr('Press "Enter" to continue', blank=True) == 'stop':
break
# Some Padding
print('\n\n')
आइए इसे चलाते हैं:
$ python simple_math_game.py
Round down to one Number after the Comma.
When asked to press enter to continue, type stop to stop.
5 ** 4 = 625
Correct!
Points: 1
Press "Enter" to continue
9 ** 18 = 190
Wrong!
Solution: 150094635296999121
Points: 0
Press "Enter" to continue
7 - 17 = -10
Correct!
Points: 1
Press "Enter" to continue
stop
विस्मयकारी! अब आप जानते हैं कि PyInputPlus के साथ एक साधारण कंसोल गणित गेम कैसे बनाया जाता है। आप यहां पूरा कोड प्राप्त कर सकते हैं ।
#python
1633577889
पायथन में ओपनसीवी या मूवीपी लाइब्रेरी के साथ टाइमस्टैम्प के साथ वीडियो से फ्रेम निकालने के लिए दो अलग-अलग तरीके बनाना।
जैसा कि आप पहले से ही जानते हैं, एक वीडियो छवियों की एक श्रृंखला से बना होता है। इन छवियों को फ्रेम कहा जाता है और एक निश्चित दर पर लगातार एक-एक करके खेला जाता है जिसे मानव आंख द्वारा गति के रूप में पहचाना जाएगा।
इस ट्यूटोरियल में, आप पायथन में वीडियो फ़ाइलों से फ़्रेम निकालने के दो तरीके सीखेंगे। सबसे पहले, हम जाने-माने ओपनसीवी लाइब्रेरी के साथ ऐसा कैसे कर सकते हैं । उसके बाद, हम MoviePy लाइब्रेरी का उपयोग करके फ़्रेम निकालने की अन्य विधि का पता लगाएंगे।
आरंभ करने के लिए, आइए पुस्तकालयों को स्थापित करें:
$ pip install python-opencv moviepy
मैं extract_frames_opencv.py
फ़ाइल बनाउंगा और आवश्यक मॉड्यूल आयात करूंगा :
from datetime import timedelta
import cv2
import numpy as np
import os
चूंकि सभी वीडियो की लंबाई और FPS समान नहीं होते हैं , इसलिए हम यह समायोजित करने के लिए एक पैरामीटर परिभाषित करेंगे कि हम प्रति सेकंड कितने फ़्रेम निकालना और सहेजना चाहते हैं:
# i.e if video of duration 30 seconds, saves 10 frame per second = 300 frames saved in total
SAVING_FRAMES_PER_SECOND = 10
हम इस पैरामीटर का उपयोग दोनों विधियों पर करेंगे। उदाहरण के लिए, यदि यह अभी के लिए १० पर सेट है, तो यह वीडियो के केवल १० फ्रेम प्रति सेकंड को बचाएगा, भले ही वीडियो एफपीएस २४ है। यदि वीडियो की अवधि ३० सेकंड है, तो कुल ३०० फ्रेम सहेजे जाएंगे . आप इस पैरामीटर को 0.5 कहने के लिए भी सेट कर सकते हैं, जो प्रति 2 सेकंड में एक फ्रेम को बचाएगा, और इसी तरह।
अगला, आइए दो सहायक कार्यों को परिभाषित करें:
def format_timedelta(td):
"""Utility function to format timedelta objects in a cool way (e.g 00:00:20.05)
omitting microseconds and retaining milliseconds"""
result = str(td)
try:
result, ms = result.split(".")
except ValueError:
return result + ".00".replace(":", "-")
ms = int(ms)
ms = round(ms / 1e4)
return f"{result}.{ms:02}".replace(":", "-")
def get_saving_frames_durations(cap, saving_fps):
"""A function that returns the list of durations where to save the frames"""
s = []
# get the clip duration by dividing number of frames by the number of frames per second
clip_duration = cap.get(cv2.CAP_PROP_FRAME_COUNT) / cap.get(cv2.CAP_PROP_FPS)
# use np.arange() to make floating-point steps
for i in np.arange(0, clip_duration, 1 / saving_fps):
s.append(i)
return s
format_timedelta()
समारोह एक को स्वीकार करता है timedelta वस्तु और मिलीसेकेंड और माइक्रोसेकंड को छोड़ते हुए के साथ एक अच्छा स्ट्रिंग प्रतिनिधित्व देता है।
get_saving_frames_durations()
समारोह को स्वीकार करता है VideoCapture
OpenCV से वस्तु, और हम पैरामीटर बचत पहले चर्चा की और जहां हम फ्रेम को बचाने चाहिए पर अवधि के धब्बे की एक सूची देता है।
अब जब हमारे पास ये सहायक कार्य हैं, तो आइए मुख्य कार्य को परिभाषित करें और इसकी व्याख्या करें:
def main(video_file):
filename, _ = os.path.splitext(video_file)
filename += "-opencv"
# make a folder by the name of the video file
if not os.path.isdir(filename):
os.mkdir(filename)
# read the video file
cap = cv2.VideoCapture(video_file)
# get the FPS of the video
fps = cap.get(cv2.CAP_PROP_FPS)
# if the SAVING_FRAMES_PER_SECOND is above video FPS, then set it to FPS (as maximum)
saving_frames_per_second = min(fps, SAVING_FRAMES_PER_SECOND)
# get the list of duration spots to save
saving_frames_durations = get_saving_frames_durations(cap, saving_frames_per_second)
# start the loop
count = 0
while True:
is_read, frame = cap.read()
if not is_read:
# break out of the loop if there are no frames to read
break
# get the duration by dividing the frame count by the FPS
frame_duration = count / fps
try:
# get the earliest duration to save
closest_duration = saving_frames_durations[0]
except IndexError:
# the list is empty, all duration frames were saved
break
if frame_duration >= closest_duration:
# if closest duration is less than or equals the frame duration,
# then save the frame
frame_duration_formatted = format_timedelta(timedelta(seconds=frame_duration))
cv2.imwrite(os.path.join(filename, f"frame{frame_duration_formatted}.jpg"), frame)
# drop the duration spot from the list, since this duration spot is already saved
try:
saving_frames_durations.pop(0)
except IndexError:
pass
# increment the frame count
count += 1
उपरोक्त फ़ंक्शन जटिल दिखता है, लेकिन ऐसा नहीं है, यहाँ हम क्या कर रहे हैं:
"-opencv"
केवल विधियों को अलग करने के लिए जोड़ते हैं , लेकिन आप इसे हटा सकते हैं।os.mkdir()
फ़ंक्शन का उपयोग करके फ़ोल्डर बनाते हैं यदि पहले से नहीं बनाया गया है।cv2.VideoCapture
, और cap.get()
विधि का उपयोग करके FPS को पुनः प्राप्त करते हैं और FPS के लिए कोड पास करते हैं, जो कि cv2.CAP_PROP_FPS
.saving_frames_durations
सूची में है। हम फ़्रेम का उपयोग करके सहेजते हैं cv2.imwrite()
, और फ़्रेम का नाम वास्तविक अवधि पर सेट करते हैं।मुख्य कोड को परिभाषित करना:
if __name__ == "__main__":
import sys
video_file = sys.argv[1]
main(video_file)
चूंकि हम कमांड-लाइन तर्कों का उपयोग करके वीडियो फ़ाइल पास कर रहे हैं, चलिए इसे चलाते हैं:
$ python extract_frames_opencv.py zoo.mp4
उपरोक्त आदेश के निष्पादन के बाद, एक नया फ़ोल्डर "zoo-opencv"
बनाया जाता है और इसमें वह शामिल होता है:
जैसा कि आप देख सकते हैं, फ़्रेम फ़ाइल नाम में टाइमस्टैम्प के साथ सहेजे गए हैं।
इस पद्धति में, हम OpenCV का उपयोग नहीं करने जा रहे हैं, लेकिन MoviePy नामक एक अन्य लाइब्रेरी के साथ, मैं एक फ़ाइल बनाने जा रहा हूँ जिसका नाम है extract_frames_moviepy.py
और आवश्यक मॉड्यूल आयात करें:
from moviepy.editor import VideoFileClip
import numpy as np
import os
from datetime import timedelta
पहली विधि की तरह, हम SAVING_FRAMES_PER_SECOND
यहाँ भी पैरामीटर का उपयोग करेंगे :
# i.e if video of duration 30 seconds, saves 10 frame per second = 300 frames saved in total
SAVING_FRAMES_PER_SECOND = 10
इसका वास्तव में क्या अर्थ है, यह जानने के लिए इस ट्यूटोरियल के पहले भाग को देखें। पहले की तरह, हमें format_timedelta()
भी फ़ंक्शन की आवश्यकता है:
def format_timedelta(td):
"""Utility function to format timedelta objects in a cool way (e.g 00:00:20.05)
omitting microseconds and retaining milliseconds"""
result = str(td)
try:
result, ms = result.split(".")
except ValueError:
return result + ".00".replace(":", "-")
ms = int(ms)
ms = round(ms / 1e4)
return f"{result}.{ms:02}".replace(":", "-")
अब मुख्य समारोह में जा रहे हैं:
def main(video_file):
# load the video clip
video_clip = VideoFileClip(video_file)
# make a folder by the name of the video file
filename, _ = os.path.splitext(video_file)
filename += "-moviepy"
if not os.path.isdir(filename):
os.mkdir(filename)
# if the SAVING_FRAMES_PER_SECOND is above video FPS, then set it to FPS (as maximum)
saving_frames_per_second = min(video_clip.fps, SAVING_FRAMES_PER_SECOND)
# if SAVING_FRAMES_PER_SECOND is set to 0, step is 1/fps, else 1/SAVING_FRAMES_PER_SECOND
step = 1 / video_clip.fps if saving_frames_per_second == 0 else 1 / saving_frames_per_second
# iterate over each possible frame
for current_duration in np.arange(0, video_clip.duration, step):
# format the file name and save it
frame_duration_formatted = format_timedelta(timedelta(seconds=current_duration)).replace(":", "-")
frame_filename = os.path.join(filename, f"frame{frame_duration_formatted}.jpg")
# save the frame with the current duration
video_clip.save_frame(frame_filename, current_duration)
जैसा कि आप पहले ही देख सकते हैं, इस विधि के लिए कम कोड की आवश्यकता होती है। सबसे पहले, हम VideoFileClip()
क्लास का उपयोग करके अपनी वीडियो क्लिप लोड करते हैं , हम अपना फ़ोल्डर बनाते हैं और सुनिश्चित करते हैं कि बचत एफपीएस वीडियो एफपीएस से कम या बराबर है।
फिर हम अपने लूपिंग स्टेप को परिभाषित करते हैं, जिसे 1 सेविंग एफपीएस से विभाजित किया जाता है, अगर हम SAVING_FRAMES_PER_SECOND
10 को सेट करते हैं , तो स्टेप 0.1 होगा (यानी हर 0.1 सेकंड में सेविंग फ्रेम)।
यहां अंतर यह है कि VideoFileClip
ऑब्जेक्ट में save_frame()
विधि है, जो दो तर्कों को स्वीकार करती है: फ्रेम फ़ाइल नाम, और उस फ्रेम की अवधि जिसे आप सहेजना चाहते हैं। तो हमने जो किया वह यह है कि हम प्रत्येक फ्रेम पर कदम उठाने np.arange()
के लिए (नियमित range()
फ़ंक्शन के फ़्लोटिंग-पॉइंट संस्करण ) का उपयोग करके लूप करते हैं, और save_frame()
तदनुसार विधि को कॉल करते हैं ।
यहाँ मुख्य कोड है:
if __name__ == "__main__":
import sys
video_file = sys.argv[1]
main(video_file)
आइए इसका परीक्षण करें:
$ python extract_frames_moviepy.py zoo.mp4
कुछ सेकंड के बाद, zoo-moviepy
फोल्डर बन जाता है, और फ्रेम्स उस फोल्डर के अंदर सेव हो जाते हैं।
मेरे मामले में दोनों विधियों का उपयोग करने के बाद, मैंने देखा कि विधि एक (ओपनसीवी का उपयोग करके) समय निष्पादन के मामले में तेज़ है लेकिन मूवीपी की तुलना में बड़ी छवियों को सहेजती है।
कि डेमो वीडियो के मामले में, के आकार 190 फ्रेम था 2.8MB दूसरी विधि (MoviePy प्रयोग करके) और का उपयोग कर 5.46MB OpenCV का उपयोग कर। हालाँकि, MoviePy पद्धति की अवधि 2.3 सेकंड थी, जबकि OpenCV में लगभग 0.6 सेकंड का समय लगा।
कहा जा रहा है, मैंने आपके हाथों में पायथन में वीडियो से फ्रेम निकालने के दो तरीके रखे हैं, यह आप पर निर्भर है कि आपको कौन सा तरीका सबसे अच्छा लगता है।
दोनों विधियों का पूरा कोड यहां देखें ।
#python