File size: 7,413 Bytes
7d88a24
 
39dff4c
 
 
99914ec
4a0366f
c352f02
a147fbd
8d84915
ed0aa7b
24ed9e0
c6ddc86
3661992
4854a72
 
 
 
176b9ce
 
 
 
 
 
 
 
4854a72
 
 
176b9ce
d354d71
d50b1d6
176b9ce
 
 
 
 
 
 
 
 
 
 
d50b1d6
176b9ce
 
 
4854a72
176b9ce
 
 
 
 
 
 
 
 
 
 
 
d354d71
176b9ce
 
4854a72
 
 
 
bb31795
 
176b9ce
4854a72
 
176b9ce
4854a72
176b9ce
4854a72
f2e5be8
 
 
 
 
 
 
 
6b796ae
f2e5be8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b796ae
f2e5be8
 
 
 
 
 
 
 
 
 
 
 
 
6b796ae
f2e5be8
 
6b796ae
f2e5be8
 
 
 
 
 
 
6b796ae
f2e5be8
3516f35
f2e5be8
 
867aaf1
 
 
 
 
7d88a24
8f92439
 
 
 
3a23947
 
98c0e59
3a23947
 
98c0e59
3a23947
 
 
 
1d48332
f2e5be8
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# Welcome to Team Tonic's MultiMed

import gradio as gr
import requests
import json
from decouple import Config

config = Config('.env')


def query_vectara(question):
    user_message = question

    # Read authentication parameters from the .env file
    CUSTOMER_ID = config('CUSTOMER_ID')
    CORPUS_ID = config('CORPUS_ID')
    API_KEY = config('API_KEY')

    # Define the headers
    api_key_header = {
        "customer-id": CUSTOMER_ID,
        "x-api-key": API_KEY
    }

    # Define the request body in the structure provided in the example
    request_body = {
        "query": [
            {
                "query": user_message,
                "queryContext": "",
                "start": 1,
                "numResults": 25,
                "contextConfig": {
                    "charsBefore": 0,
                    "charsAfter": 0,
                    "sentencesBefore": 2,
                    "sentencesAfter": 2,
                    "startTag": "%START_SNIPPET%",
                    "endTag": "%END_SNIPPET%",
                },
                "rerankingConfig": {
                    "rerankerId": 272725718,
                    "mmrConfig": {
                        "diversityBias": 0.35
                    }
                },
                "corpusKey": [
                    {
                        "customerId": CUSTOMER_ID,
                        "corpusId": CORPUS_ID,
                        "semantics": 0,
                        "metadataFilter": "",
                        "lexicalInterpolationConfig": {
                            "lambda": 0
                        },
                        "dim": []
                    }
                ],
                "summary": [
                    {
                        "maxSummarizedResults": 5,
                        "responseLang": "eng",
                        "summarizerPromptName": "vectara-summary-ext-v1.2.0"
                    }
                ]
            }
        ]
    }

    # Make the API request using Gradio
    response = requests.post(
        "https://api.vectara.io/v1/query",
        json=request_body,  # Use json to automatically serialize the request body
        verify=True,
        headers=api_key_header
    )

    if response.status_code == 200:    
        query_data = response.json()    
        if query_data:    
            sources_info = []    
              
            # Extract the summary.  
            summary = query_data['responseSet'][0]['summary'][0]['text']  
  
            # Iterate over all response sets    
            for response_set in query_data.get('responseSet', []):    
                # Extract sources    
                for source in response_set.get('response', [])[:5]:  # Limit to top 5 sources.  
                    source_metadata = source.get('metadata', [])    
                    source_info = {}    
    
                    for metadata in source_metadata:    
                        metadata_name = metadata.get('name', '')    
                        metadata_value = metadata.get('value', '')    
    
                        if metadata_name == 'title':    
                            source_info['title'] = metadata_value    
                        elif metadata_name == 'author':    
                            source_info['author'] = metadata_value    
                        elif metadata_name == 'pageNumber':    
                            source_info['page number'] = metadata_value    
    
                    if source_info:    
                        sources_info.append(source_info)    
              
            result = {"summary": summary, "sources": sources_info}  
            return f"{json.dumps(result, indent=2)}"    
        else:    
            return "No data found in the response."    
    else:    
        return f"Error: {response.status_code}"    


def convert_to_markdown(vectara_response_json):  
    vectara_response = json.loads(vectara_response_json)  
    if vectara_response:  
        summary = vectara_response.get('summary', 'No summary available')  
        sources_info = vectara_response.get('sources', [])  
  
        # Format the summary as Markdown  
        markdown_summary = f'**Summary:** {summary}\n\n'  
  
        # Format the sources as a numbered list  
        markdown_sources = ""  
        for i, source_info in enumerate(sources_info):  
            author = source_info.get('author', 'Unknown author')  
            title = source_info.get('title', 'Unknown title')  
            page_number = source_info.get('page number', 'Unknown page number')  
            markdown_sources += f"{i+1}. {title} by {author}, Page {page_number}\n"  
  
        return f"{markdown_summary}**Sources:**\n{markdown_sources}"  
    else:  
        return "No data found in the response."  
  
  
iface = gr.Interface(  
    fn=lambda text: convert_to_markdown(query_vectara(text)),  
    inputs=[gr.Textbox(label="Input Text")],  
    outputs=[gr.Markdown(label="Output Text")],  
    title="👋🏻Welcome to Team🚀Tonic's 😷MultiMed⚕️",  
    description="""<h2>How To Use 😷MultiMed⚕️:</h2><h3>🗣️📝Interact with 😷MultiMed⚕️ in any language using audio or text!🗣️📝</h3>
    <h3>This is an educational and accessible conversational tool to improve wellness and sanitation in support of public health. 📚🌟💼 You can use 😷MultiMed⚕️ on your own data & in your own way by cloning this space. 🧬🔬🔍 Simply click here: <a style="display:inline-block" href="https://huggingface.co/spaces/TeamTonic/MultiMed?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHY dmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a></h3>
    <h3>🌟TeamTonic🌟 is always making cool demos!</h3> 
    <h3>Join our active builder's community on Discord: <a href="https://discord.gg/GWpVpekp"><img src="https://discordapp.com/api/guilds/1109943800132010065/widget.png"></a> On Huggingface: <a href="https://huggingface.co/TeamTonic">TeamTonic</a> & <a href="https://huggingface.co/MultiTransformer">MultiTransformer</a> On Github: <a href="https://github.com/tonic-ai">Polytonic<img src="https://img.shields.io/github/followers/Tonic-AI.svg?style=social&label=Follow&maxAge=2592000"></a> & contribute to <a href="https://github.com/tonic-ai/polygpt-alpha">PolyGPT</h3>""",
    examples=[
        ["What is the proper treatment for buccal herpes?"],
        ["Male, 40 presenting with swollen genitals and a rash"],
        ["How does cellular metabolism work TCA cycle"],
        ["What special care must be provided to children with chicken pox?"],
        ["When and how often should I wash my hands ?"],
        ["بکل ہرپس کا صحیح علاج کیا ہے؟"],
        ["구강 헤르페스의 적절한 치료법은 무엇입니까?"],
        ["Je, ni matibabu gani sahihi kwa herpes ya buccal?"]
    ]
)
  
iface.launch()