Spaces:
Runtime error

Atsuyabuddy / app.py
prakashdev03's picture
Update app.py
cbad4a8 verified
Raw History Blame Contribute Delete
17.1 kB
from typing import Generator, Tuple
from huggingface_hub import InferenceClient
import gradio as gr
# Initialize the Hugging Face InferenceClient
client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
def format_prompt(message: str, history: list[Tuple[str, str]]) -> str:
"""
Format the conversation history and current message into a prompt format
suitable for text generation.
Args:
message (str): The user's current message.
history (list[Tuple[str, str]]): List of tuples containing pairs of user prompts and bot responses.
Returns:
str: Formatted prompt string.
"""
prompt = "<s>"
for user_prompt, bot_response in history:
prompt += f"[INST] {user_prompt} [/INST]"
prompt += f" {bot_response}</s> "
prompt += f"[INST] {message} [/INST]"
return prompt
def generate(
prompt: str,
history: list[Tuple[str, str]],
temperature: float = 0.6,
max_new_tokens: int = 2500,
top_p: float = 0.95,
repetition_penalty: float = 1.0,
) -> Generator[str, None, str]:
"""
Generate a response based on the given prompt and conversation history.
Args:
prompt (str): The current prompt (user's message).
history (list[Tuple[str, str]]): List of tuples containing pairs of user prompts and bot responses.
temperature (float, optional): Controls the randomness of token generation. Defaults to 0.6.
max_new_tokens (int, optional): Maximum number of tokens to generate in the response. Defaults to 2500.
top_p (float, optional): Cumulative probability for nucleus sampling. Defaults to 0.95.
repetition_penalty (float, optional): Penalty for repeating tokens. Defaults to 1.0.
Yields:
Generator[str, None, str]: Generated text responses.
Returns:
str: Final generated output.
"""
temperature = float(temperature)
if temperature < 1e-2:
temperature = 1e-2
top_p = float(top_p)
generate_kwargs = dict(
temperature=temperature,
max_new_tokens=max_new_tokens,
top_p=top_p,
repetition_penalty=repetition_penalty,
do_sample=True,
seed=42,
)
system_prompt = """
Certainly! Here’s a revised system prompt that clearly instructs to only use the provided text without making any assumptions or skipping fields. This will help ensure that the conversion process strictly adheres to the given data.
---
**System Prompt:**
Convert the following text into a JSON object according to the specified structure. Ensure that each field is populated strictly based on the provided text. If any information is missing or not explicitly provided in the text, use an appropriate placeholder or an empty value as defined in the JSON schema. Do not make any assumptions or skip any fields. If a field's value is not mentioned in the text, leave it as an empty string or zero (`0.0`) as applicable.
Here is the JSON structure you need to follow:
```json
{
"storeDetails": {
"storeBrand": "",
"storeName": "",
"storeBranch": "",
"storeCountry": "",
"storeTaxId": "",
"storeAddress": "",
"storeContactNo": "",
"storeLocation": {
"latitude": "",
"longitude": "",
"timeZone": ""
}
},
"billDate": "",
"billRefId": "",
"billPrintType": "",
"user": "",
"customerName": "",
"customerMobile": "",
"customerAddress": "",
"customerEmail": "",
"salesAssistant": "",
"itemList": [
{
"serialNo": "",
"hsnCode": "",
"productCode": "",
"productDescription": "",
"category": "",
"taxPercent": 0.0,
"discountPercent": 0.0,
"discountAmount": 0.0,
"quantity": 0.0,
"unit": "",
"rateAmount": 0.0,
"amount": 0.0
}
],
"subTotal": 0.0,
"totalQuantity": 0.0,
"totalDiscount": 0.0,
"netAmount": 0.0,
"taxType": "",
"taxDetails": [
{
"gstPercent": 0.0,
"cgst": 0.0,
"sgst": 0.0,
"serialNumbers": [],
"taxableAmount": 0.0,
"gstAmount": 0.0,
"cgstAmount": 0.0,
"sgstAmount": 0.0
}
],
"taxableTotalAmount": 0.0,
"taxTotalAmount": 0.0,
"totalAmount": 0.0,
"currencyType": "",
"tenderDetails": {
"paymentType": "",
"paymentAmount": 0.0,
"paymentStatus": "",
"paymentDate": "",
"paymentReference": ""
},
"additionalCharges": {
"serviceCharge": "",
"deliveryCharge": "",
"roundingAdjustment": ""
},
"notes": "",
"regulatoryInformation": {
"storeTaxId": "",
"regulatoryNotes": ""
}
}
```
**Instructions:**
1. **Extract and Map Information:** Carefully read the provided text and extract information to populate the fields in the JSON structure. Each field must be filled according to the information given.
2. **No Assumptions:** Do not assume any values or make up information. Use only what is provided in the text. If a field is not mentioned in the text, use the appropriate placeholder (empty string for text fields or `0.0` for numeric fields).
3. **Complete Conversion:** Ensure that all fields in the JSON structure are addressed. Do not skip any fields or sections.
4. **No Comments or Incomplete Data:** Provide a fully populated JSON object without comments or partial data. Every field should be accounted for as per the given text.
**Example Conversion:**
*Text Input:*
```
Store Brand: TechWorld
Store Name: TechWorld Electronics
Store Branch: Downtown
Store Country: USA
Store Tax ID: 123456789
Store Address: 123 Tech Lane, Silicon Valley
Store Contact No: 555-1234
Store Location: Latitude 37.7749, Longitude -122.4194, Time Zone PST
Bill Date: 2024-08-26
Bill Ref ID: BW20240826
Bill Print Type: Receipt
User: John Doe
Customer Name: Jane Smith
Customer Address: 456 Elm Street, Silicon Valley
Sales Assistant: Emily Clark
Item List:
1. Serial No: 001, HSN Code: 1234, Product Code: P001, Product Description: Laptop, Category: Electronics, Tax Percent: 10.0, Discount Percent: 5.0, Discount Amount: 50.0, Quantity: 1, Unit: Unit, Rate Amount: 1000.0, Amount: 950.0
Sub Total: 950.0
Total Quantity: 1
Total Discount: 50.0
Net Amount: 950.0
Tax Type: GST
Tax Details:
1. GST Percent: 10.0, CGST: 5.0, SGST: 5.0, Serial Numbers: [001], Taxable Amount: 900.0, GST Amount: 90.0, CGST Amount: 45.0, SGST Amount: 45.0
Taxable Total Amount: 900.0
Tax Total Amount: 90.0
Total Amount: 950.0
Currency Type: USD
Tender Details: Payment Type: Credit Card, Payment Amount: 950.0, Payment Status: Completed, Payment Date: 2024-08-26, Payment Reference: CC20240826
Additional Charges: Service Charge: 0.0, Delivery Charge: 0.0, Rounding Adjustment: 0.0
Notes: Thank you for shopping with us!
Regulatory Information: Store Tax ID: 123456789, Regulatory Notes: N/A
```
*JSON Output:*
```json
{
"storeDetails": {
"storeBrand": "TechWorld",
"storeName": "TechWorld Electronics",
"storeBranch": "Downtown",
"storeCountry": "USA",
"storeTaxId": "123456789",
"storeAddress": "123 Tech Lane, Silicon Valley",
"storeContactNo": "555-1234",
"storeLocation": {
"latitude": "37.7749",
"longitude": "-122.4194",
"timeZone": "PST"
}
},
"billDate": "2024-08-26",
"billRefId": "BW20240826",
"billPrintType": "Receipt",
"user": "John Doe",
"customerName": "Jane Smith",
"customerMobile": "",
"customerAddress": "456 Elm Street, Silicon Valley",
"customerEmail": "",
"salesAssistant": "Emily Clark",
"itemList": [
{
"serialNo": "001",
"hsnCode": "1234",
"productCode": "P001",
"productDescription": "Laptop",
"category": "Electronics",
"taxPercent": 10.0,
"discountPercent": 5.0,
"discountAmount": 50.0,
"quantity": 1.0,
"unit": "Unit",
"rateAmount": 1000.0,
"amount": 950.0
}
],
"subTotal": 950.0,
"totalQuantity": 1.0,
"totalDiscount": 50.0,
"netAmount": 950.0,
"taxType": "GST",
"taxDetails": [
{
"gstPercent": 10.0,
"cgst": 5.0,
"sgst": 5.0,
"serialNumbers": ["001"],
"taxableAmount": 900.0,
"gstAmount": 90.0,
"cgstAmount": 45.0,
"sgstAmount": 45.0
}
],
"taxableTotalAmount": 900.0,
"taxTotalAmount": 90.0,
"totalAmount": 950.0,
"currencyType": "USD",
"tenderDetails": {
"paymentType": "Credit Card",
"paymentAmount": 950.0,
"paymentStatus": "Completed",
"paymentDate": "2024-08-26",
"paymentReference": "CC20240826"
},
"additionalCharges": {
"serviceCharge": "0.0",
"deliveryCharge": "0.0",
"roundingAdjustment": "0.0"
},
"notes": "Thank you for shopping with us!",
"regulatoryInformation": {
"storeTaxId": "123456789",
"regulatoryNotes": "N/A"
}
}
```
This prompt ensures that the conversion is performed accurately, with all fields addressed based on the provided text, and no assumptions or omissions are made.
"""
formatted_prompt = format_prompt(f"{system_prompt}, {prompt}", history)
stream = client.text_generation(
formatted_prompt,
**generate_kwargs,
stream=True,
details=True,
return_full_text=False,
)
output = ""
for response in stream:
output += response.token.text
yield output
return output
demo = gr.ChatInterface(
fn=generate,
chatbot=gr.Chatbot(
avatar_images=["./user.png", "./logo.png"],
bubble_full_width=False,
show_label=False,
show_copy_button=True,
likeable=True,
),
description="Ask questions about technical doubts",
theme="soft",
examples=[
"""
BIBA
BibaApparels PytLtd
GST No- 36AABCB9274B617T
Unit No-F-ROOSB F-Level Domestic Sha
Rajiv Gandhi International Aiport
Shamshabad, Hyderabad
Lan-No - 040-66603933
INVOICE
Date: 10/Jul/2024 02:27 PM Customer:
Ref.ID: HYD /24-25/00075 Mobile #
User: owner Sales Assistant:owner
SNo CODE GST% Disc® Oty Fate
HSN CODE PRODUCT DESCRIPTION Dis.Amt Amount
1 11 18.00 0.00 1.000 95.00
0 Kalifh's Masalasey 0.00 95.00
2 149652 9.00 0.00 4 699.00
62114290 COREKLOO1 0.00 2796.00
3 159002 9.00 0.00 2 999.00
62114290 CREPE KU15957 0.00 1998.00
SubTotal: Fis: 4889.00
Qty ¥.00 Disc 0.00 Net: Rs.4889.00
GST SNO Taxable Amt GST Amt CGSTAmt SGST Amt
18.00(1) 1 80.51 14.49 4.20 4.20
CGSTS.00% , SGST9.00%
5.00(1) 2,3 4565. 72 228.28 114.14 114.14
CGST2.50% , SGST2.50%
Total: 4646.23 242.77 121.39 121.39
Tender Details
Cash 4889.00
Balance : 0.00
Terms & Conditions:
1.Goods sold will be exchanged with in 15 days.
2.No exchange will be entertained without Original Bill Copy.
3.No cash Refund.
4,Please Follow washing instructions.
3. There will be No Return, No Exchange during EOSS & Promotion period
Thank You..... Visit Again.
""",
"""
TAX INVOICE
safari
Safari Industries Itd ( Grand High SSOLD TO :- SRM-J INFRA PVT LTD InvoiceNo :- GHSS23/97
GF 15,grand high street, indian lan Address :.Invoice Date :- 19/05/2023 19:06:
global industrial park,hingawadi, CIN No :
mulshi pune-411057 PAN No :
Mobile No: 9096898777
Email ID : GST No : 27AAHHCS5888E2ZU
PAN No : 27ABICS1317G1ZG State :
GST No :27ABICS1317G1ZG
SrNo Item Description HSNcode Qty MRP Rate Disc%. Discamt Taxableamt SGST% SGSTamt CGST% CGSTamt Net Amount
1 OZONE 56 4W MIDNIGHT Blue 42021200 3049.00 3049.00 0 0 2583.90 9 232.55 9 232.55 3049.00
Total Qty : 1 SGST 232.55 CGST 232.55
Total Value : 3049.00
Disc Amt : 0.00
Net Payable : 3049.00
TAX SUMMARY
"We also accept the following payment modes":-
Tax% Tax Amount Taxable Value Debit Card powered by RuPay / UPI/ UPI QR Code
9.00 232.55 2583.90
9.00 232.55 TENDER DETAILS 2583.90
Cash Rs 3049.00
Amount In Words :- Rupees Three Thousand Fourty Nine Only
Document Remark :
Thank You for shopping at Safari
TERMS AND CONDITIONS
1.Merchandise shall be subject to limited warranty period as per Seller's warranty policy and such period of warranty shall be as specified on warranty card attached to merchandise.
2.The Warranty Card is valid only if it is duly filled in, signed and stamped by Safari authorized dealer/store/outlet or is accompanied by original invoice. Further, to avail warranty
services, the warranty card or original invoice for the purchase must-be produced along with the defective product.
and accordingly Company's decision shall be final and binding.
4.The defective merchandise shall be replaced subject to the condition that the terms and conditions of the warranty policy are fulfilled.Cash will not be refunded in any circumstances.
5.Safari Industries (India) Limited's liability towards the customer, whether in contract, in tort, under any warranty, in negligence or otherwise, shall not exceed, in any case, the amount
of the purchase price paid by the customer as per invoice.
6.Claims by the Customer for shortages or errors in the delivery must be made within 7 days after the delivery of Goods.
telephone number as mentioned on the Seller's website or may mail at customercare@safari.in.
8.The Customer agrees that the validity, interpretation and performance of any agreement arising out of this transaction shall be governed by the applicable laws of India. Customer
and Seller hereby submit to the exclusive jurisdiction for the resolution of any disputes hereunder, to the courts of Mumbai, India. This shall be the sole and exclusive jurisdiction and
venue for the purpose of adjudication of any rights and liabilities hereunder.
Bill details will be sent to you on your email id & SMS on phone, if provided by you. In case you do not receive such eMail & SMS within 24
hours then mail us at customercare@safari.in
For Safari Industries I Itd ( Grand High.
Print Date :- 22/05/2023 11:16:47
Regd. Off.: Safari Industries (India) Ltd., 302-303, A Wing, The Qube CTS No.1498, A/2, M.V. Road, Marol, Andheri (E),Mumbai - 400 059, Maharashtra, India Authorised Signatory
Mob.: 9819547085 | Email id: customercare@safar.in | Website: www.safaribags.com
""",
"""
mamaearth
UG -Q4Upper Ground Floor,RMZ Galleria Is
RM2 Galleria,
Ambedkar Colony, Yelahanka New Town
560064
GST No:29AADCH9716L1Z0
Tax Invoice
Ms SARITA
Mobile No:9663395251
Bill No:003812300385
Date & Time:13-May-2023 / 13:16
Product Qty MRP Value
GST12-HSN:3004901112
After Bite Roll On 40ml 1.00 249.00 174.30
Discount Rate 174.30
GST18 - HSN : 3304999018
Woody Brown Kajal 2.00 349.00 488.60
Discount Rate 244.30
HSN:3304999018
Rice Face Scrub 20G 1.00 99.00 0.00
Discount Rate
HSN:3305909018
Rice Wonder Water 100 1.00 349.00 244.30
ml Discount Rate 244.30
HSN : 3305909018
Rice Wonder Water 100 2.00 349.00 488.60
ml
Discount Rate 244.30
HSN : 3305901118
ONION HAIR OIL FOR 1.00 599.00 419.30
HAIR REGROWTH
HAIR FALL CONTROL
250ML
Discount Rate 419.30
HSN : 3304999018
Charcoal Black Long 1.00 499.00 349.30
Stay Kohl1.2 g
Discount Rate 349.30
HSN :3304999018
Rice face scrub 100g 1.00 349.00 244.30
Discount Rate 244.30
HSN3304999018
Ubtan Face Mask 20G 1.00 99.00 0.00
Discount Rate 0.00
HSN:3401309018
VIT C Face Wash 20ML 1.00 99.00 0.00
Discount Rate 0.00
GrossAmount : 2049.18
Tax Amount : 359.52
Total Amount : 2409.00
Bll Dlscount Amount : 0.00
Invoice Amount : 2409.00
Tax Details (Incluced In the Invoice Amount)
Tax Description. Taxable Value CGST SGST
GST12 155.62 9.34 9.34
GST10 1893.56 170.42 170.42
Total 2049.16 179.76 179.76
Round off 0.30
Payment Details
BYCASH Amount recived 2409.00
For any queries,feel free to reach out to our customer
care team at 91-8901555444
"""
],
fill_height=True,
cache_examples=True,
title="Atsuya Buddy",
)
demo.queue().launch(show_api=False)