File size: 4,843 Bytes
c6a6d99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
import os
from dotenv import load_dotenv
import time
load_dotenv()
API_KEY=os.getenv("API_KEY")
def get_sentiment(text):
    API_URL = "https://api-inference.huggingface.co/models/distilbert-base-uncased-finetuned-sst-2-english"
    HEADERS = {"Authorization": f"Bearer {API_KEY}"}

    data = {"inputs": text}
    response = requests.post(API_URL, headers=HEADERS, json=data)

    try:
        result = response.json()

        if isinstance(result, list) and len(result) > 0 and isinstance(result[0], list):
            best_label = max(result[0], key=lambda x: x["score"])  # Extract highest score
            return best_label["label"]
        else:
            return "Error: Unexpected response format"

    except requests.exceptions.JSONDecodeError:
        return "Error: Empty or invalid JSON response"



def summarize_text(text, max_length=150, min_length=50):
    API_URL = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"
    HEADERS = {"Authorization": f"Bearer {API_KEY}"}

    data = {
        "inputs": text,
        "parameters": {"max_length": max_length, "min_length": min_length, "do_sample": False}
    }

    response = requests.post(API_URL, headers=HEADERS, json=data)

    try:
        result = response.json()
        if isinstance(result, list) and "summary_text" in result[0]:
            return result[0]["summary_text"]  # Extract summary text
        else:
            return "Error: Unexpected response format"

    except requests.exceptions.JSONDecodeError:
        return "Error: Empty or invalid JSON response"  

def extract_keywords(text, top_n=5):
    API_URL = "https://api-inference.huggingface.co/models/ml6team/keyphrase-extraction-kbir-inspec"
    HEADERS = {"Authorization": f"Bearer {API_KEY}"}

    data = {"inputs": text}

    response = requests.post(API_URL, headers=HEADERS, json=data)

    try:
        result = response.json()
        if isinstance(result, list) and len(result) > 0:
            keywords = [item["word"] for item in result[:top_n]]
            return keywords
        else:
            return "Error: Unexpected response format"

    except requests.exceptions.JSONDecodeError:
        return "Error: Empty or invalid JSON response"
    
def text_to_speech(text):
    API_URL = 'https://api-inference.huggingface.co/models/facebook/mms-tts-hin'
    headers = {'Authorization': f'Bearer {API_KEY}'}
    payload = {'inputs': text}
    response = requests.post(API_URL, headers=headers, json=payload)
    if response.status_code == 200:
        with open('output.wav', 'wb') as f:
            f.write(response.content)
        print('Audio content written to output.wav')
    else:
        print(f'Error: {response.status_code}, {response.text}')




HEADERS = {"Authorization": f"Bearer {API_KEY}"}
MODELS = {
    "comparison": "https://api-inference.huggingface.co/models/sentence-transformers/all-MiniLM-L6-v2",
    "sentiment": "https://api-inference.huggingface.co/models/distilbert-base-uncased-finetuned-sst-2-english"
}

def request_huggingface(api_url, payload, retries=3, delay=2):
    for attempt in range(retries):
        try:
            response = requests.post(api_url, headers=HEADERS, json=payload)
            
            if response.status_code == 200:
                return response.json()

            elif response.status_code in [429, 503]:  # Rate limited or service unavailable
                print(f"Rate limited. Retrying in {delay} seconds...")
                time.sleep(delay)
            else:
                print(f"Error {response.status_code}: {response.text}")
                return None

        except requests.exceptions.RequestException as e:
            print(f"Request failed: {e}")

    print("Failed to get a valid response after retries.")
    return None

def comparison_impact(text1, text2):
    # Comparison Analysis
    comparison_payload = {"inputs": {"source_sentence": text1, "sentences": [text2]}}
    comparison_result = request_huggingface(MODELS["comparison"], comparison_payload)

    # Sentiment Analysis for Impact
    sentiment1 = request_huggingface(MODELS["sentiment"], {"inputs": text1})
    sentiment2 = request_huggingface(MODELS["sentiment"], {"inputs": text2})

    if sentiment1 and sentiment2:
        sentiment1_label = max(sentiment1[0], key=lambda x: x["score"])["label"]
        sentiment2_label = max(sentiment2[0], key=lambda x: x["score"])["label"]

        impact_analysis = f"Sentiment Shift: '{sentiment1_label}' → '{sentiment2_label}'"
    else:
        impact_analysis = "Error in sentiment analysis."

    return {
        "Comparison Result": comparison_result,
        "Impact Analysis": impact_analysis
    }